@vielzeug/codex 26.11.24 → 26.11.25
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,270 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"apiSource": "export * from './array/chunk';\nexport * from './array/filterMap';\nexport * from './array/groupBy';\nexport * from './array/indexBy';\nexport * from './array/paginate';\nexport * from './array/partition';\nexport * from './array/sort';\nexport * from './array/uniq';\nexport * from './async/abortable';\nexport * from './async/abortError';\nexport * from './async/attempt';\nexport * from './async/backoff';\nexport * from './async/parallel';\nexport * from './async/retry';\nexport * from './async/sleep';\nexport * from './async/taskPool';\nexport * from './async/timer';\nexport * from './async/waitFor';\nexport * from './cache/cache';\nexport * from './cache/memo';\nexport * from './encoding/base64url';\nexport * from './encoding/compression';\nexport * from './encoding/share-code';\nexport * from './errors';\nexport * from './function/debounce';\nexport * from './function/once';\nexport * from './function/pipe';\nexport * from './function/tapper';\nexport * from './function/throttle';\nexport * from './guards/combinators';\nexport * from './guards/isDefined';\nexport * from './guards/isEqual';\nexport * from './guards/isNil';\nexport * from './guards/isPlainObject';\nexport * from './math/allocate';\nexport * from './math/clamp';\nexport * from './math/range';\nexport * from './object/getPath';\nexport * from './object/hash';\nexport * from './object/omit';\nexport * from './object/pick';\nexport * from './random/random';\nexport * from './random/source';\nexport * from './string/camelCase';\nexport * from './types';\n",
|
|
3
|
-
"docs": {
|
|
4
|
-
"index": "---\ntitle: 'Arsenal: Utility library for TypeScript'\ndescription: Tree-shakeable TypeScript utilities with focused category entry points for arrays, async work, caching, objects, strings, math, and guards.\npackage: arsenal\ncategory: utilities\nkeywords: [utility, array, pagination, sorting, string, object, math, async, cache]\nexports: [paginate, sort, retry, taskPool, cache]\nrelated: [tempo, sourcerer, spell, coins]\nenvironments: [browser, node, ssr, deno]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"arsenal\" />\n\n## Why Arsenal?\n\nArsenal provides typed, zero-dependency utilities that reduce repeated application code: collection transforms, numeric operations, retry and cancellation, caching, safe-path traversal, and deterministic serialization. The root stays curated while category entry points expose the broader toolkit. Exact platform aliases remain excluded.\n\n```ts\n// Before\nconst users = JSON.parse(raw).filter((user) => user.name.includes(query));\n\n// After\nimport { fuzzyFilter } from '@vielzeug/arsenal/array';\nimport { tryParseJson } from '@vielzeug/arsenal/object';\n\nconst parsed = tryParseJson(raw);\nconst users = parsed.ok ? fuzzyFilter(parsed.value as User[], query, { select: (user) => user.name }) : [];\n```\n\n| Feature | Arsenal | lodash-es | Remeda |\n| ------------------------- | --------------------------------------------- | -------------------------------------------- | -------------------------------------------- |\n| Bundle size | <PackageInfo package=\"arsenal\" type=\"size\" /> | ~72 kB | ~18 kB |\n| Typed root utilities | <ore-icon name=\"check\" size=\"16\"></ore-icon> | Partial | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n| Category entry points | <ore-icon name=\"check\" size=\"16\"></ore-icon> | Partial | Partial |\n| Async task pool and cache | <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 Arsenal when** you need one typed utility dependency with focused subpaths for specialized behavior.\n\n**Consider narrower alternatives when** you need only platform APIs or a small functional subset.\n\n</div>\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/arsenal\n```\n\n```sh [npm]\nnpm install @vielzeug/arsenal\n```\n\n```sh [yarn]\nyarn add @vielzeug/arsenal\n```\n\n:::\n\n## Quick Start\n\n```ts\nimport { groupBy, retry } from '@vielzeug/arsenal';\nimport { cache } from '@vielzeug/arsenal/cache';\nimport { taskPool } from '@vielzeug/arsenal/async';\n\nconst byRole = groupBy([{ role: 'admin' }, { role: 'user' }], (user) => user.role);\n\nconst pool = taskPool({ concurrency: 2 });\nconst health = await pool.run((signal) =>\n retry(() => fetch('/health', { signal }).then((response) => response.json())),\n);\n\nconst responses = cache<string, unknown>({ ttlMs: 60_000 });\nconst profile = await responses.getOrLoad('/profile', () => fetch('/profile').then((response) => response.json()));\n\npool.dispose();\nconsole.log(byRole, health, profile);\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- **`retry`**: retry async work with cancellation support from package root\n- **`taskPool`**: bounded, disposable concurrent work from `/async`\n- **`cache`**: identity-keyed TTL cache with async load deduplication from `/cache`\n- **`fuzzyFilter`**: explicit-field fuzzy filtering from `/array`\n- **`tryParseJson`**: preserve JSON syntax failures from `/object`\n- **`allocate`**: lossless proportional distribution from `/math`\n- **`chunk`, `zip`, `compact`**: typed collection transforms from `/array`\n- **`paginate`**: one page plus its totals from an in-memory list, in a one- or zero-based page base\n- **`sort`**: selector, `{ key: direction }`, or ordered grid criteria from one entry point\n- **`range`, `average`, `median`**: common numeric operations from `/math`\n- **`assert`, `tap`**: typed control-flow helpers from `/function`\n- **`isEqual`**: structural equality from package root\n- **`hash`**: deterministic serialization for stable cache keys from `/object`\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- [Spell](/spell/): validate `unknown` JSON data after `tryParseJson`.\n- [Vault](/vault/): persistent storage; Arsenal cache is in-memory only.\n- [Tempo](/tempo/): date/time utilities kept outside Arsenal.\n- [Coins](/coins/): money formatting and currency conversion.\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
|
|
5
|
-
"api": "---\ntitle: 'Arsenal: API Reference'\ndescription: Reference for Arsenal root utilities and category entry points.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution | Common gotcha |\n| ----------------------------------- | ---------------------------------------------------------- | --------- | --------------------------------------------------------------------------- |\n| `groupBy` | Group values by key (prototype-pollution guarded) | Sync | Root export |\n| `chunk` / `zip` / `compact` | Typed collection transforms | Sync | Available from `/array` |\n| `paginate` | Cut one page and its totals out of a list | Sync | Pages past the last return empty `items`, unclamped |\n| `sort` | Sort by a selector, keyed fields, or ordered path criteria | Sync | Criteria paths are resolved safely; mixed value types throw |\n| `range` / `average` / `median` | Numeric generation and aggregation | Sync | Available from `/math` |\n| `assert` | Assert and narrow a condition | Sync | Available from `/function` |\n| `retry` | Retry async work | Async | Rethrows final error |\n| `taskPool` | Bound concurrent tasks | Async | Available from `/async` |\n| `timer` | Re-armable single-slot timeout | Async | Available from `/async` |\n| `cache` | In-memory identity-keyed cache | Async | Available from `/cache` |\n| `fuzzyFilter` | Filter string or selected object fields | Sync | Object collections require `select` |\n| `fuzzyScore` | Rank string or selected object fields | Sync | Object collections require `select` |\n| `tryParseJson` | Preserve JSON syntax result | Sync | Returns `unknown` on success |\n| `getPath` | Optional object lookup (safe-path guarded) | Sync | Available from `/object` |\n| `allocate` | Lossless proportional distribution | Sync | Available from `/math` |\n| `isEqual` | Structural equality | Sync | Root export |\n| `hash` | Deterministic serialization for cache keys | Sync | Available from `/object` |\n| `compressBytes` / `decompressBytes` | Native byte compression with bounded decompression | Async | Requires native compression streams; decoding requires an output limit |\n| `pack` / `unpack` | Versioned, compressed, URL-safe payload envelope | Async | Both sides bound the payload with `maxBytes`; compression falls back to raw |\n\n## Package Entry Points\n\n| Import | Purpose |\n| ---------------------------- | ----------------------------------------------------------------------- |\n| `@vielzeug/arsenal` | Curated common utilities |\n| `@vielzeug/arsenal/array` | Immutable transforms, pagination, set operations, sorting, fuzzy search |\n| `@vielzeug/arsenal/async` | Retry, cancellation, task pool, timing |\n| `@vielzeug/arsenal/cache` | In-memory cache and memoization |\n| `@vielzeug/arsenal/encoding` | Base64url and native byte compression |\n| `@vielzeug/arsenal/function` | Assertions, composition, timing, teardown |\n| `@vielzeug/arsenal/guards` | Type guards, predicate combinators, equality guards |\n| `@vielzeug/arsenal/math` | Ranges, aggregation, statistics, interpolation, exact allocation |\n| `@vielzeug/arsenal/object` | Paths, transforms, hash, JSON parse result |\n| `@vielzeug/arsenal/random` | Cryptographic-entropy selection and shuffle |\n| `@vielzeug/arsenal/string` | Unicode-aware case transforms and similarity |\n\n## Array\n\n### Typed transforms\n\n```ts\nchunk<T>(input: readonly T[], size?: number): T[][]\ncompact<T>(array: readonly T[]): Array<Exclude<T, false | '' | 0 | 0n | null | undefined>>\nfirst<T>(array: readonly T[], fallback?: T): T | undefined\nlast<T>(array: readonly T[], fallback?: T): T | undefined\nreplace<T>(array: readonly T[], predicate: (value: T) => boolean, value: T): T[]\nrotate<T>(array: readonly T[], positions: number, options?: { wrap?: boolean }): T[]\nzip(...arrays): Array<tuple>\nunzip(rows): tupleOfArrays\n```\n\n`take`, `takeLast`, `drop`, and `dropLast` return new arrays and normalize negative counts to zero. Set operations accept optional selectors for object identity.\n\n### paginate\n\n```ts\npaginate<T>(items: readonly T[], options?: PaginateOptions): PageEnvelope<T>\n```\n\nCuts one page out of an in-memory list and returns the items with the arithmetic that produced them. `pageOffset` selects the caller's page base: `1` (default) for one-based paging, `0` for zero-based servers such as Spring. The default `page` is the first page in that base, and the default `pageSize` is `20`. `totalPages` is at least 1, even for an empty list, so `page < totalPages` never underflows. Pages past the last yield empty `items` and echo the requested page rather than clamping it. Throws `TypeError` for a non-array and `RangeError` when `page` is not an integer in the selected base or `pageSize` is not a positive integer.\n\n| Option | Type | Default | Description |\n| ------------ | -------- | --------------------------------- | ------------------------------------------------------------------------ |\n| `page` | `number` | First page in `pageOffset`'s base | Requested page; must be an integer greater than or equal to `pageOffset` |\n| `pageSize` | `number` | `20` | Number of items per page; must be a positive integer |\n| `pageOffset` | `0 \\| 1` | `1` | Page-number base: `0` for zero-based callers, `1` for one-based callers |\n\n```ts\nimport { paginate } from '@vielzeug/arsenal/array';\n\npaginate([1, 2, 3, 4, 5], { page: 2, pageSize: 2 });\n// { items: [3, 4], page: 2, pageSize: 2, totalItems: 5, totalPages: 3 }\n\nconst springPage = 0;\npaginate([1, 2, 3, 4, 5], { page: springPage, pageOffset: 0 });\n// { items: [1, 2, 3, 4, 5], page: 0, pageSize: 20, totalItems: 5, totalPages: 1 }\n```\n\nThe envelope is server-neutral: it models no HTTP dialect, so adapters map their response onto it and map it back out.\n\n### sort\n\n```ts\nsort<T>(array: readonly T[], selector: (item: T) => unknown, direction?: SortDirection): T[];\nsort<T>(array: readonly T[], selectors: SortSelectors<T>): T[];\nsort<T>(array: readonly T[], criteria: ReadonlyArray<SortCriterion<T>>): T[];\n```\n\nThree forms, one entry point. The selector form sorts by one extracted value; the selectors form accepts an object mapping property keys to directions; the criteria form sorts by an ordered list of paths, which is the shape a data grid hands over when its sortable columns are runtime strings.\n\n```ts\nimport { sort } from '@vielzeug/arsenal/array';\n\nconst users = [\n { name: 'Ada', age: 41 },\n { name: 'Grace', age: 30 },\n];\nsort(users, (user) => user.name);\nsort(users, { name: 'asc', age: 'desc' });\n\nconst rows = [\n { address: { city: 'Berlin' }, age: 41 },\n { address: { city: 'Aachen' }, age: 30 },\n];\nsort(rows, [{ key: 'address.city' }, { key: 'age', direction: 'desc' }]);\n```\n\nCriteria paths are resolved with `getPath`, so dotted and bracketed paths (`'address.city'`, `'tags[0]'`) work and prototype-access segments are refused. The first criterion that differs wins and earlier ties keep their input order. Ordering is delegated to `compare`, so a column that mixes value types (a number beside a string) throws a `TypeError` instead of guessing an order.\n\n### fuzzyFilter / fuzzyScore\n\n```ts\nfuzzyFilter(strings: readonly string[], query: string, options?: FuzzyOptions): string[]\nfuzzyFilter<T>(items: readonly T[], query: string, options: FuzzySelection<T>): T[]\nfuzzyScore(strings: readonly string[], query: string, options?: FuzzyOptions): ScoredResult<string>[]\nfuzzyScore<T>(items: readonly T[], query: string, options: FuzzySelection<T>): ScoredResult<T>[]\n```\n\n`fuzzyFilter` preserves input order. `fuzzyScore` orders results by descending score.\n\n```ts\nimport { fuzzyFilter } from '@vielzeug/arsenal/array';\n\nconst users = [{ email: 'alice@example.com', name: 'Alice' }];\nconst matches = fuzzyFilter(users, 'alice', { select: (user) => [user.name, user.email] });\n```\n\n---\n\n## Async\n\n### taskPool\n\n```ts\ninterface TaskPool {\n run<T>(task: (signal: AbortSignal) => Promise<T>): Promise<T>;\n idle(): Promise<void>;\n dispose(reason?: unknown): void;\n readonly active: number;\n readonly pending: number;\n readonly disposed: boolean;\n readonly disposalSignal: AbortSignal;\n}\n\ntaskPool(options?: { concurrency?: number }): TaskPool\n```\n\n`dispose()` aborts running cooperative tasks and rejects pending tasks.\n\n```ts\nimport { taskPool } from '@vielzeug/arsenal/async';\n\nconst pool = taskPool({ concurrency: 2 });\nconst user = await pool.run((signal) => fetch('/user', { signal }).then((response) => response.json()));\npool.dispose();\n```\n\n### timer\n\n```ts\ninterface Timer {\n arm(ms: number): void;\n cancel(): void;\n readonly pending: boolean;\n}\n\ntimer(fn: () => void): Timer\n```\n\nA single-slot, re-armable timeout. `arm()` cancels any pending run first, so at most one run is ever scheduled. `pending` is already `false` inside the callback, which may re-arm the timer.\n\n```ts\nimport { timer } from '@vielzeug/arsenal/async';\n\nconst idleFlush = timer(() => flush());\nidleFlush.arm(500); // debounced: re-arming restarts the delay\nidleFlush.cancel();\n```\n\n---\n\n## Cache\n\n### cache\n\n```ts\ninterface Cache<K, T> {\n entries(): ReadonlyArray<readonly [K, T]>;\n get(key: K): T | undefined;\n set(key: K, value: T, options?: { ttlMs?: number }): void;\n getOrLoad(key: K, load: () => Promise<T>): Promise<T>;\n delete(key: K): boolean;\n clear(): void;\n readonly size: number;\n}\n\ncache<K, T>(options?: CacheOptions): Cache<K, T>\n```\n\nKeys use native `Map` identity. Expiry is lazy, evaluated by `get`, `getOrLoad`, `set`, and `entries`. `entries()` trims expired values and returns a new insertion-ordered snapshot without exposing internal storage. The `size` getter does not evict expired entries.\n\n```ts\nimport { cache } from '@vielzeug/arsenal/cache';\n\nconst profiles = cache<string, Profile>({ ttlMs: 60_000 });\nconst profile = await profiles.getOrLoad('me', loadProfile);\n```\n\n---\n\n## Encoding\n\nURL-safe base64 (`base64url`) codecs without `btoa`/`Buffer`, so the same code runs in browsers, workers, and Node.\n\n```ts\nimport { base64UrlToBytes, base64UrlToText, bytesToBase64Url, textToBase64Url, utf8Bytes } from '@vielzeug/arsenal';\n\ntextToBase64Url('{\"build\":\"hero\"}'); // never contains '+', '/', or '='\nbase64UrlToText(textToBase64Url('League of Legends')); // round-trips any UTF-8 text\nbytesToBase64Url(Uint8Array.from([0, 1, 250])); // byte-level codec for binary payloads\nbase64UrlToBytes(code); // throws on characters outside the alphabet\nutf8Bytes('Hunter äöü'); // 11: byte length of a UTF-8 string\n```\n\n### compressBytes\n\n```ts\ncompressBytes(bytes: Uint8Array, options?: CompressionOptions): Promise<Uint8Array>\n```\n\nCompresses bytes using the native `CompressionStream` API without modifying the input.\n\n| Option | Type | Default | Meaning |\n| -------- | ------------------- | --------------- | --------------------------------------------------------- |\n| `format` | `CompressionFormat` | `'deflate-raw'` | Compression format; the receiver must use the same format |\n\n**Returns:** Compressed bytes. Rejects with `ArsenalSerializationError` when the format or capability is unavailable, or stream processing fails. Does not fall back to another format.\n\n**Example:** Encode compressed bytes for a URL.\n\n```ts\nimport { bytesToBase64Url, compressBytes } from '@vielzeug/arsenal';\n\nconst bytes = new TextEncoder().encode(JSON.stringify({ name: 'Hunters' }));\nconst code = bytesToBase64Url(await compressBytes(bytes));\n```\n\n---\n\n### decompressBytes\n\n```ts\ndecompressBytes(bytes: Uint8Array, options: DecompressionOptions): Promise<Uint8Array>\n```\n\nDecompresses bytes using the native `DecompressionStream` API, enforcing the output limit while reading chunks.\n\n| Option | Type | Default | Meaning |\n| ---------------- | ------------------- | --------------- | ------------------------------------------------------ |\n| `format` | `CompressionFormat` | `'deflate-raw'` | Format used by the sender |\n| `maxOutputBytes` | `number` | Required | Non-negative safe integer; maximum decoded byte length |\n\n**Returns:** Decompressed bytes. Rejects with `ArsenalSerializationError` for invalid limits, corrupt or truncated data, unavailable formats/capabilities, or output exceeding the limit. A failed stream is canceled and its reader lock released. Bound encoded input separately before calling this function.\n\n**Example:** Decode text within an application-defined byte limit.\n\n```ts\nimport { compressBytes, decompressBytes } from '@vielzeug/arsenal';\n\nconst compressed = await compressBytes(new TextEncoder().encode('Hunters'));\nconst bytes = await decompressBytes(compressed, { maxOutputBytes: 8192 });\nconst text = new TextDecoder('utf-8', { fatal: true }).decode(bytes);\n```\n\n---\n\n### pack\n\n```ts\npack(payload: unknown, options: ShareCodeOptions): Promise<string>\n```\n\nSerializes `payload` as JSON and encodes it into a compact share code: `prefix` + mode marker + base64url bytes, compressed with raw DEFLATE when the compressed form is shorter and the runtime supports the streams.\n\n| Option | Type | Meaning |\n| ---------- | -------- | ------------------------------------------------------------------- |\n| `maxBytes` | `number` | Positive safe integer; maximum serialized payload size |\n| `prefix` | `string` | 1–8 alphanumeric characters identifying the code family and version |\n\n**Returns:** The shorter of the raw (`prefix` + `r`) and compressed (`prefix` + `d`) representations. Throws `ShareCodeError` (`too-large`, `invalid`) for oversized payloads and misconfigured options.\n\n**Example:** Encode a shareable build as a code small enough for a URL.\n\n```ts\nimport { pack } from '@vielzeug/arsenal';\n\nconst code = await pack({ cards: ['slash', 'guard'] }, { maxBytes: 8192, prefix: 'ab1' });\n```\n\n---\n\n### unpack\n\n```ts\nunpack(code: string, options: ShareCodeOptions): Promise<unknown>\n```\n\nDecodes a share code produced by `pack` with the same options. Both sides are bounded: input longer than `maxBytes` could carry is refused up front, streamed decompression stops at `maxBytes`, and non-canonical base64url is rejected by round-trip.\n\n**Returns:** The parsed JSON payload. Throws `ShareCodeError` (`invalid` for foreign or malformed codes, `too-large` for budget overruns, `compression-unavailable` when a compressed code arrives on a runtime without `DecompressionStream`). Underlying compression failures surface as `ArsenalSerializationError`.\n\n**Example:** Decode untrusted input within the byte budget.\n\n```ts\nimport { unpack } from '@vielzeug/arsenal';\n\nconst payload = await unpack(code, { maxBytes: 8192, prefix: 'ab1' });\n```\n\n## Object\n\n### tryParseJson\n\n```ts\ntype JsonParseResult = { ok: true; value: unknown } | { error: SyntaxError; ok: false };\n\ntryParseJson(text: string): JsonParseResult\n```\n\nUse a schema validator after success to refine `unknown` data.\n\n```ts\nimport { tryParseJson } from '@vielzeug/arsenal/object';\n\nconst result = tryParseJson(raw);\nif (!result.ok) throw result.error;\n```\n\n### getPath\n\n```ts\ngetPath<T extends Record<string, unknown>, P extends string>(item: T, path: P): PathValue<T, P> | undefined\ngetPathOr<T extends Record<string, unknown>, P extends string, F>(item: T, path: P, fallback: F): PathValue<T, P> | F\nrequirePath<T extends Record<string, unknown>, P extends string>(item: T, path: P): Exclude<PathValue<T, P>, undefined>\n```\n\n### hash\n\n```ts\nhash(value: unknown, options?: HashOptions): string\n```\n\nProduces a deterministic, order-independent serialization. Handles `Date`, `RegExp`, `Set`, `Map`, and `bigint`. Circular references produce a sentinel. Useful for stable cache keys.\n\n---\n\n## Math\n\n### Numeric toolkit\n\n```ts\nrange(stop: number): number[]\nrange(start: number, stop: number, step?: number): number[]\nclamp(value: number, min?: number, max?: number): number\nsum<T>(values: readonly T[], select?: (value: T) => number): number\naverage<T>(values: readonly T[], select?: (value: T) => number): number | undefined\nmedian<T>(values: readonly T[], select?: (value: T) => number): number | undefined\nvariance<T>(values: readonly T[], select?: (value: T) => number): number\nstandardDeviation<T>(values: readonly T[], select?: (value: T) => number): number\n```\n\n`sum` and `average` reject non-finite values. `gcd` and `lcm` require safe integers. `linspace` requires finite bounds and a positive integer point count. `variance` and `standardDeviation` compute population statistics.\n\n### allocate\n\n```ts\nallocate(amount: number, ratios: number[] | number): number[]\nallocate(amount: bigint, ratios: number[] | number): bigint[]\n```\n\nDistributes an amount proportionally across ratios. The indivisible remainder is applied to the last bucket so the sum equals the original amount exactly: critical for financial operations.\n\n## Types\n\n```ts\ntype FuzzyOptions = {\n normalize?: boolean;\n threshold?: number;\n};\n\ntype FuzzySelection<T> = FuzzyOptions & {\n select: (item: T) => string | readonly string[];\n};\n\ntype ScoredResult<T> = { item: T; score: number };\n\ntype PageEnvelope<T> = Readonly<{\n items: readonly T[];\n page: number;\n pageSize: number;\n totalItems: number;\n totalPages: number;\n}>;\n\ntype PaginateOptions = Readonly<{\n page?: number;\n pageSize?: number;\n pageOffset?: 0 | 1;\n}>;\n\ntype SortDirection = 'asc' | 'desc';\n\ntype SortSelectors<T> = Partial<Record<keyof T, SortDirection>>;\n\ntype SortCriterion<T> = Readonly<{\n key: keyof T | (string & {});\n direction?: SortDirection;\n}>;\n\ntype CacheOptions = {\n capacity?: number;\n now?: () => number;\n ttlMs?: number;\n};\n\ninterface CompressionOptions {\n format?: CompressionFormat;\n}\n\ninterface DecompressionOptions extends CompressionOptions {\n maxOutputBytes: number;\n}\n```\n\n## Errors\n\n- `RangeError`: invalid numeric bounds, capacity, concurrency, or retry count.\n- `TypeError`: invalid value types, unsupported comparison, or required path missing.\n- `ArsenalSerializationError`: memo or hash cannot serialize supplied input; compression fails, is unavailable, receives an invalid output limit, or exceeds that limit. Stream failures retain the original error as `cause`.\n- `ShareCodeError`: a share code cannot be encoded or decoded; the `reason` field is `invalid`, `too-large`, or `compression-unavailable`.\n",
|
|
6
|
-
"usage": "---\ntitle: 'Arsenal: Usage Guide'\ndescription: Use Arsenal root utilities for common work and category entry points for specialized collection, async, cache, object, and string behavior.\n---\n\n[[toc]]\n\n## Basic Usage\n\nStart at package root for common utilities. Move to a category entry point for the broader typed toolkit. Arsenal keeps helpers that improve readability, narrowing, immutable updates, or edge-case consistency; exact platform aliases stay out.\n\n```ts\nimport { groupBy, retry } from '@vielzeug/arsenal';\n\nconst users = [\n { id: 'a1', role: 'admin' },\n { id: 'u1', role: 'user' },\n { id: 'u2', role: 'user' },\n];\n\nconst byRole = groupBy(users, (user) => user.role);\nconst health = await retry(() => fetch('/health').then((response) => response.json()));\n\nconsole.log(byRole, health);\n```\n\nUse category imports for APIs absent from root:\n\n```ts\nimport { fuzzyFilter } from '@vielzeug/arsenal/array';\nimport { taskPool } from '@vielzeug/arsenal/async';\nimport { cache } from '@vielzeug/arsenal/cache';\nimport { tryParseJson } from '@vielzeug/arsenal/object';\n```\n\n## Transform Collections\n\nUse `/array` for transforms that preserve input immutability. `filterMap` combines mapping and omission; `indexBy` and `groupBy` build lookup structures without mutation.\n\n```ts\nimport { filterMap, indexBy, sort } from '@vielzeug/arsenal/array';\n\nconst products = [\n { id: 'p1', price: 20, published: true },\n { id: 'p2', price: 10, published: false },\n { id: 'p3', price: 15, published: true },\n];\n\nconst publishedLabels = filterMap(products, (product) =>\n product.published ? `${product.id}: ${product.price}` : undefined,\n);\nconst byId = indexBy(products, (product) => product.id);\nconst byPrice = sort(products, (product) => product.price);\n\nconsole.log(publishedLabels, byId, byPrice);\n```\n\n## Page an In-Memory List\n\nUse `paginate` when the whole list is local and a view needs one page plus its totals.\n\n```ts\nimport { paginate } from '@vielzeug/arsenal/array';\n\nconst rows = Array.from({ length: 45 }, (_, index) => ({ id: index + 1 }));\n\nconst first = paginate(rows, { pageSize: 10 });\nconst past = paginate(rows, { page: 9, pageSize: 10 });\n\nconsole.log(first.totalPages, past.items); // 5 []\n```\n\n`page` is echoed rather than clamped, so a stale page number reads as an empty page instead of\nsilently jumping elsewhere. Pass `{ pageOffset: 0 }` for a zero-based caller and the envelope comes\nback in that same base.\n\n## Sort by Grid Criteria\n\n`sort` accepts the ordering a data grid already holds: an ordered list of column paths, each with a direction.\n\n```ts\nimport { sort } from '@vielzeug/arsenal/array';\n\nconst rows = [\n { address: { city: 'Berlin' }, age: 41 },\n { address: { city: 'Aachen' }, age: 30 },\n { address: { city: 'Berlin' }, age: 27 },\n];\n\nconst ordered = sort(rows, [{ key: 'address.city' }, { key: 'age', direction: 'desc' }]);\n```\n\nPaths are resolved safely, so nested and indexed columns work and prototype access is refused. The\nfirst criterion that differs decides the order and ties keep their input order. Keep each column\ntyped: a column mixing numbers and strings throws a `TypeError` rather than guessing an order.\n\n## Search Explicit Fields\n\nSearch string arrays directly. Object collections require `select`, so callers define exactly what can match.\n\n```ts\nimport { fuzzyFilter, fuzzyScore } from '@vielzeug/arsenal/array';\n\nconst users = [\n { email: 'alice@example.com', name: 'Alice' },\n { email: 'bob@example.com', name: 'Bob' },\n];\n\nconst matches = fuzzyFilter(users, 'alice', { select: (user) => [user.name, user.email] });\nconst ranked = fuzzyScore(users, 'ali', { select: (user) => user.name });\n```\n\n## Work with Object Data\n\nUse `/object` for paths, key selection, stable cache keys, and object transforms.\n\n```ts\nimport { getPathOr, hash, omit, pick } from '@vielzeug/arsenal/object';\n\nconst config = { api: { host: 'localhost', port: 3000 }, debug: true };\nconst port = getPathOr(config, 'api.port', 8080);\nconst publicConfig = pick(config, ['api']);\nconst productionConfig = omit(config, ['debug']);\nconst key = hash({ port, productionConfig });\n\nconsole.log(publicConfig, key);\n```\n\n## Parse and Validate JSON\n\n`tryParseJson` distinguishes syntax failure from schema failure. Treat successful values as `unknown`, then validate with Spell or application code.\n\n```ts\nimport { tryParseJson } from '@vielzeug/arsenal/object';\nimport { s } from '@vielzeug/spell';\n\nconst User = s.object({ id: s.string(), name: s.string() });\nconst parsed = tryParseJson(raw);\n\nif (!parsed.ok) throw parsed.error;\n\nconst user = User.parse(parsed.value);\n```\n\n## Bound Concurrent Work\n\nUse `parallel` for one finite collection. Use `taskPool` when tasks arrive over time or need disposal.\n\n```ts\nimport { parallel, taskPool } from '@vielzeug/arsenal/async';\n\nconst metadata = await parallel(urls, (url) => fetch(url).then((response) => response.json()), { limit: 4 });\n\nconst pool = taskPool({ concurrency: 2 });\nconst profile = await pool.run((signal) => fetch('/profile', { signal }).then((response) => response.json()));\n\nawait pool.idle();\npool.dispose();\n\nconsole.log(metadata, profile);\n```\n\n## Cache Loaded Values\n\nUse `cache` for process-local values. Keys retain native `Map` identity. `getOrLoad` deduplicates concurrent loads for one key.\n\n```ts\nimport { cache } from '@vielzeug/arsenal/cache';\n\ntype Profile = { id: string; name: string };\n\nconst profiles = cache<string, Profile>({ capacity: 100, ttlMs: 60_000 });\nconst profile = await profiles.getOrLoad('me', () => fetch('/profile').then((response) => response.json()));\n\nconsole.log(profiles.entries());\nprofiles.delete('me');\nconst freshProfile = await profiles.getOrLoad('me', () => fetch('/profile').then((response) => response.json()));\n\nconsole.log(profile, freshProfile);\n```\n\n## Test Deterministic Randomness\n\nRandom helpers use cryptographic entropy by default. Pass `RandomSource` in tests when output must be deterministic.\n\n```ts\nimport { random, randomFloat, type RandomSource } from '@vielzeug/arsenal/random';\n\nconst source: RandomSource = { next: () => 0.5 };\n\nrandomFloat(source); // 0.5\nrandom(1, 4, source); // 3\n```\n\n## Encode Text for URLs and QR Codes\n\nShare codes ride in URLs and QR payloads, where `+`, `/`, and padding `=` break consumers. The base64url codecs are environment-independent: no `btoa`, no `Buffer`, so the same encode/decode pair works in the browser, in workers, and in Node.\n\n```ts\nimport { base64UrlToText, textToBase64Url } from '@vielzeug/arsenal';\n\nconst code = textToBase64Url(JSON.stringify({ seat: 4, version: 2 }));\n// eyJzZWF0Ijo0LCJ2ZXJzaW9uIjoyfQ: safe in a query string or QR\n\nconst payload = JSON.parse(base64UrlToText(code));\n```\n\nDecoding throws on characters outside the base64url alphabet, so corrupted input fails loudly instead of decoding to garbage.\n\n## Compress Share Payloads\n\nCompress UTF-8 bytes before Base64url encoding. Set a decoded-byte limit before accepting compressed input from another device.\n\n```ts\nimport { base64UrlToBytes, bytesToBase64Url, compressBytes, decompressBytes } from '@vielzeug/arsenal';\n\nconst payload = JSON.stringify({ name: 'Hunters', notes: 'An expedition through Alborea. '.repeat(20) });\nconst compressed = await compressBytes(new TextEncoder().encode(payload));\nconst code = bytesToBase64Url(compressed);\nconst bytes = await decompressBytes(base64UrlToBytes(code), { maxOutputBytes: 8192 });\nconst restored = new TextDecoder('utf-8', { fatal: true }).decode(bytes);\nconsole.log(restored === payload);\n```\n\nBoth helpers default to `deflate-raw`. You can explicitly select `gzip` or `deflate`; use the same format at both ends. The helpers reject when native streams do not support the selected format. They do not choose a fallback or define a wire protocol.\n\nFor a complete versioned envelope over these primitives — prefix, compression mode marker, byte budgets on both sides — see [`pack` / `unpack`](./api.md#pack).\n\nCompression can enlarge small inputs. Compare the final encoded strings, including any format marker, before choosing a representation. Bound input size before decoding Base64url and validate decompressed JSON against your schema. The decompression limit bounds retained output, not native stream working memory.\n\n## Working with Other Vielzeug Libraries\n\nUse Spell after `tryParseJson` for typed external data. Use Vault instead of `cache` when data must survive reloads or process restart.\n\n```ts\nimport { tryParseJson } from '@vielzeug/arsenal/object';\nimport { s } from '@vielzeug/spell';\n\nconst Settings = s.object({ theme: s.string() });\nconst parsed = tryParseJson(rawSettings);\nconst settings = parsed.ok ? Settings.parse(parsed.value) : { theme: 'system' };\n```\n\n## Best Practices\n\n- Import common utilities from package root.\n- Import the broader toolkit from category entry points.\n- Prefer Arsenal when a helper improves typing, intent, immutable updates, or edge-case behavior.\n- Use the platform directly for exact aliases such as `crypto.randomUUID()` and `Array.prototype.flat()`.\n- Pass `select` for every fuzzy search over objects.\n- Validate parsed JSON before using it as application data.\n- Use `parallel` for finite batches and `taskPool` for ongoing work.\n- Dispose task pools when their owner ends.\n- Use `cache` only for in-memory data.\n- Inject `RandomSource` in deterministic tests.\n",
|
|
7
|
-
"examples": "---\ntitle: 'Arsenal: Examples'\ndescription: Practical examples and recipes for arsenal.\n---\n\n## Examples\n\n- [Array utilities](./examples/array.md)\n- [Async utilities](./examples/async.md)\n- [Cache utilities](./examples/cache.md)\n- [Encoding utilities](./examples/encoding.md)\n- [Function utilities](./examples/function.md)\n- [Guards / Typed predicates](./examples/typed.md)\n- [Math utilities](./examples/math.md)\n- [Object utilities](./examples/object.md): includes `getPath`, `tryParseJson`, `hash`, `diff`, `deepMerge`\n- [Random utilities](./examples/random.md)\n- [String utilities](./examples/string.md)\n"
|
|
8
|
-
},
|
|
9
|
-
"examples": [
|
|
10
|
-
{
|
|
11
|
-
"id": "array-chunk",
|
|
12
|
-
"code": "import { chunk } from '@vielzeug/arsenal'\n\nconst numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n\nconsole.log('Original:', numbers)\nconsole.log('Chunks of 3:', chunk(numbers, 3))\nconsole.log('Chunks of 4:', chunk(numbers, 4))\n\n// Practical use case: Batch processing\nconst userIds = [101, 102, 103, 104, 105, 106, 107, 108]\nconst batches = chunk(userIds, 3)\nconsole.log('User ID batches:', batches)",
|
|
13
|
-
"name": "chunk - Split array into chunks"
|
|
14
|
-
},
|
|
15
|
-
{
|
|
16
|
-
"id": "array-filter",
|
|
17
|
-
"code": "import { filterMap } from '@vielzeug/arsenal'\n\nconst users = [\n { name: 'Alice', age: 25, active: true },\n { name: 'Bob', age: 30, active: false },\n { name: 'Charlie', age: 35, active: true },\n { name: 'David', age: 28, active: true }\n]\n\nconst activeUsers = filterMap(users, user =>\n user.active ? user : undefined\n)\nconsole.log('Active users:', activeUsers)\n\nconst over30 = filterMap(users, user =>\n user.age > 30 ? user : undefined\n)\nconsole.log('Users over 30:', over30)\n\nconst activeNames = filterMap(users, user =>\n user.active ? user.name : undefined\n)\nconsole.log('Active user names:', activeNames)",
|
|
18
|
-
"name": "filterMap - Filter and map array elements"
|
|
19
|
-
},
|
|
20
|
-
{
|
|
21
|
-
"id": "array-group",
|
|
22
|
-
"code": "import { groupBy } from '@vielzeug/arsenal'\n\nconst items = [\n { type: 'fruit', name: 'apple', price: 1.2 },\n { type: 'vegetable', name: 'carrot', price: 0.8 },\n { type: 'fruit', name: 'banana', price: 0.5 },\n { type: 'vegetable', name: 'broccoli', price: 1.5 },\n { type: 'fruit', name: 'orange', price: 0.9 }\n]\n\nconst byType = groupBy(items, item => item.type)\nconsole.log('Grouped by type:', byType)\n\nconst byPriceRange = groupBy(items, item =>\n item.price < 1 ? 'cheap' : 'expensive'\n)\nconsole.log('Grouped by price:', byPriceRange)",
|
|
23
|
-
"name": "groupBy - Group array by key"
|
|
24
|
-
},
|
|
25
|
-
{
|
|
26
|
-
"id": "array-map",
|
|
27
|
-
"code": "import { filterMap } from '@vielzeug/arsenal'\n\nconst numbers = [1, 2, 3, 4, 5]\n\nconst doubled = filterMap(numbers, number => number * 2)\nconsole.log('Doubled:', doubled)\n\nconst strings = filterMap(numbers, number => `Number: ${number}`)\nconsole.log('Formatted:', strings)\n\nconst evenDoubled = filterMap(numbers, number =>\n number % 2 === 0 ? number * 2 : undefined\n)\nconsole.log('Even numbers doubled:', evenDoubled)",
|
|
28
|
-
"name": "filterMap - Transform array elements"
|
|
29
|
-
},
|
|
30
|
-
{
|
|
31
|
-
"id": "array-paginate",
|
|
32
|
-
"code": "import { paginate } from '@vielzeug/arsenal'\n\nconst rows = Array.from({ length: 45 }, (_, index) => ({ id: index + 1 }))\n\nconst first = paginate(rows, { pageSize: 10 })\nconsole.log('Page:', first.page, 'of', first.totalPages)\nconsole.log('Items:', first.items.map((row) => row.id))\n\n// A zero-based caller (Spring-style) gets its own base back\nconst zeroBased = paginate(rows, { page: 0, pageSize: 10, pageOffset: 0 })\nconsole.log('Zero-based page:', zeroBased.page, zeroBased.items.length)\n\n// Pages past the last echo the request instead of clamping it\nconst past = paginate(rows, { page: 9, pageSize: 10 })\nconsole.log('Past the end:', past.items, 'of', past.totalItems)",
|
|
33
|
-
"name": "paginate - Page an array"
|
|
34
|
-
},
|
|
35
|
-
{
|
|
36
|
-
"id": "array-search",
|
|
37
|
-
"code": "import { fuzzyFilter, fuzzyScore } from '@vielzeug/arsenal/array'\n\nconst users = [\n { name: 'Alice Johnson', role: 'admin' },\n { name: 'Bob Smith', role: 'user' },\n { name: 'Charlie Brown', role: 'user' },\n]\n\nconst byName = fuzzyFilter(users, 'alice', { select: user => user.name })\nconsole.log('Filtered:', byName)\n\nconst ranked = fuzzyScore(users, 'smith', { select: user => [user.name, user.role] })\nconsole.log('Ranked:', ranked)",
|
|
38
|
-
"name": "fuzzyFilter - Explicit searchable fields"
|
|
39
|
-
},
|
|
40
|
-
{
|
|
41
|
-
"id": "array-search-normalize",
|
|
42
|
-
"code": "import { fuzzyFilter, fuzzyScore } from '@vielzeug/arsenal/array'\n\nconst names = ['José', 'Élise', 'café', 'naïve', 'resume']\n\nconst noNorm = fuzzyFilter(names, 'jose', { threshold: 0.9 })\nconsole.log('normalize:false:', noNorm)\n\nconst withNorm = fuzzyFilter(names, 'jose', { normalize: true, threshold: 0.9 })\nconsole.log('normalize:true:', withNorm)\n\nconst scored = fuzzyScore(names, 'elise', { normalize: true, threshold: 0.5 })\nconsole.log('Scored:', scored)",
|
|
43
|
-
"name": "fuzzyFilter - Unicode normalization"
|
|
44
|
-
},
|
|
45
|
-
{
|
|
46
|
-
"id": "array-sort-criteria",
|
|
47
|
-
"code": "import { sort } from '@vielzeug/arsenal'\n\nconst rows = [\n { address: { city: 'Berlin' }, age: 41, name: 'Ada' },\n { address: { city: 'Aachen' }, age: 30, name: 'Grace' },\n { address: { city: 'Berlin' }, age: 27, name: 'Linus' },\n]\n\n// A grid hands over ordered column paths, each with a direction\nconst ordered = sort(rows, [{ key: 'address.city' }, { key: 'age', direction: 'desc' }])\nconsole.log('City asc, then age desc:', ordered.map((row) => `${row.name} (${row.address.city})`))\n\n// Selector form for one extracted value\nconsole.log('By name:', sort(rows, (row) => row.name).map((row) => row.name))\n\n// Selectors form for a keyed object\nconsole.log('By age desc:', sort(rows, { age: 'desc' }).map((row) => row.age))",
|
|
48
|
-
"name": "sort - Selector, selectors, or grid criteria"
|
|
49
|
-
},
|
|
50
|
-
{
|
|
51
|
-
"id": "array-uniq",
|
|
52
|
-
"code": "import { uniq } from '@vielzeug/arsenal'\n\nconst numbers = [1, 2, 2, 3, 3, 3, 4, 5, 5]\nconsole.log('Unique numbers:', uniq(numbers))\n\nconst tags = ['javascript', 'react', 'vue', 'react', 'angular', 'vue']\nconsole.log('Unique tags:', uniq(tags))\n\n// Works with objects too (by reference)\nconst obj1 = { id: 1 }\nconst obj2 = { id: 2 }\nconst objects = [obj1, obj2, obj1, obj2]\nconsole.log('Unique objects:', uniq(objects))",
|
|
53
|
-
"name": "uniq - Remove duplicates"
|
|
54
|
-
},
|
|
55
|
-
{
|
|
56
|
-
"id": "async-attempt",
|
|
57
|
-
"code": "import { attempt, isFail, isOk, retry } from '@vielzeug/arsenal/async'\n\n// attempt() wraps any async function: never throws, always returns { ok, value|error }\nconst ok = await attempt(async () => {\n await new Promise(r => setTimeout(r, 10))\n return { id: 1, title: 'Buy groceries' }\n})\n\nif (isOk(ok)) {\n console.log('Success:', ok.value)\n}\n\n// Failure path: errors are captured, not thrown\nconst fail = await attempt(async () => {\n throw new Error('network timeout')\n})\n\nif (isFail(fail)) {\n console.log('Caught:', fail.error.message) // 'network timeout'\n}\n\n// Combine with retry() for resilient operations\nlet calls = 0\nconst result = await attempt(() =>\n retry(async () => {\n calls++\n if (calls < 3) throw new Error('not ready')\n return 'ready'\n }, { times: 5, delay: 10 })\n)\n\nconsole.log('ok?', result.ok) // true\nconsole.log('value:', result.value) // 'ready'\nconsole.log('calls:', calls) // 3",
|
|
58
|
-
"name": "attempt - Safe async execution with isFail/isOk helpers"
|
|
59
|
-
},
|
|
60
|
-
{
|
|
61
|
-
"id": "async-parallel",
|
|
62
|
-
"code": "import { parallel } from '@vielzeug/arsenal/async'\n\nconst items = [1, 2, 3, 4, 5, 6, 7, 8]\n\nconst results = await parallel(\n items,\n async item => {\n console.log(`Processing: ${item}`)\n await new Promise(resolve => setTimeout(resolve, 100))\n return item * 2\n },\n { limit: 2 }\n)\n\nconsole.log('Results:', results)",
|
|
63
|
-
"name": "parallel - Controlled parallel execution"
|
|
64
|
-
},
|
|
65
|
-
{
|
|
66
|
-
"id": "async-pool",
|
|
67
|
-
"code": "import { taskPool } from '@vielzeug/arsenal/async'\n\nconst pool = taskPool({ concurrency: 3 })\nconst tasks = Array.from({ length: 6 }, (_, index) =>\n pool.run(async () => {\n console.log(`Task ${index + 1} started`)\n await new Promise(resolve => setTimeout(resolve, 100))\n return `Result ${index + 1}`\n }),\n)\n\nconsole.log('All results:', await Promise.all(tasks))\nawait pool.idle()\npool.dispose()",
|
|
68
|
-
"name": "taskPool - Parallel execution with concurrency limit"
|
|
69
|
-
},
|
|
70
|
-
{
|
|
71
|
-
"id": "async-queue",
|
|
72
|
-
"code": "import { taskPool } from '@vielzeug/arsenal/async'\n\nconst pool = taskPool({ concurrency: 2 })\nconst tasks = [100, 50, 75, 30].map((delay, index) =>\n pool.run(async (signal) => {\n await new Promise((resolve, reject) => {\n const timer = setTimeout(resolve, delay)\n signal.addEventListener('abort', () => {\n clearTimeout(timer)\n reject(signal.reason)\n }, { once: true })\n })\n return 'task-' + (index + 1)\n }),\n)\n\nconsole.log('After enqueue:', { active: pool.active, pending: pool.pending })\nconsole.log('Results:', await Promise.all(tasks))\nawait pool.idle()\npool.dispose()",
|
|
73
|
-
"name": "taskPool - Bounded concurrent work"
|
|
74
|
-
},
|
|
75
|
-
{
|
|
76
|
-
"id": "async-retry",
|
|
77
|
-
"code": "import { retry } from '@vielzeug/arsenal/async'\n\nlet attempts = 0\nconst unreliableOperation = async () => {\n attempts++\n console.log(`Attempt #${attempts}`)\n\n if (attempts < 3) {\n throw new Error('Failed!')\n }\n\n return 'Success!'\n}\n\ntry {\n const result = await retry(unreliableOperation, {\n times: 5,\n delay: 100\n })\n console.log('Result:', result)\n console.log('Total attempts:', attempts)\n} catch (err) {\n console.error('All retries failed:', err.message)\n}",
|
|
78
|
-
"name": "retry - Retry failed operations"
|
|
79
|
-
},
|
|
80
|
-
{
|
|
81
|
-
"id": "async-waitFor",
|
|
82
|
-
"code": "import { waitFor } from '@vielzeug/arsenal/async'\n\n// Simulate a value that becomes ready after a short delay\nlet ready = false\nsetTimeout(() => { ready = true }, 200)\n\nconsole.log('Waiting for ready...')\nawait waitFor(() => ready, { interval: 50, timeout: 2000 })\nconsole.log('Ready!')\n\n// Abort early with an external signal\nconst ac = new AbortController()\nsetTimeout(() => ac.abort(new Error('user cancelled')), 100)\n\ntry {\n await waitFor(() => false, {\n interval: 50,\n signal: ac.signal,\n timeout: 5000,\n })\n} catch (err) {\n console.log('Aborted:', err.message) // 'user cancelled'\n}",
|
|
83
|
-
"name": "waitFor - Poll until condition is true or timeout/abort fires"
|
|
84
|
-
},
|
|
85
|
-
{
|
|
86
|
-
"id": "encoding-compression",
|
|
87
|
-
"code": "import { base64UrlToBytes, bytesToBase64Url, compressBytes, decompressBytes } from '@vielzeug/arsenal'\n\nconst text = JSON.stringify({ notes: 'An expedition through Alborea. '.repeat(20) })\nconst original = new TextEncoder().encode(text)\nconst code = bytesToBase64Url(await compressBytes(original))\nconst restored = await decompressBytes(base64UrlToBytes(code), { maxOutputBytes: 8192 })\n\nconsole.log('Original bytes:', original.length)\nconsole.log('Compressed code characters:', code.length)\nconsole.log('Matches original:', new TextDecoder('utf-8', { fatal: true }).decode(restored) === text)",
|
|
88
|
-
"name": "compressBytes - Bounded share payload compression"
|
|
89
|
-
},
|
|
90
|
-
{
|
|
91
|
-
"id": "function-debounce",
|
|
92
|
-
"code": "import { debounce } from '@vielzeug/arsenal/function'\n\n// --- Trailing (default) ---\nlet trailingCount = 0\nconst onSearch = debounce((q) => {\n trailingCount++\n console.log(`Trailing #${trailingCount}: \"${q}\"`)\n}, 200)\n\nonSearch('c')\nonSearch('ca')\nonSearch('cat') // only this fires after 200ms\n\n// --- Leading-only ---\nlet leadingCount = 0\nconst onSubmit = debounce((q) => {\n leadingCount++\n console.log(`Leading #${leadingCount}: \"${q}\"`)\n}, 200, { leading: true, trailing: false })\n\nonSubmit('first') // fires immediately\nonSubmit('second') // silenced (within 200ms window)\nonSubmit('third') // silenced\n\n// --- Leading + Trailing: fires on both edges ---\nlet bothCount = 0\nconst onBoth = debounce(() => {\n bothCount++\n console.log(`Both edge #${bothCount}`)\n}, 200, { leading: true, trailing: true })\n\nonBoth() // fires immediately (leading)\n// trailing edge fires after 200ms (bothCount becomes 2)\n\nsetTimeout(() => {\n console.log('Trailing fires:', trailingCount, '| Leading fires:', leadingCount, '| Both fires:', bothCount)\n // trailing: 1 | leading: 1 | both: 2\n}, 400)",
|
|
93
|
-
"name": "debounce - Trailing (default) and leading-edge options"
|
|
94
|
-
},
|
|
95
|
-
{
|
|
96
|
-
"id": "function-memo",
|
|
97
|
-
"code": "import { memo } from '@vielzeug/arsenal/cache'\n\n// LRU cache capped at 3 entries: oldest evicted when full\nlet callCount = 0\nconst compute = memo(\n (n) => { callCount++; return n * n },\n { maxSize: 3 }\n)\n\nconsole.log(compute(2)) // 4: computed\nconsole.log(compute(3)) // 9: computed\nconsole.log(compute(4)) // 16: computed\nconsole.log(compute(2)) // 4: cache hit\nconsole.log('calls so far:', callCount) // 3\nconsole.log('cached entries:', compute.size) // 3\n\n// Adding a 4th entry evicts the oldest (key 2)\nconsole.log(compute(5)) // 25: computed, evicts 2\nconsole.log('after 4th entry, size:', compute.size) // 3\n\n// Invalidate a specific entry\ncompute.invalidate(3)\nconsole.log('after invalidate(3), size:', compute.size) // 2\nconsole.log(compute(3)) // 9: recomputed\nconsole.log('total calls:', callCount) // 5",
|
|
98
|
-
"name": "memo - LRU cache with size tracking and invalidation"
|
|
99
|
-
},
|
|
100
|
-
{
|
|
101
|
-
"id": "function-pipe",
|
|
102
|
-
"code": "import { pipe } from '@vielzeug/arsenal'\n\n// pipe: left-to-right function composition\nconst add5 = (n) => n + 5\nconst multiply2 = (n) => n * 2\nconst square = (n) => n * n\n\nconst transform = pipe(add5, multiply2, square)\nconsole.log('transform(3):', transform(3)) // (3+5)*2 = 16, 16^2 = 256\n\n// Works with string transformations too\nconst normalise = pipe(\n (s) => s.trim(),\n (s) => s.toLowerCase(),\n (s) => s.replace(/\\s+/g, '-'),\n)\nconsole.log('normalise result:', normalise(' Hello World ')) // 'hello-world'\n\n// Zero args returns the identity function\nconst id = pipe()\nconsole.log('identity:', id(42)) // 42",
|
|
103
|
-
"name": "pipe - Left-to-right function composition"
|
|
104
|
-
},
|
|
105
|
-
{
|
|
106
|
-
"id": "function-runAll",
|
|
107
|
-
"code": "import { runAll } from '@vielzeug/arsenal/function'\n\n// Run every teardown function: collect errors instead of stopping on first failure\nconst log = []\n\nconst teardowns = [\n () => { log.push('cleanup A'); },\n () => { log.push('cleanup B'); throw new Error('B failed'); },\n () => { log.push('cleanup C'); },\n]\n\ntry {\n runAll(teardowns, { reverse: true }) // LIFO order matches setup-teardown semantics\n} catch (err) {\n console.log('errors collected:', err instanceof AggregateError) // true\n console.log('error count:', err.errors.length) // 1\n console.log('still ran:', log) // ['cleanup C', 'cleanup B', 'cleanup A']\n}\n\n// Without failures: just runs all in order\nconst steps = []\nrunAll([() => steps.push(1), () => steps.push(2), () => steps.push(3)])\nconsole.log('steps:', steps) // [1, 2, 3]",
|
|
108
|
-
"name": "runAll - Run all callbacks, collect errors"
|
|
109
|
-
},
|
|
110
|
-
{
|
|
111
|
-
"id": "function-stash-async",
|
|
112
|
-
"code": "import { cache } from '@vielzeug/arsenal/cache'\n\nconst users = cache({ ttlMs: 5000 })\nlet fetchCount = 0\n\nfunction fetchUser(id) {\n return users.getOrLoad('user:' + id, async () => {\n fetchCount++\n await new Promise(resolve => setTimeout(resolve, 10))\n return { id, name: 'User ' + id }\n })\n}\n\nconst [first, second] = await Promise.all([fetchUser(1), fetchUser(1)])\nconsole.log('fetch count:', fetchCount)\nconsole.log('same reference:', first === second)\n\nusers.delete('user:1')\nconsole.log('fresh:', await fetchUser(1))",
|
|
113
|
-
"name": "cache - Async load deduplication"
|
|
114
|
-
},
|
|
115
|
-
{
|
|
116
|
-
"id": "function-throttle",
|
|
117
|
-
"code": "import { throttle } from '@vielzeug/arsenal/function'\n\nlet scrollCount = 0\nconst handleScroll = () => {\n scrollCount++\n console.log(`Scroll event #${scrollCount}`)\n}\n\nconst throttledScroll = throttle(handleScroll, 200)\n\n// Simulate rapid scroll events\nfor (let i = 0; i < 10; i++) {\n setTimeout(() => throttledScroll(), i * 50)\n}\n\nsetTimeout(() => {\n console.log('Total throttled calls:', scrollCount)\n}, 1000)",
|
|
118
|
-
"name": "throttle - Throttle function calls"
|
|
119
|
-
},
|
|
120
|
-
{
|
|
121
|
-
"id": "math-average",
|
|
122
|
-
"code": "import { average, median, sum } from '@vielzeug/arsenal/math'\n\nconst numbers = [10, 20, 30, 40, 50]\nconsole.log('Average:', average(numbers))\nconsole.log('Sum:', sum(numbers))\nconsole.log('Min:', Math.min(...numbers))\nconsole.log('Max:', Math.max(...numbers))\nconsole.log('Median:', median(numbers))",
|
|
123
|
-
"name": "average - Calculate average"
|
|
124
|
-
},
|
|
125
|
-
{
|
|
126
|
-
"id": "object-diff",
|
|
127
|
-
"code": "import { diff } from '@vielzeug/arsenal/object'\n\nconst before = {\n name: 'Alice',\n age: 25,\n email: 'alice@old.com',\n settings: { theme: 'light', lang: 'en' }\n}\n\nconst after = {\n name: 'Alice',\n age: 26,\n email: 'alice@new.com',\n settings: { theme: 'dark', lang: 'en' }\n}\n\nconst changes = diff(after, before)\nconsole.log('Changes detected:', changes)",
|
|
128
|
-
"name": "diff - Compare objects"
|
|
129
|
-
},
|
|
130
|
-
{
|
|
131
|
-
"id": "object-diffArrays",
|
|
132
|
-
"code": "import { diffArrays } from '@vielzeug/arsenal/object'\n\n// Default 'set' strategy: order independent\nconst v1 = [1, 2, 3]\nconst v2 = [2, 3, 4]\nconst setDiff = diffArrays(v1, v2)\nconsole.log('set diff:', setDiff) // { added: [4], removed: [1] }\n\n// 'lcs' strategy: ordered minimal diff\nconst before = [1, 2, 3, 4, 5]\nconst after = [1, 3, 4, 5, 6]\nconst lcsDiff = diffArrays(before, after, { strategy: 'lcs' })\nconsole.log('lcs diff:', lcsDiff) // { added: [6], removed: [2] }\n\n// With custom compareFn for objects\nconst oldUsers = [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }]\nconst newUsers = [{ id: 2, name: 'Bob' }, { id: 3, name: 'Charlie' }]\nconst userDiff = diffArrays(oldUsers, newUsers, { compareFn: (a, b) => a.id === b.id })\nconsole.log('users:', userDiff) // { added: [{id:3,...}], removed: [{id:1,...}] }",
|
|
133
|
-
"name": "diffArrays - Set and LCS strategies"
|
|
134
|
-
},
|
|
135
|
-
{
|
|
136
|
-
"id": "object-getPath",
|
|
137
|
-
"code": "import { getPath, getPathOr, requirePath } from '@vielzeug/arsenal/object'\n\nconst config = {\n server: { host: 'localhost', ports: [3000, 3001] },\n db: { name: 'mydb', pool: { min: 2, max: 10 } }\n}\n\n// Standard dot-notation\nconsole.log(getPath(config, 'server.host')) // 'localhost'\nconsole.log(getPath(config, 'db.pool.max')) // 10\nconsole.log(getPath(config, 'server.ports.0')) // 3000\nconsole.log(getPathOr(config, 'missing', 'default')) // 'default'\nconsole.log(getPath(config, 'server.ports[1]')) // 3001\n\ntry {\n requirePath(config, 'db.pool.timeout')\n} catch (e) {\n console.log('threw:', e.message)\n}\n\nconsole.log(getPathOr(config, '__proto__.polluted', 'safe')) // 'safe'",
|
|
138
|
-
"name": "getPath - Dot-notation access"
|
|
139
|
-
},
|
|
140
|
-
{
|
|
141
|
-
"id": "object-hash",
|
|
142
|
-
"code": "import { hash } from '@vielzeug/arsenal/object'\n\n// Stable cache key regardless of object key insertion order\nconst key1 = hash({ sort: 'asc', filter: { role: 'admin' } })\nconst key2 = hash({ filter: { role: 'admin' }, sort: 'asc' })\nconsole.log('Same key?', key1 === key2) // true\nconsole.log('Key:', key1) // '{\"filter\":{\"role\":\"admin\"},\"sort\":\"asc\"}'\n\n// Handles Date, RegExp, Set, Map, bigint\nconsole.log(hash(new Date('2024-01-01T00:00:00Z'))) // '[Date:2024-01-01T00:00:00.000Z]'\nconsole.log(hash(new Set([3, 1, 2]))) // '[Set:1,2,3]': sorted\nconsole.log(hash(new Map([['b', 2], ['a', 1]]))) // '[Map:\"a\"=>1,\"b\"=>2]': sorted\nconsole.log(hash(42n)) // '42n'\nconsole.log(hash(/foo/gi)) // '[RegExp:foo/gi]'\n\n// Circular references produce a sentinel: no stack overflow\nconst obj = { x: 1 }\nobj.self = obj\nconsole.log(hash(obj)) // '{\"self\":[Circular],\"x\":1}'\n\n// Class instances coerce to String(instance) by default\nclass Point {\n constructor(x, y) { this.x = x; this.y = y }\n toString() { return `Point(${this.x},${this.y})` }\n}\nconsole.log(hash(new Point(1, 2))) // 'Point(1,2)'",
|
|
143
|
-
"name": "hash - Deterministic cache key from any value"
|
|
144
|
-
},
|
|
145
|
-
{
|
|
146
|
-
"id": "object-merge",
|
|
147
|
-
"code": "import { deepMerge, shallowMerge } from '@vielzeug/arsenal/object'\n\nconst obj1 = { a: 1, b: { c: 2 }, d: [1, 2] }\nconst obj2 = { b: { d: 3 }, e: 4, d: [3, 4] }\nconst obj3 = { a: 10, f: 5 }\n\nconst deeplyMerged = deepMerge([obj1, obj2, obj3])\nconsole.log('Deep merge:', deeplyMerged)\n\nconst shallowlyMerged = shallowMerge(obj1, obj2, obj3)\nconsole.log('Shallow merge:', shallowlyMerged)\n\nconst config1 = {\n api: { baseUrl: 'https://api.dev', timeout: 5000 },\n features: { darkMode: true },\n}\nconst config2 = {\n api: { timeout: 10000, retries: 3 },\n features: { notifications: true },\n}\n\nconsole.log('Merged configs:', deepMerge([config1, config2]))",
|
|
148
|
-
"name": "deepMerge - Merge objects"
|
|
149
|
-
},
|
|
150
|
-
{
|
|
151
|
-
"id": "object-parseJSON",
|
|
152
|
-
"code": "import { tryParseJson } from '@vielzeug/arsenal/object'\n\nconst valid = tryParseJson('{\"id\":1,\"name\":\"Alice\"}')\nconst invalid = tryParseJson('{')\n\nif (valid.ok) console.log('Parsed:', valid.value)\nif (!invalid.ok) console.log('Syntax error:', invalid.error.message)",
|
|
153
|
-
"name": "tryParseJson - Preserve JSON syntax errors"
|
|
154
|
-
},
|
|
155
|
-
{
|
|
156
|
-
"id": "object-prune",
|
|
157
|
-
"code": "import { prune } from '@vielzeug/arsenal/object'\n\nconst data = {\n name: ' Alice ',\n age: 30,\n tags: ['js', null, '', 'ts', undefined],\n settings: { theme: 'dark', extra: null, empty: {} }\n}\n\nconst cleaned = prune(data)\nconsole.log('Pruned object:', cleaned)\n\n// Prune array\nconst mixed = [1, null, 2, undefined, '', 3]\nconsole.log('Pruned array:', prune(mixed))\n\n// Prune string\nconsole.log('Trimmed:', prune(' hello world '))\nconsole.log('Empty string:', prune(' ')) // undefined",
|
|
158
|
-
"name": "prune - Remove empty values"
|
|
159
|
-
},
|
|
160
|
-
{
|
|
161
|
-
"id": "object-stash",
|
|
162
|
-
"code": "import { cache } from '@vielzeug/arsenal/cache'\n\nlet time = 0\nconst users = cache({ now: () => time, ttlMs: 5000 })\n\nusers.set('greeting', 'hello')\nconsole.log('get:', users.get('greeting'))\n\nconst loadUser = (id) => new Promise(resolve => setTimeout(() => resolve({ id, name: 'Alice' }), 50))\nconst [first, second] = await Promise.all([\n users.getOrLoad('user:1', () => loadUser(1)),\n users.getOrLoad('user:1', () => loadUser(1)),\n])\nconsole.log('same value:', first === second)\n\ntime = 5000\nconsole.log('expired:', users.get('greeting'))",
|
|
163
|
-
"name": "cache - Identity keys, TTL, and load deduplication"
|
|
164
|
-
},
|
|
165
|
-
{
|
|
166
|
-
"id": "string-camelcase",
|
|
167
|
-
"code": "import { camelCase, pascalCase, kebabCase, snakeCase } from '@vielzeug/arsenal/string'\n\nconst input = 'hello world example'\n\nconsole.log('camelCase:', camelCase(input))\nconsole.log('PascalCase:', pascalCase(input))\nconsole.log('kebab-case:', kebabCase(input))\nconsole.log('snake_case:', snakeCase(input))\n\n// Different input formats\nconst formats = [\n 'hello-world',\n 'hello_world',\n 'HelloWorld',\n 'helloWorld'\n]\n\nformats.forEach(str => {\n console.log(`\"${str}\" → camelCase: ${camelCase(str)}`)\n})",
|
|
168
|
-
"name": "camelCase - Convert to camelCase"
|
|
169
|
-
},
|
|
170
|
-
{
|
|
171
|
-
"id": "typed-is",
|
|
172
|
-
"code": "import { allOf, anyOf, isEmpty, isEqual, isMatch, isPlainObject, noneOf, shallowEqual } from '@vielzeug/arsenal/guards'\n\nconst values = ['hello', 42, [1, 2, 3], {}, null]\n\nvalues.forEach(value => {\n console.log({\n empty: isEmpty(value),\n plainObject: isPlainObject(value),\n })\n})\n\n// Deep structural equality (handles nested objects, arrays, Dates, Maps, Sets)\nconsole.log('deep equal:', isEqual({ a: [1, 2] }, { a: [1, 2] })) // true\n\n// Shallow equality (one level, uses Object.is so NaN === NaN)\nconsole.log('shallow equal:', shallowEqual([1, 2, 3], [1, 2, 3])) // true\n\n// Partial deep match: source properties must be present and equal\nconsole.log('is match:', isMatch({ a: 1, b: 2, c: 3 }, { a: 1 })) // true\n\n// Predicate combinators with vacuous-truth semantics\nconst isWorkingAge = allOf<number>(\n (n) => n >= 18,\n (n) => n < 65,\n)\nconst isSpecial = anyOf<number>(\n (n) => n === 0,\n (n) => n === 100,\n)\nconst isOdd = noneOf((n) => n % 2 === 0)\n\nconsole.log('working age:', isWorkingAge(30)) // true\nconsole.log('special:', isSpecial(100)) // true\nconsole.log('odd:', [1, 2, 3, 4].filter(isOdd)) // [1, 3]",
|
|
173
|
-
"name": "Guards, equality, and predicate combinators"
|
|
174
|
-
}
|
|
175
|
-
],
|
|
176
|
-
"typeSignatures": {
|
|
177
|
-
"chunk": "export function chunk(input: string, size?: number): string[];\n\nexport function chunk<T>(input: readonly T[], size?: number): T[][];\n\nexport function chunk<T>(input: readonly T[] | string, size = 2): string[] | T[][] {\n if (!Array.isArray(input) && typeof input !== 'string')\n throw new TypeError('chunk: argument must be an array or string');\n\n if (!Number.isInteger(size) || size < 1) throw new RangeError('chunk: size must be a positive integer');\n\n return Array.from({ length: Math.ceil(input.length / size) }, (_, i) => input.slice(i * size, i * size + size)) as\n | string[]\n | T[][];\n}",
|
|
178
|
-
"filterMap": "export function filterMap<T, R>(\n array: readonly T[],\n callback: (item: T, index: number, array: readonly T[]) => R | undefined,\n): R[] {\n const result: R[] = [];\n\n for (let index = 0; index < array.length; index++) {\n const value = callback(array[index], index, array);\n\n if (value !== undefined) {\n result.push(value);\n }\n }\n\n return result;\n}",
|
|
179
|
-
"groupBy": "export function groupBy<T>(array: readonly T[], selector: (item: T) => Primitive): Record<string, T[]> {\n const result: Record<string, T[]> = {};\n\n for (const item of array) {\n const rawKey = selector(item);\n const key = rawKey === undefined || rawKey === null ? '_' : String(rawKey);\n\n if (isUnsafeKey(key)) continue;\n\n if (!result[key]) {\n result[key] = [];\n }\n\n result[key].push(item);\n }\n\n return result;\n}",
|
|
180
|
-
"indexBy": "export function indexBy<T>(array: readonly T[], selector: (item: T) => Primitive): Record<string, T> {\n const result: Record<string, T> = {};\n\n for (const item of array) {\n const key = String(selector(item));\n\n if (isUnsafeKey(key)) continue;\n\n result[key] = item;\n }\n\n return result;\n}",
|
|
181
|
-
"PageEnvelope": "export type PageEnvelope<T> = Readonly<{\n /** The page's items; empty when `page` is past the last page. */\n items: readonly T[];\n /** The requested page, echoed in the caller's base. */\n page: number;\n /** Items per page. */\n pageSize: number;\n /** Size of the full list the page was cut from. */\n totalItems: number;\n /** At least 1, even for an empty list, so `page < totalPages` never underflows. */\n totalPages: number;\n}>;",
|
|
182
|
-
"PaginateOptions": "export type PaginateOptions = Readonly<{\n /** Page to cut, in the caller's base. Defaults to the first page of that base. */\n page?: number;\n /** Items per page. Default 20. */\n pageSize?: number;\n /** Base of `page`: 0 for zero-based servers (Spring), 1 for one-based (default). */\n pageOffset?: 0 | 1;\n}>;",
|
|
183
|
-
"paginate": "export function paginate<T>(items: readonly T[], options: PaginateOptions = {}): PageEnvelope<T> {\n if (!Array.isArray(items)) throw new TypeError('paginate: first argument must be an array');\n\n const { pageOffset = 1, pageSize = 20 } = options;\n const page = options.page ?? pageOffset;\n\n if (!Number.isInteger(pageSize) || pageSize < 1)\n throw new RangeError('paginate: pageSize must be a positive integer');\n if (!Number.isInteger(page) || page < pageOffset)\n throw new RangeError(`paginate: page must be an integer >= ${pageOffset}`);\n\n const totalPages = Math.max(1, Math.ceil(items.length / pageSize));\n const start = (page - pageOffset) * pageSize;\n\n return {\n items: items.slice(start, start + pageSize),\n page,\n pageSize,\n totalItems: items.length,\n totalPages,\n };\n}",
|
|
184
|
-
"partition": "export function partition<T>(\n array: readonly T[],\n predicate: (item: T, index: number, array: readonly T[]) => boolean,\n): [T[], T[]] {\n const accepted: T[] = [];\n const rejected: T[] = [];\n\n for (let index = 0; index < array.length; index++) {\n if (predicate(array[index], index, array)) {\n accepted.push(array[index]);\n } else {\n rejected.push(array[index]);\n }\n }\n\n return [accepted, rejected];\n}",
|
|
185
|
-
"SortDirection": "export type SortDirection = 'asc' | 'desc';",
|
|
186
|
-
"SortSelectors": "export type SortSelectors<T> = Partial<Record<keyof T, SortDirection>>;",
|
|
187
|
-
"SortCriterion": "export type SortCriterion<T> = Readonly<{\n key: keyof T | (string & {});\n direction?: SortDirection;\n}>;",
|
|
188
|
-
"sort": "export function sort<T>(array: readonly T[], selector: (item: T) => unknown, direction?: SortDirection): T[];\n\nexport function sort<T>(array: readonly T[], selectors: SortSelectors<T>): T[];\n\nexport function sort<T>(array: readonly T[], criteria: ReadonlyArray<SortCriterion<T>>): T[];\n\nexport function sort<T>(\n array: readonly T[],\n selectorOrSelectors: ((item: T) => unknown) | ReadonlyArray<SortCriterion<T>> | SortSelectors<T>,\n direction: SortDirection = 'asc',\n): T[] {\n if (!Array.isArray(array)) throw new TypeError('sort: first argument must be an array');\n\n if (typeof selectorOrSelectors === 'function') {\n const multiplier = direction === 'desc' ? -1 : 1;\n\n return [...array].sort((a, b) => compare(selectorOrSelectors(a), selectorOrSelectors(b)) * multiplier);\n }\n\n if (isCriteriaForm(selectorOrSelectors)) {\n const criteria = selectorOrSelectors.map(({ direction: dir = 'asc', key }) => ({\n multiplier: dir === 'desc' ? -1 : 1,\n path: String(key),\n }));\n\n return [...array].sort((a, b) => {\n for (const { multiplier, path } of criteria) {\n const result = compare(getPath(a, path), getPath(b, path)) * multiplier;\n\n if (result !== 0) return result;\n }\n\n return 0;\n });\n }\n\n return [...array].sort(compareBy(selectorOrSelectors));\n}",
|
|
189
|
-
"uniq": "export function uniq<T>(array: readonly T[], selector?: (item: T) => Primitive): T[] {\n if (array.length <= 1) {\n return [...array];\n }\n\n if (!selector) {\n return [...new Set(array)];\n }\n\n return dedupeBySelector(array, selector);\n}",
|
|
190
|
-
"abortable": "export function abortable<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {\n if (signal.aborted) {\n return Promise.reject(abortError(signal));\n }\n\n return new Promise<T>((resolve, reject) => {\n const onAbort = () => reject(abortError(signal));\n\n signal.addEventListener('abort', onAbort, { once: true });\n\n promise\n .then((value) => resolve(value))\n .catch((error) => reject(error))\n .finally(() => signal.removeEventListener('abort', onAbort));\n });\n}",
|
|
191
|
-
"abortError": "export function abortError(signal?: AbortSignal, message = 'Aborted'): unknown {\n return signal?.reason ?? new DOMException(message, 'AbortError');\n}",
|
|
192
|
-
"AttemptResult": "export type AttemptResult<T> =\n | { ok: true; value: T }\n // eslint-disable-next-line perfectionist/sort-object-types\n | { ok: false; error: unknown };",
|
|
193
|
-
"isOk": "export function isOk<T>(result: AttemptResult<T>): result is { ok: true; value: T } {\n return result.ok === true;\n}",
|
|
194
|
-
"isFail": "export function isFail<T>(result: AttemptResult<T>): result is { ok: false; error: unknown } {\n return result.ok === false;\n}",
|
|
195
|
-
"attempt": "export async function attempt<T>(fn: () => T | Promise<T>): Promise<AttemptResult<T>> {\n try {\n return { ok: true, value: await fn() };\n } catch (error) {\n return { error, ok: false };\n }\n}",
|
|
196
|
-
"backoff": "export function backoff(attempt: number, maxMs = 30_000): number {\n const n = Math.max(0, Number.isNaN(attempt) ? 0 : Math.floor(attempt));\n\n return Math.min(1000 * 2 ** n, maxMs);\n}",
|
|
197
|
-
"parallel": "export async function parallel<T, R>(\n array: readonly T[],\n callback: (item: T, index: number, array: readonly T[]) => Promise<R> | R,\n options: { abortOnError?: boolean; limit?: number; signal?: AbortSignal } = {},\n): Promise<R[]> {\n const { abortOnError = false, limit = Infinity, signal } = options;\n\n if (limit < 1) {\n throw new RangeError(`parallel: limit must be at least 1, got ${limit}`);\n }\n\n if (signal?.aborted) {\n throw abortError(signal);\n }\n\n if (array.length === 0) {\n return [];\n }\n\n const results: R[] = new Array(array.length);\n let currentIndex = 0;\n const failFastController = abortOnError ? new AbortController() : undefined;\n\n const worker = async (): Promise<void> => {\n while (true) {\n if (signal?.aborted) {\n throw abortError(signal);\n }\n\n if (failFastController?.signal.aborted) {\n return;\n }\n\n if (currentIndex >= array.length) {\n return;\n }\n\n const index = currentIndex++;\n\n try {\n results[index] = await callback(array[index]!, index, array);\n } catch (err) {\n failFastController?.abort();\n throw err;\n }\n }\n };\n\n const workerCount = Math.min(limit, array.length);\n const workers = Array.from({ length: workerCount }, () => worker());\n\n await Promise.all(workers);\n\n return results;\n}",
|
|
198
|
-
"RetryOptions": "export type RetryOptions = {\n delay?: number | ((attempt: number) => number);\n shouldRetry?: (error: unknown, attempt: number) => boolean;\n signal?: AbortSignal;\n timeout?: number;\n times?: number;\n};",
|
|
199
|
-
"retry": "export async function retry<T>(\n fn: (signal?: AbortSignal) => Promise<T>,\n { delay = 250, shouldRetry, signal, timeout, times = 3 }: RetryOptions = {},\n): Promise<T> {\n if (!Number.isInteger(times) || times < 1) {\n throw new RangeError(`retry: times must be a positive integer, got ${times}`);\n }\n\n for (let tryCount = 1; tryCount <= times; tryCount++) {\n if (signal?.aborted) throw abortError(signal);\n\n const callSignal = buildSignal(timeout, signal);\n\n try {\n return await fn(callSignal);\n } catch (err) {\n if (tryCount === times) throw err;\n\n if (shouldRetry && !shouldRetry(err, tryCount - 1)) throw err;\n\n const ms = typeof delay === 'function' ? delay(tryCount - 1) : delay;\n\n if (ms > 0) await sleep(ms, signal);\n }\n }\n\n /* unreachable: the loop always returns or throws before exhausting all attempts */\n return undefined as never;\n}",
|
|
200
|
-
"sleep": "export async function sleep(timeout: number, signal?: AbortSignal): Promise<void> {\n if (!signal) {\n return new Promise((resolve) => setTimeout(resolve, timeout));\n }\n\n if (signal.aborted) {\n return Promise.reject(abortError(signal));\n }\n\n return new Promise<void>((resolve, reject) => {\n const id = setTimeout(() => {\n signal.removeEventListener('abort', onAbort);\n resolve();\n }, timeout);\n\n const onAbort = () => {\n clearTimeout(id);\n signal.removeEventListener('abort', onAbort);\n reject(abortError(signal));\n };\n\n signal.addEventListener('abort', onAbort);\n });\n}",
|
|
201
|
-
"TaskPool": "export interface TaskPool {\n readonly active: number;\n readonly disposalSignal: AbortSignal;\n dispose(reason?: unknown): void;\n readonly disposed: boolean;\n idle(): Promise<void>;\n readonly pending: number;\n run<T>(task: (signal: AbortSignal) => Promise<T>): Promise<T>;\n [Symbol.dispose](): void;\n}",
|
|
202
|
-
"taskPool": "export function taskPool({ concurrency = 1 }: { concurrency?: number } = {}): TaskPool {\n if (!Number.isInteger(concurrency) || concurrency < 1) {\n throw new RangeError('taskPool: concurrency must be a positive integer');\n }\n\n const controller = new AbortController();\n const pending: PendingTask[] = [];\n let active = 0;\n let disposed = false;\n let idleDeferred: ReturnType<typeof Promise.withResolvers<void>> | undefined;\n\n const resolveIdle = (): void => {\n if (active === 0 && pending.length === 0) {\n idleDeferred?.resolve();\n idleDeferred = undefined;\n }\n };\n\n const start = (): void => {\n while (active < concurrency && pending.length > 0) {\n const next = pending.shift()!;\n\n active++;\n void Promise.resolve()\n .then(() => next.run(controller.signal))\n .then(next.resolve, next.reject)\n .finally(() => {\n active--;\n start();\n resolveIdle();\n });\n }\n };\n\n return {\n get active(): number {\n return active;\n },\n get disposalSignal(): AbortSignal {\n return controller.signal;\n },\n dispose: (reason: unknown = new DOMException('Task pool disposed', 'AbortError')): void => {\n if (disposed) return;\n\n disposed = true;\n controller.abort(reason);\n\n for (const task of pending.splice(0)) task.reject(reason);\n\n resolveIdle();\n },\n get disposed(): boolean {\n return disposed;\n },\n idle: (): Promise<void> => {\n if (active === 0 && pending.length === 0) return Promise.resolve();\n\n idleDeferred ??= Promise.withResolvers<void>();\n\n return idleDeferred.promise;\n },\n get pending(): number {\n return pending.length;\n },\n run: <T>(task: (signal: AbortSignal) => Promise<T>): Promise<T> => {\n const deferred = Promise.withResolvers<T>();\n\n if (disposed) {\n deferred.reject(controller.signal.reason);\n\n return deferred.promise;\n }\n\n pending.push({\n reject: deferred.reject,\n resolve: deferred.resolve as (value: unknown) => void,\n run: task as (signal: AbortSignal) => Promise<unknown>,\n });\n start();\n\n return deferred.promise;\n },\n [Symbol.dispose](): void {\n this.dispose();\n },\n };\n}",
|
|
203
|
-
"Timer": "export type Timer = {\n /** (Re)starts the timer: any pending run is cancelled first, so at most one run is ever scheduled. */\n arm(ms: number): void;\n /** Cancels the pending run, if any. Safe to call repeatedly. */\n cancel(): void;\n /** `true` while a run is scheduled and has not fired yet. */\n readonly pending: boolean;\n};",
|
|
204
|
-
"timer": "export function timer(fn: () => void): Timer {\n let id: ReturnType<typeof setTimeout> | undefined;\n\n const cancel = (): void => {\n if (id === undefined) return;\n\n clearTimeout(id);\n id = undefined;\n };\n\n return {\n arm(ms) {\n cancel();\n id = setTimeout(() => {\n id = undefined;\n fn();\n }, ms);\n },\n cancel,\n get pending() {\n return id !== undefined;\n },\n };\n}",
|
|
205
|
-
"WaitForOptions": "export type WaitForOptions = {\n interval?: number;\n signal?: AbortSignal;\n timeout?: number;\n};",
|
|
206
|
-
"waitFor": "export async function waitFor(\n condition: (signal: AbortSignal) => boolean | Promise<boolean>,\n { interval = 100, signal, timeout: ms = 5000 }: WaitForOptions = {},\n): Promise<void> {\n const deadline = AbortSignal.timeout(ms);\n const merged = signal ? AbortSignal.any([signal, deadline]) : deadline;\n\n merged.throwIfAborted();\n\n while (true) {\n merged.throwIfAborted();\n\n if (await condition(merged)) return;\n\n await sleep(interval, merged);\n }\n}",
|
|
207
|
-
"CacheOptions": "export type CacheOptions = {\n capacity?: number;\n now?: () => number;\n ttlMs?: number;\n};",
|
|
208
|
-
"Cache": "export interface Cache<K, T> {\n clear(): void;\n delete(key: K): boolean;\n entries(): ReadonlyArray<readonly [K, T]>;\n get(key: K): T | undefined;\n getOrLoad(key: K, load: () => Promise<T>): Promise<T>;\n set(key: K, value: T, options?: { ttlMs?: number }): void;\n readonly size: number;\n}",
|
|
209
|
-
"cache": "export function cache<K, T>({ capacity = Infinity, now = Date.now, ttlMs }: CacheOptions = {}): Cache<K, T> {\n if (capacity !== Infinity && (!Number.isInteger(capacity) || capacity < 1)) {\n throw new RangeError(`cache: capacity must be a positive integer or Infinity, got ${capacity}`);\n }\n\n const entries = new Map<K, Entry<T>>();\n const pending = new Map<K, Promise<T>>();\n const revisions = new Map<K, number>();\n let generation = 0;\n\n const advanceRevision = (key: K): number => {\n const revision = (revisions.get(key) ?? 0) + 1;\n\n revisions.set(key, revision);\n\n return revision;\n };\n\n const expiresAt = (duration: number | undefined): number | undefined => {\n if (duration === undefined || duration === Infinity) return undefined;\n\n if (!Number.isFinite(duration) || duration < 0) {\n throw new RangeError(`cache: ttlMs must be a non-negative finite number or Infinity, got ${duration}`);\n }\n\n return now() + duration;\n };\n\n const read = (key: K): T | undefined => {\n const entry = entries.get(key);\n\n if (!entry) return undefined;\n\n if (entry.expiresAt !== undefined && entry.expiresAt <= now()) {\n entries.delete(key);\n\n return undefined;\n }\n\n return entry.value;\n };\n\n const trim = (): void => {\n for (const [key, entry] of entries) {\n if (entry.expiresAt !== undefined && entry.expiresAt <= now()) entries.delete(key);\n }\n\n while (entries.size > capacity) {\n const oldest = entries.keys().next().value;\n\n if (oldest === undefined) return;\n\n entries.delete(oldest);\n }\n };\n\n const set = (key: K, value: T, options: { ttlMs?: number } = {}): void => {\n advanceRevision(key);\n entries.delete(key);\n entries.set(key, { expiresAt: expiresAt(options.ttlMs ?? ttlMs), value });\n trim();\n };\n\n const getOrLoad = (key: K, load: () => Promise<T>): Promise<T> => {\n const cached = read(key);\n\n if (cached !== undefined || entries.has(key)) return Promise.resolve(cached as T);\n\n const existing = pending.get(key);\n\n if (existing) return existing;\n\n const capturedGeneration = generation;\n const capturedRevision = advanceRevision(key);\n const result = load().then(\n (value) => {\n if (pending.get(key) === result) pending.delete(key);\n\n if (generation === capturedGeneration && revisions.get(key) === capturedRevision) {\n set(key, value);\n }\n\n return value;\n },\n (error: unknown) => {\n if (pending.get(key) === result) pending.delete(key);\n\n throw error;\n },\n );\n\n pending.set(key, result);\n\n return result;\n };\n\n return {\n clear: () => {\n generation++;\n entries.clear();\n pending.clear();\n revisions.clear();\n },\n delete: (key) => {\n pending.delete(key);\n advanceRevision(key);\n\n return entries.delete(key);\n },\n entries: () => {\n trim();\n return [...entries].map(([key, entry]) => [key, entry.value] as const);\n },\n get: read,\n getOrLoad,\n set,\n get size() {\n return entries.size;\n },\n };\n}",
|
|
210
|
-
"MemoOptions": "export type MemoOptions<T extends Fn> = {\n key?: (...args: Parameters<T>) => PropertyKey;\n maxSize?: number;\n};",
|
|
211
|
-
"Memoized": "export type Memoized<T extends Fn> = ((...args: Parameters<T>) => ReturnType<T>) & {\n clear(): void;\n invalidate(...args: Parameters<T>): void;\n readonly size: number;\n};",
|
|
212
|
-
"memo": "export function memo<T extends Fn>(fn: SyncFn<T>, { key, maxSize = Infinity }: MemoOptions<T> = {}): Memoized<T> {\n if (maxSize !== Infinity && (!Number.isInteger(maxSize) || maxSize < 1)) {\n throw new RangeError(`memo: maxSize must be a positive integer or Infinity, got ${maxSize}`);\n }\n\n const cache = new LruMap<PropertyKey, ReturnType<T>>(maxSize);\n\n const resolveKey = (...args: Parameters<T>): PropertyKey => (key ? key(...args) : defaultKey(args));\n\n const memoized = (...args: Parameters<T>): ReturnType<T> => {\n const cacheKey = resolveKey(...args);\n\n if (cache.has(cacheKey)) {\n const cached = cache.get(cacheKey)!;\n\n cache.set(cacheKey, cached);\n\n return cached;\n }\n\n const value = fn(...args) as ReturnType<T>;\n\n cache.set(cacheKey, value);\n\n return value;\n };\n\n const result = Object.assign(memoized, {\n clear: () => cache.clear(),\n invalidate: (...args: Parameters<T>): void => {\n cache.delete(resolveKey(...args));\n },\n });\n\n Object.defineProperty(result, 'size', { get: () => cache.size });\n\n return result as Memoized<T>;\n}",
|
|
213
|
-
"bytesToBase64Url": "export function bytesToBase64Url(bytes: Uint8Array): string {\n let output = '';\n for (let index = 0; index < bytes.length; index += 3) {\n const a = bytes[index]!;\n const b = bytes[index + 1];\n const c = bytes[index + 2];\n output += ALPHABET[a >> 2]!;\n output += ALPHABET[((a & 0b11) << 4) | ((b ?? 0) >> 4)]!;\n if (b !== undefined) output += ALPHABET[((b & 0b1111) << 2) | ((c ?? 0) >> 6)]!;\n if (c !== undefined) output += ALPHABET[c & 0b111111]!;\n }\n return output;\n}",
|
|
214
|
-
"base64UrlToBytes": "export function base64UrlToBytes(text: string): Uint8Array {\n const bytes: number[] = [];\n let buffer = 0;\n let bits = 0;\n for (const char of text) {\n const value = LOOKUP.get(char);\n if (value === undefined) throw new Error(`Invalid base64url character \"${char}\"`);\n buffer = (buffer << 6) | value;\n bits += 6;\n if (bits >= 8) {\n bits -= 8;\n bytes.push((buffer >> bits) & 0xff);\n }\n }\n return new Uint8Array(bytes);\n}",
|
|
215
|
-
"textToBase64Url": "export function textToBase64Url(text: string): string {\n return bytesToBase64Url(encoder.encode(text));\n}",
|
|
216
|
-
"base64UrlToText": "export function base64UrlToText(text: string): string {\n return decoder.decode(base64UrlToBytes(text));\n}",
|
|
217
|
-
"utf8Bytes": "export function utf8Bytes(text: string): number {\n return encoder.encode(text).length;\n}",
|
|
218
|
-
"CompressionOptions": "export interface CompressionOptions {\n format?: CompressionFormat;\n}",
|
|
219
|
-
"DecompressionOptions": "export interface DecompressionOptions extends CompressionOptions {\n maxOutputBytes: number;\n}",
|
|
220
|
-
"compressBytes": "export async function compressBytes(bytes: Uint8Array, options: CompressionOptions = {}): Promise<Uint8Array> {\n try {\n return await transformBytes(bytes, new CompressionStream(options.format ?? 'deflate-raw'), Infinity);\n } catch (cause) {\n if (cause instanceof ArsenalSerializationError) throw cause;\n throw new ArsenalSerializationError('Compression is unavailable for this format.', { cause });\n }\n}",
|
|
221
|
-
"decompressBytes": "export async function decompressBytes(bytes: Uint8Array, options: DecompressionOptions): Promise<Uint8Array> {\n if (!Number.isSafeInteger(options.maxOutputBytes) || options.maxOutputBytes < 0)\n throw new ArsenalSerializationError('maxOutputBytes must be a non-negative safe integer.');\n try {\n return await transformBytes(\n bytes,\n new DecompressionStream(options.format ?? 'deflate-raw'),\n options.maxOutputBytes,\n );\n } catch (cause) {\n if (cause instanceof ArsenalSerializationError) throw cause;\n throw new ArsenalSerializationError('Decompression is unavailable for this format.', { cause });\n }\n}",
|
|
222
|
-
"ShareCodeOptions": "export interface ShareCodeOptions {\n /** Maximum serialized payload size in bytes; decoding also refuses codes that could carry more. */\n readonly maxBytes: number;\n /** Versioned identifier at the start of every code, e.g. `'pb1'`: 1–8 alphanumeric characters. */\n readonly prefix: string;\n}",
|
|
223
|
-
"pack": "export async function pack(payload: unknown, options: ShareCodeOptions): Promise<string> {\n assertOptions(options);\n const { maxBytes, prefix } = options;\n let serialized: string | undefined;\n try {\n serialized = JSON.stringify(payload);\n } catch (error) {\n throw new ShareCodeError('invalid', 'The share payload is not JSON-serializable.', { cause: error });\n }\n if (serialized === undefined) {\n throw new ShareCodeError('invalid', 'The share payload is not JSON-serializable.');\n }\n const bytes = encoder.encode(serialized);\n if (bytes.length > maxBytes) {\n throw new ShareCodeError('too-large', 'The share payload exceeds the byte limit.');\n }\n const raw = `${prefix}r.${bytesToBase64Url(bytes)}`;\n if (!streamsAvailable()) return raw;\n // Compression can enlarge small payloads: ship whichever representation is shorter.\n const compressed = `${prefix}d.${bytesToBase64Url(await compressBytes(bytes))}`;\n return compressed.length < raw.length ? compressed : raw;\n}",
|
|
224
|
-
"unpack": "export async function unpack(code: string, options: ShareCodeOptions): Promise<unknown> {\n assertOptions(options);\n const { maxBytes, prefix } = options;\n const text = code.trim();\n // A code can only carry so many bytes when base64url-encoded: refuse longer input up front.\n const maxCodeLength = Math.ceil((maxBytes * 4) / 3) + prefix.length + 2;\n if (text.length > maxCodeLength) {\n throw new ShareCodeError('too-large', 'The share code exceeds the length limit.');\n }\n const mode = text.slice(prefix.length, prefix.length + 1);\n if (!text.startsWith(prefix) || (mode !== 'r' && mode !== 'd') || text[prefix.length + 1] !== '.') {\n throw new ShareCodeError('invalid', 'That share code format is not supported.');\n }\n const encoded = text.slice(prefix.length + 2);\n if (!/^[A-Za-z0-9_-]+$/.test(encoded)) {\n throw new ShareCodeError('invalid', 'Malformed share code.');\n }\n const bytes = base64UrlToBytes(encoded);\n // Base64url is not injective: round-trip so crafted non-canonical encodings fail.\n if (bytesToBase64Url(bytes) !== encoded) {\n throw new ShareCodeError('invalid', 'Malformed share code.');\n }\n if (mode === 'd' && !decompressionAvailable()) {\n throw new ShareCodeError('compression-unavailable', 'Raw-DEFLATE decompression is unavailable in this browser.');\n }\n // Decompression enforces its own output budget; its typed error carries that failure.\n const decoded = mode === 'd' ? await decompressBytes(bytes, { maxOutputBytes: maxBytes }) : bytes;\n if (decoded.length > maxBytes) {\n throw new ShareCodeError('too-large', 'The share payload exceeds the byte limit.');\n }\n try {\n return JSON.parse(decoder.decode(decoded));\n } catch (error) {\n throw new ShareCodeError('invalid', 'The share code payload is not valid UTF-8 JSON.', { cause: error });\n }\n}",
|
|
225
|
-
"ArsenalError": "export class ArsenalError 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}",
|
|
226
|
-
"ArsenalSerializationError": "export class ArsenalSerializationError extends ArsenalError {}",
|
|
227
|
-
"ShareCodeReason": "export type ShareCodeReason = 'compression-unavailable' | 'invalid' | 'too-large';",
|
|
228
|
-
"ShareCodeError": "export class ShareCodeError extends ArsenalError {\n readonly reason: ShareCodeReason;\n\n constructor(reason: ShareCodeReason, message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.reason = reason;\n }\n}",
|
|
229
|
-
"DebounceOptions": "export type DebounceOptions = {\n /** Invoke on the leading edge of the delay window. Default: `false`. */\n leading?: boolean;\n /** Invoke on the trailing edge of the delay window. Default: `true`. */\n trailing?: boolean;\n};",
|
|
230
|
-
"Debounced": "export type Debounced<T extends Fn> = ((...args: Parameters<T>) => ReturnType<T> | undefined) & {\n cancel(): void;\n flush(): ReturnType<T> | undefined;\n pending(): boolean;\n};",
|
|
231
|
-
"debounce": "export function debounce<T extends Fn>(\n fn: T,\n delay = 300,\n options: DebounceOptions = { leading: false, trailing: true },\n): Debounced<T> {\n const leading = options.leading ?? false;\n const trailing = options.trailing ?? true;\n\n if (!leading && !trailing) {\n warn('debounce: both `leading` and `trailing` are false: the wrapped function will never be invoked.');\n }\n\n let timerId: ReturnType<typeof setTimeout> | undefined;\n let lastArgs: Parameters<T> | undefined;\n let lastResult: ReturnType<T> | undefined;\n let leadingFired = false;\n\n const clearTimer = () => {\n if (timerId !== undefined) {\n clearTimeout(timerId);\n timerId = undefined;\n }\n };\n\n const invokeTrailing = () => {\n clearTimer();\n leadingFired = false;\n\n if (!lastArgs) return undefined;\n\n const args = lastArgs;\n\n lastArgs = undefined;\n lastResult = fn(...args) as ReturnType<T>;\n\n return lastResult;\n };\n\n return Object.assign(\n (...args: Parameters<T>): ReturnType<T> | undefined => {\n lastArgs = args;\n\n if (leading && !leadingFired) {\n leadingFired = true;\n lastResult = fn(...args) as ReturnType<T>;\n // Clear args regardless of `trailing`: the leading call already consumed this\n // invocation. The trailing timer below only re-invokes `fn` if a *further* call\n // arrives during the cooldown window and repopulates `lastArgs`.\n lastArgs = undefined;\n\n if (!trailing) {\n // Leading-only: start cooldown: no trailing call needed\n timerId = setTimeout(() => {\n timerId = undefined;\n leadingFired = false;\n }, delay);\n\n return lastResult;\n }\n }\n\n // When leading-only, ignore calls within the cooldown window\n if (leading && !trailing && leadingFired) return lastResult;\n\n clearTimer();\n timerId = setTimeout(invokeTrailing, delay);\n\n return lastResult;\n },\n {\n cancel: () => {\n clearTimer();\n lastArgs = undefined;\n leadingFired = false;\n },\n flush: (): ReturnType<T> | undefined => invokeTrailing(),\n pending: () => timerId !== undefined,\n },\n );\n}",
|
|
232
|
-
"Once": "export type Once<T extends Fn> = T & { reset: () => void };",
|
|
233
|
-
"once": "export const once = <T extends Fn>(fn: T): Once<T> => {\n let result: ReturnType<T> | undefined;\n let called = false;\n\n const wrappedFn = ((...args: Parameters<T>): ReturnType<T> => {\n if (!called) {\n result = fn(...args) as ReturnType<T>;\n called = true;\n }\n\n return result as ReturnType<T>;\n }) as Once<T>;\n\n wrappedFn.reset = () => {\n result = undefined;\n called = false;\n };\n\n return wrappedFn;\n};",
|
|
234
|
-
"pipe": "export function pipe(): <T>(x: T) => T;\n\nexport function pipe<T extends readonly [Fn, ...Fn[]]>(...fns: T): (...args: FirstParameters<T>) => LastReturnType<T>;\n\nexport function pipe(...fns: Fn[]): Fn {\n if (fns.length === 0) return <T>(x: T): T => x;\n\n const [firstFn, ...restFns] = fns;\n\n return (...args: never[]) =>\n restFns.reduce<unknown>((prev, fn) => (fn as (x: unknown) => unknown)(prev), firstFn(...args));\n}",
|
|
235
|
-
"Tapper": "export interface Tapper<Event> {\n /** Remove all handlers (call from `dispose()`). */\n clear(): void;\n /** Deliver an event to every handler. Handler errors are swallowed; zero cost when idle. */\n emit(event: Event): void;\n /** Number of registered handlers. */\n readonly size: number;\n /** Register a handler; auto-detaches when `signal` aborts. Returns an unsubscribe function. */\n tap(handler: (event: Event) => void, options?: { readonly signal?: AbortSignal }): Unsubscribe;\n}",
|
|
236
|
-
"tapper": "export function tapper<Event>(): Tapper<Event> {\n const handlers = new Set<(event: Event) => void>();\n\n return {\n clear(): void {\n handlers.clear();\n },\n emit(event: Event): void {\n if (handlers.size === 0) return;\n for (const handler of [...handlers]) {\n try {\n handler(event);\n } catch {\n // Observability must never affect package behavior.\n }\n }\n },\n get size(): number {\n return handlers.size;\n },\n tap(handler: (event: Event) => void, options?: { readonly signal?: AbortSignal }): Unsubscribe {\n const signal = options?.signal;\n if (signal?.aborted) return noop;\n\n handlers.add(handler);\n\n const detach = (): void => {\n handlers.delete(handler);\n signal?.removeEventListener('abort', detach);\n };\n\n signal?.addEventListener('abort', detach, { once: true });\n\n return detach;\n },\n };\n}",
|
|
237
|
-
"ThrottleOptions": "export type ThrottleOptions = {\n leading?: boolean; // invoke at the start of the window\n trailing?: boolean; // invoke at the end with the last args\n};",
|
|
238
|
-
"Throttled": "export type Throttled<T extends Fn> = ((...args: Parameters<T>) => ReturnType<T> | undefined) & {\n cancel(): void;\n flush(): ReturnType<T> | undefined;\n pending(): boolean; // whether there's a pending call that flush() would execute\n};",
|
|
239
|
-
"throttle": "export function throttle<T extends Fn>(\n fn: T,\n delay = 700,\n options: ThrottleOptions = { leading: true, trailing: false },\n): Throttled<T> {\n const leading = options.leading ?? true;\n const trailing = options.trailing ?? false;\n\n let timerId: ReturnType<typeof setTimeout> | undefined;\n let lastInvokeTime = -Infinity;\n let lastArgs: Parameters<T> | undefined;\n let lastResult: ReturnType<T> | undefined;\n\n const clearTimer = () => {\n if (timerId !== undefined) {\n clearTimeout(timerId);\n timerId = undefined;\n }\n };\n\n const scheduleTimer = (delayMs: number) => {\n timerId = setTimeout(timerExpired, delayMs);\n };\n\n const invoke = (now: number) => {\n lastInvokeTime = now;\n clearTimer();\n\n if (!lastArgs) return undefined;\n\n const args = lastArgs;\n\n lastArgs = undefined;\n lastResult = fn(...args) as ReturnType<T>;\n\n return lastResult;\n };\n\n const remaining = (now: number) => delay - (now - lastInvokeTime);\n\n const timerExpired = () => {\n const now = Date.now();\n\n if (lastArgs && remaining(now) <= 0) {\n // trailing edge invoke\n invoke(now);\n } else if (lastArgs) {\n // reschedule until a window elapses\n scheduleTimer(remaining(now));\n } else {\n clearTimer();\n }\n };\n\n return Object.assign(\n (...args: Parameters<T>): ReturnType<T> | undefined => {\n const now = Date.now();\n\n if (lastInvokeTime === -Infinity && !leading) {\n // If leading is false, start the window now but don't invoke immediately\n lastInvokeTime = now;\n }\n\n lastArgs = args;\n\n const rem = remaining(now);\n\n if (rem <= 0) {\n // Window elapsed: invoke now\n return invoke(now);\n } else if (trailing && !timerId) {\n // Schedule trailing call if not already scheduled\n scheduleTimer(rem);\n }\n\n return lastResult;\n },\n {\n cancel: () => {\n clearTimer();\n lastArgs = undefined;\n lastInvokeTime = -Infinity;\n },\n flush: (): ReturnType<T> | undefined => {\n if (!lastArgs) return undefined;\n\n return invoke(Date.now());\n },\n // Pending if a trailing call is scheduled OR there are queued args.\n pending: () => lastArgs !== undefined || timerId !== undefined,\n },\n );\n}",
|
|
240
|
-
"allOf": "export function allOf<T>(...predicates: Predicate<T>[]): Predicate<T> {\n return (value) => predicates.every((predicate) => predicate(value));\n}",
|
|
241
|
-
"anyOf": "export function anyOf<T>(...predicates: Predicate<T>[]): Predicate<T> {\n return (value) => predicates.some((predicate) => predicate(value));\n}",
|
|
242
|
-
"noneOf": "export function noneOf<T>(...predicates: Predicate<T>[]): Predicate<T> {\n return (value) => predicates.every((predicate) => !predicate(value));\n}",
|
|
243
|
-
"not": "export function not<T>(predicate: Predicate<T>): Predicate<T> {\n return (value) => !predicate(value);\n}",
|
|
244
|
-
"isDefined": "export function isDefined<T>(arg: T | undefined): arg is T {\n return arg !== undefined;\n}",
|
|
245
|
-
"isEqual": "export function isEqual(a: unknown, b: unknown): boolean {\n return safeIsEqual(a, b, new WeakMap());\n}",
|
|
246
|
-
"isNil": "export function isNil(arg: unknown): arg is null | undefined {\n return arg === undefined || arg === null;\n}",
|
|
247
|
-
"isPlainObject": "export function isPlainObject(value: unknown): value is Record<string, unknown> {\n if (value == null || typeof value !== 'object') return false;\n\n const prototype = Object.getPrototypeOf(value);\n\n return prototype === Object.prototype || prototype === null;\n}",
|
|
248
|
-
"allocate": "export function allocate(amount: number, ratios: number[] | number): number[];\n\nexport function allocate(amount: bigint, ratios: number[] | number): bigint[];\n\nexport function allocate(amount: number | bigint, ratios: number[] | number): (number | bigint)[] {\n // If second param is a number, validate and treat it as number of equal parts\n if (typeof ratios === 'number') {\n if (!Number.isInteger(ratios) || ratios < 1) {\n throw new RangeError(`allocate: parts must be a positive integer, got ${ratios}`);\n }\n }\n\n const actualRatios = Array.isArray(ratios) ? ratios : Array(ratios).fill(1);\n\n if (actualRatios.length === 0) {\n throw new RangeError('Ratios array cannot be empty');\n }\n\n if (actualRatios.some((r) => r < 0)) {\n throw new RangeError('Ratios must be non-negative');\n }\n\n const totalRatio = actualRatios.reduce((sum, ratio) => sum + ratio, 0);\n\n if (totalRatio === 0) {\n throw new RangeError('Total ratio cannot be zero');\n }\n\n if (typeof amount === 'bigint') {\n const totalRatioBigInt = BigInt(totalRatio);\n const results = Array.from(\n { length: actualRatios.length - 1 },\n (_, i) => (amount * BigInt(actualRatios[i])) / totalRatioBigInt,\n );\n\n results.push(amount - results.reduce((s, v) => s + v, 0n));\n\n return results;\n }\n\n // For number type, use proportional allocation for all ratios uniformly\n const results = Array.from({ length: actualRatios.length - 1 }, (_, i) =>\n Math.floor((amount * actualRatios[i]) / totalRatio),\n );\n\n results.push(amount - results.reduce((s, v) => s + v, 0));\n\n return results;\n}",
|
|
249
|
-
"clamp": "export function clamp(n: number, min?: number, max?: number): number {\n if (min != null && n < min) return min;\n\n if (max != null && n > max) return max;\n\n return n;\n}",
|
|
250
|
-
"range": "export function range(stop: number): number[];\n\nexport function range(start: number, stop: number): number[];\n\nexport function range(start: number, stop: number, step: number): number[];\n\nexport function range(startOrStop: number, stop?: number, step?: number): number[] {\n const [resolvedStart, resolvedStop, resolvedStep] =\n stop === undefined ? [0, startOrStop, 1] : step === undefined ? [startOrStop, stop, 1] : [startOrStop, stop, step];\n\n if (!Number.isFinite(resolvedStart) || !Number.isFinite(resolvedStop) || !Number.isFinite(resolvedStep)) {\n throw new RangeError('range: start, stop, and step must be finite numbers');\n }\n\n if (resolvedStep === 0) throw new RangeError('range: step cannot be 0');\n\n if (resolvedStart === resolvedStop) {\n return [];\n }\n\n const raw = (resolvedStop - resolvedStart) / resolvedStep;\n const length = Math.max(0, Number.isInteger(raw) ? raw : Math.ceil(raw + Number.EPSILON));\n\n if (length > 10_000_000) throw new RangeError('range: exceeds maximum allowed size of 10,000,000');\n\n return Array.from({ length }, (_, i) => resolvedStart + i * resolvedStep);\n}",
|
|
251
|
-
"getPath": "export function getPath<T extends Obj, P extends string>(item: T, path: P): PathValue<T, P> | undefined {\n return readPath(item, path) as PathValue<T, P> | undefined;\n}",
|
|
252
|
-
"getPathOr": "export function getPathOr<T extends Obj, P extends string, F>(item: T, path: P, fallback: F): PathValue<T, P> | F {\n const value = readPath(item, path);\n\n return (value === undefined ? fallback : value) as PathValue<T, P> | F;\n}",
|
|
253
|
-
"requirePath": "export function requirePath<T extends Obj, P extends string>(item: T, path: P): Exclude<PathValue<T, P>, undefined> {\n const value = readPath(item, path);\n\n if (value === undefined) throw new TypeError(`Path does not exist: '${path}'`);\n\n return value as Exclude<PathValue<T, P>, undefined>;\n}",
|
|
254
|
-
"HashOptions": "export type HashOptions = {\n /**\n * What to do when a class instance is encountered (an object whose prototype is\n * neither `Object.prototype` nor `null`).\n *\n * - `'coerce'` (default): calls `String(value)`.\n * - `'throw'`: throws an `ArsenalSerializationError`.\n */\n onClassInstance?: 'coerce' | 'throw';\n};",
|
|
255
|
-
"hash": "export function hash(value: unknown, options?: HashOptions): string {\n return _hash(value, options, new Set<object>());\n}",
|
|
256
|
-
"omit": "export function omit<T extends Obj, K extends keyof T>(obj: T, omittedKeys: readonly K[]): Omit<T, K> {\n const blacklist = new Set<PropertyKey>(omittedKeys as readonly PropertyKey[]);\n const out = {} as Omit<T, K>;\n\n for (const key of Object.keys(obj) as Array<keyof T>) {\n if (isUnsafeKey(key as PropertyKey)) continue;\n\n if (!blacklist.has(key)) {\n (out as T)[key] = obj[key];\n }\n }\n\n return out;\n}",
|
|
257
|
-
"pick": "export function pick<T extends Obj, K extends keyof T>(obj: T, selectedKeys: readonly K[]): Pick<T, K> {\n const out = {} as Pick<T, K>;\n\n for (const key of selectedKeys) {\n if (isUnsafeKey(key as PropertyKey)) continue;\n\n if (Object.hasOwn(obj, key)) {\n out[key] = obj[key];\n }\n }\n\n return out;\n}",
|
|
258
|
-
"random": "export function random(min: number, max: number, source?: RandomSource): number {\n if (min > max) throw new RangeError('random: minimum value must not be greater than maximum value');\n\n return randomIndex(max - min + 1, source) + min;\n}",
|
|
259
|
-
"RandomSource": "export type RandomSource = {\n next(): number;\n};",
|
|
260
|
-
"randomFloat": "export function randomFloat(source?: RandomSource): number {\n const value = source?.next() ?? crypto.getRandomValues(new Uint32Array(1))[0]! / 0x100000000;\n\n if (!Number.isFinite(value) || value < 0 || value >= 1) {\n throw new RangeError('random source must return a finite number in [0, 1)');\n }\n\n return value;\n}",
|
|
261
|
-
"camelCase": "export function camelCase(str: string): string {\n return normalizeCase(str, ' ')\n .replace(/[^\\p{L}\\p{N}]+(.)/gu, (_, char) => char.toUpperCase())\n .replace(/^./, (char) => char.toLowerCase());\n}",
|
|
262
|
-
"Unsubscribe": "export type Unsubscribe = () => void;",
|
|
263
|
-
"Subscribable": "export interface Subscribable<T> {\n getSnapshot(): T;\n subscribe(listener: () => void): Unsubscribe;\n}",
|
|
264
|
-
"Fn": "export type Fn<Args extends unknown[] = never[], Result = unknown> = (...args: Args) => Result;",
|
|
265
|
-
"Obj": "export type Obj = Record<string, unknown>;",
|
|
266
|
-
"Predicate": "export type Predicate<T> = (value: T) => boolean;",
|
|
267
|
-
"Sorter": "export type Sorter<T> = (a: T, b: T) => number;",
|
|
268
|
-
"Primitive": "export type Primitive = string | number | boolean;"
|
|
269
|
-
}
|
|
270
|
-
}
|
package/data/packages/assay.json
DELETED
|
@@ -1,52 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"apiSource": "export { walkFlatTree } from './dom';\nexport { AssayError, AssayQueryError, AssayTimeoutError } from './errors';\nexport {\n dispatch,\n fireBlur,\n fireChange,\n fireClick,\n fireCustom,\n fireFocus,\n fireInput,\n fireKeyDown,\n fireKeyUp,\n fireSubmit,\n} from './events';\nexport { installFormInternalsPolyfill } from './form-internals';\nexport { installPopoverPolyfill } from './popover';\nexport { getSlotted, type QueryScope, queryAllInShadow, queryInShadow, queryPart, within } from './query';\nexport {\n type DelayOptions,\n delay,\n type EventuallyOptions,\n eventually,\n type WaitOptions,\n waitForEvent,\n waitUntil,\n} from './wait';\n",
|
|
3
|
-
"docs": {
|
|
4
|
-
"index": "---\ntitle: 'Assay: Framework-agnostic DOM testing primitives'\ndescription: Scoped DOM queries, exact event dispatch, and cancellable async waiting for browser tests.\npackage: assay\ncategory: testing\nkeywords: [testing, dom, events, queries, custom-elements]\nrelated: [ore, refine]\nexports:\n [\n within,\n queryInShadow,\n queryAllInShadow,\n queryPart,\n getSlotted,\n dispatch,\n fireBlur,\n fireChange,\n fireClick,\n fireCustom,\n fireFocus,\n fireInput,\n fireKeyDown,\n fireKeyUp,\n fireSubmit,\n waitUntil,\n eventually,\n waitForEvent,\n delay,\n walkFlatTree,\n installFormInternalsPolyfill,\n AssayError,\n AssayQueryError,\n AssayTimeoutError,\n ]\nenvironments: [browser]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"assay\" />\n\n## Why Assay?\n\nAssay provides focused DOM test primitives that work with vanilla elements, custom elements, and framework-rendered output. It scopes queries, dispatches exact browser event classes, and waits on explicit conditions without imposing a renderer or browser automation stack.\n\n```ts\n// Before\nbutton.dispatchEvent(new MouseEvent('click', { bubbles: true }));\nawait new Promise((resolve) => setTimeout(resolve, 100));\n\n// After\nfireClick(view.get('button.submit'));\nawait waitUntil(() => view.queryByText('Saved') !== null);\n```\n\n| Feature | Assay | Testing Library DOM | Browser automation |\n| ------------------- | -------------------------------------------- | ---------------------------------------- | ---------------------------------------- |\n| Bundle size | <PackageInfo package=\"assay\" type=\"size\" /> | Larger query layer | Browser runtime required |\n| Zero 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| Scoped DOM queries | `within()` and shadow helpers | Renderer-oriented queries | Manual selectors |\n| Deterministic waits | `waitUntil()` and `waitForEvent()` | Framework-dependent | Full browser timing |\n\n<div class=\"decision-callout\">\n\n**Use Assay when** a DOM unit test needs readable queries, dispatched events, or a bounded async wait without adopting a rendering framework.\n\n**Consider browser integration tests when** correctness depends on browser default actions, focus behavior, pointer capture, layout, or accessibility-tree behavior.\n\n</div>\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add -D @vielzeug/assay\n```\n\n```sh [npm]\nnpm install -D @vielzeug/assay\n```\n\n```sh [yarn]\nyarn add -D @vielzeug/assay\n```\n\n:::\n\n## Quick Start\n\nScope a test fixture, dispatch an event, and wait for resulting DOM state.\n\n```ts\nimport { fireClick, waitUntil, within } from '@vielzeug/assay';\n\nconst panel = document.createElement('section');\npanel.innerHTML = '<button>Save</button><output></output>';\npanel.querySelector('button')!.addEventListener('click', () => {\n panel.querySelector('output')!.textContent = 'Saved';\n});\n\nconst view = within(panel);\nfireClick(view.get('button'));\nawait waitUntil(() => view.queryByText('Saved') !== null);\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- `within(root)` scopes nullable and required DOM queries.\n- `queryInShadow`, `queryPart`, and `getSlotted` cross custom-element boundaries explicitly.\n- `fireClick`, `fireInput`, `fireKeyDown`, and peers dispatch exact synchronous events.\n- `waitUntil`, `eventually`, and `waitForEvent` provide bounded, abortable async waiting.\n- `delay` models explicit cancellable timer scheduling.\n- `walkFlatTree` traverses the flat tree across slot boundaries jsdom's light-DOM queries miss.\n- `installFormInternalsPolyfill` gives jsdom the `ElementInternals` form-association API.\n- `AssayError`, `AssayQueryError`, and `AssayTimeoutError` provide typed failures.\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- [Ore](/ore/): component authoring and test fixtures that pair with Assay DOM helpers.\n- [Refine](/refine/): accessible components with component-specific test assertions.\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
|
|
5
|
-
"api": "---\ntitle: 'Assay: API Reference'\ndescription: API reference for @vielzeug/assay queries, event dispatch, async waiting, and test-environment helpers.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution mode | Common gotcha |\n| -------------------------------------------- | --------------------------------- | -------------- | ----------------------------------------------- |\n| `within` | Creates scoped query API | Sync | Required `get*` methods throw `AssayQueryError` |\n| `queryInShadow` / `queryPart` / `getSlotted` | Crosses custom-element boundaries | Sync | Open shadow roots are required |\n\n| `fire*` / `dispatch` | Dispatches platform event instances | Sync | Does not reproduce browser default behavior |\n| `waitUntil` / `eventually` / `waitForEvent` | Waits for conditions, assertions, or events | Async | Use a signal or timeout for bounded waits |\n| `delay` | Schedules a cancellable timer | Async | Pass a signal to cancel a pending wait |\n| `walkFlatTree` | Walks the flat tree across slot boundaries | Sync | jsdom-only need: browsers already use the flat tree |\n| `installFormInternalsPolyfill` | Polyfills `ElementInternals` form association for jsdom | Sync | Global patches: only install in suites that need them |\n\n## Package Entry Point\n\n| Import | Purpose |\n| ----------------- | ------------------------------------------------------------------------------ |\n| `@vielzeug/assay` | DOM queries, events, wait helpers, test-environment helpers, errors, and types |\n\n## Queries\n\n### `within(root)`\n\nCreates a `QueryScope` for an `Element`, `ShadowRoot`, `Document`, or `DocumentFragment`.\n\n| Method | Returns | Use |\n| --------------------------------- | ----------------- | -------------------------------------------- |\n| `get(selector)` | `Element` | Required CSS match; throws `AssayQueryError` |\n| `query(selector)` | `Element \\| null` | Optional CSS match |\n| `queryAll(selector)` | `Element[]` | All CSS matches |\n| `getByText(text, selector?)` | `Element` | Required exact trimmed-text match |\n| `queryByText(text, selector?)` | `Element \\| null` | Optional exact trimmed-text match |\n| `queryAllByText(text, selector?)` | `Element[]` | All exact trimmed-text matches |\n| `getByTestId(id)` | `Element` | Required `data-testid` match |\n| `queryByTestId(id)` | `Element \\| null` | Optional `data-testid` match |\n| `queryAllByTestId(id)` | `Element[]` | All `data-testid` matches |\n\nText selectors default to `'*'`. Required-query failures include the lookup and a bounded view of the scoped DOM.\n\n### Shadow and slot helpers\n\n| Function | Returns | Description |\n| ---------------------------------- | ----------------- | ---------------------------------------------------- |\n| `queryInShadow(host, selector)` | `Element \\| null` | First match in an open shadow root |\n| `queryAllInShadow(host, selector)` | `Element[]` | All matches in an open shadow root |\n| `queryPart(host, part)` | `Element \\| null` | First shadow element whose `part` token matches |\n| `getSlotted(host, slotName?)` | `Element[]` | Direct light-DOM children in a named or default slot |\n\nThese helpers return `null` or `[]` when there is no shadow root. Dynamic test IDs, parts, and slot names are matched\nas attribute values rather than interpolated into CSS selectors.\n\n## Event dispatch\n\nAll event helpers synchronously return `dispatchEvent()`'s boolean result.\n\n```ts\nimport {\n dispatch,\n fireBlur,\n fireChange,\n fireClick,\n fireCustom,\n fireFocus,\n fireInput,\n fireKeyDown,\n fireKeyUp,\n fireSubmit,\n} from '@vielzeug/assay';\n\nfireClick(button, { clientX: 20 });\nfireInput(input);\nfireKeyDown(input, { key: 'Enter' });\nfireCustom(element, 'item-added', { detail: { id: '42' } });\ndispatch(element, new Event('ready'));\n```\n\n| Function | Event class | Defaults |\n| --------------------------- | --------------- | ------------------------------------------------------ |\n| `fireBlur` / `fireFocus` | `FocusEvent` | Platform defaults (`bubbles: false`) |\n| `fireChange` | `Event` | `bubbles: true` |\n| `fireInput` | `InputEvent` | `bubbles: true` |\n| `fireClick` | `MouseEvent` | `bubbles: true`, `cancelable: true` |\n| `fireKeyDown` / `fireKeyUp` | `KeyboardEvent` | `bubbles: true`, `cancelable: true` |\n| `fireSubmit` | `SubmitEvent` | `bubbles: true`, `cancelable: true` |\n| `fireCustom` | `CustomEvent` | `bubbles: true`, `cancelable: true`, `composed: false` |\n\n`fireCustom(target, type, init?)` dispatches a `CustomEvent` with the given type. Assay intentionally does not\nprovide browser-default or fallback pointer/touch simulation.\n\n## Async waiting\n\n```ts\nawait waitUntil(() => ready, { interval: 20, signal, timeout: 1000 });\nawait eventually(() => expect(spy).toHaveBeenCalled(), { signal, timeout: 1000 });\nawait waitForEvent(target, 'ready', { signal, timeout: 1000 });\nawait delay(100, { signal });\n```\n\n| Function | Success condition | Options |\n| -------------------------------------- | ------------------------ | ------------------------------------------ |\n| `waitUntil(predicate, options?)` | Predicate returns `true` | `timeout`, `interval`, `signal` |\n| `eventually(assertion, options?)` | Assertion stops throwing | `timeout`, `interval`, `signal`, `message` |\n| `waitForEvent(target, type, options?)` | Target emits `type` | `timeout`, `signal` |\n| `delay(ms?, options?)` | Timer elapses | `signal` |\n\n`waitUntil()`, `eventually()`, and `waitForEvent()` reject with `AssayTimeoutError` when their shared deadline expires. `waitUntil()` and `eventually()` remain bounded while an asynchronous callback is pending. Abort rejects with the signal reason and removes Assay-owned timers and listeners. Callback work itself must cooperate with application cancellation.\n\n`timeout` and delay milliseconds must be finite, non-negative, and no greater than 2,147,483,647 ms; `interval` must be finite, positive, and within the same timer limit. Invalid durations throw `RangeError`. `eventually()` also accepts `message` for diagnostic timeout context.\n\n## Test-environment helpers\n\n### `walkFlatTree(root, visit)`\n\n```ts\nfunction walkFlatTree(root: Element, visit: (element: HTMLElement) => void): void;\n```\n\nWalks the flat tree below `root`, calling `visit` for each assigned or ordinary descendant (not for `root` itself).\nAt each `<slot>` it expands `assignedElements()` instead of descending into its (always empty, in jsdom) literal\nchildren. jsdom only\nimplements the light DOM tree, so `querySelectorAll()` never crosses a slot into its assigned elements; real\nbrowsers use the flat tree for that. This helper closes the gap for tests that must find form-associated (or\notherwise slotted) elements through shadow boundaries.\n\n```ts\nconst named: HTMLElement[] = [];\n\nwalkFlatTree(form, (el) => {\n if (el.hasAttribute('name')) named.push(el);\n});\n```\n\n### `installFormInternalsPolyfill()`\n\n```ts\nfunction installFormInternalsPolyfill(): () => void;\n```\n\njsdom implements none of the `ElementInternals` form-association API: not `setFormValue`, not `setValidity`, not\nthe `checkValidity`/`reportValidity`/`validity`/`validationMessage` mixin real browsers put on every\n`formAssociated: true` element, not even `FormData` collecting a form-associated element's set value, or\n`<form>.reset()` invoking `formResetCallback()`. Every one of those gaps is exercised by `useField()` from\n`@vielzeug/ore`, so any package testing a form-associated component needs all of them.\n\nCall it from a test setup when the suite tests form-associated components; it returns an `uninstall()` that\nrestores every patched global. The patches are global monkey-patches and skip APIs already implemented by the\nenvironment, so suites without form-associated components shouldn't install them. If `ElementInternals` is absent,\nthe installer is a no-op. A downstream package should\nrely on this instead of hand-rolling its own copy.\n\n```ts\n// vitest.setup.ts\nimport { installFormInternalsPolyfill } from '@vielzeug/assay';\nimport { install } from '@vielzeug/ore/testing';\nimport { afterAll, afterEach } from 'vitest';\n\ninstall(afterEach);\nafterAll(installFormInternalsPolyfill());\n```\n\n## Types\n\n```ts\nexport interface QueryScope {\n get<E extends Element = Element>(selector: string): E;\n getByTestId<E extends Element = Element>(testId: string): E;\n getByText<E extends Element = Element>(text: string, selector?: string): E;\n query<E extends Element = Element>(selector: string): E | null;\n queryAll<E extends Element = Element>(selector: string): E[];\n queryAllByTestId<E extends Element = Element>(testId: string): E[];\n queryAllByText<E extends Element = Element>(text: string, selector?: string): E[];\n queryByTestId<E extends Element = Element>(testId: string): E | null;\n queryByText<E extends Element = Element>(text: string, selector?: string): E | null;\n}\n```\n\nScoped query helpers returned by `within(root)`.\n\n```ts\nexport interface WaitOptions {\n /** Polling interval in ms (default: 50). */\n interval?: number;\n /** Cancel the pending wait. */\n signal?: AbortSignal;\n /** Maximum wait time in ms (default: 1000). */\n timeout?: number;\n}\n\nexport interface EventuallyOptions extends WaitOptions {\n /** Context included in the timeout error. */\n message?: string;\n}\n\nexport interface DelayOptions {\n /** Cancel the pending delay. */\n signal?: AbortSignal;\n}\n```\n\n`WaitOptions` configures `waitUntil()`. `EventuallyOptions` configures `eventually()`. `DelayOptions` configures `delay()`.\n\n## Errors\n\n| Error | Meaning |\n| ------------------- | -------------------------------------- |\n| `AssayError` | Base class for Assay-originated errors |\n| `AssayQueryError` | A required `get*` query had no match |\n| `AssayTimeoutError` | A wait operation reached its timeout |\n\nUse `instanceof AssayError` to narrow any value to the Assay error hierarchy.\n",
|
|
6
|
-
"usage": "---\ntitle: 'Assay: Usage Guide'\ndescription: Scoped DOM queries, exact event dispatch, and cancellable waiting with @vielzeug/assay.\n---\n\n[[toc]]\n\n## Basic Usage\n\n`within(root)` is Assay's query API. It accepts an element, document fragment, or shadow root and keeps every lookup\nin that scope. Use `get*` when a match is required and nullable `query*` methods when absence is part of the assertion.\n\n```ts\nimport { within } from '@vielzeug/assay';\n\nconst view = within(panel.shadowRoot!);\n\nconst save = view.get<HTMLButtonElement>('button.save');\nconst status = view.queryByText('Saved');\n\nexpect(view.query('.error')).toBeNull();\nexpect(view.getByTestId('summary').textContent).toContain('Complete');\n```\n\n`get()`, `getByText()`, and `getByTestId()` throw `AssayQueryError` with the lookup and a bounded rendering of the\nscoped DOM. This keeps a failed required lookup diagnosable without non-null assertions.\n\nUse the cross-boundary helpers for custom elements:\n\n```ts\nimport { getSlotted, queryAllInShadow, queryPart } from '@vielzeug/assay';\n\nconst trigger = queryPart(menu, 'trigger');\nconst options = queryAllInShadow(menu, '[role=\"option\"]');\nconst footerActions = getSlotted(dialog, 'footer');\n```\n\n## Exact event dispatch\n\nAssay dispatches the platform event class named by each helper. It does not model browser activation, focus\nmanagement, or form defaults. `fireFocus()` and `fireBlur()` use their non-bubbling platform defaults; use\n`focusin`/`focusout` events when testing delegated focus listeners. Use `element.click()` when native activation is\nthe behavior under test; use Assay when testing an event listener or a controlled state transition.\n\n```ts\nimport { fireClick, fireCustom, fireInput, fireKeyDown } from '@vielzeug/assay';\n\ninput.value = 'Ada';\nfireInput(input);\n\nfireKeyDown(input, { key: 'Enter' });\nfireClick(saveButton);\nfireCustom(panel, 'value-change', { detail: { value: 42 } });\n```\n\nEvery helper returns `dispatchEvent()`'s boolean result. `dispatch(target, event)` is available when an existing\nevent instance is the clearest expression of the test.\n\n## Waiting\n\nChoose the waiting primitive by the test's assertion shape:\n\n```ts\nimport { delay, eventually, waitForEvent, waitUntil } from '@vielzeug/assay';\n\nawait waitUntil(() => panel.querySelector('.status')?.textContent === 'Ready');\n\nawait eventually(\n () => {\n expect(onSave).toHaveBeenCalledOnce();\n },\n { message: 'save callback did not run' },\n);\n\nconst completed = waitForEvent<CustomEvent<{ id: string }>>(panel, 'save-complete', {\n signal: AbortSignal.timeout(1000),\n});\nfireClick(saveButton);\nexpect((await completed).detail.id).toBeDefined();\n\nawait delay(100); // real timer dependency, such as a debounce\n```\n\n`waitUntil()` polls a boolean predicate. `eventually()` retries a throwing assertion and can include a diagnostic `message`. Both enforce one hard deadline while asynchronous callbacks are pending. Abort rejects immediately with the signal reason, but cannot stop callback-owned work; forward an application signal into that work when needed.\n\nTimeouts reject with `AssayTimeoutError`. Timeout and delay values must be finite and non-negative; polling intervals must be finite and positive. All durations must fit the platform timer limit of 2,147,483,647 ms.\n\n## Testing custom elements\n\nUse Ore for component mounting and Assay for generic DOM concerns:\n\n```ts\nimport { fireClick } from '@vielzeug/assay';\nimport { html } from '@vielzeug/ore';\nimport { mount } from '@vielzeug/ore/testing';\n\nconst fixture = await mount(\n () => html`\n <button @click=${onSave}>Save</button>\n `,\n);\n\nfireClick(fixture.get('button'));\nawait fixture.flush();\n\nexpect(onSave).toHaveBeenCalledOnce();\n```\n\nRefine's testing entry point contains only Refine-specific assertions and typed mount wrappers. Import Assay helpers\ndirectly instead of routing generic DOM operations through another package.\n\nWhen a suite tests a form-associated custom element (one built on `useField()` from `@vielzeug/ore`), install the\nform-internals polyfill in the setup file so jsdom gains the `ElementInternals` API it lacks:\n\n```ts\n// vitest.setup.ts\nimport { installFormInternalsPolyfill } from '@vielzeug/assay';\nimport { install } from '@vielzeug/ore/testing';\nimport { afterAll, afterEach } from 'vitest';\n\ninstall(afterEach);\nafterAll(installFormInternalsPolyfill());\n```\n\n## Traverse slotted content in jsdom\n\nUse `walkFlatTree()` when a test must visit descendants assigned through slots. It expands each slot into its assigned\nelements, including nested slots, instead of relying on jsdom's light-DOM-only `querySelectorAll()`.\n\n```ts\nimport { walkFlatTree } from '@vielzeug/assay';\n\nconst named: HTMLElement[] = [];\nwalkFlatTree(form, (element) => {\n if (element.hasAttribute('name')) named.push(element);\n});\n```\n\nThe callback receives descendants in the flat tree, not the root element or slot elements themselves. Browsers already\nuse the flat tree for DOM algorithms; this helper is for test code that needs equivalent traversal in jsdom.\n\n## Best Practices\n\n- Scope multiple assertions with `within()` rather than repeatedly querying the document.\n- Prefer `get*` for required controls and `query*` for intentional absence checks.\n- Make form state and event boundaries explicit: assign `.value`, then call `fireInput()` or `fireChange()`.\n- Use browser integration tests for focus, disabled activation, pointer capture, and other browser-default behavior.\n- Use `waitForEvent()` for an emitted event, `waitUntil()` for a condition, and `eventually()` for assertions.\n- Add a diagnostic `message` to waits whose final assertion does not identify the tested workflow.\n",
|
|
7
|
-
"examples": "---\ntitle: 'Assay: Examples'\ndescription: Practical examples and recipes for assay.\n---\n\n## Examples\n\n- [Custom Element Interaction](./examples/custom-element-interaction.md)\n- [Waiting for Async Updates](./examples/waiting-for-async-updates.md)\n"
|
|
8
|
-
},
|
|
9
|
-
"examples": [
|
|
10
|
-
{
|
|
11
|
-
"id": "scoped-queries",
|
|
12
|
-
"code": "import { fireClick, fireInput, within } from '@vielzeug/assay'\n\n// Build a small app DOM to probe (the REPL runs inside the sandbox iframe).\ndocument.body.innerHTML = `\n <form id=\"signup\">\n <input data-testid=\"email\" placeholder=\"email\" />\n <button type=\"submit\">Sign up</button>\n <p class=\"status\" hidden></p>\n </form>`\n\n// within() keeps every lookup scoped to one root.\nconst view = within(document.getElementById('signup'))\nconst email = view.getByTestId('email')\nconst status = view.get('.status')\n\nemail.value = 'ada@example.com'\nfireInput(email)\n\nview.getByText('Sign up').addEventListener('click', () => {\n status.hidden = false\n status.textContent = 'Welcome, ' + email.value\n})\n\nfireClick(view.getByText('Sign up'))\nconsole.log('status after click:', status.textContent)\n\n// get* throws AssayQueryError when a required match is missing;\n// query* returns null instead.\nconsole.log('missing element:', view.query('.error'))\ntry {\n view.get('.error')\n} catch (e) {\n console.log('get threw:', e.name)\n}",
|
|
13
|
-
"name": "Scoped Queries And Events"
|
|
14
|
-
},
|
|
15
|
-
{
|
|
16
|
-
"id": "waiting",
|
|
17
|
-
"code": "import { eventually, waitForEvent, waitUntil } from '@vielzeug/assay'\n\nconst box = document.createElement('div')\nbox.textContent = 'idle'\ndocument.body.appendChild(box)\n\n// Simulate async work that settles later.\nsetTimeout(() => { box.textContent = 'ready' }, 120)\n\n// waitUntil polls until the predicate passes.\nawait waitUntil(() => box.textContent === 'ready')\nconsole.log('waitUntil settled on:', box.textContent)\n\n// eventually retries an assertion until it stops throwing.\nsetTimeout(() => { box.classList.add('done') }, 120)\nawait eventually(() => {\n if (!box.classList.contains('done')) throw new Error('not yet')\n})\nconsole.log('eventually saw .done:', box.classList.contains('done'))\n\n// waitForEvent resolves with the next matching event.\nsetTimeout(() => { box.dispatchEvent(new CustomEvent('ping', { detail: 7 })) }, 120)\nconst ping = await waitForEvent(box, 'ping')\nconsole.log('waitForEvent detail:', ping.detail)",
|
|
18
|
-
"name": "Cancellable Waiting"
|
|
19
|
-
}
|
|
20
|
-
],
|
|
21
|
-
"typeSignatures": {
|
|
22
|
-
"walkFlatTree": "export { walkFlatTree } from './dom';",
|
|
23
|
-
"AssayError": "export { AssayError, AssayQueryError, AssayTimeoutError } from './errors';",
|
|
24
|
-
"AssayQueryError": "export { AssayError, AssayQueryError, AssayTimeoutError } from './errors';",
|
|
25
|
-
"AssayTimeoutError": "export { AssayError, AssayQueryError, AssayTimeoutError } from './errors';",
|
|
26
|
-
"dispatch": "export {\n dispatch,\n fireBlur,\n fireChange,\n fireClick,\n fireCustom,\n fireFocus,\n fireInput,\n fireKeyDown,\n fireKeyUp,\n fireSubmit,\n} from './events';",
|
|
27
|
-
"fireBlur": "export {\n dispatch,\n fireBlur,\n fireChange,\n fireClick,\n fireCustom,\n fireFocus,\n fireInput,\n fireKeyDown,\n fireKeyUp,\n fireSubmit,\n} from './events';",
|
|
28
|
-
"fireChange": "export {\n dispatch,\n fireBlur,\n fireChange,\n fireClick,\n fireCustom,\n fireFocus,\n fireInput,\n fireKeyDown,\n fireKeyUp,\n fireSubmit,\n} from './events';",
|
|
29
|
-
"fireClick": "export {\n dispatch,\n fireBlur,\n fireChange,\n fireClick,\n fireCustom,\n fireFocus,\n fireInput,\n fireKeyDown,\n fireKeyUp,\n fireSubmit,\n} from './events';",
|
|
30
|
-
"fireCustom": "export {\n dispatch,\n fireBlur,\n fireChange,\n fireClick,\n fireCustom,\n fireFocus,\n fireInput,\n fireKeyDown,\n fireKeyUp,\n fireSubmit,\n} from './events';",
|
|
31
|
-
"fireFocus": "export {\n dispatch,\n fireBlur,\n fireChange,\n fireClick,\n fireCustom,\n fireFocus,\n fireInput,\n fireKeyDown,\n fireKeyUp,\n fireSubmit,\n} from './events';",
|
|
32
|
-
"fireInput": "export {\n dispatch,\n fireBlur,\n fireChange,\n fireClick,\n fireCustom,\n fireFocus,\n fireInput,\n fireKeyDown,\n fireKeyUp,\n fireSubmit,\n} from './events';",
|
|
33
|
-
"fireKeyDown": "export {\n dispatch,\n fireBlur,\n fireChange,\n fireClick,\n fireCustom,\n fireFocus,\n fireInput,\n fireKeyDown,\n fireKeyUp,\n fireSubmit,\n} from './events';",
|
|
34
|
-
"fireKeyUp": "export {\n dispatch,\n fireBlur,\n fireChange,\n fireClick,\n fireCustom,\n fireFocus,\n fireInput,\n fireKeyDown,\n fireKeyUp,\n fireSubmit,\n} from './events';",
|
|
35
|
-
"fireSubmit": "export {\n dispatch,\n fireBlur,\n fireChange,\n fireClick,\n fireCustom,\n fireFocus,\n fireInput,\n fireKeyDown,\n fireKeyUp,\n fireSubmit,\n} from './events';",
|
|
36
|
-
"installFormInternalsPolyfill": "export { installFormInternalsPolyfill } from './form-internals';",
|
|
37
|
-
"installPopoverPolyfill": "export { installPopoverPolyfill } from './popover';",
|
|
38
|
-
"getSlotted": "export { getSlotted, type QueryScope, queryAllInShadow, queryInShadow, queryPart, within } from './query';",
|
|
39
|
-
"QueryScope": "export { getSlotted, type QueryScope, queryAllInShadow, queryInShadow, queryPart, within } from './query';",
|
|
40
|
-
"queryAllInShadow": "export { getSlotted, type QueryScope, queryAllInShadow, queryInShadow, queryPart, within } from './query';",
|
|
41
|
-
"queryInShadow": "export { getSlotted, type QueryScope, queryAllInShadow, queryInShadow, queryPart, within } from './query';",
|
|
42
|
-
"queryPart": "export { getSlotted, type QueryScope, queryAllInShadow, queryInShadow, queryPart, within } from './query';",
|
|
43
|
-
"within": "export { getSlotted, type QueryScope, queryAllInShadow, queryInShadow, queryPart, within } from './query';",
|
|
44
|
-
"DelayOptions": "export {\n type DelayOptions,\n delay,\n type EventuallyOptions,\n eventually,\n type WaitOptions,\n waitForEvent,\n waitUntil,\n} from './wait';",
|
|
45
|
-
"delay": "export {\n type DelayOptions,\n delay,\n type EventuallyOptions,\n eventually,\n type WaitOptions,\n waitForEvent,\n waitUntil,\n} from './wait';",
|
|
46
|
-
"EventuallyOptions": "export {\n type DelayOptions,\n delay,\n type EventuallyOptions,\n eventually,\n type WaitOptions,\n waitForEvent,\n waitUntil,\n} from './wait';",
|
|
47
|
-
"eventually": "export {\n type DelayOptions,\n delay,\n type EventuallyOptions,\n eventually,\n type WaitOptions,\n waitForEvent,\n waitUntil,\n} from './wait';",
|
|
48
|
-
"WaitOptions": "export {\n type DelayOptions,\n delay,\n type EventuallyOptions,\n eventually,\n type WaitOptions,\n waitForEvent,\n waitUntil,\n} from './wait';",
|
|
49
|
-
"waitForEvent": "export {\n type DelayOptions,\n delay,\n type EventuallyOptions,\n eventually,\n type WaitOptions,\n waitForEvent,\n waitUntil,\n} from './wait';",
|
|
50
|
-
"waitUntil": "export {\n type DelayOptions,\n delay,\n type EventuallyOptions,\n eventually,\n type WaitOptions,\n waitForEvent,\n waitUntil,\n} from './wait';"
|
|
51
|
-
}
|
|
52
|
-
}
|