@vielzeug/codex 26.11.24 → 26.11.26
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/README.md +5 -4
- package/data/snapshot.json +1 -0
- package/dist/catalog.d.ts +35 -39
- package/dist/catalog.js +112 -139
- package/dist/catalog.js.map +1 -1
- package/dist/cli.js +25 -16
- package/dist/cli.js.map +1 -1
- package/dist/http.js +1 -1
- package/dist/http.js.map +1 -1
- package/dist/index.d.ts +5 -7
- package/dist/index.js +4 -6
- package/dist/index.js.map +1 -1
- package/dist/server.d.ts +9 -7
- package/dist/server.js +14 -6
- package/dist/server.js.map +1 -1
- package/dist/snapshot.d.ts +8 -22
- package/dist/snapshot.js +41 -176
- package/dist/snapshot.js.map +1 -1
- package/dist/tools/index.d.ts +1 -1
- package/dist/tools/index.js.map +1 -1
- package/dist/tools/packages.js +49 -82
- package/dist/tools/packages.js.map +1 -1
- package/dist/tools/refine.d.ts +1 -2
- package/dist/tools/refine.js +90 -82
- package/dist/tools/refine.js.map +1 -1
- package/dist/tools/schema.d.ts +2 -1
- package/dist/tools/schema.js +9 -5
- package/dist/tools/schema.js.map +1 -1
- package/dist/tools/shared.d.ts +2 -2
- package/dist/types.d.ts +77 -64
- package/dist/types.js +6 -2
- package/dist/types.js.map +1 -1
- package/package.json +2 -2
- package/skills/vielzeug/SKILL.md +18 -20
- package/data/catalog.json +0 -2539
- package/data/llms-full.txt +0 -40978
- package/data/llms.txt +0 -60
- package/data/manifest.json +0 -4
- package/data/packages/archive.json +0 -87
- package/data/packages/arsenal.json +0 -270
- package/data/packages/assay.json +0 -52
- package/data/packages/atlas.json +0 -81
- package/data/packages/bard.json +0 -38
- package/data/packages/beacon.json +0 -51
- package/data/packages/clockwork.json +0 -69
- package/data/packages/codex.json +0 -37
- package/data/packages/coins.json +0 -99
- package/data/packages/conduit.json +0 -67
- package/data/packages/courier.json +0 -66
- package/data/packages/dnd.json +0 -60
- package/data/packages/familiar.json +0 -38
- package/data/packages/flux.json +0 -97
- package/data/packages/focus.json +0 -51
- package/data/packages/forge.json +0 -65
- package/data/packages/gesture.json +0 -65
- package/data/packages/herald.json +0 -80
- package/data/packages/illusionist.json +0 -132
- package/data/packages/ink.json +0 -41
- package/data/packages/keymap.json +0 -55
- package/data/packages/ledger.json +0 -60
- package/data/packages/lingua.json +0 -68
- package/data/packages/mesh.json +0 -52
- package/data/packages/necromancer.json +0 -55
- package/data/packages/orbit.json +0 -100
- package/data/packages/ore.json +0 -78
- package/data/packages/palette.json +0 -42
- package/data/packages/patchwork.json +0 -55
- package/data/packages/postmaster.json +0 -49
- package/data/packages/prism.json +0 -99
- package/data/packages/pulse.json +0 -71
- package/data/packages/refine.json +0 -36
- package/data/packages/ripple.json +0 -84
- package/data/packages/rune.json +0 -78
- package/data/packages/sandbox.json +0 -26
- package/data/packages/scout.json +0 -66
- package/data/packages/scribe.json +0 -57
- package/data/packages/scroll.json +0 -110
- package/data/packages/sentinel.json +0 -46
- package/data/packages/sigil.json +0 -52
- package/data/packages/sourcerer.json +0 -86
- package/data/packages/spell.json +0 -126
- package/data/packages/stage.json +0 -26
- package/data/packages/tabula.json +0 -39
- package/data/packages/tandem.json +0 -31
- package/data/packages/tavern.json +0 -34
- package/data/packages/tempo.json +0 -68
- package/data/packages/vault.json +0 -81
- package/data/packages/ward.json +0 -77
- package/data/packages/wayfinder.json +0 -126
- package/data/packages/wire.json +0 -51
- package/data/refine.json +0 -17277
- package/dist/consumer.d.ts +0 -17
- package/dist/consumer.js +0 -114
- package/dist/consumer.js.map +0 -1
- package/dist/port.d.ts +0 -2
- package/dist/port.js +0 -12
- package/dist/port.js.map +0 -1
|
@@ -1,65 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"apiSource": "export {\n createDragGesture,\n type DragEndReason,\n type DragGesture,\n type DragGestureDetail,\n type DragGestureEndDetail,\n type DragGestureOptions,\n type DragPoint,\n} from './drag-gesture.js';\nexport { GestureConfigError, GestureError } from './errors.js';\nexport {\n createLongPress,\n type LongPress,\n type LongPressDetail,\n type LongPressOptions,\n} from './long-press.js';\nexport {\n createPanGesture,\n type PanAxis,\n type PanEndReason,\n type PanGesture,\n type PanGestureDetail,\n type PanGestureEndDetail,\n type PanGestureOptions,\n} from './pan-gesture.js';\nexport {\n createPinchGesture,\n type PinchEndReason,\n type PinchGesture,\n type PinchGestureDetail,\n type PinchGestureEndDetail,\n type PinchGestureOptions,\n type PinchPoint,\n} from './pinch-gesture.js';\nexport {\n createWheelGesture,\n normalizeWheel,\n type WheelDetail,\n type WheelGesture,\n type WheelOptions,\n} from './wheel-gesture.js';\n",
|
|
3
|
-
"docs": {
|
|
4
|
-
"index": "---\ntitle: 'Gesture: Pointer movement primitives'\ndescription: Framework-neutral pointer drag, pan, pinch, and wheel recognition with lifecycle-owned handles.\npackage: gesture\ncategory: input\nkeywords: [pointer, pan, swipe, gesture, touch, drag, long press, pinch, zoom, wheel]\nexports:\n [createDragGesture, createPanGesture, createLongPress, createPinchGesture, createWheelGesture, GestureConfigError]\nrelated: [refine, dnd, keymap]\nenvironments: [browser]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"gesture\" />\n\n## Why Gesture?\n\nPointer-driven interfaces need reliable one-pointer movement tracking without coupling recognition to rendering, drag-and-drop semantics, or product-specific completion policy.\n\n```ts\n// Before\nelement.addEventListener('pointermove', (event) => {\n // Coordinate tracking, pointer identity, direction locking, and cleanup\n});\n\n// After\nimport { createPanGesture } from '@vielzeug/gesture';\n\nconst pan = createPanGesture(element, {\n axis: 'x',\n onMove: ({ distance }) => console.log('distance', distance),\n onEnd: ({ reason }) => console.log('ended', reason),\n});\n```\n\n| Feature | Gesture | Ad-hoc pointer handling |\n| ----------------------------- | --------------------------------------------- | ----------------------- |\n| Bundle size | <PackageInfo package=\"gesture\" type=\"size\" /> | n/a |\n| Zero dependencies | <ore-icon name=\"check\" size=\"16\"></ore-icon> | n/a |\n| Two-dimensional drag tracking | Built in | Manual |\n| Axis intent recognition | Built in | Manual |\n| Pointer ownership | Tracked across the document | Manual |\n| Lifecycle cleanup | `dispose()` + `disposalSignal` | Manual |\n\n<div class=\"decision-callout\">\n\n**Use Gesture when** UI surfaces need consistent free drag or axis-locked pan tracking while retaining their own rendering and completion rules.\n\n**Consider direct pointer handling when** the interaction is isolated and does not need reusable lifecycle or direction-lock behavior.\n\n</div>\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/gesture\n```\n\n```sh [npm]\nnpm install @vielzeug/gesture\n```\n\n```sh [yarn]\nyarn add @vielzeug/gesture\n```\n\n:::\n\n## Quick Start\n\n```ts\nimport { createPanGesture } from '@vielzeug/gesture';\n\nconst element = document.querySelector<HTMLElement>('[data-swipe]');\nif (!element) throw new Error('Missing [data-swipe] element');\n\nconst pan = createPanGesture(element, {\n axis: 'x',\n onMove: ({ distance }) => {\n element.style.transform = `translateX(${distance}px)`;\n },\n onEnd: ({ distance, reason }) => {\n element.style.transform = '';\n if (reason === 'release' && Math.abs(distance) >= 48) {\n pan.dispose();\n element.remove();\n }\n },\n});\n\nwindow.addEventListener('pagehide', () => pan.dispose(), { once: true });\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- `createDragGesture()`: unrestricted two-dimensional pointer movement tracking\n- `createPanGesture()`: one-axis pointer movement with direction intent recognition\n- `createLongPress()`: hold recognition with slop cancellation and click swallowing\n- `createPinchGesture()`: two-pointer scale and rotation with per-frame deltas\n- `createWheelGesture()`: wheel and trackpad input with pixel-normalized deltas\n- Direction locking: activates only when movement favors the configured axis\n- Configurable pointer capture: own the pointer by default or preserve native targeting\n- Configurable `activationDistance`: tune slop for touch density and component needs\n- Consumer-owned policy: completion thresholds, snapping, and outcomes stay in application code\n- Stable completion: one `onEnd` callback for release and cancellation\n- Lifecycle ownership: `dispose()`, `disposed`, `disposalSignal`, optional owner `signal`, and `[Symbol.dispose]()`\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/): components that use pan recognition for carousel, drawer, toast, and list interactions.\n- [Dnd](/dnd/): builds touch sorting on `createDragGesture()` and adds files, previews, drop targets, keyboard reordering, and connected-list transactions.\n- [Keymap](/keymap/): keyboard interaction primitives for complementary input paths.\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
|
|
5
|
-
"api": "---\ntitle: 'Gesture: API Reference'\ndescription: API reference for drag, pan, long-press, pinch, and wheel recognition.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution mode | Common gotcha |\n| ------------------------------------------ | --------------------------------------------------- | -------------- | -------------------------------------------------------- |\n| `createDragGesture()` | Track unrestricted two-dimensional pointer movement | Sync | Does not provide DOM movement or drop semantics |\n| `createPanGesture()` | Track pointer movement projected onto one axis | Sync | Cross-axis intent ends a pending interaction |\n| `createLongPress()` | Recognize a primary pointer held in place | Sync | The click that follows a fired hold is swallowed |\n| `createPinchGesture()` | Track two-pointer scale and rotation | Sync | Ends when either pointer lifts |\n| `createWheelGesture()` | Track wheel input with pixel-normalized deltas | Sync | Never prevents scrolling unless `preventDefault` opts in |\n| `normalizeWheel()` | Convert wheel deltas to CSS pixels for any mode | Sync | Page-mode scaling uses the target's client box |\n| `DragGesture` / `PanGesture` / `LongPress` | Control recognition lifecycle | Sync | `dispose()` does not invoke `onEnd` |\n| `DragGestureOptions` | Configure free-drag recognition | Sync | `activationDistance` uses Euclidean distance |\n| `PanGestureOptions` | Configure axis-locked recognition | Sync | Completion thresholds belong in `onEnd` |\n| `LongPressOptions` | Configure hold recognition | Sync | `durationMs` and `slopPx` are validated at construction |\n| `PinchGestureOptions` | Configure pinch/rotate recognition | Sync | `activationDistance` is a span change, not pointer move |\n| `WheelOptions` | Configure wheel recognition | Sync | `preventDefault` accepts a per-event predicate |\n\n## Package Entry Point\n\n| Import | Purpose |\n| ------------------- | -------------------------------------------------------------------------------------------------------------- |\n| `@vielzeug/gesture` | Drag, pan, long-press, pinch, and wheel factories, handles, callback details, options, points, and end reasons |\n\n## Core Functions\n\n### `createDragGesture()`\n\n```ts\nfunction createDragGesture(target: Element, options?: DragGestureOptions): DragGesture;\n```\n\nTracks one primary pointer without restricting movement to an axis.\n\n| Parameter | Type | Description |\n| --------- | -------------------- | --------------------------------------------------------------------- |\n| `target` | `Element` | Element that owns pointer admission and optional capture |\n| `options` | `DragGestureOptions` | Activation, admission, capture, callback, and lifecycle configuration |\n\n**Returns:** A lifecycle-owned `DragGesture` handle.\n\n**Example**\n\n```ts\nimport { createDragGesture } from '@vielzeug/gesture';\n\nconst drag = createDragGesture(element, {\n onMove: ({ delta }) => {\n element.style.translate = `${delta.x}px ${delta.y}px`;\n },\n onEnd: () => {\n element.style.translate = '';\n },\n});\n```\n\n---\n\n### `createPanGesture()`\n\n```ts\nfunction createPanGesture(target: Element, options?: PanGestureOptions): PanGesture;\n```\n\nTracks one primary pointer after movement establishes intent on the configured axis.\n\n| Parameter | Type | Description |\n| --------- | ------------------- | --------------------------------------------------------------------------- |\n| `target` | `Element` | Element that owns pointer admission and optional capture |\n| `options` | `PanGestureOptions` | Axis, activation, admission, capture, callback, and lifecycle configuration |\n\n**Returns:** A lifecycle-owned `PanGesture` handle.\n\n**Example**\n\n```ts\nimport { createPanGesture } from '@vielzeug/gesture';\n\nconst pan = createPanGesture(element, {\n axis: 'x',\n onEnd: ({ distance, reason }) => {\n if (reason === 'release' && Math.abs(distance) >= 48) dismiss();\n },\n});\n```\n\nBoth handles expose the same members:\n\n| Member | Type | Contract |\n| -------------------- | --------------- | ---------------------------------------------------------------------------------------------------------------- |\n| `active` | `boolean` | `true` after activation and before release or cancellation |\n| `cancel()` | `() => boolean` | Clears pending recognition or ends active recognition with `reason: 'cancel'`; returns whether a session existed |\n| `disposalSignal` | `AbortSignal` | Aborts when the handle is disposed |\n| `dispose()` | `() => void` | Aborts `disposalSignal`, clears recognition, releases capture, and detaches listeners; idempotent |\n| `disposed` | `boolean` | `true` after disposal |\n| `[Symbol.dispose]()` | `() => void` | Calls `dispose()` |\n\n---\n\n### `createLongPress()`\n\n```ts\nfunction createLongPress(target: Element, options?: LongPressOptions): LongPress;\n```\n\nRecognizes a primary pointer held in place: `onLongPress` fires with the originating pointerdown once the hold outlasts `durationMs`.\n\n| Parameter | Type | Description |\n| --------- | ------------------ | ---------------------------------------------------------------------------- |\n| `target` | `Element` | Element that owns pointer admission, document tracking, and click swallowing |\n| `options` | `LongPressOptions` | Hold time, slop distance, admission, callback, and lifecycle configuration |\n\n**Returns:** A lifecycle-owned `LongPress` handle with the same members as the other gestures; `active` is `true` while a hold is pending.\n\n**Example**\n\n```ts\nimport { createLongPress } from '@vielzeug/gesture';\n\nconst hold = createLongPress(list, {\n shouldStart: (event) => event.pointerType !== 'mouse',\n onLongPress: (detail) => {\n const tile = (detail.event.target as HTMLElement).closest('.tile');\n openDetail(tile?.dataset.id);\n },\n});\n```\n\nMovement beyond `slopPx`, a second touch, window blur, or a hidden document cancels a pending hold. The dynamic `disabled` predicate is checked again before the timer fires. The pointer-generated click following a fired hold is swallowed through a capture-phase listener on `target`; keyboard clicks (`detail: 0`) remain available. Bind `target` to a stable ancestor of the pressed controls so the swallow precedes their click handlers.\n\n---\n\n### `createPinchGesture()`\n\n```ts\nfunction createPinchGesture(target: Element, options?: PinchGestureOptions): PinchGesture;\n```\n\nTracks two pointers and reports scale and rotation relative to the positions where they went down.\n\n| Parameter | Type | Description |\n| --------- | --------------------- | --------------------------------------------------------------------- |\n| `target` | `Element` | Element that owns pointer admission and optional capture |\n| `options` | `PinchGestureOptions` | Activation, admission, capture, callback, and lifecycle configuration |\n\n**Returns:** A lifecycle-owned `PinchGesture` handle with the same members as the other gestures.\n\n**Example**\n\n```ts\nimport { createPinchGesture } from '@vielzeug/gesture';\n\nconst pinch = createPinchGesture(stage, {\n onMove: ({ deltaScale, deltaRotation, deltaCentroid }) => {\n camera.zoomBy(1 + deltaScale);\n camera.rotateBy(deltaRotation);\n camera.panBy(deltaCentroid.x, deltaCentroid.y);\n },\n});\n```\n\nThe gesture activates once the span between the pointers changes by `activationDistance` pixels. It ends when either pointer lifts (`reason: 'release'`) or the session is cancelled; the remaining pointer never continues the gesture. A third pointer down is ignored.\n\n---\n\n### `createWheelGesture()`\n\n```ts\nfunction createWheelGesture(target: Element, options?: WheelOptions): WheelGesture;\n```\n\nReports wheel events with deltas normalized to CSS pixels. The handle is disposal-only: it has `dispose()`, `disposed`, `disposalSignal`, and `[Symbol.dispose]()`, but no `active` or `cancel()` because wheel events are stateless.\n\n| Parameter | Type | Description |\n| --------- | -------------- | ------------------------------------------------------------ |\n| `target` | `Element` | Element the `wheel` listener is attached to |\n| `options` | `WheelOptions` | Prevention, admission, callback, and lifecycle configuration |\n\n**Returns:** A disposal-only `WheelGesture` handle.\n\n**Example**\n\n```ts\nimport { createWheelGesture } from '@vielzeug/gesture';\n\nconst wheel = createWheelGesture(stage, {\n preventDefault: true,\n onWheel: ({ deltaX, deltaY, pinch }) => {\n if (pinch) camera.zoomBy(Math.exp(-deltaY * 0.01));\n else camera.panBy(-deltaX, -deltaY);\n },\n});\n```\n\n`pinch` is `true` when `ctrlKey` is set, which is how browsers report trackpad pinch-zoom. Prevention defaults to `false`; the listener is non-passive so `preventDefault` works when opted in.\n\n---\n\n### `normalizeWheel()`\n\n```ts\nfunction normalizeWheel(event: WheelEvent, target: Element): { deltaX: number; deltaY: number };\n```\n\nConverts a wheel event's deltas to CSS pixels for any `deltaMode`: pixel mode passes through, line mode multiplies by 16, and page mode multiplies by the larger of the target's client width and height (falling back to the window box). Exported for consumers that already own their wheel listener.\n\n## Types\n\n### Drag types\n\n```ts\ntype DragEndReason = 'cancel' | 'release';\n\ntype DragPoint = Readonly<{\n x: number;\n y: number;\n}>;\n\ntype DragGestureDetail = Readonly<{\n current: DragPoint;\n delta: DragPoint;\n event: PointerEvent;\n pointerId: number;\n pointerType: string;\n start: DragPoint;\n target: Element;\n velocity: DragPoint;\n}>;\n\ntype DragGestureEndDetail = DragGestureDetail &\n Readonly<{\n reason: DragEndReason;\n }>;\n\ntype DragGestureOptions = Readonly<{\n activationDistance?: number;\n disabled?: boolean | (() => boolean | undefined);\n onEnd?: (detail: DragGestureEndDetail) => void;\n onMove?: (detail: DragGestureDetail) => void;\n onStart?: (detail: DragGestureDetail) => void;\n pointerCapture?: boolean;\n shouldActivate?: (detail: DragGestureDetail) => boolean;\n shouldStart?: (event: PointerEvent) => boolean;\n signal?: AbortSignal;\n}>;\n```\n\n`start`, `current`, and `delta` use viewport `clientX` and `clientY` coordinates. Activation uses `Math.hypot(delta.x, delta.y)`.\n\n### Pan types\n\n```ts\ntype PanAxis = 'x' | 'y';\ntype PanEndReason = 'cancel' | 'release';\n\ntype PanGestureDetail = Readonly<{\n axis: PanAxis;\n current: number;\n distance: number;\n event: PointerEvent;\n pointerId: number;\n pointerType: string;\n start: number;\n target: Element;\n velocity: number;\n}>;\n\ntype PanGestureEndDetail = PanGestureDetail &\n Readonly<{\n reason: PanEndReason;\n }>;\n\ntype PanGestureOptions = Readonly<{\n activationDistance?: number;\n axis?: PanAxis | (() => PanAxis);\n disabled?: boolean | (() => boolean | undefined);\n onEnd?: (detail: PanGestureEndDetail) => void;\n onMove?: (detail: PanGestureDetail) => void;\n onStart?: (detail: PanGestureDetail) => void;\n pointerCapture?: boolean;\n shouldActivate?: (detail: PanGestureDetail) => boolean;\n shouldStart?: (event: PointerEvent) => boolean;\n signal?: AbortSignal;\n}>;\n```\n\nPan details project `start`, `current`, and `distance` onto `axis`. The default axis is `'x'`.\n\nVelocity is signed CSS pixels per second over the trailing 90 ms. Samples include pointerdown, movement (including activation), and release. A window with fewer than two distinct sample times reports zero velocity; a pause longer than the window removes earlier movement.\n\n### Long-press types\n\n```ts\ntype LongPressDetail = Readonly<{\n event: PointerEvent;\n pointerId: number;\n pointerType: string;\n target: Element;\n}>;\n\ntype LongPressOptions = Readonly<{\n durationMs?: number;\n disabled?: boolean | (() => boolean | undefined);\n onLongPress?: (detail: LongPressDetail) => void;\n shouldStart?: (event: PointerEvent) => boolean;\n slopPx?: number;\n signal?: AbortSignal;\n}>;\n```\n\n`durationMs` defaults to `500` and `slopPx` to `8`. `event` is the pointerdown that started the hold, so `event.target` is the pressed element.\n\n### Pinch types\n\n```ts\ntype PinchEndReason = 'cancel' | 'release';\n\ntype PinchPoint = Readonly<{\n x: number;\n y: number;\n}>;\n\ntype PinchGestureDetail = Readonly<{\n centroid: PinchPoint;\n deltaCentroid: PinchPoint;\n deltaRotation: number;\n deltaScale: number;\n event: PointerEvent;\n rotation: number;\n scale: number;\n startCentroid: PinchPoint;\n target: Element;\n}>;\n\ntype PinchGestureEndDetail = PinchGestureDetail &\n Readonly<{\n reason: PinchEndReason;\n }>;\n\ntype PinchGestureOptions = Readonly<{\n activationDistance?: number;\n disabled?: boolean | (() => boolean | undefined);\n onEnd?: (detail: PinchGestureEndDetail) => void;\n onMove?: (detail: PinchGestureDetail) => void;\n onStart?: (detail: PinchGestureDetail) => void;\n pointerCapture?: boolean;\n signal?: AbortSignal;\n}>;\n```\n\n`scale` is the current pointer span divided by the span when the pointers went down; `rotation` is the pointer-line angle since pointerdown in radians, positive clockwise, wrapped to `(-π, π]`. `deltaScale`, `deltaRotation`, and `deltaCentroid` are the change since the previous event (the start event's baseline for the first callback), which is what incremental transforms consume. Centroid coordinates are viewport `clientX`/`clientY` space. `activationDistance` is a span change in pixels and defaults to `6`. Pinch has no `shouldStart`; the first two pointers down after creation are tracked and later pointers are ignored.\n\n### Wheel types\n\n```ts\ntype WheelDetail = Readonly<{\n deltaX: number;\n deltaY: number;\n event: WheelEvent;\n pinch: boolean;\n target: Element;\n}>;\n\ntype WheelOptions = Readonly<{\n disabled?: boolean | (() => boolean | undefined);\n onWheel?: (detail: WheelDetail) => void;\n preventDefault?: boolean | ((event: WheelEvent) => boolean);\n signal?: AbortSignal;\n}>;\n\ntype WheelGesture = Readonly<{\n [Symbol.dispose]: () => void;\n readonly disposalSignal: AbortSignal;\n dispose(): void;\n readonly disposed: boolean;\n}>;\n```\n\n`deltaX`/`deltaY` are normalized to CSS pixels (see `normalizeWheel()`); positive moves content right/down. `pinch` mirrors `ctrlKey`.\n\n### Handle types\n\n```ts\ntype DragGesture = {\n readonly active: boolean;\n [Symbol.dispose](): void;\n cancel(): boolean;\n readonly disposalSignal: AbortSignal;\n dispose(): void;\n readonly disposed: boolean;\n};\n\ntype PanGesture = DragGesture;\n\ntype PinchGesture = DragGesture;\n```\n\n### Shared option behavior\n\n| Option | Default | Contract |\n| -------------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------- |\n| `activationDistance` | `6` | Non-negative finite CSS pixels; drag uses Euclidean distance, pan waits for dominant-axis intent |\n| `axis` | `'x'` | Pan only; fixed value or getter sampled when each interaction starts |\n| `disabled` | `false` | Fixed value or getter; blocks starts and cancels active recognition on the next matching pointer event |\n| `pointerCapture` | `true` | Best-effort capture after activation; document tracking continues when capture is disabled or fails |\n| `shouldStart` | N/A | Admission predicate evaluated for the primary pointer before tracking starts |\n| `shouldActivate` | N/A | Drag/pan predicate evaluated once after distance/axis recognition and before capture or callbacks; false rejects the session |\n| `signal` | N/A | Disposes the handle when the external owner aborts |\n| `onStart` | N/A | Runs once on the activating movement |\n| `onMove` | N/A | Runs on the activating movement and each later matching movement |\n| `onEnd` | N/A | Runs once for active release or cancellation; pending interactions end without callbacks |\n\nOptions and callback details are readonly. Fixed callbacks and capture policy are snapshotted at construction. Function-valued `axis` and `disabled` options remain dynamic.\n\nGesture tracks accepted movement with capture-phase listeners on the target's current owner document. Window blur, hidden-document transition, `pointercancel`, pointer capture loss on the gesture target, and a second touch anywhere in that document cancel recognition. A `lostpointercapture` event bubbling from a descendant does not cancel the target's gesture. Exact diagonal ties remain pending until one axis dominates; cross-axis dominance rejects the pending pan. Gesture does not arbitrate ownership between recognizers on the same axis.\n\n## Errors\n\n| Error | Trigger | Notable properties |\n| -------------------- | --------------------------------------------- | --------------------------------------------------- |\n| `GestureError` | Base class for every gesture-originated error | `instanceof GestureError` catches any gesture error |\n| `GestureConfigError` | Invalid option value | Extends `GestureError` |\n\n- Invalid `activationDistance` values throw `GestureConfigError` during construction.\n- Invalid fixed `axis` values throw `GestureConfigError` during construction.\n- Invalid values returned by a dynamic `axis` getter throw `GestureConfigError` when a pointer interaction starts.\n",
|
|
6
|
-
"usage": "---\ntitle: 'Gesture: Usage Guide'\ndescription: Track unrestricted pointer dragging and axis-locked pans with application-owned rendering and completion.\n---\n\n[[toc]]\n\n## Basic Usage\n\nCreate one handle for the element that owns the interaction. This example creates its surface, applies the required touch policy, and disposes the handle when the page unloads.\n\n```ts\nimport { createPanGesture } from '@vielzeug/gesture';\n\nconst row = document.body.appendChild(document.createElement('div'));\nrow.textContent = 'Swipe to archive';\nrow.style.touchAction = 'pan-y';\n\nconst pan = createPanGesture(row, {\n axis: 'x',\n onMove: ({ distance }) => {\n row.style.transform = `translateX(${distance}px)`;\n },\n onEnd: ({ distance, reason }) => {\n row.style.transform = '';\n if (reason === 'release' && Math.abs(distance) >= 64) {\n pan.dispose();\n row.remove();\n }\n },\n});\n\nwindow.addEventListener('pagehide', () => pan.dispose(), { once: true });\n```\n\n## Track Two-Dimensional Dragging\n\nUse `createDragGesture()` when movement must remain unrestricted in both dimensions:\n\n```ts\nimport { createDragGesture } from '@vielzeug/gesture';\n\nconst card = document.querySelector<HTMLElement>('[data-draggable]');\nif (!card) throw new Error('Missing [data-draggable] element');\n\nconst drag = createDragGesture(card, {\n activationDistance: 6,\n onMove: ({ delta }) => {\n card.style.translate = `${delta.x}px ${delta.y}px`;\n },\n onEnd: () => {\n card.style.translate = '';\n },\n});\n\nwindow.addEventListener('pagehide', () => drag.dispose(), { once: true });\n```\n\n`start`, `current`, and `delta` are readonly `{ x, y }` points. Set `touch-action: none` when the surface owns movement in both dimensions. Drag recognition does not provide previews, drop targets, DOM movement, or `DataTransfer`; use Dnd for those semantics.\n\n## Recognize Long Presses\n\nUse `createLongPress()` for hold interactions: the touch counterpart of a keyboard preview key. `onLongPress` receives the originating pointerdown once the hold outlasts `durationMs`:\n\n```ts\nimport { createLongPress } from '@vielzeug/gesture';\n\nconst hold = createLongPress(grid, {\n durationMs: 500,\n shouldStart: (event) => event.pointerType !== 'mouse' && (event.target as HTMLElement).closest('.tile') !== null,\n onLongPress: (detail) => {\n const tile = (detail.event.target as HTMLElement).closest<HTMLElement>('.tile');\n openPreview(tile?.dataset.id);\n },\n});\n```\n\nMovement beyond `slopPx` cancels back to a normal press, so scrolling never triggers the hold. The click that follows a fired hold is swallowed through a capture-phase listener on `target`: bind `target` to a stable ancestor of the pressed controls so the swallow precedes their click handlers, and gate `shouldStart` to the elements the hold belongs to.\n\n## Recognize Pinch and Rotate\n\nUse `createPinchGesture()` for two-pointer scale and rotation. `scale` and `rotation` are relative to the positions where the two pointers went down, so a transform applied from `onStart` onward composes against the gesture's own baseline:\n\n```ts\nimport { createPinchGesture } from '@vielzeug/gesture';\n\nconst stage = document.querySelector<HTMLElement>('[data-stage]');\nif (!stage) throw new Error('Missing [data-stage] element');\n\nconst card = stage.querySelector<HTMLElement>('[data-card]');\nif (!card) throw new Error('Missing [data-card] element');\n\nlet x = 0;\nlet y = 0;\ncreatePinchGesture(stage, {\n onMove: ({ scale, rotation, deltaCentroid }) => {\n x += deltaCentroid.x;\n y += deltaCentroid.y;\n card.style.transform = `translate(${x}px, ${y}px) scale(${scale}) rotate(${rotation}rad)`;\n },\n});\n```\n\nThe gesture activates once the pointer span changes by `activationDistance` pixels (default 6), which keeps two-finger taps from jittering the canvas. `deltaScale`, `deltaRotation`, and `deltaCentroid` carry the movement since the previous event, which is what incremental camera transforms consume. The session ends when either pointer lifts; the remaining pointer never continues the gesture. Set `touch-action: none` on the target.\n\nCentroid coordinates are client-space, like every other pointer coordinate in this package. When the target is offset from the viewport origin, convert to target-local coordinates with `getBoundingClientRect()` before applying them to content.\n\nPair pinch with a single-pointer drag or pan by cancelling the single-pointer gesture from pinch's `onStart`; the drag handle's `cancel()` ends its active session without firing `onEnd`, so dragging and pinching never fight over the same surface.\n\n## Recognize Wheel and Trackpad Zoom\n\nUse `createWheelGesture()` for scroll-wheel and trackpad input. Deltas are normalized to CSS pixels regardless of the browser's `deltaMode` (pixels, lines, or pages), and `pinch` marks the ctrl-key wheel events macOS sends for trackpad pinch-zoom:\n\n```ts\nimport { createWheelGesture } from '@vielzeug/gesture';\n\nconst wheel = createWheelGesture(stage, {\n preventDefault: (event) => event.ctrlKey || stage.contains(event.target as Node),\n onWheel: ({ deltaX, deltaY, pinch }) => {\n if (pinch) {\n camera.zoomBy(Math.exp(-deltaY * 0.01));\n } else {\n camera.panBy(-deltaX, -deltaY);\n }\n },\n});\n```\n\nThe recognizer never prevents silently: `preventDefault` defaults to `false`, and the listener is registered non-passive so prevention works when you opt in. `normalizeWheel()` is exported for code that already listens for wheel events and only needs the normalization.\n\n## Completion Rules\n\nGesture reports movement and terminal state but does not decide what constitutes a swipe. Apply thresholds and allowed directions in `onEnd`.\n\n```ts\nconst pan = createPanGesture(panel, {\n axis: 'x',\n onEnd: ({ distance, reason }) => {\n if (reason === 'release' && distance <= -80) {\n openNext();\n } else {\n resetPanel();\n }\n },\n});\n```\n\n## Direction Recognition\n\nThe gesture remains pending during small movement and exact diagonal ties. It activates only after movement strictly favors the configured axis. Cross-axis movement ends the pending interaction without invoking callbacks.\n\nThe default `activationDistance` is 6 pixels. Tune direction-recognition slop for touch density or component-specific needs:\n\n```ts\nconst pan = createPanGesture(row, {\n axis: 'x',\n activationDistance: 12,\n onMove,\n onEnd,\n});\n```\n\nSet `activationDistance: 0` when the first pointer move with non-zero displacement should activate immediately. Zero-motion events remain pending.\n\nUse the corresponding `touch-action` value so the browser retains native scrolling on the other axis.\n\n```css\n.swipe-row {\n touch-action: pan-y pinch-zoom;\n}\n```\n\n```ts\nconst pan = createPanGesture(row, { axis: 'x', onMove });\n```\n\nUse `shouldStart` to exclude controls at pointerdown. Use `shouldActivate` for direction or boundary checks that require movement; rejection happens before capture or callbacks.\n\n```ts\nconst pan = createPanGesture(panel, {\n axis: 'y',\n shouldActivate: ({ distance }) => distance > 0 && scroller.scrollTop <= 0,\n onMove: renderPull,\n onEnd: settlePull,\n});\n```\n\nGesture cancels pending and active touch recognition when a second finger touches the owner document. Reset presentation on `reason: 'cancel'`; never commit an action from cancellation. Native scroll and pinch behavior still depends on the surface's CSS and event handling. Once native scrolling owns a touch sequence, start a fresh swipe at the boundary rather than attempting a mid-scroll handoff.\n\n## Pointer Capture\n\nPointer capture is enabled by default. After axis intent is accepted, Gesture attempts to capture the pointer while continuing to track movement through document-level listeners. Capture failure (for example after target detachment or pointer termination) falls back to document tracking without stranding the session.\n\nDisable capture when nested or newly revealed controls must retain native pointer-up and click targeting:\n\n```ts\nconst pan = createPanGesture(row, {\n axis: 'x',\n pointerCapture: false,\n onMove: renderReveal,\n onEnd: settleReveal,\n});\n```\n\nDocument-level tracking still keeps the pan active outside the target. Disabling capture changes event targeting, not gesture tracking.\n\n## Interactive Descendants\n\nUse `shouldStart` when buttons, links, or form controls inside the surface must not start a pan.\n\n```ts\nconst pan = createPanGesture(notification, {\n axis: 'x',\n pointerCapture: false,\n shouldStart: (event) =>\n !event.composedPath().some((node) => node instanceof Element && node.matches('button, a, input, select, textarea')),\n onMove,\n onEnd,\n});\n```\n\n`shouldStart` protects controls under the initial pointer. `pointerCapture: false` additionally protects controls that appear beneath the pointer during a reveal interaction.\n\n## Disabled State\n\nA boolean disables the recognizer permanently. A getter supports state that changes while the handle is alive.\n\n```ts\nconst pan = createPanGesture(row, {\n disabled: () => isLocked,\n onEnd: ({ reason }) => {\n if (reason === 'cancel') resetRow();\n },\n});\n```\n\nWhen the getter becomes `true`, the next pointer event cancels an active pan. Window blur or a hidden owner document also cancels active tracking so a lost release cannot block later gestures.\n\nGesture snapshots fixed callbacks and capture policy at construction. Use the `axis` and `disabled` functions for behavior that must remain dynamic instead of mutating the options object.\n\n## Lifecycle\n\nDispose the target-bound handle when its owning UI scope unmounts.\n\n```ts\nconst element = document.querySelector<HTMLElement>('[data-pan]');\nif (!element) throw new Error('Missing [data-pan] element');\n\nconst owner = new AbortController();\nconst request = new AbortController();\nconst pan = createPanGesture(element, {\n axis: 'x',\n signal: owner.signal,\n});\n\nconst childSignal = AbortSignal.any([pan.disposalSignal, request.signal]);\nwindow.addEventListener('pagehide', () => owner.abort(), { once: true });\n```\n\nPass `{ signal }` to dispose with an existing owner signal. `disposalSignal` always aborts when Gesture finishes teardown, so child work can compose with the handle regardless of how disposal starts.\n\nUse `cancel()` to stop a pending or active interaction without disposing the handle. An active interaction emits `onEnd` with `reason: 'cancel'`. Call `cancel()` before `dispose()` when a connected surface needs its `onEnd` reset path; disposal itself does not invoke callbacks.\n\n## Framework Integration\n\nCreate the handle after the target element exists and dispose it on unmount.\n\n::: code-group\n\n```tsx [React]\nimport { useEffect, useRef } from 'react';\nimport { createPanGesture } from '@vielzeug/gesture';\n\nfunction SwipeRow({ onDismiss }: { onDismiss: () => void }) {\n const rowRef = useRef<HTMLDivElement>(null);\n\n useEffect(() => {\n const row = rowRef.current;\n if (!row) return;\n\n const pan = createPanGesture(row, {\n axis: 'x',\n onMove: ({ distance }) => {\n row.style.transform = `translateX(${distance}px)`;\n },\n onEnd: ({ distance, reason }) => {\n row.style.transform = '';\n if (reason === 'release' && Math.abs(distance) >= 64) onDismiss();\n },\n });\n\n return () => pan.dispose();\n }, [onDismiss]);\n\n return <div ref={rowRef}>Swipe me</div>;\n}\n```\n\n```vue [Vue 3]\n<script setup lang=\"ts\">\nimport { onMounted, onUnmounted, ref } from 'vue';\nimport { createPanGesture, type PanGesture } from '@vielzeug/gesture';\n\nconst emit = defineEmits<{ dismiss: [] }>();\nconst rowEl = ref<HTMLDivElement | null>(null);\nlet pan: PanGesture | undefined;\n\nonMounted(() => {\n const row = rowEl.value;\n if (!row) return;\n\n pan = createPanGesture(row, {\n axis: 'x',\n onEnd: ({ distance, reason }) => {\n if (reason === 'release' && Math.abs(distance) >= 64) emit('dismiss');\n },\n });\n});\n\nonUnmounted(() => pan?.dispose());\n</script>\n\n<template>\n <div ref=\"rowEl\">Swipe me</div>\n</template>\n```\n\n```svelte [Svelte]\n<script lang=\"ts\">\n import { onMount } from 'svelte';\n import { createPanGesture } from '@vielzeug/gesture';\n\n let { ondismiss = () => {} }: { ondismiss: () => void } = $props();\n let rowEl: HTMLDivElement;\n\n onMount(() => {\n const pan = createPanGesture(rowEl, {\n axis: 'x',\n onEnd: ({ distance, reason }) => {\n if (reason === 'release' && Math.abs(distance) >= 64) ondismiss();\n },\n });\n\n return () => pan.dispose();\n });\n</script>\n\n<div bind:this={rowEl}>Swipe me</div>\n```\n\n:::\n\n## Working with Other Vielzeug Libraries\n\n### Gesture + Refine\n\nRefine uses Gesture internally for carousel, drawer, toast, and list-item pointer interactions. Custom surfaces can use the same pan lifecycle while keeping visual state local.\n\n```ts\nimport { createPanGesture } from '@vielzeug/gesture';\n\nconst pan = createPanGesture(panel, {\n axis: 'x',\n onMove: ({ distance }) => {\n panel.style.transform = `translateX(${distance}px)`;\n },\n onEnd: ({ distance, reason }) => {\n panel.style.transform = '';\n if (reason === 'release' && Math.abs(distance) >= 80) revealActions();\n },\n});\n```\n\n### Gesture + Dnd\n\nGesture owns pointer recognition: unrestricted two-dimensional drag and one-axis pan. Dnd builds touch sorting on `createDragGesture()`, then owns `DataTransfer`, previews, hit-testing, file drop zones, keyboard sorting, DOM reordering, and connected-list transactions. Use Dnd when an item is picked up and dropped; use Gesture directly when application code owns rendering and completion.\n\n## Best Practices\n\n- **Set** `touch-action` for the axis the browser should continue scrolling.\n- **Use** `shouldStart` to exclude nested interactive controls.\n- **Disable** pointer capture when nested or newly revealed controls must keep native release targeting.\n- **Apply** completion thresholds and direction rules in `onEnd`; use `activationDistance` only for recognition slop.\n- **Treat** `reason: 'cancel'` as a reset path, never a commit path. Pointer capture loss on the gesture target cancels; capture loss bubbling from a descendant does not.\n- **Keep** `onMove` rendering lightweight.\n- **Dispose** the handle when its target leaves the UI.\n",
|
|
7
|
-
"examples": "---\ntitle: 'Gesture: Examples'\ndescription: Worked examples for @vielzeug/gesture.\n---\n\n## Examples\n\n- [Carousel Pan Navigation](./examples/carousel-swipe-navigation.md)\n- [Swipe-to-Dismiss Notifications](./examples/swipe-dismiss-notifications.md)\n"
|
|
8
|
-
},
|
|
9
|
-
"examples": [
|
|
10
|
-
{
|
|
11
|
-
"id": "drag-basic",
|
|
12
|
-
"code": "import { createDragGesture } from '@vielzeug/gesture'\n\nconst surface = document.createElement('div')\nsurface.textContent = 'Drag freely'\nsurface.style.cssText = 'width:160px;padding:32px;text-align:center;background:#dcfce7;border-radius:12px;touch-action:none;user-select:none;'\ndocument.body.appendChild(surface)\n\nconst drag = createDragGesture(surface, {\n onMove: ({ delta }) => {\n surface.style.translate = `${delta.x}px ${delta.y}px`\n },\n onEnd: () => {\n surface.style.translate = ''\n },\n})\n\nconsole.log('Drag gesture ready:', drag.disposed === false)",
|
|
13
|
-
"name": "createDragGesture - Basic"
|
|
14
|
-
},
|
|
15
|
-
{
|
|
16
|
-
"id": "pan-basic",
|
|
17
|
-
"code": "import { createPanGesture } from '@vielzeug/gesture'\n\nconst surface = document.createElement('div')\nsurface.textContent = 'Drag horizontally'\nsurface.style.cssText = 'width:240px;padding:32px;text-align:center;background:#e0e7ff;border-radius:12px;touch-action:pan-y;user-select:none;'\ndocument.body.appendChild(surface)\n\nconst output = document.createElement('pre')\ndocument.body.appendChild(output)\n\nconst pan = createPanGesture(surface, {\n axis: 'x',\n onMove: ({ distance }) => {\n surface.style.transform = `translateX(${distance}px)`\n output.textContent = `distance: ${Math.round(distance)}px`\n },\n onEnd: ({ distance, reason }) => {\n surface.style.transform = ''\n output.textContent = reason === 'release' && Math.abs(distance) >= 48\n ? `swipe: ${distance < 0 ? 'left' : 'right'}`\n : `ended: ${reason}`\n },\n})\n\nconsole.log('Pan gesture ready:', pan.disposed === false)",
|
|
18
|
-
"name": "createPanGesture - Basic"
|
|
19
|
-
},
|
|
20
|
-
{
|
|
21
|
-
"id": "pinch-basic",
|
|
22
|
-
"code": "import { createPinchGesture } from '@vielzeug/gesture'\n\nconst stage = document.createElement('div')\nstage.style.cssText = 'width:100%;height:280px;display:grid;place-items:center;background:#f1f5f9;border-radius:12px;touch-action:none;user-select:none;'\nconst card = document.createElement('div')\ncard.textContent = 'Pinch me'\ncard.style.cssText = 'padding:24px 32px;background:#6366f1;color:white;border-radius:12px;font-weight:600;'\nstage.appendChild(card)\ndocument.body.appendChild(stage)\n\nconst output = document.createElement('pre')\ndocument.body.appendChild(output)\n\nlet x = 0\nlet y = 0\ncreatePinchGesture(stage, {\n onMove: ({ scale, rotation, deltaCentroid }) => {\n x += deltaCentroid.x\n y += deltaCentroid.y\n card.style.transform = `translate(${x}px, ${y}px) scale(${scale}) rotate(${rotation}rad)`\n output.textContent = `scale: ${scale.toFixed(2)} rotation: ${(rotation * 57.3).toFixed(0)}°`\n },\n onEnd: ({ reason }) => {\n output.textContent = `ended: ${reason}`\n },\n})\n\nconsole.log('Pinch gesture ready')",
|
|
23
|
-
"name": "createPinchGesture - Basic"
|
|
24
|
-
},
|
|
25
|
-
{
|
|
26
|
-
"id": "wheel-basic",
|
|
27
|
-
"code": "import { createWheelGesture } from '@vielzeug/gesture'\n\nconst viewport = document.createElement('div')\nviewport.style.cssText = 'width:100%;height:220px;overflow:hidden;background:#f1f5f9;border-radius:12px;touch-action:none;'\nconst content = document.createElement('div')\ncontent.style.cssText = 'width:200%;height:400%;display:grid;place-items:center;font-weight:600;color:#475569;'\ncontent.textContent = 'Scroll inside'\nviewport.appendChild(content)\ndocument.body.appendChild(viewport)\n\nconst output = document.createElement('pre')\ndocument.body.appendChild(output)\n\nlet x = 0\nlet y = 0\ncreateWheelGesture(viewport, {\n preventDefault: true,\n onWheel: ({ deltaX, deltaY, pinch }) => {\n if (pinch) {\n output.textContent = `pinch-zoom wheel: ${deltaY.toFixed(1)}px`\n return\n }\n x = Math.max(-400, Math.min(0, x - deltaX))\n y = Math.max(-800, Math.min(0, y - deltaY))\n content.style.transform = `translate(${x}px, ${y}px)`\n output.textContent = `offset: ${Math.round(x)}px, ${Math.round(y)}px`\n },\n})\n\nconsole.log('Wheel gesture ready')",
|
|
28
|
-
"name": "createWheelGesture - Basic"
|
|
29
|
-
}
|
|
30
|
-
],
|
|
31
|
-
"typeSignatures": {
|
|
32
|
-
"createDragGesture": "export {\n createDragGesture,\n type DragEndReason,\n type DragGesture,\n type DragGestureDetail,\n type DragGestureEndDetail,\n type DragGestureOptions,\n type DragPoint,\n} from './drag-gesture.js';",
|
|
33
|
-
"DragEndReason": "export {\n createDragGesture,\n type DragEndReason,\n type DragGesture,\n type DragGestureDetail,\n type DragGestureEndDetail,\n type DragGestureOptions,\n type DragPoint,\n} from './drag-gesture.js';",
|
|
34
|
-
"DragGesture": "export {\n createDragGesture,\n type DragEndReason,\n type DragGesture,\n type DragGestureDetail,\n type DragGestureEndDetail,\n type DragGestureOptions,\n type DragPoint,\n} from './drag-gesture.js';",
|
|
35
|
-
"DragGestureDetail": "export {\n createDragGesture,\n type DragEndReason,\n type DragGesture,\n type DragGestureDetail,\n type DragGestureEndDetail,\n type DragGestureOptions,\n type DragPoint,\n} from './drag-gesture.js';",
|
|
36
|
-
"DragGestureEndDetail": "export {\n createDragGesture,\n type DragEndReason,\n type DragGesture,\n type DragGestureDetail,\n type DragGestureEndDetail,\n type DragGestureOptions,\n type DragPoint,\n} from './drag-gesture.js';",
|
|
37
|
-
"DragGestureOptions": "export {\n createDragGesture,\n type DragEndReason,\n type DragGesture,\n type DragGestureDetail,\n type DragGestureEndDetail,\n type DragGestureOptions,\n type DragPoint,\n} from './drag-gesture.js';",
|
|
38
|
-
"DragPoint": "export {\n createDragGesture,\n type DragEndReason,\n type DragGesture,\n type DragGestureDetail,\n type DragGestureEndDetail,\n type DragGestureOptions,\n type DragPoint,\n} from './drag-gesture.js';",
|
|
39
|
-
"GestureConfigError": "export { GestureConfigError, GestureError } from './errors.js';",
|
|
40
|
-
"GestureError": "export { GestureConfigError, GestureError } from './errors.js';",
|
|
41
|
-
"createLongPress": "export {\n createLongPress,\n type LongPress,\n type LongPressDetail,\n type LongPressOptions,\n} from './long-press.js';",
|
|
42
|
-
"LongPress": "export {\n createLongPress,\n type LongPress,\n type LongPressDetail,\n type LongPressOptions,\n} from './long-press.js';",
|
|
43
|
-
"LongPressDetail": "export {\n createLongPress,\n type LongPress,\n type LongPressDetail,\n type LongPressOptions,\n} from './long-press.js';",
|
|
44
|
-
"LongPressOptions": "export {\n createLongPress,\n type LongPress,\n type LongPressDetail,\n type LongPressOptions,\n} from './long-press.js';",
|
|
45
|
-
"createPanGesture": "export {\n createPanGesture,\n type PanAxis,\n type PanEndReason,\n type PanGesture,\n type PanGestureDetail,\n type PanGestureEndDetail,\n type PanGestureOptions,\n} from './pan-gesture.js';",
|
|
46
|
-
"PanAxis": "export {\n createPanGesture,\n type PanAxis,\n type PanEndReason,\n type PanGesture,\n type PanGestureDetail,\n type PanGestureEndDetail,\n type PanGestureOptions,\n} from './pan-gesture.js';",
|
|
47
|
-
"PanEndReason": "export {\n createPanGesture,\n type PanAxis,\n type PanEndReason,\n type PanGesture,\n type PanGestureDetail,\n type PanGestureEndDetail,\n type PanGestureOptions,\n} from './pan-gesture.js';",
|
|
48
|
-
"PanGesture": "export {\n createPanGesture,\n type PanAxis,\n type PanEndReason,\n type PanGesture,\n type PanGestureDetail,\n type PanGestureEndDetail,\n type PanGestureOptions,\n} from './pan-gesture.js';",
|
|
49
|
-
"PanGestureDetail": "export {\n createPanGesture,\n type PanAxis,\n type PanEndReason,\n type PanGesture,\n type PanGestureDetail,\n type PanGestureEndDetail,\n type PanGestureOptions,\n} from './pan-gesture.js';",
|
|
50
|
-
"PanGestureEndDetail": "export {\n createPanGesture,\n type PanAxis,\n type PanEndReason,\n type PanGesture,\n type PanGestureDetail,\n type PanGestureEndDetail,\n type PanGestureOptions,\n} from './pan-gesture.js';",
|
|
51
|
-
"PanGestureOptions": "export {\n createPanGesture,\n type PanAxis,\n type PanEndReason,\n type PanGesture,\n type PanGestureDetail,\n type PanGestureEndDetail,\n type PanGestureOptions,\n} from './pan-gesture.js';",
|
|
52
|
-
"createPinchGesture": "export {\n createPinchGesture,\n type PinchEndReason,\n type PinchGesture,\n type PinchGestureDetail,\n type PinchGestureEndDetail,\n type PinchGestureOptions,\n type PinchPoint,\n} from './pinch-gesture.js';",
|
|
53
|
-
"PinchEndReason": "export {\n createPinchGesture,\n type PinchEndReason,\n type PinchGesture,\n type PinchGestureDetail,\n type PinchGestureEndDetail,\n type PinchGestureOptions,\n type PinchPoint,\n} from './pinch-gesture.js';",
|
|
54
|
-
"PinchGesture": "export {\n createPinchGesture,\n type PinchEndReason,\n type PinchGesture,\n type PinchGestureDetail,\n type PinchGestureEndDetail,\n type PinchGestureOptions,\n type PinchPoint,\n} from './pinch-gesture.js';",
|
|
55
|
-
"PinchGestureDetail": "export {\n createPinchGesture,\n type PinchEndReason,\n type PinchGesture,\n type PinchGestureDetail,\n type PinchGestureEndDetail,\n type PinchGestureOptions,\n type PinchPoint,\n} from './pinch-gesture.js';",
|
|
56
|
-
"PinchGestureEndDetail": "export {\n createPinchGesture,\n type PinchEndReason,\n type PinchGesture,\n type PinchGestureDetail,\n type PinchGestureEndDetail,\n type PinchGestureOptions,\n type PinchPoint,\n} from './pinch-gesture.js';",
|
|
57
|
-
"PinchGestureOptions": "export {\n createPinchGesture,\n type PinchEndReason,\n type PinchGesture,\n type PinchGestureDetail,\n type PinchGestureEndDetail,\n type PinchGestureOptions,\n type PinchPoint,\n} from './pinch-gesture.js';",
|
|
58
|
-
"PinchPoint": "export {\n createPinchGesture,\n type PinchEndReason,\n type PinchGesture,\n type PinchGestureDetail,\n type PinchGestureEndDetail,\n type PinchGestureOptions,\n type PinchPoint,\n} from './pinch-gesture.js';",
|
|
59
|
-
"createWheelGesture": "export {\n createWheelGesture,\n normalizeWheel,\n type WheelDetail,\n type WheelGesture,\n type WheelOptions,\n} from './wheel-gesture.js';",
|
|
60
|
-
"normalizeWheel": "export {\n createWheelGesture,\n normalizeWheel,\n type WheelDetail,\n type WheelGesture,\n type WheelOptions,\n} from './wheel-gesture.js';",
|
|
61
|
-
"WheelDetail": "export {\n createWheelGesture,\n normalizeWheel,\n type WheelDetail,\n type WheelGesture,\n type WheelOptions,\n} from './wheel-gesture.js';",
|
|
62
|
-
"WheelGesture": "export {\n createWheelGesture,\n normalizeWheel,\n type WheelDetail,\n type WheelGesture,\n type WheelOptions,\n} from './wheel-gesture.js';",
|
|
63
|
-
"WheelOptions": "export {\n createWheelGesture,\n normalizeWheel,\n type WheelDetail,\n type WheelGesture,\n type WheelOptions,\n} from './wheel-gesture.js';"
|
|
64
|
-
}
|
|
65
|
-
}
|
|
@@ -1,80 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"apiSource": "export { createBus } from './bus';\nexport { BusDisposedError, HeraldError } from './errors';\nexport type {\n Bus,\n BusOptions,\n EventKey,\n EventMap,\n HeraldEvent,\n Listener,\n SubscribeOptions,\n Unsubscribe,\n WaitAnyResult,\n} from './types';\n",
|
|
3
|
-
"docs": {
|
|
4
|
-
"index": "---\ntitle: 'Herald: Typed event bus for TypeScript'\ndescription: Typed synchronous event delivery with wildcard subscriptions, one-shot waits, tracing, and AbortSignal lifecycle.\npackage: herald\ncategory: events\nkeywords: [event-bus, typed-events, pub-sub, async-wait, abort-signal]\nrelated: [ripple, wayfinder, familiar]\nexports: [createBus, HeraldError, BusDisposedError]\nenvironments: [browser, node, ssr, deno]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"herald\" />\n\n## Why Herald?\n\nRaw event emitters lose payload inference and leave one-shot waiting, cancellation, diagnostics, and teardown to every caller. Herald keeps events temporal: use [Ripple](/ripple/) when you need retained state.\n\n```ts\n// Before\nconst listeners = new Set<(payload: unknown) => void>();\nlisteners.add((payload) => loadProfile((payload as { id: string }).id));\n\n// After\nimport { createBus } from '@vielzeug/herald';\n\ninterface AppEvents {\n 'user:login': { id: string };\n}\n\nfunction loadProfile(id: string): void {\n console.log(id);\n}\n\nconst bus = createBus<AppEvents>();\nbus.on('user:login', ({ id }) => loadProfile(id));\n```\n\nDelivery is synchronous and temporal: events are not retained or replayed. Listener failures do not stop later listeners; `emit()` rethrows the first failure after dispatch, while `tap()` exposes every failure for diagnostics.\n\n| Feature | Herald | mitt | EventEmitter3 |\n| ------------------------ | -------------------------------------------- | ----------------------------------------------------- | ----------------------------------------------------- |\n| Bundle size | <PackageInfo package=\"herald\" type=\"size\" /> | ~200 B | ~1.5 kB |\n| Typed payloads | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"triangle-alert\" size=\"16\"></ore-icon> | <ore-icon name=\"triangle-alert\" size=\"16\"></ore-icon> |\n| One-shot async wait | <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| AbortSignal lifecycle | <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| Runtime activity tracing | <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| Zero dependencies | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n\n<div class=\"decision-callout\">\n\n**Use Herald when** modules need typed temporal event delivery with owned lifecycle.\n\n**Consider Ripple when** consumers need current state and replayed values.\n\n</div>\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/herald\n```\n\n```sh [npm]\nnpm install @vielzeug/herald\n```\n\n```sh [yarn]\nyarn add @vielzeug/herald\n```\n\n:::\n\n## Quick Start\n\n```ts\nimport { createBus } from '@vielzeug/herald';\n\ninterface AppEvents {\n 'user:login': { id: string };\n 'user:logout': void;\n}\n\nconst bus = createBus<AppEvents>();\nconst stop = bus.on('user:login', ({ id }) => console.log(id));\n\nbus.emit('user:login', { id: '42' });\nstop();\nbus.dispose();\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- `on()` / `once()`: typed subscriptions with explicit teardown\n- `onAny()`: cross-cutting event observation\n- `tap()`: observe bus activity for logging and diagnostics\n- `wait()` / `waitAny()`: one-shot async coordination\n- `listenerCount()` / `wildcardCount()` / `eventNames()`: listener inspection\n- `error` tap events: isolate listener failures without interrupting delivery\n- `AbortSignal`: subscription, wait, tap, and disposal ownership\n- `createTestBus()`: emitted-payload recording for tests\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- [Ripple](/ripple/): retained reactive state.\n- [Wayfinder](/wayfinder/): route lifecycle events.\n- [Familiar](/familiar/): worker completion events.\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
|
|
5
|
-
"api": "---\ntitle: 'Herald: API Reference'\ndescription: Reference for typed synchronous events, subscriptions, waits, tracing, lifecycle, and test helpers.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution | Common gotcha |\n| ---------------------- | --------------------------------- | --------- | ------------------------------------------------------------------ |\n| `createBus()` | Create a typed temporal event bus | Sync | Events are not retained or replayed |\n| `emit()` | Deliver one event | Sync | Returns `void`; rethrows the first listener failure after dispatch |\n| `on()` / `once()` | Subscribe to one event | Sync | Keep the unsubscribe function or pass a signal |\n| `onAny()` | Subscribe to every event | Sync | Payload is `unknown` |\n| `wait()` / `waitAny()` | Await future one-shot events | Async | Disposal and external abort reject the promise |\n| `tap()` | Observe bus runtime activity | Sync | Tap-handler failures are swallowed |\n| `createTestBus()` | Record emitted payloads | Sync | Import from `/testing` |\n\n## Package Entry Points\n\n| Import | Purpose |\n| -------------------------- | ----------------------------------------- |\n| `@vielzeug/herald` | Bus factory, errors, and public bus types |\n| `@vielzeug/herald/testing` | `createTestBus()` and `TestBus` |\n\n## `createBus()`\n\n```ts\nfunction createBus<T extends EventMap = Record<string, unknown>>(options?: BusOptions): Bus<T>;\n```\n\nCreates a synchronous bus for future event delivery. Construction has no external side effects.\n\n```ts\nimport { createBus } from '@vielzeug/herald';\n\ninterface Events {\n count: number;\n ready: void;\n}\n\nconst bus = createBus<Events>({ maxListeners: 20, name: 'worker' });\nbus.emit('count', 1);\nbus.emit('ready');\nbus.dispose();\n```\n\n### `BusOptions`\n\n```ts\ntype BusOptions = {\n maxListeners?: number;\n name?: string;\n};\n```\n\n| Field | Description |\n| -------------- | ---------------------------------------------------------------------------------------------------------------------------- |\n| `maxListeners` | Development warning threshold applied separately to one event's listeners and wildcard listeners. Omit to disable the check. |\n| `name` | Display name included in disposal errors and listener-threshold warnings. |\n\n## `Bus`\n\n```ts\ntype Bus<T extends EventMap> = {\n [Symbol.dispose](): void;\n readonly disposalSignal: AbortSignal;\n dispose(): void;\n readonly disposed: boolean;\n emit<K extends EventKey<T>>(event: K, ...args: T[K] extends void ? [] : [payload: T[K]]): void;\n eventNames(): EventKey<T>[];\n listenerCount(event?: EventKey<T>): number;\n on<K extends EventKey<T>>(event: K, listener: Listener<T[K]>, options?: SubscribeOptions): Unsubscribe;\n onAny(listener: (event: EventKey<T>, payload: unknown) => void, options?: SubscribeOptions): Unsubscribe;\n once<K extends EventKey<T>>(event: K, listener: Listener<T[K]>, options?: SubscribeOptions): Unsubscribe;\n tap(handler: (event: HeraldEvent<T>) => void, options?: SubscribeOptions): Unsubscribe;\n wait<K extends EventKey<T>>(event: K, options?: SubscribeOptions): Promise<T[K]>;\n waitAny<const K extends readonly EventKey<T>[]>(events: K, options?: SubscribeOptions): Promise<WaitAnyResult<T, K>>;\n wildcardCount(): number;\n};\n```\n\n### `emit()`\n\nCalls a snapshot of event-specific listeners synchronously, then wildcard listeners, then emits an `emit` trace event. It always returns `void`. Synchronous listener failures produce `error` trace events without stopping delivery; after dispatch, the first failure is rethrown.\n\nAfter disposal, emission is a no-op.\n\n### `on()` and `once()`\n\n```ts\ntype Listener<T> = (payload: T) => void;\ntype SubscribeOptions = { signal?: AbortSignal };\ntype Unsubscribe = () => void;\n```\n\n`SubscribeOptions` is the single options type for every subscription-shaped method: `on`, `once`, `onAny`, `tap`, `wait`, and `waitAny`. `on()` returns an idempotent unsubscribe function. `once()` is the one-shot variant: it unsubscribes before invoking the listener. An already-aborted signal creates no subscription.\n\n### `onAny()`\n\nReceives `(event, payload)` after event-specific listeners and supports `signal`. Wildcard listeners are excluded from `listenerCount()` and reported by `wildcardCount()`.\n\n### `wait()`\n\nResolves with the next payload for one event. It rejects with the external signal's reason when aborted, or `BusDisposedError` when bus disposal wins. Earlier emissions are not replayed.\n\n### `waitAny()`\n\nAccepts one or more event keys. It resolves once with a typed `{ event, payload }` discriminated union and removes every losing subscription. An empty list throws a synchronous `TypeError`.\n\n```ts\nconst result = await bus.waitAny(['count', 'ready']);\nif (result.event === 'count') console.log(result.payload);\n```\n\n### Listener inspection\n\n- `listenerCount(event)` returns specific listeners for one key.\n- `listenerCount()` returns all specific listeners.\n- `wildcardCount()` returns `onAny()` listeners.\n- `eventNames()` returns keys with active specific listeners.\n\n### `tap()`\n\nObserves runtime activity without affecting delivery. It returns an idempotent unsubscribe function and accepts an ownership signal. Tap-handler errors are swallowed.\n\n```ts\nconst stop = bus.tap((event) => {\n if (event.type === 'error') recordListenerFailure(event.error);\n});\n```\n\n### Disposal\n\n`dispose()` is permanent and idempotent. It emits a final `dispose` trace event, aborts `disposalSignal` with `BusDisposedError`, rejects pending waits, removes subscriptions, and clears taps. `[Symbol.dispose]()` delegates to it.\n\n## Runtime Events\n\n```ts\ntype HeraldEvent<T extends EventMap = EventMap> =\n | { readonly event: EventKey<T>; readonly listeners: number; readonly payload: unknown; readonly type: 'emit' }\n | { readonly event: EventKey<T>; readonly type: 'subscribe' }\n | { readonly event: EventKey<T>; readonly type: 'unsubscribe' }\n | { readonly type: 'subscribe-any' }\n | { readonly type: 'unsubscribe-any' }\n | { readonly error: unknown; readonly event: EventKey<T>; readonly type: 'error' }\n | { readonly type: 'dispose' };\n```\n\n`listeners` on an `emit` event counts every specific and wildcard listener invoked, including listeners that threw. Runtime events intentionally contain no timestamp; observers can add one using their own clock.\n\n## Shared Types\n\n```ts\ntype EventMap = object;\ntype EventKey<T extends EventMap> = Extract<keyof T, string>;\n\ntype WaitAnyResult<T extends EventMap, K extends readonly EventKey<T>[]> = {\n [I in keyof K]: K[I] extends EventKey<T> ? { event: K[I]; payload: T[K[I]] } : never;\n}[number];\n```\n\nInterfaces and object type aliases are valid event maps. Only string keys participate in the bus API.\n\n## Testing\n\n### `createTestBus()`\n\n```ts\nimport { createTestBus } from '@vielzeug/herald/testing';\n\nfunction createTestBus<T extends EventMap = Record<string, unknown>>(options?: BusOptions): TestBus<T>;\n```\n\nCreates a regular bus that records every dispatched payload through a `tap()` observer, including dispatches whose listeners throw.\n\n### `TestBus`\n\n```ts\ntype TestBus<T extends EventMap> = Bus<T> & {\n allEmitted(): { [K in EventKey<T>]?: T[K][] };\n emitted<K extends EventKey<T>>(event: K): T[K][];\n emittedCount<K extends EventKey<T>>(event: K): number;\n reset(): void;\n};\n```\n\n`emitted()` and `allEmitted()` return array snapshots. `reset()` clears records without affecting subscriptions. Disposal clears records and the underlying bus. To prevent prototype mutation in the returned plain object, `allEmitted()` omits records named `__proto__`, `constructor`, or `prototype`; `emitted(event)` remains available for those keys.\n\n## Errors\n\n| Error | Trigger | Notable properties |\n| ------------------ | ------------------------------------------------------------------------- | ------------------------------------------ |\n| `BusDisposedError` | Bus disposal aborts `disposalSignal` or interrupts `wait()` / `waitAny()` | Configured bus name appears in the message |\n| `HeraldError` | Base class for Herald-originated errors | Use `instanceof HeraldError` |\n",
|
|
6
|
-
"usage": "---\ntitle: 'Herald: Usage Guide'\ndescription: Define typed events, own subscriptions, await one-shot events, trace failures, and test emissions.\n---\n\n[[toc]]\n\n## Basic Usage\n\nUse an interface or object type whose string keys are event names and whose values are payloads. Use `void` or `undefined` for payloadless events.\n\n```ts\nimport { createBus } from '@vielzeug/herald';\n\ninterface AppEvents {\n 'cart:updated': { count: number };\n 'user:logout': void;\n}\n\nusing bus = createBus<AppEvents>({ name: 'app' });\nconst stop = bus.on('cart:updated', ({ count }) => console.log(count));\n\nbus.emit('cart:updated', { count: 1 });\nbus.emit('user:logout');\nstop();\n```\n\n`emit()` calls listeners synchronously and returns `void`. Event-specific listeners run before wildcard listeners. Events emitted without listeners are discarded.\n\n## Own Subscription Lifetimes\n\nKeep the returned unsubscribe function or bind a subscription to an `AbortSignal`. `once()` unsubscribes before invoking the listener.\n\n```ts\nconst controller = new AbortController();\n\nbus.on('cart:updated', renderCart, { signal: controller.signal });\nbus.once('user:logout', clearSession);\n\ncontroller.abort();\n```\n\nAn already-aborted signal creates no subscription and returns an idempotent no-op unsubscribe function.\n\n## Observe Every Event\n\nUse `onAny()` for cross-cutting application behavior. Wildcard listeners receive the event key and untyped payload after event-specific listeners.\n\n```ts\nconst stop = bus.onAny((event, payload) => {\n audit(event, payload);\n});\n\nstop();\n```\n\n`wildcardCount()` reports wildcard listeners separately from `listenerCount()`.\n\n## Await One Event\n\n`wait()` resolves on the next matching event. `waitAny()` accepts one or more keys and returns a discriminated union.\n\n```ts\nconst cart = await bus.wait('cart:updated', { signal: AbortSignal.timeout(5_000) });\nconst result = await bus.waitAny(['cart:updated', 'user:logout'], {\n signal: AbortSignal.timeout(5_000),\n});\n\nif (result.event === 'cart:updated') console.log(result.payload.count);\n```\n\nThese methods do not replay earlier events. External cancellation rejects with the signal reason. Bus disposal rejects pending waits with `BusDisposedError`. `waitAny()` with an empty event list throws a synchronous `TypeError`.\n\n## Handle Listener Failures\n\nListener exceptions do not prevent remaining specific or wildcard listeners from running. Each failure produces a `error` tap event, then `emit()` rethrows the first error after dispatch.\n\n```ts\nconst stopTrace = bus.tap((event) => {\n if (event.type === 'error') {\n recordListenerFailure(event.error);\n }\n});\n\nstopTrace();\n```\n\nHerald captures synchronous listener throws only, and `tap()` does not suppress the error rethrown after dispatch. A listener that starts asynchronous work must handle its own rejected promises.\n\n## Trace Bus Activity\n\n`tap()` observes subscriptions, unsubscriptions, wildcard subscriptions, emissions, listener failures, and disposal without changing bus behavior. Tap-handler failures are swallowed.\n\n```ts\nconst stopTrace = bus.tap(\n (event) => {\n recordHeraldEvent(event);\n },\n { signal: owner.signal },\n);\n```\n\nAn `emit` trace includes the event key, payload, and number of specific plus wildcard listeners invoked. Trace events do not include timestamps; add them in the observer if needed.\n\n## Inspect Listeners\n\n```ts\nbus.listenerCount('cart:updated'); // specific listeners for this key\nbus.listenerCount(); // all specific listeners\nbus.wildcardCount(); // onAny listeners\nbus.eventNames(); // keys with active specific listeners\n```\n\n`eventNames()` does not include events that only have wildcard listeners.\n\n## Dispose the Bus\n\n`dispose()` is permanent and idempotent. It emits a final tap event, aborts `disposalSignal` with `BusDisposedError`, clears all listeners and taps, and rejects pending waits. Later subscriptions and emissions are no-ops.\n\n```ts\nusing scopedBus = createBus<AppEvents>({ name: 'checkout' });\nscopedBus.disposalSignal.addEventListener('abort', () => releaseOwnedWork());\n```\n\nThe configured name appears in disposal errors and listener-threshold warnings.\n\n## Test Emissions\n\nImport test helpers from the focused testing entry point.\n\n```ts\nimport { createTestBus } from '@vielzeug/herald/testing';\n\nusing testBus = createTestBus<AppEvents>();\ntestBus.emit('cart:updated', { count: 2 });\n\nexpect(testBus.emitted('cart:updated')).toEqual([{ count: 2 }]);\nexpect(testBus.emittedCount('cart:updated')).toBe(1);\nexpect(testBus.allEmitted()).toEqual({ 'cart:updated': [{ count: 2 }] });\n\ntestBus.reset();\n```\n\nReturned recordings are snapshots. `reset()` clears recording history without removing listeners; disposal clears both.\n\n## Working with Other Vielzeug Libraries\n\nUse Herald for temporal facts, Ripple for retained state, Rune for structured logging inside `tap()`, and Postmaster when work must survive reloads or retry durably.\n\n## Best Practices\n\n- Define one explicit event map per module or application boundary.\n- Emit facts, not mutable retained state.\n- Keep synchronous listeners short.\n- Handle rejected promises inside asynchronous listener work.\n- Keep unsubscribe functions or pass ownership signals.\n- Use `wait()` and `waitAny()` only for future one-shot events.\n- Install a `tap()` observer when listener failures must be visible.\n- Dispose owner-scoped buses.\n",
|
|
7
|
-
"examples": "---\ntitle: 'Herald: Examples'\ndescription: Recipes for typed delivery, waits, lifecycle ownership, diagnostics, bridging, and testing.\n---\n\n## Examples\n\n- [Standalone Bus](./examples/standalone-entry.md)\n- [Module-Level Bus](./examples/module-level-bus.md)\n- [Await a One-Time Event](./examples/awaiting-a-one-time-event.md)\n- [Inspect Listener Counts](./examples/inspecting-listener-counts.md)\n- [Observe Listener Failures](./examples/custom-error-boundary.md)\n- [Handle Disposal in Async Code](./examples/handling-disposal-in-async-code.md)\n- [Scope a Bus to a Request](./examples/request-scoping.md)\n- [Consume Ongoing Events](./examples/streaming-with-events.md)\n- [Bridge Buses Explicitly](./examples/bus-bridging-with-pipeevents.md)\n- [Test with `createTestBus()`](./examples/testing-with-createtestbus.md)\n"
|
|
8
|
-
},
|
|
9
|
-
"examples": [
|
|
10
|
-
{
|
|
11
|
-
"id": "abort-signal",
|
|
12
|
-
"code": "import { createBus, BusDisposedError } from '@vielzeug/herald'\n\n// Demonstrate AbortSignal auto-unsubscribe and BusDisposedError\nconst bus = createBus()\n\nconst controller = new AbortController()\nconst { signal } = controller\n\nbus.on('message', (msg) => {\n console.log('listener received:', msg)\n}, { signal })\n\nbus.emit('message', 'first') // fires\nbus.emit('message', 'second') // fires\n\ncontroller.abort() // removes the listener\n\nbus.emit('message', 'third') // ignored: no listeners\nconsole.log('listeners after abort:', bus.listenerCount())\n\n// BusDisposedError: pending wait() rejects when bus is disposed\nconst bus2 = createBus()\n\nvoid bus2.wait('done').catch((err) => {\n if (err instanceof BusDisposedError) {\n console.log('BusDisposedError caught:', err.message)\n }\n})\n\nbus2.dispose()",
|
|
13
|
-
"name": "AbortSignal & BusDisposedError"
|
|
14
|
-
},
|
|
15
|
-
{
|
|
16
|
-
"id": "async-wait",
|
|
17
|
-
"code": "import { createBus } from '@vielzeug/herald'\n\n// Await a single event with wait(), race multiple with waitAny()\nconst bus = createBus()\n\n// Emit after a short delay\nsetTimeout(() => bus.emit('user:login', { userId: '42', email: 'alice@example.com' }), 50)\nsetTimeout(() => bus.emit('theme:change', 'dark'), 80)\n\n// wait() resolves on the next emit of that event\nconst loginPayload = await bus.wait('user:login')\nconsole.log('got login:', loginPayload.userId)\n\n// Reset and race two events: whichever fires first wins\nsetTimeout(() => bus.emit('user:login', { userId: '1', email: 'a@b.com' }), 20)\nsetTimeout(() => bus.emit('theme:change', 'light'), 60)\n\nconst result = await bus.waitAny(['user:login', 'theme:change'])\n\nif (result.event === 'user:login') {\n console.log('login won the race:', result.payload.userId)\n} else {\n console.log('theme won the race:', result.payload)\n}\n\nbus.dispose()",
|
|
18
|
-
"name": "Async wait()"
|
|
19
|
-
},
|
|
20
|
-
{
|
|
21
|
-
"id": "basic-bus",
|
|
22
|
-
"code": "import { createBus } from '@vielzeug/herald'\n\n// Typed pub/sub with on(), emit(), and once()\nconst bus = createBus()\n\nconst unsub = bus.on('user:login', ({ userId, email }) => {\n console.log('login:', userId, email)\n})\n\nbus.once('user:logout', () => {\n console.log('logged out (fires once)')\n})\n\nbus.emit('user:login', { userId: '1', email: 'alice@example.com' })\nbus.emit('user:logout')\nbus.emit('user:logout') // once() already removed; no output\n\nunsub()\nbus.emit('user:login', { userId: '2', email: 'bob@example.com' }) // no output: unsubscribed\n\nbus.dispose()",
|
|
23
|
-
"name": "Basic Bus"
|
|
24
|
-
},
|
|
25
|
-
{
|
|
26
|
-
"id": "bus-basics",
|
|
27
|
-
"code": "import { createBus } from '@vielzeug/herald'\n\n// on() returns an unsubscribe handle; emit() delivers to all active listeners\nconst bus = createBus()\n\nconst unsubLogin = bus.on('user:login', (payload) => {\n console.log('login:', payload.name, '(' + payload.userId + ')')\n})\n\nbus.on('user:logout', () => console.log('logged out'))\nbus.on('notification', (msg) => console.log('notification:', msg))\n\nbus.emit('user:login', { userId: '123', name: 'Alice' })\nbus.emit('notification', 'welcome back!')\n\nunsubLogin()\n\nbus.emit('user:login', { userId: '456', name: 'Bob' }) // no output: unsubscribed\nconsole.log('active listeners:', bus.listenerCount())\n\nbus.dispose()",
|
|
28
|
-
"name": "createBus - Basics"
|
|
29
|
-
},
|
|
30
|
-
{
|
|
31
|
-
"id": "disposal-signal",
|
|
32
|
-
"code": "import { createBus } from '@vielzeug/herald'\n\n// disposalSignal ties an external subscription's lifetime to this bus\nconst mainBus = createBus()\nconst childBus = createBus()\n\n// Pass disposalSignal so the child listener is removed when mainBus disposes\nchildBus.on('data:update', ({ value }) => {\n console.log('child received:', value)\n}, { signal: mainBus.disposalSignal })\n\nconsole.log('child listeners before dispose:', childBus.listenerCount())\n\nchildBus.emit('data:update', { value: 10 }) // fires: listener is active\n\nmainBus.dispose() // disposalSignal fires: child listener auto-removed\n\nconsole.log('child listeners after mainBus.dispose():', childBus.listenerCount())\n\nchildBus.emit('data:update', { value: 20 }) // no output: listener is gone\nconsole.log('mainBus.disposed:', mainBus.disposed)\nconsole.log('disposalSignal aborted:', mainBus.disposalSignal.aborted)",
|
|
33
|
-
"name": "disposalSignal"
|
|
34
|
-
},
|
|
35
|
-
{
|
|
36
|
-
"id": "error-handling",
|
|
37
|
-
"code": "import { createBus, HeraldError } from '@vielzeug/herald'\n\n// tap() captures every listener error; emit() rethrows the first after all listeners run\nconst errors = []\n\nconst bus = createBus()\n\nbus.tap((event) => {\n if (event.type === 'error') {\n errors.push({ event: event.event, message: event.error instanceof Error ? event.error.message : String(event.error) })\n }\n})\n\nbus.on('order:placed', () => console.log('confirmation email sent'))\nbus.on('order:placed', () => {\n throw new Error('inventory check failed')\n})\nbus.on('order:placed', () => console.log('analytics event recorded')) // still runs\n\ntry {\n bus.emit('order:placed', { id: 'ORD-1', total: 49.99 })\n} catch (err) {\n console.log('first error rethrown:', err.message)\n}\n\nconsole.log('captured errors:', errors)\n// [{ event: 'order:placed', message: 'inventory check failed' }]\n\n// Disposal interrupts pending waits with BusDisposedError\nconst pending = bus.wait('order:placed')\n\nbus.dispose()\n\npending.catch((err) => {\n console.log('caught herald error?', err instanceof HeraldError, '-', err.message)\n})",
|
|
38
|
-
"name": "Error Handling"
|
|
39
|
-
},
|
|
40
|
-
{
|
|
41
|
-
"id": "named-bus",
|
|
42
|
-
"code": "import { createBus } from '@vielzeug/herald'\n\n// name appears in BusDisposedError messages\nconst authBus = createBus({ name: 'auth', maxListeners: 1 })\n\nauthBus.on('login', (userId) => console.log('user:', userId))\nauthBus.on('login', (userId) => console.log('audit:', userId)) // triggers maxListeners warn\n\nauthBus.emit('login', 'alice')\n\nconst pending = authBus.wait('logout')\nauthBus.dispose()\n\npending.catch((err) => {\n console.log('error name:', err.name)\n console.log('error message:', err.message)\n})",
|
|
43
|
-
"name": "Named Bus"
|
|
44
|
-
},
|
|
45
|
-
{
|
|
46
|
-
"id": "once-and-wait",
|
|
47
|
-
"code": "import { createBus } from '@vielzeug/herald'\n\n// once() fires exactly once then auto-removes; wait() resolves on the next emit\nconst bus = createBus()\n\nbus.once('data:ready', (payload) => {\n console.log('data (once):', payload.items.join(', '))\n})\n\nbus.emit('data:ready', { items: ['alpha', 'beta', 'gamma'] }) // fires\nbus.emit('data:ready', { items: ['ignored'] }) // once already consumed\n\nasync function waitForTask() {\n console.log('waiting for task...')\n const result = await bus.wait('task:done')\n console.log('task done! result:', result.result)\n}\n\nvoid waitForTask()\n\nsetTimeout(() => {\n bus.emit('task:done', { result: 99 })\n}, 50)",
|
|
48
|
-
"name": "once() and wait()"
|
|
49
|
-
},
|
|
50
|
-
{
|
|
51
|
-
"id": "test-bus",
|
|
52
|
-
"code": "import { createTestBus } from '@vielzeug/herald/testing'\n\n// TestBus wraps a normal bus with emission recording: no mocking required\nconst bus = createTestBus()\n\nconst stop = bus.on('cart:updated', (cart) => console.log('handler saw total:', cart.total))\n\nbus.emit('cart:updated', { items: 1, total: 19.99 })\nbus.emit('cart:updated', { items: 2, total: 39.98 })\nbus.emit('user:logout')\n\nconsole.log('emitted count:', bus.emittedCount('cart:updated')) // 2\nconsole.log('all payloads:', bus.emitted('cart:updated'))\nconsole.log('every recorded event:', bus.allEmitted())\n\nstop()\nbus.emit('cart:updated', { items: 3, total: 59.97 }) // still recorded\n\nconsole.log('after unsubscribe:', bus.emitted('cart:updated'))\n\nbus.dispose()",
|
|
53
|
-
"name": "createTestBus()"
|
|
54
|
-
},
|
|
55
|
-
{
|
|
56
|
-
"id": "wait-any",
|
|
57
|
-
"code": "import { createBus } from '@vielzeug/herald'\n\n// waitAny resolves with { event, payload } for whichever event fires first\nconst bus = createBus()\n\nasync function watchNextSessionEvent() {\n console.log('waiting for first session event...')\n\n const result = await bus.waitAny(['user:login', 'user:logout', 'session:expired'])\n\n if (result.event === 'user:login') {\n console.log('login:', result.payload.email, '(id:', result.payload.userId + ')')\n } else if (result.event === 'session:expired') {\n console.log('session expired:', result.payload.reason)\n } else {\n console.log('user logged out')\n }\n}\n\nvoid watchNextSessionEvent()\n\nsetTimeout(() => {\n bus.emit('user:login', { email: 'alice@example.com', userId: '42' })\n bus.emit('user:logout') // ignored: waitAny already resolved\n}, 30)",
|
|
58
|
-
"name": "waitAny()"
|
|
59
|
-
},
|
|
60
|
-
{
|
|
61
|
-
"id": "wildcard-listeners",
|
|
62
|
-
"code": "import { createBus } from '@vielzeug/herald'\n\ntype AppEvents = {\n 'user:login': { userId: string }\n 'user:logout': void\n 'cart:updated': { items: number }\n}\n\nconst bus = createBus<AppEvents>({ name: 'app' })\n\n// onAny receives every event: useful for logging, analytics, tracing\nconst unsub = bus.onAny((event, payload) => {\n console.log('[audit]', event, payload)\n})\n\nconsole.log('wildcard listeners:', bus.wildcardCount()) // 1\n\nbus.emit('user:login', { userId: 'alice' })\nbus.emit('cart:updated', { items: 3 })\nbus.emit('user:logout')\n\n// Remove the wildcard listener\nunsub()\nconsole.log('after unsub:', bus.wildcardCount()) // 0\n\nbus.dispose()",
|
|
63
|
-
"name": "onAny + wildcardCount()"
|
|
64
|
-
}
|
|
65
|
-
],
|
|
66
|
-
"typeSignatures": {
|
|
67
|
-
"createBus": "export { createBus } from './bus';",
|
|
68
|
-
"BusDisposedError": "export { BusDisposedError, HeraldError } from './errors';",
|
|
69
|
-
"HeraldError": "export { BusDisposedError, HeraldError } from './errors';",
|
|
70
|
-
"Bus": "export type {\n Bus,\n BusOptions,\n EventKey,\n EventMap,\n HeraldEvent,\n Listener,\n SubscribeOptions,\n Unsubscribe,\n WaitAnyResult,\n} from './types';",
|
|
71
|
-
"BusOptions": "export type {\n Bus,\n BusOptions,\n EventKey,\n EventMap,\n HeraldEvent,\n Listener,\n SubscribeOptions,\n Unsubscribe,\n WaitAnyResult,\n} from './types';",
|
|
72
|
-
"EventKey": "export type {\n Bus,\n BusOptions,\n EventKey,\n EventMap,\n HeraldEvent,\n Listener,\n SubscribeOptions,\n Unsubscribe,\n WaitAnyResult,\n} from './types';",
|
|
73
|
-
"EventMap": "export type {\n Bus,\n BusOptions,\n EventKey,\n EventMap,\n HeraldEvent,\n Listener,\n SubscribeOptions,\n Unsubscribe,\n WaitAnyResult,\n} from './types';",
|
|
74
|
-
"HeraldEvent": "export type {\n Bus,\n BusOptions,\n EventKey,\n EventMap,\n HeraldEvent,\n Listener,\n SubscribeOptions,\n Unsubscribe,\n WaitAnyResult,\n} from './types';",
|
|
75
|
-
"Listener": "export type {\n Bus,\n BusOptions,\n EventKey,\n EventMap,\n HeraldEvent,\n Listener,\n SubscribeOptions,\n Unsubscribe,\n WaitAnyResult,\n} from './types';",
|
|
76
|
-
"SubscribeOptions": "export type {\n Bus,\n BusOptions,\n EventKey,\n EventMap,\n HeraldEvent,\n Listener,\n SubscribeOptions,\n Unsubscribe,\n WaitAnyResult,\n} from './types';",
|
|
77
|
-
"Unsubscribe": "export type {\n Bus,\n BusOptions,\n EventKey,\n EventMap,\n HeraldEvent,\n Listener,\n SubscribeOptions,\n Unsubscribe,\n WaitAnyResult,\n} from './types';",
|
|
78
|
-
"WaitAnyResult": "export type {\n Bus,\n BusOptions,\n EventKey,\n EventMap,\n HeraldEvent,\n Listener,\n SubscribeOptions,\n Unsubscribe,\n WaitAnyResult,\n} from './types';"
|
|
79
|
-
}
|
|
80
|
-
}
|
|
@@ -1,132 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"apiSource": "export * from './commerce/commerce';\nexport * from './date/date';\nexport * from './errors';\nexport * from './factory';\nexport * from './finance/finance';\nexport * from './internet/internet';\nexport * from './location/location';\nexport * from './lorem/lorem';\nexport * from './person/person';\nexport * from './seed/create-seed';\nexport * from './seed/mulberry32';\nexport * from './types';\n",
|
|
3
|
-
"docs": {
|
|
4
|
-
"index": "---\ntitle: 'Illusionist: Fake Data Generator for TypeScript'\ndescription: Typed, deterministic, locale-aware fake data generator with a seeded PRNG, eight data categories, and zero external runtime dependencies.\npackage: illusionist\ncategory: data\nkeywords: [fake-data, mock, seed, faker, test-fixtures, deterministic]\nexports: [createIllusion, createSeed, mulberry32]\nrelated: [arsenal, coins, tempo]\nenvironments: [browser, node, ssr]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"illusionist\" />\n\n## Why Illusionist?\n\nIllusionist generates realistic fake data from a single seeded random source. The same seed always produces the same output, so test fixtures and snapshots stay reproducible across runs, machines, and CI. Every category shares one bound instance with one locale, so a person, their email, and their address stay internally consistent.\n\n```ts\n// Before\nconst user = {\n name: 'Test User',\n email: 'test@example.com',\n address: '123 Main St',\n};\n\n// After\nimport { createIllusion } from '@vielzeug/illusionist';\nimport { en } from '@vielzeug/illusionist/locales';\n\nconst illusion = createIllusion({ seed: 12345, locale: en });\n\nconst user = {\n name: illusion.person.fullName(),\n email: illusion.internet.email(),\n address: illusion.location.streetAddress(),\n};\n```\n\n| Feature | Illusionist | Faker.js | @faker-js/faker |\n| -------------------------- | ------------------------------------------------- | -------------------------------------------- | -------------------------------------------- |\n| Bundle size | <PackageInfo package=\"illusionist\" type=\"size\" /> | External dependency | External dependency |\n| Zero external dependencies | <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| Seeded determinism | <ore-icon name=\"check\" size=\"16\"></ore-icon> | Partial | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n| Locale-aware datasets | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n| TypeScript-native types | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n\n<div class=\"decision-callout\">\n\n**Use Illusionist when** test fixtures, mock APIs, or database seeds must be realistic and reproducible from a single seed value.\n\n**Consider @faker-js/faker when** you need a large catalog of locale datasets beyond `en` and `de` or a community plugin ecosystem.\n\n</div>\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/illusionist\n```\n\n```sh [npm]\nnpm install @vielzeug/illusionist\n```\n\n```sh [yarn]\nyarn add @vielzeug/illusionist\n```\n\n:::\n\n## Quick Start\n\nCreate a bound instance with a seed and locale. All categories share that seed, so output is deterministic.\n\n```ts\nimport { createIllusion } from '@vielzeug/illusionist';\nimport { en } from '@vielzeug/illusionist/locales';\n\nconst illusion = createIllusion({ seed: 12345, locale: en });\n\nillusion.person.fullName(); // 'Ashley Harris'\nillusion.internet.email(); // 'samantha.sanchez@mail.com'\nillusion.commerce.price(); // Money { amount: 76640n, currency: USD }\nillusion.date.past({ years: 2 }); // Temporal.ZonedDateTime\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- **`person`**: names, gender, prefixes, suffixes, job titles\n- **`internet`**: emails, usernames, passwords, URLs, IPs, MACs, HTTP metadata\n- **`commerce`**: product names, departments, prices as coins `Money`\n- **`date`**: past, future, recent, between, birthday as tempo `Temporal` objects\n- **`finance`**: amounts, IBANs, BICs, credit cards, crypto addresses\n- **`location`**: cities, streets, states, countries, GPS coordinates\n- **`lorem`**: words, sentences, paragraphs, slugs\n- **`system`**: file paths, semver, UUIDs, ports, cron expressions\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- [Arsenal](/arsenal/): random primitives (`RandomSource`, `uuid`) that Illusionist builds on.\n- [Coins](/coins/): exact money type returned by `commerce.price()` and `finance.amount()`.\n- [Tempo](/tempo/): `Temporal` date utilities returned by every `date` function.\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
|
|
5
|
-
"api": "---\ntitle: 'Illusionist: API Reference'\ndescription: createIllusion, all category functions, seed utilities, types, and errors.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution | Common gotcha |\n| ---------------- | ---------------------------------- | --------- | ------------------------------------------- |\n| `createIllusion` | Create a bound, seeded instance | Sync | Locale is fixed for the instance lifetime |\n| `person.*` | Names, gender, job titles | Sync | Locale-specific datasets (`en`, `de`) |\n| `internet.*` | Emails, URLs, IPs, HTTP metadata | Sync | `ip()` defaults to IPv4 |\n| `commerce.*` | Product names, prices | Sync | `price()` returns coins `Money` |\n| `date.*` | Past, future, recent, birthday | Sync | Returns tempo `Temporal` objects |\n| `finance.*` | IBANs, cards, crypto addresses | Sync | IBANs pass mod-97; cards pass Luhn |\n| `location.*` | Cities, streets, GPS | Sync | Locale-specific datasets |\n| `lorem.*` | Words, sentences, paragraphs | Sync | Word pool is fixed |\n| `system.*` | Files, semver, UUIDs, ports | Sync | `port()` avoids well-known ports by default |\n| `createSeed` | Build a `RandomSource` from a seed | Sync | Non-finite numeric seeds throw |\n| `mulberry32` | Low-level 32-bit PRNG | Sync | Not cryptographically secure |\n\n## Package Entry Point\n\n| Import | Purpose |\n| ---------------------------------- | --------------------------------------------------------------------------------------------------------------------- |\n| `@vielzeug/illusionist` | `createIllusion`, `createSeed`, `mulberry32`, `Illusionist`, `IllusionistOptions`, `IllusionistLocale`, error classes |\n| `@vielzeug/illusionist/locales` | Tree-shakeable barrel: `en`, `de` locale objects |\n| `@vielzeug/illusionist/locales/en` | English locale object only |\n| `@vielzeug/illusionist/locales/de` | German locale object only |\n\n## createIllusion\n\n```ts\nfunction createIllusion(options: IllusionistOptions): Illusionist;\n```\n\nCreates a bound instance. All categories share one seeded random source and one locale. Locale data is included only when its dedicated subpath is imported; the root entry does not statically import a default locale. For dynamic switching, use `await import('@vielzeug/illusionist/locales')` before calling this synchronous factory.\n\n| Option | Type | Default | Description |\n| -------- | ------------------- | ----------- | ----------------------------------------------------------------- |\n| `seed` | `number \\| string` | `undefined` | Seed for deterministic output. Omit for cryptographic randomness. |\n| `locale` | `IllusionistLocale` | Required | Explicit locale object for locale-aware categories. |\n\n**Returns:** `Illusionist`: an object with `person`, `internet`, `commerce`, `date`, `finance`, `location`, `lorem`, and `system` categories, plus readonly `seed` and `locale` values. It owns no external resources and requires no cleanup.\n\n```ts\nimport { createIllusion } from '@vielzeug/illusionist';\nimport { en } from '@vielzeug/illusionist/locales';\n\nconst illusion = createIllusion({ seed: 12345, locale: en });\nillusion.person.fullName();\n```\n\n---\n\n## Person\n\n### `person.firstName()`\n\n```ts\nfunction firstName(): string;\n```\n\nReturns a random first name from the locale dataset.\n\n### `person.lastName()`\n\n```ts\nfunction lastName(): string;\n```\n\nReturns a random last name from the locale dataset.\n\n### `person.fullName()`\n\n```ts\nfunction fullName(): string;\n```\n\nReturns a first and last name separated by a space.\n\n### `person.gender()`\n\n```ts\nfunction gender(): string;\n```\n\nReturns a random gender label from the locale dataset.\n\n### `person.prefix()`\n\n```ts\nfunction prefix(): string;\n```\n\nReturns a random name prefix (e.g. `Mr.`, `Dr.`).\n\n### `person.suffix()`\n\n```ts\nfunction suffix(): string;\n```\n\nReturns a random name suffix. Returns an empty string when the locale dataset has no suffixes.\n\n### `person.jobTitle()`\n\n```ts\nfunction jobTitle(): string;\n```\n\nReturns a job area and job type joined by a space.\n\n---\n\n## Internet\n\n### `internet.email()`\n\n```ts\nfunction email(): string;\n```\n\nReturns an email of the form `firstname.lastname@domain.tld`.\n\n### `internet.username()`\n\n```ts\nfunction username(): string;\n```\n\nReturns either a random alphanumeric string or a `firstname.lastname` pattern.\n\n### `internet.password(options?)`\n\n```ts\nfunction password(options?: PasswordOptions): string;\n```\n\n| Option | Type | Default | Description |\n| ----------- | --------- | ------- | ------------------------------------- |\n| `length` | `number` | `12` | Password length. |\n| `memorable` | `boolean` | `false` | Build from name fragments and digits. |\n\nReturns a password mixing upper/lowercase letters, digits, and special characters.\n\n### `internet.url()`\n\n```ts\nfunction url(): string;\n```\n\nReturns a URL of the form `protocol://sub.domain.tld/path/...`.\n\n### `internet.domainName()`\n\n```ts\nfunction domainName(): string;\n```\n\nReturns a domain of the form `domain.tld`.\n\n### `internet.ip(version?)`\n\n```ts\nfunction ip(version?: 4 | 6): string;\n```\n\nReturns an IPv4 or IPv6 address. Defaults to IPv4.\n\n### `internet.mac()`\n\n```ts\nfunction mac(): string;\n```\n\nReturns a MAC address of the form `XX:XX:XX:XX:XX:XX`.\n\n### `internet.userAgent()`\n\n```ts\nfunction userAgent(): string;\n```\n\nReturns a random user agent string.\n\n### `internet.httpMethod()`\n\n```ts\nfunction httpMethod(): string;\n```\n\nReturns a random HTTP method.\n\n### `internet.statusCode()`\n\n```ts\nfunction statusCode(): number;\n```\n\nReturns a random HTTP status code.\n\n### `internet.mimeType()`\n\n```ts\nfunction mimeType(): string;\n```\n\nReturns a random MIME type.\n\n---\n\n## Commerce\n\n### `commerce.productAdjective()`\n\n```ts\nfunction productAdjective(): string;\n```\n\nReturns a random product adjective.\n\n### `commerce.productMaterial()`\n\n```ts\nfunction productMaterial(): string;\n```\n\nReturns a random product material.\n\n### `commerce.productNoun()`\n\n```ts\nfunction productNoun(): string;\n```\n\nReturns a random product noun.\n\n### `commerce.productName()`\n\n```ts\nfunction productName(): string;\n```\n\nReturns an adjective, material, and noun joined by spaces.\n\n### `commerce.department()`\n\n```ts\nfunction department(): string;\n```\n\nReturns a random department name.\n\n### `commerce.price(options?)`\n\n```ts\nfunction price(options?: PriceOptions): Money;\n```\n\n| Option | Type | Default | Description |\n| ---------- | ------------------------- | ------- | -------------- |\n| `min` | `number` | `0.01` | Minimum price. |\n| `max` | `number` | `1000` | Maximum price. |\n| `currency` | `'USD' \\| 'EUR' \\| 'GBP'` | `'USD'` | Currency code. |\n\nReturns a coins `Money` value with two decimal places.\n\n### `commerce.productDescription()`\n\n```ts\nfunction productDescription(): string;\n```\n\nReturns one or two sentences describing a product.\n\n---\n\n## Date\n\nAll date functions return tempo `Temporal` objects.\n\n### `date.past(options?)`\n\n```ts\nfunction past(options?: { years?: number; ref?: Temporal.ZonedDateTime }): Temporal.ZonedDateTime;\n```\n\nReturns a date in the past within `years` (default `1`) from `ref` (default now).\n\n### `date.future(options?)`\n\n```ts\nfunction future(options?: { years?: number; ref?: Temporal.ZonedDateTime }): Temporal.ZonedDateTime;\n```\n\nReturns a date in the future within `years` (default `1`) from `ref` (default now).\n\n### `date.recent(options?)`\n\n```ts\nfunction recent(options?: { days?: number; ref?: Temporal.ZonedDateTime }): Temporal.ZonedDateTime;\n```\n\nReturns a date within `days` (default `1`) in the past from `ref` (default now).\n\n### `date.between(from, to)`\n\n```ts\nfunction between(from: Temporal.ZonedDateTime, to: Temporal.ZonedDateTime): Temporal.ZonedDateTime;\n```\n\nReturns a date between `from` and `to`. Returns `from` if `from` is after `to`.\n\n### `date.birthday(options?)`\n\n```ts\nfunction birthday(options?: { minAge?: number; maxAge?: number; ref?: Temporal.ZonedDateTime }): Temporal.PlainDate;\n```\n\nReturns a `PlainDate` with a random age between `minAge` (default `18`) and `maxAge` (default `80`).\n\n### `date.weekday(locale?)`\n\n```ts\nfunction weekday(locale?: string): string;\n```\n\nReturns a random weekday name. Uses the instance locale unless overridden.\n\n### `date.month(locale?)`\n\n```ts\nfunction month(locale?: string): string;\n```\n\nReturns a random month name. Uses the instance locale unless overridden.\n\n---\n\n## Finance\n\n### `finance.amount(options?)`\n\n```ts\nfunction amount(options?: AmountOptions): Money;\n```\n\n| Option | Type | Default | Description |\n| ---------- | ------------------------- | ------- | --------------- |\n| `min` | `number` | `100` | Minimum amount. |\n| `max` | `number` | `10000` | Maximum amount. |\n| `currency` | `'USD' \\| 'EUR' \\| 'GBP'` | `'USD'` | Currency code. |\n\nReturns a coins `Money` value with two decimal places.\n\n### `finance.iban(countryCode?)`\n\n```ts\nfunction iban(countryCode?: string): string;\n```\n\nReturns an IBAN. Pass a country code to fix the country; otherwise a random supported country is chosen. The check digits are computed so the IBAN passes mod-97 validation.\n\n### `finance.bic()`\n\n```ts\nfunction bic(): string;\n```\n\nReturns a BIC/SWIFT code of 8 or 11 characters.\n\n### `finance.creditCardNumber(type?)`\n\n```ts\nfunction creditCardNumber(type?: 'visa' | 'mastercard' | 'amex'): string;\n```\n\nReturns a card number with a valid Luhn check digit. Amex returns 15 digits; others return 16.\n\n### `finance.creditCardCVV(type?)`\n\n```ts\nfunction creditCardCVV(type?: 'visa' | 'mastercard' | 'amex'): string;\n```\n\nReturns a CVV. Amex returns 4 digits; others return 3.\n\n### `finance.bitcoinAddress()`\n\n```ts\nfunction bitcoinAddress(): string;\n```\n\nReturns a Bitcoin address with a `1`, `3`, or `bc1` prefix.\n\n### `finance.ethereumAddress()`\n\n```ts\nfunction ethereumAddress(): string;\n```\n\nReturns a 42-character Ethereum address prefixed with `0x`.\n\n### `finance.transactionType()`\n\n```ts\nfunction transactionType(): string;\n```\n\nReturns a random transaction type label.\n\n### `finance.bank()`\n\n```ts\nfunction bank(): string;\n```\n\nReturns a random bank name.\n\n---\n\n## Location\n\n### `location.city()`\n\n```ts\nfunction city(): string;\n```\n\nReturns a random city from the locale dataset.\n\n### `location.street()`\n\n```ts\nfunction street(): string;\n```\n\nReturns a random street from the locale dataset.\n\n### `location.streetAddress()`\n\n```ts\nfunction streetAddress(): string;\n```\n\nReturns a house number (1–999) followed by a street name.\n\n### `location.zipCode()`\n\n```ts\nfunction zipCode(): string;\n```\n\nReturns a ZIP code matching the locale's pattern.\n\n### `location.state()`\n\n```ts\nfunction state(): string;\n```\n\nReturns a random state or region from the locale dataset.\n\n### `location.country()`\n\n```ts\nfunction country(): string;\n```\n\nReturns a random country from the locale dataset.\n\n### `location.latitude()`\n\n```ts\nfunction latitude(): number;\n```\n\nReturns a latitude in the range `[-90, 90]`.\n\n### `location.longitude()`\n\n```ts\nfunction longitude(): number;\n```\n\nReturns a longitude in the range `[-180, 180]`.\n\n### `location.nearbyGPSCoordinate(ref?)`\n\n```ts\nfunction nearbyGPSCoordinate(ref?: Coordinate): Coordinate;\n```\n\nReturns a coordinate within ~1 degree of `ref`. When `ref` is omitted, a random coordinate is used as the base.\n\n---\n\n## Lorem\n\n### `lorem.word()`\n\n```ts\nfunction word(): string;\n```\n\nReturns a single random word.\n\n### `lorem.words(count?)`\n\n```ts\nfunction words(count?: number): string;\n```\n\nReturns `count` (default `3`) space-joined words.\n\n### `lorem.sentence(wordCount?)`\n\n```ts\nfunction sentence(wordCount?: number): string;\n```\n\nReturns a sentence of `wordCount` words (default 6–12) with a capital first letter and trailing period.\n\n### `lorem.sentences(count?)`\n\n```ts\nfunction sentences(count?: number): string;\n```\n\nReturns `count` (default `3`) space-joined sentences.\n\n### `lorem.paragraph(sentenceCount?)`\n\n```ts\nfunction paragraph(sentenceCount?: number): string;\n```\n\nReturns a paragraph of `sentenceCount` sentences (default 3–7).\n\n### `lorem.paragraphs(count?)`\n\n```ts\nfunction paragraphs(count?: number): string;\n```\n\nReturns `count` (default `3`) newline-joined paragraphs.\n\n### `lorem.slug(wordCount?)`\n\n```ts\nfunction slug(wordCount?: number): string;\n```\n\nReturns a hyphen-joined slug of `wordCount` (default `3`) words.\n\n### `lorem.lines(count?)`\n\n```ts\nfunction lines(count?: number): string;\n```\n\nReturns `count` (default `5`) newline-joined lines, each a sentence.\n\n---\n\n## System\n\n### `system.fileExtension()`\n\n```ts\nfunction fileExtension(): string;\n```\n\nReturns a random file extension.\n\n### `system.fileName()`\n\n```ts\nfunction fileName(): string;\n```\n\nReturns a random file name with extension.\n\n### `system.filePath()`\n\n```ts\nfunction filePath(): string;\n```\n\nReturns a path with 1–4 directory segments and a file name.\n\n### `system.mimeType()`\n\n```ts\nfunction mimeType(): string;\n```\n\nReturns a random MIME type.\n\n### `system.semver(options?)`\n\n```ts\nfunction semver(options?: { maxMajor?: number; includePrerelease?: boolean }): string;\n```\n\n| Option | Type | Default | Description |\n| ------------------- | --------- | ------- | --------------------------------------- |\n| `maxMajor` | `number` | `20` | Maximum major version. |\n| `includePrerelease` | `boolean` | `false` | Occasionally append a prerelease label. |\n\nReturns a semver string.\n\n### `system.uuid()`\n\n```ts\nfunction uuid(): string;\n```\n\nReturns a random UUID via `crypto.randomUUID()`. **Not deterministic**: ignores the seeded `RandomSource`. Use only when uniqueness matters more than reproducibility.\n\n### `system.port(options?)`\n\n```ts\nfunction port(options?: { min?: number; max?: number }): number;\n```\n\n| Option | Type | Default | Description |\n| ------ | -------- | ------- | ------------- |\n| `min` | `number` | `1024` | Minimum port. |\n| `max` | `number` | `65535` | Maximum port. |\n\nReturns a random port number.\n\n### `system.cron()`\n\n```ts\nfunction cron(): string;\n```\n\nReturns a random cron expression from common patterns.\n\n### `system.process()`\n\n```ts\nfunction process(): string;\n```\n\nReturns a random process name of the form `prefix_suffix`.\n\n---\n\n## Seed\n\n```ts\nimport { createSeed, mulberry32 } from '@vielzeug/illusionist';\n```\n\n### `createSeed(seed?)`\n\n```ts\nfunction createSeed(seed?: number | string): RandomSource;\n```\n\nCreates a `RandomSource` from a seed. Number seeds are used directly as mulberry32 state. String seeds are hashed to a 32-bit integer. Omit the seed for cryptographic randomness via `crypto.getRandomValues`. Throws `IllusionistSeedError` for non-finite numeric seeds.\n\n```ts\nconst a = createSeed(12345); // deterministic\nconst b = createSeed('hello'); // deterministic (hashed)\nconst c = createSeed(); // cryptographic\n```\n\n### `mulberry32(seed)`\n\n```ts\nfunction mulberry32(seed: number): RandomSource;\n```\n\nLow-level 32-bit PRNG. Not cryptographically secure. Returns a `RandomSource` producing floats in `[0, 1)`.\n\n---\n\n## Types\n\n```ts\ntype PersonLocaleData = {\n readonly firstNameFemale: readonly string[];\n readonly firstNameMale: readonly string[];\n readonly gender: readonly string[];\n readonly jobAreas: readonly string[];\n readonly jobTypes: readonly string[];\n readonly lastName: readonly string[];\n readonly prefix: readonly string[];\n readonly suffix: readonly string[];\n};\n\ntype LocationLocaleData = {\n readonly cities: readonly string[];\n readonly countries: readonly string[];\n readonly states: readonly string[];\n readonly streets: readonly string[];\n readonly zipPattern: string;\n};\n\ntype IllusionistLocale = {\n readonly code: string;\n readonly person: PersonLocaleData;\n readonly location: LocationLocaleData;\n};\n\ntype IllusionistOptions = {\n seed?: number | string;\n locale: IllusionistLocale;\n};\n\ntype Illusionist = {\n readonly person: typeof person;\n readonly internet: typeof internet;\n readonly commerce: typeof commerce;\n readonly date: typeof date;\n readonly finance: typeof finance;\n readonly location: typeof location;\n readonly lorem: typeof lorem;\n readonly system: typeof system;\n readonly seed: number | string | undefined;\n readonly locale: IllusionistLocale;\n};\n\ntype Coordinate = {\n lat: number;\n lng: number;\n};\n\ntype PasswordOptions = {\n length?: number;\n memorable?: boolean;\n};\n\ntype PriceOptions = {\n readonly min?: number;\n readonly max?: number;\n readonly currency?: 'USD' | 'EUR' | 'GBP';\n};\n\ntype AmountOptions = {\n readonly min?: number;\n readonly max?: number;\n readonly currency?: 'USD' | 'EUR' | 'GBP';\n};\n\n// Re-exported from @vielzeug/arsenal\ntype RandomSource = {\n next(): number; // finite float in [0, 1)\n};\n```\n\nCategory helpers throw `RangeError` when a custom source returns a non-finite value or a value outside `[0, 1)`.\n\n## Errors\n\nAll errors extend `IllusionistError`, which extends `Error`. Use `instanceof IllusionistError` to catch any illusionist-originated error.\n\n| Error | Trigger | Notable properties |\n| ---------------------- | ------------------------------------------------------------------------------- | ------------------ |\n| `IllusionistError` | Base class for all illusionist errors | `name`, `message` |\n| `IllusionistSeedError` | Non-finite numeric seed passed to `createSeed` (`NaN`, `Infinity`, `-Infinity`) | `name`, `message` |\n\n```ts\nimport { IllusionistError, IllusionistSeedError, createSeed } from '@vielzeug/illusionist';\n\ntry {\n createSeed(Number.NaN);\n} catch (error) {\n if (error instanceof IllusionistSeedError) {\n console.log(error.message);\n }\n}\n```\n",
|
|
6
|
-
"usage": "---\ntitle: 'Illusionist: Usage Guide'\ndescription: Generate deterministic, locale-aware fake data with Illusionist.\n---\n\n[[toc]]\n\n## Basic Usage\n\nCreate an illusionist instance with `createIllusion`. Access data through the eight bound categories. Each call consumes from the shared random source, so output is deterministic for a given seed.\n\n```ts\nimport { createIllusion } from '@vielzeug/illusionist';\nimport { en } from '@vielzeug/illusionist/locales';\n\nconst illusion = createIllusion({ seed: 12345, locale: en });\n\nillusion.person.firstName(); // 'Ashley'\nillusion.internet.username(); // 'fVEv9zc638m'\nillusion.commerce.productName(); // 'Intelligent Granite Table'\nillusion.date.recent({ days: 7 }); // Temporal.ZonedDateTime within the last week\nillusion.lorem.sentence(); // 'Enim ex non ea minim amet sint laborum proident nisi anim officia.'\n```\n\n## Seeded Determinism\n\nPass a number or string seed to make output reproducible. The same seed always produces the same sequence across runs, machines, and Node versions.\n\n```ts\nimport { createIllusion } from '@vielzeug/illusionist';\nimport { en } from '@vielzeug/illusionist/locales';\n\nconst a = createIllusion({ seed: 12345, locale: en });\nconst b = createIllusion({ seed: 12345, locale: en });\n\na.person.fullName() === b.person.fullName(); // true\n\nconst c = createIllusion({ seed: 'my-test-suite', locale: en });\nconst d = createIllusion({ seed: 'my-test-suite', locale: en });\n\nc.internet.email() === d.internet.email(); // true: string seeds are hashed\n```\n\nOmit the seed for cryptographic randomness backed by `crypto.getRandomValues`. Output is then non-deterministic and unsuitable for snapshots.\n\n```ts\nimport { createIllusion } from '@vielzeug/illusionist';\nimport { en } from '@vielzeug/illusionist/locales';\n\nconst random = createIllusion({ locale: en });\nrandom.person.fullName(); // different every run\n```\n\n## Locale Support\n\nImport a locale object and pass it at creation time. The `person` and `location` categories draw from that object's datasets. The `date.weekday` and `date.month` functions use its locale code.\n\n```ts\nimport { createIllusion } from '@vielzeug/illusionist';\nimport { de, en } from '@vielzeug/illusionist/locales';\n\nconst english = createIllusion({ seed: 1, locale: en });\nconst german = createIllusion({ seed: 1, locale: de });\n\nenglish.person.firstName(); // 'Mary'\ngerman.person.firstName(); // 'Mia'\n\nenglish.location.city(); // 'Austin'\ngerman.location.city(); // 'Bremen'\n\nenglish.date.month(); // 'December'\ngerman.date.month(); // 'Dezember'\n```\n\nThe locale is fixed for the lifetime of an instance. Each locale is a separate subpath, so locale data ships only when that subpath is imported; the root package does not statically include English or German data. Create a new instance to switch locales.\n\nFor dynamic app switching, load the desired locale before calling the synchronous factory:\n\n```ts\nconst { de } = await import('@vielzeug/illusionist/locales/de');\nconst german = createIllusion({ locale: de });\n```\n\n### Custom Locales\n\nThe shipped `en` and `de` objects are just plain data that `satisfies IllusionistLocale`. Build your own the same way: import the type, assemble the `person` and `location` datasets, and pass the result to `createIllusion`. No registration step; the factory accepts any object that matches the shape.\n\n```ts\nimport { createIllusion, type IllusionistLocale } from '@vielzeug/illusionist';\n\nconst fr: IllusionistLocale = {\n code: 'fr',\n person: {\n firstNameFemale: ['Marie', 'Camille', 'Sophie'],\n firstNameMale: ['Louis', 'Hugo', 'Léo'],\n lastName: ['Martin', 'Bernard', 'Dubois'],\n gender: ['féminin', 'masculin', 'non-binaire'],\n jobAreas: ['marketing', 'ingénierie', 'ventes'],\n jobTypes: ['directeur', 'ingénieur', 'analyste'],\n prefix: ['M.', 'Mme', 'Dr.'],\n suffix: ['PhD', 'Jr.'],\n },\n location: {\n cities: ['Paris', 'Lyon', 'Marseille'],\n countries: ['France', 'Belgique', 'Suisse'],\n states: ['Île-de-France', 'Auvergne-Rhône-Alpes', \"Provence-Alpes-Côte d'Azur\"],\n streets: ['rue de la Paix', 'avenue des Champs-Élysées', 'boulevard Saint-Germain'],\n zipPattern: '#####',\n },\n};\n\nconst illusion = createIllusion({ seed: 42, locale: fr });\n\nillusion.person.fullName(); // 'Camille Dubois'\nillusion.location.city(); // 'Marseille'\nillusion.person.jobTitle(); // 'marketing ingénieur'\n```\n\n`date.weekday()` and `date.month()` currently ship English and German name arrays only; a custom locale code falls through to the English set. For other languages, format a generated `Temporal` date with `@vielzeug/tempo`'s `format()` and your own `Intl.DateTimeFormat` options.\n\nUse `satisfies IllusionistLocale` instead of a bare type annotation to get error locality: TypeScript points at the offending field rather than the whole object.\n\n## Category Overview\n\n| Category | Example call | Returns |\n| ---------- | ----------------------------------- | -------------------------------- |\n| `person` | `illusion.person.fullName()` | `string` |\n| `internet` | `illusion.internet.email()` | `string` |\n| `commerce` | `illusion.commerce.price()` | `Money` (coins) |\n| `date` | `illusion.date.past({ years: 1 })` | `Temporal.ZonedDateTime` (tempo) |\n| `finance` | `illusion.finance.iban()` | `string` |\n| `location` | `illusion.location.streetAddress()` | `string` |\n| `lorem` | `illusion.lorem.paragraph()` | `string` |\n| `system` | `illusion.system.uuid()` | `string` |\n\n## Working with Other Vielzeug Libraries\n\nIllusionist integrates with other Vielzeug packages at the return-type level. `commerce.price()` and `finance.amount()` return coins `Money`, so you can format, add, or allocate them directly. `date` functions return tempo `Temporal` objects, so you can shift, compare, or format them.\n\n```ts\nimport { format, add, money } from '@vielzeug/coins';\nimport { createIllusion } from '@vielzeug/illusionist';\nimport { en } from '@vielzeug/illusionist/locales';\nimport { formatZonedDateTimeISO } from '@vielzeug/tempo';\n\nconst illusion = createIllusion({ seed: 42, locale: en });\n\nconst price = illusion.commerce.price({ min: 10, max: 50, currency: 'EUR' });\nconst tax = money('5.00', price.currency);\nconst total = add(price, tax);\n\nconsole.log(format(total, { locale: 'de-DE' }));\n\nconst orderDate = illusion.date.recent({ days: 30 });\nconsole.log(formatZonedDateTimeISO(orderDate));\n```\n\n## Best Practices\n\n- Pass a seed in tests and CI; omit it only for one-off non-reproducible mocks.\n- Create one instance per test case so each test starts from a known random state.\n- Treat instances as ordinary stateful values; they own no resources and require no cleanup.\n- Fix the locale at creation time; create a new instance to switch locales rather than mixing.\n- Use string seeds for named test suites: they are self-documenting and hash to a stable number.\n- Combine `person`, `internet`, and `location` to build internally consistent mock entities.\n- Treat `Money` and `Temporal` return values as first-class: pass them to coins and tempo functions directly.\n- Avoid sharing a single instance across concurrent async tasks; each call advances the shared random source.\n- `system.uuid()` uses `crypto.randomUUID()`, not the seeded source. Do not use it in deterministic fixtures or snapshot tests.\n",
|
|
7
|
-
"examples": "---\ntitle: 'Illusionist: Examples'\ndescription: Practical examples and recipes for @vielzeug/illusionist.\n---\n\n[[toc]]\n\n## Generating Test Fixtures\n\nBuild a batch of realistic records from a fixed seed. The same seed reproduces the same fixtures in every run. For a full Vitest setup, see the [Test Fixtures recipe](./examples/test-fixtures.md).\n\n```ts\nimport { createIllusion } from '@vielzeug/illusionist';\nimport { en } from '@vielzeug/illusionist/locales';\n\nconst illusion = createIllusion({ seed: 'fixtures-v1', locale: en });\n\nconst users = Array.from({ length: 10 }, () => ({\n name: illusion.person.fullName(),\n email: illusion.internet.email(),\n address: illusion.location.streetAddress(),\n city: illusion.location.city(),\n zip: illusion.location.zipCode(),\n}));\n```\n\n## Seeded Test Data for Snapshot Testing\n\nUse a named string seed so snapshot output is stable across CI runs. Each test creates its own instance to avoid cross-test random-state drift.\n\n```ts\nimport { createIllusion } from '@vielzeug/illusionist';\nimport { en } from '@vielzeug/illusionist/locales';\n\ntest('order receipt snapshot', () => {\n const illusion = createIllusion({ seed: 'order-receipt', locale: en });\n\n const order = {\n customer: illusion.person.fullName(),\n product: illusion.commerce.productName(),\n price: illusion.commerce.price({ min: 5, max: 50 }),\n date: illusion.date.recent({ days: 7 }),\n };\n\n expect(order).toMatchInlineSnapshot();\n});\n```\n\n## Locale-Specific Data (German)\n\nImport the German locale object to draw names, cities, and weekday labels from its dataset.\n\n```ts\nimport { createIllusion } from '@vielzeug/illusionist';\nimport { de } from '@vielzeug/illusionist/locales';\n\nconst illusion = createIllusion({ seed: 42, locale: de });\n\nillusion.person.fullName(); // 'Mathilda Scholz'\nillusion.location.city(); // 'Nürnberg'\nillusion.location.zipCode(); // '15268'\nillusion.date.weekday(); // 'Donnerstag'\nillusion.date.month(); // 'März'\n```\n\n## E-commerce Mock Data\n\nCombine `person`, `commerce`, and `location` to build a consistent customer-order-shipping record. `commerce.price()` returns coins `Money`, so you can format it directly.\n\n```ts\nimport { format } from '@vielzeug/coins';\nimport { createIllusion } from '@vielzeug/illusionist';\nimport { en } from '@vielzeug/illusionist/locales';\n\nconst illusion = createIllusion({ seed: 'ecommerce-mock', locale: en });\n\nconst order = {\n customer: {\n name: illusion.person.fullName(),\n email: illusion.internet.email(),\n },\n item: illusion.commerce.productName(),\n price: illusion.commerce.price({ min: 20, max: 200, currency: 'EUR' }),\n shipping: {\n address: illusion.location.streetAddress(),\n city: illusion.location.city(),\n zip: illusion.location.zipCode(),\n country: illusion.location.country(),\n },\n};\n\nconsole.log(format(order.price, { locale: 'de-DE' }));\n```\n\n## Database Seeding Pattern\n\nGenerate rows for a database seed script. Use a stable seed so the seed file is reproducible and reviewable.\n\n```ts\nimport { createIllusion } from '@vielzeug/illusionist';\nimport { en } from '@vielzeug/illusionist/locales';\n\nconst illusion = createIllusion({ seed: 'db-seed-2024', locale: en });\n\nconst products = Array.from({ length: 50 }, () => ({\n name: illusion.commerce.productName(),\n department: illusion.commerce.department(),\n price: illusion.commerce.price({ min: 1, max: 500 }),\n description: illusion.commerce.productDescription(),\n}));\n\nconst customers = Array.from({ length: 100 }, () => ({\n firstName: illusion.person.firstName(),\n lastName: illusion.person.lastName(),\n email: illusion.internet.email(),\n createdAt: illusion.date.past({ years: 2 }),\n}));\n```\n"
|
|
8
|
-
},
|
|
9
|
-
"examples": [
|
|
10
|
-
{
|
|
11
|
-
"id": "commerce-basic",
|
|
12
|
-
"code": "import { createIllusion } from '@vielzeug/illusionist'\nimport { en } from '@vielzeug/illusionist/locales'\n\nconst illusion = createIllusion({ seed: 12345, locale: en })\n\nconsole.log(illusion.commerce.productName())\nconsole.log(illusion.commerce.department())\nconsole.log(illusion.commerce.price({ min: 10, max: 50, currency: 'EUR' }))\nconsole.log(illusion.commerce.productDescription())",
|
|
13
|
-
"name": "commerce - Products, departments, and prices"
|
|
14
|
-
},
|
|
15
|
-
{
|
|
16
|
-
"id": "date-basic",
|
|
17
|
-
"code": "import { createIllusion } from '@vielzeug/illusionist'\nimport { en } from '@vielzeug/illusionist/locales'\n\nconst illusion = createIllusion({ seed: 12345, locale: en })\n\nconsole.log(illusion.date.past({ years: 2 }).toString())\nconsole.log(illusion.date.future({ years: 1 }).toString())\nconsole.log(illusion.date.recent({ days: 7 }).toString())\nconsole.log(illusion.date.birthday({ minAge: 25, maxAge: 35 }).toString())\nconsole.log(illusion.date.weekday())\nconsole.log(illusion.date.month())",
|
|
18
|
-
"name": "date - Past, future, birthdays, and locale labels"
|
|
19
|
-
},
|
|
20
|
-
{
|
|
21
|
-
"id": "determinism-basic",
|
|
22
|
-
"code": "import { createIllusion } from '@vielzeug/illusionist'\nimport { en } from '@vielzeug/illusionist/locales'\n\nconst a = createIllusion({ seed: 'test-fixture', locale: en })\nconst b = createIllusion({ seed: 'test-fixture', locale: en })\n\nconsole.log(a.person.fullName() === b.person.fullName())\nconsole.log(a.internet.email() === b.internet.email())",
|
|
23
|
-
"name": "seed - Deterministic output from the same seed"
|
|
24
|
-
},
|
|
25
|
-
{
|
|
26
|
-
"id": "finance-basic",
|
|
27
|
-
"code": "import { createIllusion } from '@vielzeug/illusionist'\nimport { en } from '@vielzeug/illusionist/locales'\n\nconst illusion = createIllusion({ seed: 12345, locale: en })\n\nconsole.log(illusion.finance.iban())\nconsole.log(illusion.finance.iban('DE'))\nconsole.log(illusion.finance.bic())\nconsole.log(illusion.finance.creditCardNumber('visa'))\nconsole.log(illusion.finance.creditCardCVV('amex'))\nconsole.log(illusion.finance.ethereumAddress())",
|
|
28
|
-
"name": "finance - IBANs, cards, BICs, and crypto addresses"
|
|
29
|
-
},
|
|
30
|
-
{
|
|
31
|
-
"id": "internet-basic",
|
|
32
|
-
"code": "import { createIllusion } from '@vielzeug/illusionist'\nimport { en } from '@vielzeug/illusionist/locales'\n\nconst illusion = createIllusion({ seed: 12345, locale: en })\n\nconsole.log(illusion.internet.email())\nconsole.log(illusion.internet.username())\nconsole.log(illusion.internet.url())\nconsole.log(illusion.internet.ip())\nconsole.log(illusion.internet.ip(6))\nconsole.log(illusion.internet.mac())",
|
|
33
|
-
"name": "internet - Emails, URLs, and network addresses"
|
|
34
|
-
},
|
|
35
|
-
{
|
|
36
|
-
"id": "locale-basic",
|
|
37
|
-
"code": "import { createIllusion } from '@vielzeug/illusionist'\nimport { en, de } from '@vielzeug/illusionist/locales'\n\nconst illusion = {\n en: createIllusion({ seed: 42, locale: en }),\n de: createIllusion({ seed: 42, locale: de })\n};\n\nconsole.log(illusion.en.person.fullName())\nconsole.log(illusion.de.person.fullName())\nconsole.log(illusion.en.location.city())\nconsole.log(illusion.de.location.city())\nconsole.log(illusion.en.date.month())\nconsole.log(illusion.de.date.month())",
|
|
38
|
-
"name": "locales - English and German side-by-side"
|
|
39
|
-
},
|
|
40
|
-
{
|
|
41
|
-
"id": "location-basic",
|
|
42
|
-
"code": "import { createIllusion } from '@vielzeug/illusionist'\nimport { en } from '@vielzeug/illusionist/locales'\n\nconst illusion = createIllusion({ seed: 12345, locale: en })\n\nconsole.log(illusion.location.city())\nconsole.log(illusion.location.streetAddress())\nconsole.log(illusion.location.zipCode())\nconsole.log(illusion.location.state())\nconsole.log(illusion.location.country())\nconsole.log(illusion.location.latitude())\nconsole.log(illusion.location.longitude())",
|
|
43
|
-
"name": "location - Addresses, regions, and coordinates"
|
|
44
|
-
},
|
|
45
|
-
{
|
|
46
|
-
"id": "person-basic",
|
|
47
|
-
"code": "import { createIllusion } from '@vielzeug/illusionist'\nimport { en } from '@vielzeug/illusionist/locales'\n\nconst illusion = createIllusion({ seed: 12345, locale: en })\n\nconsole.log(illusion.person.fullName())\nconsole.log(illusion.person.firstName())\nconsole.log(illusion.person.lastName())\nconsole.log(illusion.person.jobTitle())\nconsole.log(illusion.person.gender())",
|
|
48
|
-
"name": "person - Names, gender, and job titles"
|
|
49
|
-
},
|
|
50
|
-
{
|
|
51
|
-
"id": "system-basic",
|
|
52
|
-
"code": "import { createIllusion } from '@vielzeug/illusionist'\nimport { en } from '@vielzeug/illusionist/locales'\n\nconst illusion = createIllusion({ seed: 12345, locale: en })\n\nconsole.log(illusion.system.filePath())\nconsole.log(illusion.system.semver({ includePrerelease: true }))\nconsole.log(illusion.system.uuid())\nconsole.log(illusion.system.port())\nconsole.log(illusion.system.cron())\nconsole.log(illusion.system.process())",
|
|
53
|
-
"name": "system - Files, semver, UUIDs, ports, and cron"
|
|
54
|
-
}
|
|
55
|
-
],
|
|
56
|
-
"typeSignatures": {
|
|
57
|
-
"PriceOptions": "export type PriceOptions = {\n readonly min?: number;\n readonly max?: number;\n readonly currency?: 'USD' | 'EUR' | 'GBP';\n};",
|
|
58
|
-
"productAdjective": "export function productAdjective(ctx: IllusionistContext): string {\n return pick(COMMERCE_DATA.productAdjectives, ctx.source)!;\n}",
|
|
59
|
-
"productMaterial": "export function productMaterial(ctx: IllusionistContext): string {\n return pick(COMMERCE_DATA.productMaterials, ctx.source)!;\n}",
|
|
60
|
-
"productNoun": "export function productNoun(ctx: IllusionistContext): string {\n return pick(COMMERCE_DATA.productNouns, ctx.source)!;\n}",
|
|
61
|
-
"productName": "export function productName(ctx: IllusionistContext): string {\n return `${productAdjective(ctx)} ${productMaterial(ctx)} ${productNoun(ctx)}`;\n}",
|
|
62
|
-
"department": "export function department(ctx: IllusionistContext): string {\n return pick(COMMERCE_DATA.departments, ctx.source)!;\n}",
|
|
63
|
-
"price": "export function price(ctx: IllusionistContext, opts: PriceOptions = {}): Money {\n const min = opts.min ?? 0.01;\n const max = opts.max ?? 1000;\n const code = opts.currency ?? 'USD';\n const amount = floatFixed(min, max, 2, ctx.source);\n\n return money(amount.toFixed(2), CURRENCIES[code]);\n}",
|
|
64
|
-
"productDescription": "export function productDescription(ctx: IllusionistContext): string {\n const sentences = int(1, 2, ctx.source);\n const parts: string[] = [];\n\n for (let i = 0; i < sentences; i++) {\n const adjective = pick(COMMERCE_DATA.productAdjectives, ctx.source)!;\n const material = pick(COMMERCE_DATA.productMaterials, ctx.source)!;\n const noun = pick(COMMERCE_DATA.productNouns, ctx.source)!;\n const department = pick(COMMERCE_DATA.departments, ctx.source)!;\n\n parts.push(\n `The ${adjective.toLowerCase()} ${material.toLowerCase()} ${noun.toLowerCase()} is a great choice for your ${department.toLowerCase()} needs.`,\n );\n }\n\n return parts.join(' ');\n}",
|
|
65
|
-
"past": "export function past(ctx: IllusionistContext, options?: DateOptions): Temporal.ZonedDateTime {\n const ref = resolveRef(options?.ref);\n const years = options?.years ?? 1;\n const maxSeconds = years * 365 * 24 * 60 * 60;\n const minSeconds = 1;\n\n return ref.add({ seconds: -int(minSeconds, maxSeconds, ctx.source) });\n}",
|
|
66
|
-
"future": "export function future(ctx: IllusionistContext, options?: DateOptions): Temporal.ZonedDateTime {\n const ref = resolveRef(options?.ref);\n const years = options?.years ?? 1;\n const maxSeconds = years * 365 * 24 * 60 * 60;\n\n return ref.add({ seconds: int(1, maxSeconds, ctx.source) });\n}",
|
|
67
|
-
"recent": "export function recent(\n ctx: IllusionistContext,\n options?: { days?: number; ref?: Temporal.ZonedDateTime },\n): Temporal.ZonedDateTime {\n const ref = resolveRef(options?.ref);\n const days = options?.days ?? 1;\n const maxSeconds = days * 24 * 60 * 60;\n\n return ref.add({ seconds: -int(1, maxSeconds, ctx.source) });\n}",
|
|
68
|
-
"between": "export function between(\n ctx: IllusionistContext,\n from: Temporal.ZonedDateTime,\n to: Temporal.ZonedDateTime,\n): Temporal.ZonedDateTime {\n const fromNs = from.toInstant().epochNanoseconds;\n const toNs = to.toInstant().epochNanoseconds;\n\n if (fromNs > toNs) {\n return from;\n }\n\n const spanNs = toNs - fromNs;\n const spanSeconds = Number(spanNs / 1_000_000_000n);\n const offsetSeconds = Math.floor(ctx.source.next() * spanSeconds);\n\n return from.add({ seconds: offsetSeconds });\n}",
|
|
69
|
-
"birthday": "export function birthday(\n ctx: IllusionistContext,\n options?: { minAge?: number; maxAge?: number; ref?: Temporal.ZonedDateTime },\n): Temporal.PlainDate {\n const ref = resolveRef(options?.ref);\n const minAge = options?.minAge ?? 18;\n const maxAge = options?.maxAge ?? 80;\n const age = int(minAge, maxAge, ctx.source);\n const month = int(1, 12, ctx.source);\n const day = int(1, 28, ctx.source);\n\n return ref.toPlainDate().subtract({ years: age }).with({ day, month });\n}",
|
|
70
|
-
"weekday": "export function weekday(ctx: IllusionistContext, locale?: string): string {\n const days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];\n const loc = locale ?? ctx.locale.code;\n const localized =\n loc === 'de' ? ['Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag', 'Sonntag'] : days;\n\n return localized[int(0, 6, ctx.source)]!;\n}",
|
|
71
|
-
"month": "export function month(ctx: IllusionistContext, locale?: string): string {\n const months = [\n 'January',\n 'February',\n 'March',\n 'April',\n 'May',\n 'June',\n 'July',\n 'August',\n 'September',\n 'October',\n 'November',\n 'December',\n ];\n const loc = locale ?? ctx.locale.code;\n const localized =\n loc === 'de'\n ? [\n 'Januar',\n 'Februar',\n 'März',\n 'April',\n 'Mai',\n 'Juni',\n 'Juli',\n 'August',\n 'September',\n 'Oktober',\n 'November',\n 'Dezember',\n ]\n : months;\n\n return localized[int(0, 11, ctx.source)]!;\n}",
|
|
72
|
-
"IllusionistError": "export class IllusionistError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}",
|
|
73
|
-
"IllusionistSeedError": "export class IllusionistSeedError extends IllusionistError {}",
|
|
74
|
-
"IllusionistOptions": "export type { IllusionistOptions } from './types';\n\nexport type IllusionistOptions = {\n /** Numeric or string seed for deterministic output. Omit for cryptographic randomness. */\n seed?: number | string;\n /** Locale data for locale-aware categories. */\n locale: IllusionistLocale;\n};",
|
|
75
|
-
"Illusionist": "export type Illusionist = {\n readonly person: BoundApi<typeof personApi>;\n readonly internet: BoundApi<typeof internetApi>;\n readonly commerce: BoundApi<typeof commerceApi>;\n readonly date: BoundApi<typeof dateApi>;\n readonly finance: BoundApi<typeof financeApi>;\n readonly location: BoundApi<typeof locationApi>;\n readonly lorem: BoundApi<typeof loremApi>;\n readonly system: BoundApi<typeof systemApi>;\n\n /** The seed used to initialize this instance, or `undefined` for cryptographic randomness. */\n readonly seed: number | string | undefined;\n /** The active locale data. */\n readonly locale: IllusionistLocale;\n};",
|
|
76
|
-
"createIllusion": "export function createIllusion(options: IllusionistOptions): Illusionist {\n const { locale, seed } = options;\n const source: RandomSource = createSeed(seed);\n\n const ctx: IllusionistContext = { locale, source };\n\n const bind = <T extends Record<string, (ctx: IllusionistContext, ...args: never[]) => unknown>>(\n api: T,\n ): BoundApi<T> => {\n const bound = {} as Record<string, (...args: never[]) => unknown>;\n\n for (const [key, fn] of Object.entries(api)) {\n if (typeof fn === 'function') {\n bound[key] = (...args: never[]) => (fn as (ctx: IllusionistContext, ...args: never[]) => unknown)(ctx, ...args);\n }\n }\n\n return bound as unknown as BoundApi<T>;\n };\n\n return {\n commerce: bind(commerceApi),\n date: bind(dateApi),\n finance: bind(financeApi),\n internet: bind(internetApi),\n locale,\n location: bind(locationApi),\n lorem: bind(loremApi),\n person: bind(personApi),\n seed,\n system: bind(systemApi),\n };\n}",
|
|
77
|
-
"AmountOptions": "export type AmountOptions = {\n readonly min?: number;\n readonly max?: number;\n readonly currency?: 'USD' | 'EUR' | 'GBP';\n};",
|
|
78
|
-
"amount": "export function amount(ctx: IllusionistContext, opts: AmountOptions = {}): Money {\n const min = opts.min ?? 100;\n const max = opts.max ?? 10000;\n const code = opts.currency ?? 'USD';\n const value = floatFixed(min, max, 2, ctx.source);\n\n return money(value.toFixed(2), CURRENCIES[code]);\n}",
|
|
79
|
-
"iban": "export function iban(ctx: IllusionistContext, countryCode?: string): string {\n const country = (countryCode ?? pick(IBAN_COUNTRIES, ctx.source)!) as keyof typeof FINANCE_DATA.ibanLengths;\n\n if (!(country in FINANCE_DATA.ibanLengths)) {\n throw new RangeError(`iban: unsupported country code \"${countryCode}\". Supported: ${IBAN_COUNTRIES.join(', ')}`);\n }\n\n const totalLength = FINANCE_DATA.ibanLengths[country];\n const bbanLength = totalLength - 4;\n const bban = numericString(bbanLength, ctx.source);\n const checkDigits = ibanCheckDigits(country, bban);\n\n return `${country}${checkDigits}${bban}`;\n}",
|
|
80
|
-
"bic": "export function bic(ctx: IllusionistContext): string {\n const bankCode = letters(4, ctx);\n const country = letters(2, ctx);\n const location = alphanumeric(2, ctx.source).toUpperCase();\n const useBranch = int(0, 1, ctx.source) === 1;\n const branch = useBranch ? alphanumeric(3, ctx.source).toUpperCase() : '';\n\n return `${bankCode}${country}${location}${branch}`;\n}",
|
|
81
|
-
"creditCardNumber": "export function creditCardNumber(ctx: IllusionistContext, type?: CreditCardType): string {\n const cardType = type ?? pick(CREDIT_CARD_TYPES, ctx.source)!;\n const iin = pick(FINANCE_DATA.creditCardIins[cardType], ctx.source)!;\n const totalLength = cardType === 'amex' ? 15 : 16;\n const partial = iin + numericString(totalLength - iin.length - 1, ctx.source);\n const checkDigit = luhnCheckDigit(partial);\n\n return `${partial}${checkDigit}`;\n}",
|
|
82
|
-
"creditCardCVV": "export function creditCardCVV(ctx: IllusionistContext, type?: CreditCardType): string {\n const cardType = type ?? pick(CREDIT_CARD_TYPES, ctx.source)!;\n const length = cardType === 'amex' ? 4 : 3;\n\n return numericString(length, ctx.source);\n}",
|
|
83
|
-
"bitcoinAddress": "export function bitcoinAddress(ctx: IllusionistContext): string {\n const prefix = pick(['1', '3', 'bc1'], ctx.source)!;\n const suffixLength = int(25, 34, ctx.source);\n\n return `${prefix}${base58String(suffixLength, ctx.source)}`;\n}",
|
|
84
|
-
"ethereumAddress": "export function ethereumAddress(ctx: IllusionistContext): string {\n return `0x${hexString(40, ctx.source)}`;\n}",
|
|
85
|
-
"transactionType": "export function transactionType(ctx: IllusionistContext): string {\n return pick(FINANCE_DATA.transactionTypes, ctx.source)!;\n}",
|
|
86
|
-
"bank": "export function bank(ctx: IllusionistContext): string {\n return pick(FINANCE_DATA.banks, ctx.source)!;\n}",
|
|
87
|
-
"email": "export function email(ctx: IllusionistContext): string {\n const first = (\n pick(ctx.locale.person.firstNameFemale, ctx.source) ??\n pick(ctx.locale.person.firstNameMale, ctx.source) ??\n 'user'\n ).toLowerCase();\n const last = (pick(ctx.locale.person.lastName, ctx.source) ?? 'name').toLowerCase();\n const domain = pick(INTERNET_DATA.domains, ctx.source) ?? 'example';\n const tld = pick(INTERNET_DATA.tlds, ctx.source) ?? 'com';\n return `${first}.${last}@${domain}.${tld}`;\n}",
|
|
88
|
-
"username": "export function username(ctx: IllusionistContext): string {\n if (int(0, 1, ctx.source) === 0) {\n return alphanumeric(int(6, 12, ctx.source), ctx.source);\n }\n const first = (\n pick(ctx.locale.person.firstNameFemale, ctx.source) ??\n pick(ctx.locale.person.firstNameMale, ctx.source) ??\n 'user'\n ).toLowerCase();\n const last = (pick(ctx.locale.person.lastName, ctx.source) ?? 'name').toLowerCase();\n return `${first}.${last}`;\n}",
|
|
89
|
-
"PasswordOptions": "export type PasswordOptions = {\n /** Password length. Defaults to `12`. */\n length?: number;\n /** When `true`, builds a memorable password from name fragments and digits. */\n memorable?: boolean;\n};",
|
|
90
|
-
"password": "export function password(ctx: IllusionistContext, opts: PasswordOptions = {}): string {\n const length = opts.length ?? 12;\n\n if (opts.memorable) {\n const first = (\n pick(ctx.locale.person.firstNameFemale, ctx.source) ??\n pick(ctx.locale.person.firstNameMale, ctx.source) ??\n 'user'\n ).toLowerCase();\n const last = (pick(ctx.locale.person.lastName, ctx.source) ?? 'name').toLowerCase();\n const num = String(int(10, 99, ctx.source));\n const special = pick(SPECIAL_CHARS.split(''), ctx.source) ?? '!';\n const base = `${first}${last}${num}${special}`;\n if (base.length <= length) return base + alphanumeric(length - base.length, ctx.source);\n // Truncation would cut the special char/number: put them first, then fill from the name.\n const essential = `${num}${special}`;\n const remaining = length - essential.length;\n const namePart = remaining > 0 ? (first + last).slice(0, remaining) : '';\n const result = essential + namePart;\n\n return result.length < length ? result + alphanumeric(length - result.length, ctx.source) : result.slice(0, length);\n }\n\n const upper = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';\n const lower = 'abcdefghijklmnopqrstuvwxyz';\n const digits = '0123456789';\n const pools = [upper, lower, digits, SPECIAL_CHARS];\n\n // Guarantee at least one char from each pool, then fill the rest randomly.\n const chars: string[] = [];\n for (const pool of pools) {\n chars.push(pick(pool.split(''), ctx.source)!);\n }\n const all = upper + lower + digits + SPECIAL_CHARS;\n while (chars.length < length) {\n chars.push(pick(all.split(''), ctx.source)!);\n }\n\n // Shuffle via Fisher-Yates using ctx.source.\n for (let i = chars.length - 1; i > 0; i--) {\n const j = int(0, i, ctx.source);\n [chars[i], chars[j]] = [chars[j]!, chars[i]!];\n }\n\n return chars.slice(0, length).join('');\n}",
|
|
91
|
-
"url": "export function url(ctx: IllusionistContext): string {\n const protocol = pick(INTERNET_DATA.protocols, ctx.source) ?? 'https';\n const sub = pick(['www', 'api', 'app', 'mail', 'static', 'cdn'], ctx.source) ?? 'www';\n const domain = pick(INTERNET_DATA.domains, ctx.source) ?? 'example';\n const tld = pick(INTERNET_DATA.tlds, ctx.source) ?? 'com';\n const host = `${sub}.${domain}.${tld}`;\n\n const segmentCount = int(1, 4, ctx.source);\n const segments: string[] = [];\n for (let i = 0; i < segmentCount; i++) {\n const word = pick(URL_PATH_WORDS, ctx.source) ?? 'api';\n // Occasionally append a numeric or short alphanumeric suffix to a segment.\n if (int(0, 2, ctx.source) === 0) {\n segments.push(`${word}-${alphanumeric(int(2, 5), ctx.source).toLowerCase()}`);\n } else {\n segments.push(word);\n }\n }\n\n return `${protocol}://${host}/${segments.join('/')}`;\n}",
|
|
92
|
-
"domainName": "export function domainName(ctx: IllusionistContext): string {\n const domain = pick(INTERNET_DATA.domains, ctx.source) ?? 'example';\n const tld = pick(INTERNET_DATA.tlds, ctx.source) ?? 'com';\n return `${domain}.${tld}`;\n}",
|
|
93
|
-
"ip": "export function ip(ctx: IllusionistContext, version: 4 | 6 = 4): string {\n if (version === 6) {\n const groups: string[] = [];\n for (let i = 0; i < 8; i++) {\n groups.push(hexString(4, ctx.source));\n }\n return groups.join(':');\n }\n const octets: number[] = [];\n for (let i = 0; i < 4; i++) {\n octets.push(int(0, 255, ctx.source));\n }\n return octets.join('.');\n}",
|
|
94
|
-
"mac": "export function mac(ctx: IllusionistContext): string {\n const parts: string[] = [];\n for (let i = 0; i < 6; i++) {\n parts.push(hexString(2, ctx.source));\n }\n return parts.join(':');\n}",
|
|
95
|
-
"userAgent": "export function userAgent(ctx: IllusionistContext): string {\n return pick(INTERNET_DATA.userAgents, ctx.source) ?? INTERNET_DATA.userAgents[0]!;\n}",
|
|
96
|
-
"httpMethod": "export function httpMethod(ctx: IllusionistContext): string {\n return pick(INTERNET_DATA.httpMethods, ctx.source) ?? 'GET';\n}",
|
|
97
|
-
"statusCode": "export function statusCode(ctx: IllusionistContext): number {\n return pick(INTERNET_DATA.statusCodes, ctx.source) ?? 200;\n}",
|
|
98
|
-
"mimeType": "export function mimeType(ctx: IllusionistContext): string {\n return pick(INTERNET_DATA.mimeTypes, ctx.source) ?? 'text/plain';\n}",
|
|
99
|
-
"Coordinate": "export type Coordinate = {\n lat: number;\n lng: number;\n};",
|
|
100
|
-
"city": "export function city(ctx: IllusionistContext): string {\n return pick(data(ctx).cities, ctx.source)!;\n}",
|
|
101
|
-
"street": "export function street(ctx: IllusionistContext): string {\n return pick(data(ctx).streets, ctx.source)!;\n}",
|
|
102
|
-
"streetAddress": "export function streetAddress(ctx: IllusionistContext): string {\n const houseNumber = Math.floor(float(1, 1000, ctx.source));\n return `${houseNumber} ${street(ctx)}`;\n}",
|
|
103
|
-
"zipCode": "export function zipCode(ctx: IllusionistContext): string {\n const pattern = data(ctx).zipPattern;\n\n return pattern.replace(/#/g, () => String(Math.floor(nextFloat(ctx.source) * 10)));\n}",
|
|
104
|
-
"state": "export function state(ctx: IllusionistContext): string {\n return pick(data(ctx).states, ctx.source)!;\n}",
|
|
105
|
-
"country": "export function country(ctx: IllusionistContext): string {\n return pick(data(ctx).countries, ctx.source)!;\n}",
|
|
106
|
-
"latitude": "export function latitude(ctx: IllusionistContext): number {\n return float(-90, 90, ctx.source);\n}",
|
|
107
|
-
"longitude": "export function longitude(ctx: IllusionistContext): number {\n return float(-180, 180, ctx.source);\n}",
|
|
108
|
-
"nearbyGPSCoordinate": "export function nearbyGPSCoordinate(ctx: IllusionistContext, ref?: Coordinate): Coordinate {\n const base = ref ?? { lat: latitude(ctx), lng: longitude(ctx) };\n return {\n lat: float(base.lat - 1, base.lat + 1, ctx.source),\n lng: float(base.lng - 1, base.lng + 1, ctx.source),\n };\n}",
|
|
109
|
-
"word": "export function word(ctx: IllusionistContext): string {\n return pick(LOREM_DATA.words, ctx.source)!;\n}",
|
|
110
|
-
"words": "export function words(ctx: IllusionistContext, count = 3): string {\n const out: string[] = [];\n for (let i = 0; i < count; i++) {\n out.push(word(ctx));\n }\n return out.join(' ');\n}",
|
|
111
|
-
"sentence": "export function sentence(ctx: IllusionistContext, wordCount?: number): string {\n const count = wordCount ?? Math.floor(float(6, 13, ctx.source));\n const text = words(ctx, count);\n return `${text.charAt(0).toUpperCase()}${text.slice(1)}.`;\n}",
|
|
112
|
-
"sentences": "export function sentences(ctx: IllusionistContext, count = 3): string {\n const out: string[] = [];\n for (let i = 0; i < count; i++) {\n out.push(sentence(ctx));\n }\n return out.join(' ');\n}",
|
|
113
|
-
"paragraph": "export function paragraph(ctx: IllusionistContext, sentenceCount?: number): string {\n const count = sentenceCount ?? Math.floor(float(3, 8, ctx.source));\n return sentences(ctx, count);\n}",
|
|
114
|
-
"paragraphs": "export function paragraphs(ctx: IllusionistContext, count = 3): string {\n const out: string[] = [];\n for (let i = 0; i < count; i++) {\n out.push(paragraph(ctx));\n }\n return out.join('\\n');\n}",
|
|
115
|
-
"slug": "export function slug(ctx: IllusionistContext, wordCount = 3): string {\n const out: string[] = [];\n for (let i = 0; i < wordCount; i++) {\n out.push(word(ctx));\n }\n return out.join('-');\n}",
|
|
116
|
-
"lines": "export function lines(ctx: IllusionistContext, count = 5): string {\n const out: string[] = [];\n for (let i = 0; i < count; i++) {\n out.push(sentence(ctx));\n }\n return out.join('\\n');\n}",
|
|
117
|
-
"firstName": "export function firstName(ctx: IllusionistContext): string {\n const d = data(ctx);\n const pool = boolean(ctx.source) ? d.firstNameMale : d.firstNameFemale;\n return pick(pool, ctx.source)!;\n}",
|
|
118
|
-
"lastName": "export function lastName(ctx: IllusionistContext): string {\n return pick(data(ctx).lastName, ctx.source)!;\n}",
|
|
119
|
-
"fullName": "export function fullName(ctx: IllusionistContext): string {\n return `${firstName(ctx)} ${lastName(ctx)}`;\n}",
|
|
120
|
-
"gender": "export function gender(ctx: IllusionistContext): string {\n return pick(data(ctx).gender, ctx.source)!;\n}",
|
|
121
|
-
"prefix": "export function prefix(ctx: IllusionistContext): string {\n return pick(data(ctx).prefix, ctx.source)!;\n}",
|
|
122
|
-
"suffix": "export function suffix(ctx: IllusionistContext): string {\n const d = data(ctx);\n if (d.suffix.length === 0) return '';\n return pick(d.suffix, ctx.source)!;\n}",
|
|
123
|
-
"jobTitle": "export function jobTitle(ctx: IllusionistContext): string {\n const d = data(ctx);\n return `${pick(d.jobAreas, ctx.source)!} ${pick(d.jobTypes, ctx.source)!}`;\n}",
|
|
124
|
-
"createSeed": "export function createSeed(seed?: number | string): RandomSource {\n if (seed == null) return cryptoSource();\n\n if (typeof seed === 'number') {\n if (!Number.isFinite(seed)) throw new IllusionistSeedError(`createSeed: numeric seed must be finite, got ${seed}`);\n\n return mulberry32(Math.trunc(seed));\n }\n\n const hashed = JSON.stringify(seed);\n\n // FNV-1a-ish fold from the hash string into a 32-bit integer.\n let state = 0;\n\n for (let i = 0; i < hashed.length; i++) {\n state = (Math.imul(state, 31) + hashed.charCodeAt(i)) >>> 0;\n }\n\n return mulberry32(state);\n}",
|
|
125
|
-
"mulberry32": "export function mulberry32(seed: number): RandomSource {\n let state = seed >>> 0;\n\n return {\n next(): number {\n state = (state + 0x6d2b79f5) >>> 0;\n let t = state;\n\n t = Math.imul(t ^ (t >>> 15), t | 1);\n t ^= t + Math.imul(t ^ (t >>> 7), t | 61);\n\n return ((t ^ (t >>> 14)) >>> 0) / 4294967296;\n },\n };\n}",
|
|
126
|
-
"RandomSource": "export type { RandomSource };",
|
|
127
|
-
"PersonLocaleData": "export type PersonLocaleData = {\n readonly firstNameFemale: readonly string[];\n readonly firstNameMale: readonly string[];\n readonly gender: readonly string[];\n readonly jobAreas: readonly string[];\n readonly jobTypes: readonly string[];\n readonly lastName: readonly string[];\n readonly prefix: readonly string[];\n readonly suffix: readonly string[];\n};",
|
|
128
|
-
"LocationLocaleData": "export type LocationLocaleData = {\n readonly cities: readonly string[];\n readonly countries: readonly string[];\n readonly states: readonly string[];\n readonly streets: readonly string[];\n readonly zipPattern: string;\n};",
|
|
129
|
-
"IllusionistLocale": "export type IllusionistLocale = {\n readonly code: string;\n readonly person: PersonLocaleData;\n readonly location: LocationLocaleData;\n};",
|
|
130
|
-
"IllusionistContext": "export type IllusionistContext = {\n readonly source: RandomSource;\n readonly locale: IllusionistLocale;\n};"
|
|
131
|
-
}
|
|
132
|
-
}
|