@vielzeug/codex 26.11.23 → 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.
Files changed (97) hide show
  1. package/README.md +5 -4
  2. package/data/snapshot.json +1 -0
  3. package/dist/catalog.d.ts +35 -39
  4. package/dist/catalog.js +112 -139
  5. package/dist/catalog.js.map +1 -1
  6. package/dist/cli.js +25 -16
  7. package/dist/cli.js.map +1 -1
  8. package/dist/http.js +1 -1
  9. package/dist/http.js.map +1 -1
  10. package/dist/index.d.ts +5 -7
  11. package/dist/index.js +4 -6
  12. package/dist/index.js.map +1 -1
  13. package/dist/server.d.ts +9 -7
  14. package/dist/server.js +14 -6
  15. package/dist/server.js.map +1 -1
  16. package/dist/snapshot.d.ts +8 -22
  17. package/dist/snapshot.js +41 -176
  18. package/dist/snapshot.js.map +1 -1
  19. package/dist/tools/index.d.ts +1 -1
  20. package/dist/tools/index.js.map +1 -1
  21. package/dist/tools/packages.js +49 -82
  22. package/dist/tools/packages.js.map +1 -1
  23. package/dist/tools/refine.d.ts +1 -2
  24. package/dist/tools/refine.js +90 -82
  25. package/dist/tools/refine.js.map +1 -1
  26. package/dist/tools/schema.d.ts +2 -1
  27. package/dist/tools/schema.js +9 -5
  28. package/dist/tools/schema.js.map +1 -1
  29. package/dist/tools/shared.d.ts +2 -2
  30. package/dist/types.d.ts +77 -64
  31. package/dist/types.js +6 -2
  32. package/dist/types.js.map +1 -1
  33. package/package.json +2 -2
  34. package/skills/vielzeug/SKILL.md +18 -20
  35. package/data/catalog.json +0 -2536
  36. package/data/llms-full.txt +0 -40710
  37. package/data/llms.txt +0 -60
  38. package/data/manifest.json +0 -4
  39. package/data/packages/archive.json +0 -87
  40. package/data/packages/arsenal.json +0 -270
  41. package/data/packages/assay.json +0 -52
  42. package/data/packages/atlas.json +0 -70
  43. package/data/packages/bard.json +0 -38
  44. package/data/packages/beacon.json +0 -51
  45. package/data/packages/clockwork.json +0 -69
  46. package/data/packages/codex.json +0 -37
  47. package/data/packages/coins.json +0 -99
  48. package/data/packages/conduit.json +0 -67
  49. package/data/packages/courier.json +0 -66
  50. package/data/packages/dnd.json +0 -60
  51. package/data/packages/familiar.json +0 -38
  52. package/data/packages/flux.json +0 -97
  53. package/data/packages/focus.json +0 -51
  54. package/data/packages/forge.json +0 -65
  55. package/data/packages/gesture.json +0 -65
  56. package/data/packages/herald.json +0 -80
  57. package/data/packages/illusionist.json +0 -132
  58. package/data/packages/ink.json +0 -32
  59. package/data/packages/keymap.json +0 -55
  60. package/data/packages/ledger.json +0 -60
  61. package/data/packages/lingua.json +0 -68
  62. package/data/packages/mesh.json +0 -52
  63. package/data/packages/necromancer.json +0 -55
  64. package/data/packages/orbit.json +0 -100
  65. package/data/packages/ore.json +0 -78
  66. package/data/packages/palette.json +0 -42
  67. package/data/packages/patchwork.json +0 -55
  68. package/data/packages/postmaster.json +0 -49
  69. package/data/packages/prism.json +0 -99
  70. package/data/packages/pulse.json +0 -71
  71. package/data/packages/refine.json +0 -36
  72. package/data/packages/ripple.json +0 -84
  73. package/data/packages/rune.json +0 -78
  74. package/data/packages/sandbox.json +0 -26
  75. package/data/packages/scout.json +0 -66
  76. package/data/packages/scribe.json +0 -57
  77. package/data/packages/scroll.json +0 -110
  78. package/data/packages/sentinel.json +0 -46
  79. package/data/packages/sigil.json +0 -52
  80. package/data/packages/sourcerer.json +0 -86
  81. package/data/packages/spell.json +0 -126
  82. package/data/packages/stage.json +0 -25
  83. package/data/packages/tabula.json +0 -39
  84. package/data/packages/tandem.json +0 -31
  85. package/data/packages/tavern.json +0 -34
  86. package/data/packages/tempo.json +0 -68
  87. package/data/packages/vault.json +0 -81
  88. package/data/packages/ward.json +0 -77
  89. package/data/packages/wayfinder.json +0 -126
  90. package/data/packages/wire.json +0 -36
  91. package/data/refine.json +0 -17273
  92. package/dist/consumer.d.ts +0 -17
  93. package/dist/consumer.js +0 -114
  94. package/dist/consumer.js.map +0 -1
  95. package/dist/port.d.ts +0 -2
  96. package/dist/port.js +0 -12
  97. package/dist/port.js.map +0 -1
@@ -1,126 +0,0 @@
1
- {
2
- "apiSource": "export {\n type FlatError,\n type FlatErrorFirst,\n joinIssuePath,\n SpellDefinitionError,\n SpellError,\n SpellValidationError,\n} from './errors';\nexport { createParseContext, type DeepPartial, type Messages } from './messages';\nexport { s } from './s';\nexport { Schema } from './schema';\nexport {\n type AnySchema,\n type CheckContext,\n ErrorCode,\n type Infer,\n type InferInput,\n type InferOutput,\n type Issue,\n type IssuePath,\n type IssuePathSegment,\n type MessageFn,\n type ParseContext,\n type ParseResult,\n type PatternDescriptor,\n type SchemaDescriptor,\n type SchemaKind,\n type StandardSchemaV1,\n type ValidateResult,\n} from './types';\n",
3
- "docs": {
4
- "index": "---\ntitle: 'Spell: Schema validation for TypeScript'\ndescription: Zero-dependency schema validation with explicit async checks, Standard Schema interoperability, and JSON Schema export.\npackage: spell\ncategory: validation\nkeywords: [schema, validation, parsing, standard-schema, json-schema, locale, typescript, definitions]\nrelated: [forge, courier, vault]\nexports:\n [\n s,\n createParseContext,\n joinIssuePath,\n SpellValidationError,\n SpellDefinitionError,\n Schema,\n StandardSchemaV1,\n ErrorCode,\n './json',\n './predicates',\n ]\nenvironments: [browser, node, ssr, deno]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"spell\" />\n\n## Why Spell?\n\nSpell keeps runtime validation, static inference, and portable definitions in one API. Checks and transforms run in the order you chain them, and every built-in constraint appears in the exported definition.\n\nThis example shows the difference between manual branching and a single reusable schema.\n\n```ts\n// Before\nfunction parseUserBefore(value: unknown) {\n if (typeof value !== 'object' || value === null) throw new Error('Expected object');\n\n const candidate = value as Record<string, unknown>;\n\n if (typeof candidate.email !== 'string' || !candidate.email.includes('@')) {\n throw new Error('Expected valid email');\n }\n\n if (typeof candidate.role !== 'string' || !['admin', 'editor', 'viewer'].includes(candidate.role)) {\n throw new Error('Expected valid role');\n }\n\n return {\n email: candidate.email,\n role: candidate.role,\n };\n}\n\n// After\nimport { s } from '@vielzeug/spell';\n\nconst User = s.object({\n email: s.string().email(),\n role: s.enum(['admin', 'editor', 'viewer'] as const),\n});\n\nconst user = User.parse({ email: 'ada@example.com', role: 'admin' });\n```\n\n| Feature | Spell | Zod | Yup |\n| ----------------- | --------------------------------------------------------------------------- | -------------------------------------------- | -------------------------------------------- |\n| Bundle size | <PackageInfo package=\"spell\" type=\"size\" /> | ~62 kB | ~14 kB |\n| Type inference | <ore-icon name=\"check\" size=\"16\"></ore-icon> `Infer<T>` | <ore-icon name=\"check\" size=\"16\"></ore-icon> | Partial |\n| Coercion API | <ore-icon name=\"check\" size=\"16\"></ore-icon> `s.coerce.*` | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n| Async validation | <ore-icon name=\"check\" size=\"16\"></ore-icon> `.checkAsync()` | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n| Error flattening | <ore-icon name=\"check\" size=\"16\"></ore-icon> `flatten()` + `flattenFirst()` | <ore-icon name=\"check\" size=\"16\"></ore-icon> | Partial |\n| Zero dependencies | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon> |\n\n<div class=\"decision-callout\">\n\n**Use Spell when** you want a fluent schema API with strong TypeScript inference, structured errors, and no third-party runtime dependencies.\n\n**Consider alternatives when** you are already standardized on another validator ecosystem and migration cost outweighs the API benefits.\n\n</div>\n\n## Installation\n\nUse your workspace package manager to add Spell.\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/spell\n```\n\n```sh [npm]\nnpm install @vielzeug/spell\n```\n\n```sh [yarn]\nyarn add @vielzeug/spell\n```\n\n:::\n\n## Quick Start\n\nStart with a schema, then parse unknown input and use the inferred output type everywhere else.\n\n```ts\nimport { s, type Infer } from '@vielzeug/spell';\n\nconst User = s\n .object({\n email: s.string().email(),\n name: s.string().min(1),\n role: s.enum(['admin', 'editor', 'viewer'] as const),\n })\n .relaxed(); // allow extra keys: omit for strict-mode (default)\n\ntype User = Infer<typeof User>;\n\nconst payload: unknown = {\n email: 'ada@example.com',\n name: 'Ada',\n role: 'admin',\n team: 'platform',\n};\n\nconst result = User.safeParse(payload);\n\nif (!result.success) throw result.error;\nconst user = result.data;\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- `s` builders for primitives, collections, objects, unions, and recursive schemas.\n- `parse()`, `safeParse()`, `parseAsync()`, and `safeParseAsync()`; parsing stays synchronous unless a check is async.\n- `check()` and `checkAsync()` run in chain order with transforms; sync parsing never skips an async check.\n- `optional`, `nullable`, `nullish`, `default`, `catch`, and `required` modifiers; defaults are copied per parse.\n- `extend()`, `pick()`, `omit()`, `partial()`, and `tolerate()` for object composition and schema evolution.\n- `definition()` returns frozen data; `toJsonSchema()` from `@vielzeug/spell/json` converts it to JSON Schema.\n- `schema['~standard']` implements Standard Schema v1 without an adapter.\n- `createParseContext()` customizes messages per request, locale, or form.\n- `SpellValidationError` offers `flatten()`, `flattenFirst()`, and `messagesAt()` for UI errors.\n- Object and record parsing is hardened against prototype-pollution keys.\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- [Forge](/forge/): typed form state that uses Spell schemas as its validation layer\n- [Courier](/courier/): HTTP client for validating request and response payloads at service boundaries\n- [Vault](/vault/): unified storage API that accepts Spell schemas to type-gate persisted data\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
5
- "api": "---\ntitle: 'Spell: API Reference'\ndescription: Reference for Spell schema builders, schema methods, parsing, errors, parse contexts, definitions, and JSON Schema export.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution mode | Common gotcha |\n| ---------------------- | ------------------------------------------- | ------------------------------------ | --------------------------------------------------------------- |\n| `s` | Creates schemas | Sync, or async when checks are async | `checkAsync()` anywhere in the tree requires `parseAsync()` |\n| `Schema` | Base class of every schema | Sync or async | Modifiers return copies; schemas are never mutated |\n| `createParseContext()` | Creates request-local messages | Sync | Pass the context to each parse call |\n| `joinIssuePath()` | Flattens issue paths to UI keys | Sync | Empty or undefined paths join to `''` |\n| `SpellValidationError` | Carries validation issues | Sync/async parse failures | Use `safeParse()` for expected invalid data |\n| `SpellDefinitionError` | Rejects non-portable or invalid definitions | Sync | Thrown by `definition()` and object derivations, not by parsing |\n| `ErrorCode` | Issue code constants | n/a | Narrow `Issue` on `code` to read typed `params` |\n| `toJsonSchema()` | Converts a definition to JSON Schema | Sync | Imported from `@vielzeug/spell/json` |\n\n## Package Entry Point\n\n| Import | Purpose |\n| ---------------------------- | ------------------------------------------------------- |\n| `@vielzeug/spell` | Schema builders, base class, errors, types, and context |\n| `@vielzeug/spell/json` | `toJsonSchema()` and the `JsonSchema` type |\n| `@vielzeug/spell/predicates` | Standalone string format predicates |\n\n```ts\nimport { createParseContext, s, type Infer } from '@vielzeug/spell';\nimport { toJsonSchema } from '@vielzeug/spell/json';\nimport { isEmail } from '@vielzeug/spell/predicates';\n```\n\n## Builders\n\nAll builders live under `s`.\n\n| Builder | Returns | Notes |\n| ---------------------------------------------- | ------------------------------------- | ----------------------------------------------------- |\n| `s.string()` | `StringSchema` | |\n| `s.number()` | `NumberSchema` | Rejects `NaN` |\n| `s.bigint()` | `BigIntSchema` | |\n| `s.boolean()` | `BooleanSchema` | |\n| `s.date()` | `DateSchema` | Rejects invalid dates with `invalid_date` |\n| `s.literal(value)` | `LiteralSchema<T>` | `string`, `number`, `boolean`, `null`, or `undefined` |\n| `s.enum(values)` | `EnumSchema<T>` | Non-empty tuple of strings or numbers |\n| `s.null()`, `s.undefined()` | `LiteralSchema<null \\| undefined>` | |\n| `s.unknown()` | `Schema<unknown>` | Accepts any value |\n| `s.never()` | `NeverSchema` | Rejects every value |\n| `s.instanceof(cls)` | `InstanceOfSchema<T>` | Accepts abstract constructors |\n| `s.array(item)` | `ArraySchema<T>` | |\n| `s.tuple(items)` | `TupleSchema<T>` | Exact length unless `.rest()` is used |\n| `s.set(item)` | `SetSchema<T>` | |\n| `s.map(key, value)` | `MapSchema<K, V>` | |\n| `s.record(key, value)` | `RecordSchema<K, V>` | Drops unsafe keys (`__proto__`, `constructor`, …) |\n| `s.object(shape)` | `ObjectSchema<T>` | Strict by default |\n| `s.union(...schemas)` | `UnionSchema<T>` | At least two schemas; first match wins |\n| `s.intersect(...schemas)` | `IntersectSchema<T>` | At least two schemas; object outputs are deep-merged |\n| `s.discriminatedUnion(key, branches)` | `DiscriminatedUnionSchema<K, M>` | Branches are object schemas keyed by tag |\n| `s.lazy(getter)` | `LazySchema<Output, Input>` | Recursive schemas |\n| `s.coerce.string/number/boolean/bigint/date()` | Primitive schema with `unknown` input | Coercion runs before the type check |\n\n### `s.coerce`\n\n| Builder | Converts |\n| -------------------- | --------------------------------------------------------- |\n| `s.coerce.string()` | Any non-nullish value with `String()` |\n| `s.coerce.number()` | Numeric strings and booleans with `Number()` |\n| `s.coerce.boolean()` | `'true'`/`'1'`/`1` and `'false'`/`'0'`/`0` |\n| `s.coerce.bigint()` | Safe-integer numbers and integer strings up to 1000 chars |\n| `s.coerce.date()` | Strings and epoch milliseconds with `new Date()` |\n\nValues the coercer cannot convert reach the type check unchanged and fail with `invalid_type`.\n\n## Schema Methods\n\nEvery schema extends `Schema<Output, Input>`.\n\n### Parsing\n\n```ts\nparse(value: unknown, context?: ParseContext): Output;\nsafeParse(value: unknown, context?: ParseContext): ParseResult<Output>;\nparseAsync(value: unknown, context?: ParseContext): Promise<Output>;\nsafeParseAsync(value: unknown, context?: ParseContext): Promise<ParseResult<Output>>;\nis(value: unknown): value is Output;\nassert(value: unknown, label?: string): asserts value is Output;\n```\n\n**Returns:** `parse()` returns the parsed output or throws `SpellValidationError`. `safeParse()` returns a `ParseResult`.\n\n`parse()`, `safeParse()`, `is()`, and `assert()` are synchronous. If the schema or any nested schema has a `checkAsync()` step, they throw `SpellError` (\"Schema contains async checks; use parseAsync() or safeParseAsync().\") before running the async check. This is a usage error, not a validation issue, so `catch()` does not intercept it. `assert(value, label)` prefixes root-level messages with `label`.\n\n**Example:**\n\n```ts\nimport { s } from '@vielzeug/spell';\n\nconst result = s.string().email().safeParse('ada@example.com');\n\nif (result.success) console.log(result.data);\n```\n\n### Checks\n\n```ts\ncheck(fn: (value: Output, ctx: CheckContext) => ValidateResult): this;\ncheckAsync(fn: (value: Output, ctx: CheckContext) => Promise<ValidateResult>): this;\n```\n\n**Returns:** A copy of the schema with the rule appended.\n\nA check runs only when the structural type check passed. It returns `true`, `null`, or `undefined` to pass, a string to fail with that message, or `false` to fail with the default message. `ctx.addIssue({ code, message, params?, path? })` reports issues at paths relative to the schema. Passing an async function to `check()` is a type error.\n\n**Example:**\n\n```ts\nconst Signup = s.object({ confirm: s.string(), password: s.string() }).check((value, ctx) => {\n if (value.password !== value.confirm)\n ctx.addIssue({ code: 'custom', message: 'Passwords must match', path: ['confirm'] });\n});\n```\n\n### Modifiers\n\n| Method | Returns | Effect |\n| ----------------- | ------------------------------------------------- | ------------------------------------------------------------------------ |\n| `optional()` | `Schema<Output \\| undefined, Input \\| undefined>` | Accepts `undefined` |\n| `nullable()` | `Schema<Output \\| null, Input \\| null>` | Accepts `null` |\n| `nullish()` | `Schema<Output \\| null \\| undefined, …>` | Accepts `null` and `undefined` |\n| `required()` | `Schema<Exclude<Output, undefined>, …>` | Rejects `undefined` again; clears `optional()` and `default()` |\n| `default(value)` | `this` | Returns a fresh copy of `value` for `undefined`; a function is a factory |\n| `catch(fallback)` | `this` | Returns a fresh copy of `fallback` when validation fails |\n| `transform(fn)` | `Schema<Next, Input>` | Maps the value in chain order; skipped once an earlier step failed |\n| `preprocess(fn)` | `this` | Maps raw input before the type check |\n| `pipe(next)` | `PipeSchema<this, Next>` | Parses with this schema, then feeds the output to `next` |\n| `describe(text)` | `this` | Sets `description`, which `definition()` includes |\n\n`optional()`, `nullable()`, `nullish()`, `required()`, and `transform()` change the value type, so they return a base `Schema`. Chain type-specific methods such as `.min()` or `.extend()` before them.\n\n### Properties and definitions\n\n| Member | Type | Description |\n| -------------- | --------------------------------------- | ---------------------------------------------------------------- |\n| `kind` | `SchemaKind` | Schema kind, e.g. `'string'` or `'object'` |\n| `description` | `string \\| undefined` | Text set with `describe()` |\n| `isOptional` | `boolean` | `true` with `optional()`, `nullish()`, `default()`, or `catch()` |\n| `isNullable` | `boolean` | `true` with `nullable()` or `nullish()` |\n| `'~standard'` | `StandardSchemaV1.Props<Input, Output>` | Standard Schema v1 protocol |\n| `definition()` | `SchemaDescriptor` | Frozen declarative descriptor |\n\n`definition()` throws `SpellDefinitionError` when the schema, or a nested schema, has runtime-only behavior: `check()`, `checkAsync()`, `transform()`, `preprocess()` (including `s.coerce.*`, `trim()`, `lowercase()`, `uppercase()`), `default()`, `catch()`, or `array().unique({ by })`.\n\n### Standard Schema\n\n`schema['~standard'].validate(value)` returns a result synchronously unless the schema has async checks, in which case it returns a Promise. Successful results contain `value`; failures contain `{ message, path }` issues. A failed union stays one union issue.\n\n```ts\nconst User = s.object({ name: s.string() });\nconst result = await User['~standard'].validate({ name: 'Ada' });\n```\n\n## String Schema\n\n```ts\nmin(length: number, message?): this;\nmax(length: number, message?): this;\nlength(exact: number, message?): this;\nnonEmpty(message?): this;\nstartsWith(prefix: string, message?): this;\nendsWith(suffix: string, message?): this;\nincludes(substr: string, message?): this;\nregex(pattern: RegExp, message?): this;\nurl(options?: { message?: MessageFn<{ value: string }>; protocols?: readonly string[] }): this;\nnanoid(length?: number, message?): this;\ntrim(): this;\nlowercase(): this;\nuppercase(): this;\n```\n\nFormat methods take an optional `message`: `email`, `url`, `uuid`, `isoDate`, `isoDateTime`, `time`, `duration`, `ip`, `cuid`, `cuid2`, `ulid`, `nanoid`, `base64`, `base64url`, `hex`, `hexColor`, `emoji`, `jwt`, `semver`, `slug`, `numeric`.\n\nFormat and pattern failures use code `invalid_format` with `params.format` set to the method name, such as `'email'`, `'isoDate'`, `'startsWith'`, or `'regex'`. `url()` accepts `http` and `https` unless `protocols` is given. `regex()` drops the stateful `g` and `y` flags. `trim()`, `lowercase()`, and `uppercase()` are ordered transforms: constraints chained after them see the normalized value.\n\n## Number, BigInt, and Date Schemas\n\n| Schema | Methods |\n| -------------- | --------------------------------------------------------------------------------------------------------- |\n| `NumberSchema` | `min`, `max`, `positive`, `negative`, `nonNegative`, `nonPositive`, `int`, `safe`, `finite`, `multipleOf` |\n| `BigIntSchema` | `min`, `max`, `positive`, `negative`, `nonNegative`, `nonPositive`, `multipleOf` |\n| `DateSchema` | `min(date)`, `max(date)` |\n\nEach method takes an optional trailing `message`. `safe()` requires an integer within `Number.MIN_SAFE_INTEGER`…`Number.MAX_SAFE_INTEGER`.\n\n## Collection Schemas\n\n| Schema | Methods and members |\n| -------------- | ------------------------------------------------------ |\n| `ArraySchema` | `min`, `max`, `length`, `nonEmpty`, `unique(options?)` |\n| `TupleSchema` | `items`, `rest(schema)` |\n| `SetSchema` | `min`, `max`, `size`, `nonEmpty` |\n| `MapSchema` | `min`, `max`, `size`, `nonEmpty` |\n| `RecordSchema` | (none) |\n\n```ts\nunique(options?: { by?: (item: InferOutput<T>) => unknown; message?: MessageFn<{ value: unknown[] }> }): this;\n```\n\n`unique()` compares items with `Set` semantics, or compares the keys returned by `by`. A `by` selector makes `definition()` throw.\n\n## Object Schema\n\n```ts\nreadonly shape: T;\nrelaxed(): this;\nstrict(): this;\ntolerate(...keys: string[]): this;\nextend<U extends ObjectShape>(extra: U): ObjectSchema<Omit<T, keyof U> & U>;\npick<K extends keyof T & string>(...keys: K[]): ObjectSchema<Pick<T, K>>;\nomit<K extends keyof T & string>(...keys: K[]): ObjectSchema<Omit<T, K>>;\npartial(): ObjectSchema<{ [K in keyof T]: Optional<T[K]> }>;\npartial<K extends keyof T & string>(...keys: K[]): ObjectSchema<Omit<T, K> & { [P in K]: Optional<T[P]> }>;\nkeyof(): EnumSchema<[keyof T & string, ...(keyof T & string)[]]>;\n```\n\n| Method | Description |\n| ------------ | ---------------------------------------------------------------------------- |\n| `strict()` | Rejects unknown keys with one `invalid_keys` issue (default) |\n| `relaxed()` | Copies unknown keys to the output, skipping unsafe keys |\n| `tolerate()` | Accepts and drops the named keys; other unknown keys follow the current mode |\n| `extend()` | Adds fields; same-named fields are replaced |\n| `pick()` | Keeps the named fields |\n| `omit()` | Removes the named fields |\n| `partial()` | Makes all or the named fields optional |\n| `keyof()` | Enum schema of the shape keys |\n\n`extend()`, `pick()`, `omit()`, and `partial()` keep the unknown-key mode, tolerated keys, description, and `optional`/`nullable` flags. They throw `SpellDefinitionError` when the object has checks, transforms, preprocessors, a default, or a catch, because those were written for the old shape.\n\nAbsent keys whose field returns `undefined` are left out of the output. Field defaults are written for absent keys.\n\n## Composition Schemas\n\n| Schema | Members | Failure |\n| -------------------------- | ------------------------------------------- | --------------------------------------------------------------------- |\n| `UnionSchema` | `schemas` | One `invalid_union` issue; `params.errors` holds each branch's issues |\n| `IntersectSchema` | `schemas` | Issues from every failing branch |\n| `DiscriminatedUnionSchema` | `discriminator`, `branches` (`ReadonlyMap`) | `invalid_discriminator` for an unknown tag; branch issues otherwise |\n| `LazySchema` | (none) | Issues of the resolved schema |\n| `PipeSchema` | `from`, `to` | Issues of the first failing stage |\n\n`s.discriminatedUnion(key, branches)` adds `key` as a literal of the branch tag when a branch omits it. It throws `SpellDefinitionError` when a branch is not an object schema or declares `key` with a different schema.\n\nIntersections of object schemas need `.relaxed()` branches, because each strict branch rejects the other branch's keys.\n\n## Parse Contexts\n\n```ts\nfunction createParseContext(messages?: DeepPartial<Messages>): ParseContext;\n```\n\n**Returns:** A frozen parse context with the built-in messages merged with the supplied overrides. Unsafe override keys such as `__proto__` are ignored with a development warning.\n\n**Example:**\n\n```ts\nimport { createParseContext, s } from '@vielzeug/spell';\n\nconst context = createParseContext({ object: { invalidKeys: () => 'Unsupported field' } });\nconst result = s.object({ email: s.string().email() }).safeParse({ email: 'ada@example.com', extra: true }, context);\n\nif (!result.success) console.log(result.error.issues[0].message); // 'Unsupported field'\n```\n\n## JSON Schema\n\n```ts\nimport { toJsonSchema, type JsonSchema } from '@vielzeug/spell/json';\n\nfunction toJsonSchema(definition: SchemaDescriptor): JsonSchema;\n```\n\n**Returns:** A JSON Schema 2020-12 object.\n\n| Definition | JSON Schema |\n| ------------------------------- | ------------------------------------------------------------------- |\n| `isoDate`, `isoDateTime`, `url` | `format: 'date'`, `'date-time'`, `'uri'` |\n| `base64`, `base64url` | `contentEncoding` |\n| `ip` | `anyOf` of `ipv4` and `ipv6` formats |\n| Several formats or patterns | `allOf` |\n| `bigint` bounds | Numeric bounds (may lose precision above `Number.MAX_SAFE_INTEGER`) |\n| `date`, `instanceof` | `$comment` only |\n| `set`, `map` | Array with `uniqueItems`, object with `additionalProperties` |\n| `isNullable` | `anyOf` with `{ type: 'null' }` |\n\n**Example:**\n\n```ts\nimport { s } from '@vielzeug/spell';\nimport { toJsonSchema } from '@vielzeug/spell/json';\n\nconst jsonSchema = toJsonSchema(s.object({ id: s.string().uuid() }).definition());\n```\n\n## Predicates\n\n`@vielzeug/spell/predicates` exports the format tests used by `StringSchema`. Each takes a string and returns `boolean`.\n\n`isBase64`, `isBase64url`, `isCuid`, `isCuid2`, `isDuration`, `isEmail`, `isEmoji`, `isHex`, `isHexColor`, `isIp`, `isIsoDate`, `isIsoDateTime`, `isJwt`, `isNanoid(value, length = 21)`, `isNumeric`, `isSemver`, `isSlug`, `isTime`, `isUlid`, `isUrl(value, protocols = ['http', 'https'])`, `isUuid`.\n\n## Types\n\n### Inference types\n\n| Type | Resolves to |\n| ---------------------- | ----------------------------------------------- |\n| `Infer<TSchema>` | Parsed output; alias of `InferOutput<TSchema>` |\n| `InferInput<TSchema>` | Input accepted before parsing or transformation |\n| `InferOutput<TSchema>` | Value returned after parsing and transformation |\n| `AnySchema` | `Schema<unknown, unknown>`; any schema |\n\nObject input types make a field optional when its schema accepts a missing value (`optional()`, `nullish()`, `default()`, `catch()`). Use `AnySchema` as a generic constraint, and `Schema<T, unknown>` for a parameter that must parse to `T`.\n\n### Parse result and issues\n\n```ts\ntype ParseResult<T> = { data: T; success: true } | { error: SpellValidationError; success: false };\n\ntype Issue =\n | { code: 'custom'; message: string; params?: Record<string, unknown>; path: (string | number)[] }\n | { code: 'invalid_date'; message: string; params?: undefined; path: (string | number)[] }\n | {\n code: 'invalid_discriminator';\n message: string;\n params: { discriminator: string; expected: string[] };\n path: (string | number)[];\n }\n | { code: 'invalid_enum'; message: string; params: { values: readonly unknown[] }; path: (string | number)[] }\n | { code: 'invalid_finite'; message: string; params?: undefined; path: (string | number)[] }\n | {\n code: 'invalid_format';\n message: string;\n params: { format: string; includes?: string; pattern?: string; prefix?: string; suffix?: string };\n path: (string | number)[];\n }\n | { code: 'invalid_integer'; message: string; params?: undefined; path: (string | number)[] }\n | { code: 'invalid_keys'; message: string; params: { keys: string[] }; path: (string | number)[] }\n | { code: 'invalid_length'; message: string; params: { exact: number }; path: (string | number)[] }\n | { code: 'invalid_literal'; message: string; params: { expected: unknown }; path: (string | number)[] }\n | { code: 'invalid_multiple_of'; message: string; params: { step: number | bigint }; path: (string | number)[] }\n | { code: 'invalid_safe'; message: string; params?: undefined; path: (string | number)[] }\n | { code: 'invalid_type'; message: string; params?: undefined; path: (string | number)[] }\n | { code: 'invalid_union'; message: string; params: { errors: Issue[][] }; path: (string | number)[] }\n | { code: 'invalid_unique'; message: string; params?: undefined; path: (string | number)[] }\n | {\n code: 'too_big';\n message: string;\n params: { exclusive?: boolean; max: number | bigint | Date };\n path: (string | number)[];\n }\n | {\n code: 'too_small';\n message: string;\n params: { exclusive?: boolean; min: number | bigint | Date };\n path: (string | number)[];\n }\n | { code: string & {}; message: string; params?: Record<string, unknown>; path: (string | number)[] };\n```\n\n`ErrorCode` is a const object mapping each built-in code to its string literal.\n\n### Validation contracts\n\n```ts\ntype ParseContext = { readonly messages: Messages };\n\ntype CheckContext = {\n addIssue: (issue: {\n code: string;\n message: string;\n params?: Record<string, unknown>;\n path?: (string | number)[];\n }) => void;\n};\n\ntype ValidateResult = boolean | null | undefined | string;\n\ntype MessageFn<Ctx extends Record<string, unknown> = Record<string, unknown>> = string | ((ctx: Ctx) => string);\n\ntype DeepPartial<T> = { [K in keyof T]?: T[K] extends Record<string, unknown> ? DeepPartial<T[K]> : T[K] };\n```\n\n### Messages\n\n`Messages` has one group per schema type. Each entry is a function of the constraint context.\n\n```ts\ntype Messages = {\n array: { length; max; min; nonEmpty; type; unique };\n bigint: { max; min; multipleOf; negative; nonNegative; nonPositive; positive; type };\n boolean: { type };\n check: { default };\n date: { max; min; type };\n discriminatedUnion: { invalidDiscriminator: (ctx: { discriminator: string; expected: string[] }) => string; type };\n enum: { invalid: (ctx: { values: readonly unknown[] }) => string };\n instanceof: { type: (ctx: { className: string }) => string };\n literal: { expected: (ctx: { expected: unknown }) => string };\n map: { max; min; nonEmpty; size; type };\n never: { invalid };\n number: { finite; int; max; min; multipleOf; negative; nonNegative; nonPositive; positive; safe; type };\n object: { invalidKeys: (ctx: { keys: string[] }) => string; type };\n set: { max; min; nonEmpty; size; type };\n string: {\n base64;\n base64url;\n cuid;\n cuid2;\n duration;\n email;\n emoji;\n endsWith;\n hex;\n hexColor;\n includes;\n ip;\n isoDate;\n isoDateTime;\n jwt;\n length;\n max;\n min;\n nanoid;\n nonEmpty;\n numeric;\n regex;\n semver;\n slug;\n startsWith;\n time;\n type;\n ulid;\n url;\n uuid;\n };\n tuple: { length: (ctx: { exact: number }) => string; min: (ctx: { min: number }) => string; type };\n union: { invalid };\n};\n```\n\nConstraint messages receive `value` plus the constraint's parameters, e.g. `string.min` receives `{ min, value }` and `string.includes` receives `{ substr, value }`.\n\n### Descriptors\n\n```ts\ntype PatternDescriptor = { readonly flags: string; readonly source: string };\n\ntype SchemaDescriptor = { description?: string; isNullable?: true; isOptional?: true } & (\n | { kind: 'unknown' | 'never' | 'boolean' | 'lazy' }\n | {\n kind: 'bigint';\n exclusiveMaximum?: bigint;\n exclusiveMinimum?: bigint;\n maximum?: bigint;\n minimum?: bigint;\n multipleOf?: bigint;\n }\n | {\n kind: 'number';\n exclusiveMaximum?: number;\n exclusiveMinimum?: number;\n finite?: true;\n integer?: true;\n maximum?: number;\n minimum?: number;\n multipleOf?: number;\n }\n | {\n kind: 'string';\n formats?: readonly string[];\n maxLength?: number;\n minLength?: number;\n patterns?: readonly PatternDescriptor[];\n }\n | { kind: 'date'; maximum?: string; minimum?: string }\n | { className: string; kind: 'instanceof' }\n | { kind: 'literal'; value: string | number | boolean | null | undefined }\n | { kind: 'enum'; values: readonly (string | number)[] }\n | { items: SchemaDescriptor; kind: 'array'; maxItems?: number; minItems?: number; uniqueItems?: true }\n | { items: readonly SchemaDescriptor[]; kind: 'tuple'; rest: SchemaDescriptor | null }\n | {\n fields: Readonly<Record<string, SchemaDescriptor>>;\n kind: 'object';\n strict: boolean;\n tolerated?: readonly string[];\n }\n | { key: SchemaDescriptor; kind: 'record'; value: SchemaDescriptor }\n | { items: SchemaDescriptor; kind: 'set'; maxSize?: number; minSize?: number }\n | { key: SchemaDescriptor; kind: 'map'; maxSize?: number; minSize?: number; value: SchemaDescriptor }\n | { branches: readonly SchemaDescriptor[]; kind: 'union' | 'intersect' }\n | { branches: Readonly<Record<string, SchemaDescriptor>>; discriminator: string; kind: 'discriminatedUnion' }\n | { from: SchemaDescriptor; kind: 'pipe'; to: SchemaDescriptor }\n);\n\ntype SchemaKind = SchemaDescriptor['kind'];\n\ntype JsonSchema = Record<string, unknown>; // from '@vielzeug/spell/json'\n```\n\nDate bounds are ISO strings. `formats` lists format method names in chain order; `patterns` lists `regex()`, `startsWith()`, `endsWith()`, `includes()`, and `url()` protocol patterns.\n\n### Standard Schema\n\n```ts\ninterface StandardSchemaV1<Input = unknown, Output = Input> {\n readonly '~standard': StandardSchemaV1.Props<Input, Output>;\n}\n\nnamespace StandardSchemaV1 {\n interface Props<Input = unknown, Output = Input> {\n readonly types?: Types<Input, Output> | undefined;\n readonly validate: (value: unknown, options?: Options | undefined) => Result<Output> | Promise<Result<Output>>;\n readonly vendor: string;\n readonly version: 1;\n }\n type Result<Output> = { readonly issues: readonly Issue[] } | { readonly issues?: undefined; readonly value: Output };\n interface Options {\n readonly libraryOptions?: Record<string, unknown> | undefined;\n }\n interface Issue {\n readonly message: string;\n readonly path?: readonly (PropertyKey | PathSegment)[] | undefined;\n }\n interface PathSegment {\n readonly key: PropertyKey;\n }\n interface Types<Input = unknown, Output = Input> {\n readonly input: Input;\n readonly output: Output;\n }\n type InferInput<Schema extends StandardSchemaV1> = NonNullable<Schema['~standard']['types']>['input'];\n type InferOutput<Schema extends StandardSchemaV1> = NonNullable<Schema['~standard']['types']>['output'];\n}\n```\n\n### Error helpers\n\n```ts\ntype FlatError = { messages: string[]; path: (string | number)[] };\ntype FlatErrorFirst = { message: string; path: (string | number)[] };\n\ntype IssuePathSegment = PropertyKey | { readonly key: PropertyKey };\ntype IssuePath = readonly IssuePathSegment[];\n\nfunction joinIssuePath(path: IssuePath | undefined, separator?: string): string;\n```\n\n`joinIssuePath()` flattens a Spell or Standard Schema issue path into a UI key such as `'permissions.0.slug'`.\n\n## Errors\n\n| Class | Thrown when | Members |\n| ---------------------- | ------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------- |\n| `SpellError` | Base class; thrown directly when synchronous parsing meets an async check | `name`, `message` |\n| `SpellValidationError` | `parse()`, `parseAsync()`, or `assert()` receives invalid input | `issues` (frozen), `flatten()`, `flattenFirst()`, `messagesAt(...path)` |\n| `SpellDefinitionError` | `definition()` on a non-portable schema; invalid object derivation or discriminated branch | `name`, `message` |\n\n`SpellValidationError.message` lists one `path: message [code]` line per issue; root issues use `value` as the path.\n\n```ts\nconst result = s.object({ email: s.string().email() }).safeParse({ email: 'invalid' });\n\nif (!result.success) {\n const { fieldErrors, formErrors } = result.error.flatten();\n console.log(fieldErrors, formErrors);\n}\n```\n",
6
- "usage": "---\ntitle: 'Spell: Usage Guide'\ndescription: Build schemas, order checks and transforms, compose objects, customize messages, and integrate Spell with other Vielzeug packages.\n---\n\n[[toc]]\n\n## Basic Usage\n\nStart with `safeParse()` when you want explicit success and failure branches.\n\n```ts\nimport { s } from '@vielzeug/spell';\n\nconst Signup = s.object({\n email: s.string().email(),\n password: s.string().min(12),\n referralCode: s.string().optional(),\n});\n\nconst result = Signup.safeParse({\n email: 'ada@example.com',\n password: 'horse-battery-staple',\n});\n\nif (!result.success) {\n console.error(result.error.issues);\n} else {\n console.log(result.data.email);\n}\n```\n\nUse `parse()` when invalid input should throw. Use `safeParse()` when invalid input is part of normal control flow.\n\n## Building Schemas\n\nCompose schemas from the `s` builders. Every method returns a new schema, so you can share and extend base schemas safely.\n\n```ts\nimport { s } from '@vielzeug/spell';\n\nconst Article = s.object({\n id: s.string().uuid(),\n meta: s.object({ published: s.boolean(), publishedAt: s.date().nullable() }).relaxed(),\n slug: s.string().slug(),\n tags: s.array(s.string().min(1)).default([]),\n title: s.string().trim().min(1).max(120),\n});\n```\n\nObject schemas reject unknown keys by default. Call `.relaxed()` to keep extra properties in the output.\n\nFields with a `default()` are filled in when their key is absent, so `parse({})` returns a fully default-filled object.\n\n```ts\nconst Config = s.object({\n host: s.string().default('localhost'),\n port: s.number().default(3000),\n});\n\nConfig.parse({}); // { host: 'localhost', port: 3000 }\n```\n\n`default()` and `catch()` return a fresh copy of object, array, `Map`, `Set`, and `Date` values on every parse, so callers cannot mutate a shared default.\n\n## Ordering Checks and Transforms\n\nChecks, built-in constraints, and transforms run in the order you chain them. A constraint after a transform sees the transformed value.\n\n```ts\nimport { s } from '@vielzeug/spell';\n\n// trim() runs first, so ' ' fails min(1)\nconst Title = s.string().trim().min(1);\n\n// The check receives the length, not the string\nconst ShortCode = s\n .string()\n .transform((value) => value.length)\n .check((length) => length <= 8 || 'At most 8 characters');\n```\n\nTransforms are skipped once an earlier step reported an issue, so a transform never receives a value that failed validation. Use `preprocess()` to change raw input before the type check.\n\n## Optional, Nullable, and Fallback Values\n\nUse modifiers to describe missing values and recovery rules.\n\n```ts\nimport { s } from '@vielzeug/spell';\n\nconst DisplayName = s.string().trim().min(2).describe('Display name').optional().default('Guest').nullable();\n\nDisplayName.parse(undefined); // 'Guest'\nDisplayName.parse(null); // null\nDisplayName.description; // 'Display name'\n```\n\n`optional()`, `nullable()`, `nullish()`, `required()`, and `transform()` change the value type and return a base `Schema`. Chain type-specific methods such as `.min()` or `.extend()` before them.\n\nCall `.required()` to make `undefined` invalid again. It clears `optional()` and `default()` and keeps `null` and checks.\n\n```ts\nimport { s } from '@vielzeug/spell';\n\nconst NullableButRequired = s.string().optional().nullable().required();\n\nNullableButRequired.parse('Ada');\nNullableButRequired.parse(null);\nNullableButRequired.safeParse(undefined).success; // false\n```\n\nUse `.catch()` when you want a fallback output after validation fails.\n\n```ts\nimport { s } from '@vielzeug/spell';\n\nconst Port = s.number().int().min(1).max(65535).catch(3000);\n\nPort.parse('not-a-number'); // 3000\n```\n\n## Composing Object Schemas\n\nDerive new object schemas with `extend()`, `pick()`, `omit()`, and `partial()`. Derive the shape first, then add checks, transforms, defaults, or catches to the final schema.\n\n```ts\nimport { s } from '@vielzeug/spell';\n\nconst User = s.object({ email: s.string().email(), id: s.string().uuid(), name: s.string() });\n\nconst Admin = User.extend({ role: s.enum(['owner', 'editor']) });\nconst UserPatch = User.omit('id').partial();\n\nconst Signup = User.pick('email')\n .extend({ confirm: s.string(), password: s.string().min(12) })\n .check((value) => value.password === value.confirm || 'Passwords must match');\n```\n\nDeriving from an object with checks, transforms, preprocessors, a default, or a catch throws `SpellDefinitionError`. A check written for the old shape could read a field that `omit()` removed, so Spell refuses instead of guessing.\n\n## Tolerating Removed Fields\n\nRecords saved by older schema versions can carry keys the current schema no longer declares. `tolerate()` accepts and drops exactly the named keys, and other unknown keys still fail.\n\n```ts\nimport { s } from '@vielzeug/spell';\n\nconst Person = s.object({ email: s.string(), name: s.string() }).tolerate('address');\n\nPerson.parse({ address: '42 Wallaby Way', email: 'johndoe@mail.com', name: 'John Doe' });\n// { email: 'johndoe@mail.com', name: 'John Doe' }\n```\n\nFields added in later schema versions do not need `tolerate()`: give them a `default()` and older records are repaired on parse.\n\n## Custom Validation\n\nUse `check()` for synchronous domain rules and `checkAsync()` for asynchronous rules.\n\n```ts\nimport { s } from '@vielzeug/spell';\n\n// Return false to fail with the default message\nconst EvenNumber = s.number().check((n) => n % 2 === 0);\n\n// Return a string to fail with that message\nconst Username = s\n .string()\n .min(3)\n .check((v) => !v.startsWith('_') || 'Cannot start with underscore');\n\n// Report issues at specific paths with ctx.addIssue()\nconst Signup = s.object({ confirm: s.string(), password: s.string() }).check((v, ctx) => {\n if (v.password !== v.confirm) ctx.addIssue({ code: 'custom', message: 'Passwords must match', path: ['confirm'] });\n});\n```\n\nA schema containing `checkAsync()` at any depth needs `parseAsync()` or `safeParseAsync()`. The synchronous methods throw `SpellError` before running the async check, because accepting an unchecked value would be unsafe.\n\n```ts\nimport { s } from '@vielzeug/spell';\n\nconst takenEmails = new Set(['ada@example.com']);\n\nconst AccountEmail = s\n .string()\n .email()\n .checkAsync(async (value) => !takenEmails.has(value) || 'Email is already taken');\n\nawait AccountEmail.parseAsync('grace@example.com');\n```\n\n## Strings, Numbers, and Regex Safety\n\nUse the built-in constraints instead of hand-written predicates.\n\n```ts\nimport { s } from '@vielzeug/spell';\n\nconst Password = s.string().min(12).regex(/[A-Z]/).regex(/[0-9]/);\nconst Price = s.number().nonNegative().multipleOf(0.01);\nconst LaunchWindow = s.date().min(new Date('2025-01-01T00:00:00.000Z'));\nconst Website = s.string().url({ protocols: ['https'] });\n```\n\nFormat failures use the `invalid_format` code with `params.format` set to the method name. `regex()` drops the stateful `g` and `y` flags, so repeated parses agree even when you reuse a global regular expression.\n\n## Coercion and Pipelines\n\nUse `s.coerce.*` when input arrives as strings, such as query parameters or form values.\n\n```ts\nimport { s } from '@vielzeug/spell';\n\nconst Query = s.object({\n draft: s.coerce.boolean().default(false),\n limit: s.coerce.number().int().positive().default(20),\n publishedAt: s.coerce.date().nullable(),\n search: s.coerce.string().trim().min(1).optional(),\n});\n\nQuery.parse({ draft: 'true', limit: '50', publishedAt: '2025-04-01T12:00:00.000Z', search: ' vielzeug ' });\n```\n\nUse `transform()` or `pipe()` when downstream code needs a different output.\n\n```ts\nimport { s } from '@vielzeug/spell';\n\nconst LowercaseTags = s.array(s.string().trim().min(1)).transform((tags) => tags.map((tag) => tag.toLowerCase()));\nconst Slug = s.string().trim().pipe(s.string().slug());\n```\n\n## Definitions and JSON Schema\n\nUse declarative definitions when schemas feed external tooling.\n\n```ts\nimport { s } from '@vielzeug/spell';\nimport { toJsonSchema } from '@vielzeug/spell/json';\n\nconst Product = s\n .object({\n id: s.string().uuid(),\n name: s.string().min(1),\n price: s.number().positive().multipleOf(0.01),\n })\n .describe('Product');\n\nconst jsonSchema = toJsonSchema(Product.definition());\nconsole.log(jsonSchema.description); // 'Product'\n```\n\nDefinitions are frozen, serializable data. Schemas with checks, transforms, preprocessors (including `s.coerce.*` and `trim()`), defaults, or catches have no definition, and `definition()` throws `SpellDefinitionError`.\n\n## Messages\n\nSpell has no process-wide configuration. Build one parse context per request, locale, or form, and pass it explicitly.\n\n```ts\nimport { createParseContext, s } from '@vielzeug/spell';\n\nconst User = s.object({ email: s.string().email() });\nconst german = createParseContext({ object: { invalidKeys: () => 'Keine unbekannten Felder erlaubt' } });\n\nUser.safeParse({ email: 'ada@example.com', extra: true }, german);\n```\n\nDevelopment builds warn through `console.warn` when a message override uses an unsafe key such as `__proto__`.\n\n## Working with Validation Errors\n\nUse `SpellValidationError` helpers to build UI-ready error structures.\n\n```ts\nimport { joinIssuePath, s } from '@vielzeug/spell';\n\nconst User = s.object({ email: s.string().email(), profile: s.object({ name: s.string().min(2) }) });\nconst result = User.safeParse({ email: 'nope', profile: { name: '' } });\n\nif (!result.success) {\n console.log(result.error.messagesAt('profile', 'name'));\n\n for (const issue of result.error.issues) console.log(joinIssuePath(issue.path), issue.message);\n}\n```\n\nUnion failures produce one `invalid_union` issue. Use `s.discriminatedUnion()` when a tag field identifies the intended branch, so errors point at that branch's fields.\n\n## Typing Schema Parameters\n\nType a function that accepts any schema with `AnySchema`, or with `Schema<T, unknown>` when it needs the parsed type.\n\n```ts\nimport { type AnySchema, type ParseResult, type Schema, s } from '@vielzeug/spell';\n\nfunction isValid(schema: AnySchema, value: unknown): boolean {\n return schema.safeParse(value).success;\n}\n\nfunction parseWith<T>(schema: Schema<T, unknown>, value: unknown): ParseResult<T> {\n return schema.safeParse(value);\n}\n\nparseWith(s.object({ email: s.string() }), { email: 'ada@example.com' });\n```\n\n## Framework Integration\n\nSpell works anywhere you can call a function before data enters your app.\n\n::: code-group\n\n```tsx [React]\nimport { s } from '@vielzeug/spell';\n\nconst SearchParams = s\n .object({\n page: s.coerce.number().int().positive().default(1),\n q: s.string().trim().optional(),\n })\n .relaxed();\n\nexport function SearchPage({ rawParams }: { rawParams: unknown }) {\n const params = SearchParams.parse(rawParams);\n\n return (\n <div>\n {params.q ?? 'All results'}: page {params.page}\n </div>\n );\n}\n```\n\n```ts [Vue]\nimport { computed, ref } from 'vue';\nimport { s } from '@vielzeug/spell';\n\nconst Settings = s.object({\n compact: s.coerce.boolean().default(false),\n locale: s.string().min(2),\n});\n\nconst raw = ref<unknown>({ compact: 'true', locale: 'en' });\nconst settings = computed(() => Settings.parse(raw.value));\n```\n\n```svelte [Svelte]\n<script lang=\"ts\">\n import { s } from '@vielzeug/spell';\n\n const Email = s.string().email();\n let value = '';\n $: error = Email.safeParse(value).success ? '' : 'Enter a valid email';\n</script>\n\n<input bind:value />\n{#if error}<p>{error}</p>{/if}\n```\n\n:::\n\n## Working with Other Vielzeug Libraries\n\nSpell schemas implement Standard Schema, so packages that accept Standard Schema validators use them directly.\n\n```ts\nimport { createCourier } from '@vielzeug/courier';\nimport { createForm } from '@vielzeug/forge';\nimport { schemaValidator } from '@vielzeug/forge/schema';\nimport { s } from '@vielzeug/spell';\n\nconst Profile = s.object({ displayName: s.string().min(2), newsletter: s.boolean() });\n\nconst form = createForm({\n initialValues: { displayName: '', newsletter: false },\n validate: schemaValidator(Profile),\n});\n\nconst courier = createCourier({ baseUrl: '/api' });\nconst profile = Profile.parse(await courier.get('/profile'));\n```\n\n## Best Practices\n\n- Keep schemas close to the boundary where unknown data enters your app.\n- Chain constraints in the order they should apply; put `trim()` before length checks.\n- Derive object shapes with `extend()`, `pick()`, `omit()`, or `partial()` before adding checks.\n- Chain type-specific methods before `optional()`, `nullable()`, `transform()`, or `required()`.\n- Use `check()` with `ctx.addIssue()` for multi-field rules; return a message for single predicates.\n- Use `checkAsync()` with `parseAsync()` for every asynchronous domain rule.\n- Build a parse context per request, locale, or test instead of relying on global state.\n- Use `definition()` with `toJsonSchema()` for external tooling, and keep runtime-only schemas separate.\n",
7
- "examples": "---\ntitle: 'Spell: Examples'\ndescription: Practical examples and recipes for spell.\n---\n\n## Examples\n\n- [Validating API Payloads](./examples/api.md)\n- [Form-Safe Parsing](./examples/forms.md)\n- [Async Business Rules](./examples/async.md)\n- [Schema Introspection and Round-Trips](./examples/introspection.md)\n- [Unions, Intersections, and Discriminated Unions](./examples/unions.md)\n"
8
- },
9
- "examples": [
10
- {
11
- "id": "array-validation",
12
- "code": "// Validate a product tag list before it hits search filters.\nimport { s } from '@vielzeug/spell'\n\nconst ProductTags = s.array(s.string().trim().min(2)).min(1).max(4).unique()\n\nconsole.log('Valid tags:', ProductTags.safeParse(['ui', 'forms', 'docs']).success)\n\nconst invalid = ProductTags.safeParse(['ui', 'ui', 'x', 'search', 'extra'])\nconsole.log('Invalid tags:', invalid.success)\n\nif (!invalid.success) {\n console.log('Issues:', invalid.error.issues.map((issue) => issue.message))\n}",
13
- "name": "Array Validation"
14
- },
15
- {
16
- "id": "async-validate",
17
- "code": "// checkAsync() declares asynchronous domain rules.\n// Use safeParseAsync() or parseAsync() for schemas containing async checks.\nimport { s } from '@vielzeug/spell'\n\n// Simulated async check (e.g. database lookup)\nfunction isUsernameAvailable(name) {\n return new Promise(resolve => setTimeout(() => resolve(name !== 'taken'), 50))\n}\n\nconst UsernameSchema = s.string()\n .min(3)\n .checkAsync(async (name) => {\n const available = await isUsernameAvailable(name)\n return available || 'Username is already taken'\n })\n\n// Async checks require safeParseAsync() or parseAsync()\nconst ok = await UsernameSchema.safeParseAsync('alice')\nconsole.log('alice:', ok.success ? 'available' : ok.error.issues[0].message)\n\nconst fail = await UsernameSchema.safeParseAsync('taken')\nconsole.log('taken:', fail.success ? 'available' : fail.error.issues[0].message)\n\nconst tooShort = await UsernameSchema.safeParseAsync('ab')\nconsole.log('ab:', tooShort.success ? 'available' : tooShort.error.issues[0].message)",
18
- "name": "Async Validation"
19
- },
20
- {
21
- "id": "basic-parsing",
22
- "code": "// Schema definition, type inference, and safe parsing\nimport { s } from '@vielzeug/spell'\n\nconst Product = s.object({\n id: s.string().uuid(),\n name: s.string().min(1).max(120),\n price: s.number().positive().multipleOf(0.01),\n tags: s.array(s.string().min(1)).default(() => []),\n})\n\n// Infer the TypeScript type directly from the schema\n// type Product = { id: string; name: string; price: number; tags: string[] }\n\n// parse() throws on failure: use when invalid input is a programmer error\nconst product = Product.parse({\n id: '550e8400-e29b-41d4-a716-446655440000',\n name: 'Mechanical Keyboard',\n price: 129.99,\n})\nconsole.log('Parsed:', product.name, ': tags:', product.tags)\n\n// safeParse() returns a tagged result union: use at untrusted boundaries\nconst bad = Product.safeParse({ id: 'not-a-uuid', name: '', price: -5 })\nif (!bad.success) {\n const paths = bad.error.issues.map(i => i.path.join('.') || 'root')\n console.log('Validation failed at:', paths.join(', '))\n}",
23
- "name": "Basic Parsing"
24
- },
25
- {
26
- "id": "basic-schema",
27
- "code": "// Validate a signup payload before it enters application state.\nimport { s } from '@vielzeug/spell'\n\nconst Signup = s.object({\n email: s.string().email(),\n password: s.string().min(12),\n referralCode: s.string().optional(),\n})\n\nconsole.log('Accepted:', Signup.parse({\n email: 'ada@example.com',\n password: 'horse-battery-staple',\n}))\n\nconst invalid = Signup.safeParse({\n email: 'not-an-email',\n password: 'short',\n})\n\nif (!invalid.success) {\n console.log('Email errors:', invalid.error.messagesAt('email'))\n console.log('Password errors:', invalid.error.messagesAt('password'))\n}",
28
- "name": "Basic Schema Validation"
29
- },
30
- {
31
- "id": "coercion",
32
- "code": "// Coerce query params into typed search options with safe defaults.\nimport { s } from '@vielzeug/spell'\n\nconst SearchQuery = s.object({\n draft: s.coerce.boolean().default(false),\n limit: s.coerce.number().int().positive().default(20),\n page: s.coerce.number().int().positive().default(1),\n q: s.coerce.string().trim().min(1).optional(),\n})\n\nconst parsed = SearchQuery.parse({\n draft: 'true',\n limit: '50',\n page: '2',\n q: ' vielzeug ',\n})\n\nconsole.log(parsed)\nconsole.log('limit type:', typeof parsed.limit)",
33
- "name": "Type Coercion"
34
- },
35
- {
36
- "id": "descriptor-roundtrip",
37
- "code": "import { s } from '@vielzeug/spell';\nimport { toJsonSchema } from '@vielzeug/spell/json';\n\nconst Product = s.object({\n id: s.string().uuid(),\n name: s.string().min(1).describe('Display name'),\n price: s.number().positive(),\n sku: s.string().startsWith('SKU-'),\n});\n\n// definition() returns frozen, declarative data\nconst definition = Product.definition();\nconsole.log(definition.kind); // 'object'\nconsole.log(definition.fields.sku); // { kind: 'string', patterns: [{ flags: '', source: '^SKU-' }] }\n\n// toJsonSchema() maps the definition to JSON Schema 2020-12\nconsole.log(toJsonSchema(definition));\n\n// Runtime behavior has no declarative form\ntry {\n Product.check(() => true).definition();\n} catch (error) {\n console.log(error.name); // 'SpellDefinitionError'\n}\n",
38
- "name": "Declarative Definition Export"
39
- },
40
- {
41
- "id": "discriminated-union",
42
- "code": "// s.discriminatedUnion() validates a discriminated union: objects sharing a common tag field.\n// Spell automatically injects the discriminator literal into each branch.\nimport { s } from '@vielzeug/spell'\n\nconst Event = s.discriminatedUnion('type', {\n click: s.object({ x: s.number(), y: s.number() }),\n keydown: s.object({ key: s.string(), repeat: s.boolean() }),\n resize: s.object({ width: s.number(), height: s.number() }),\n})\n\nconst click = Event.parse({ type: 'click', x: 100, y: 200 })\nconsole.log('click:', click)\n\nconst key = Event.parse({ type: 'keydown', key: 'Enter', repeat: false })\nconsole.log('keydown:', key)\n\n// Wrong discriminator value\nconst bad = Event.safeParse({ type: 'unknown', x: 0 })\nconsole.log('unknown type:', bad.success ? 'ok' : bad.error.issues[0].message)\n\n// Missing required field in matched branch\nconst missingField = Event.safeParse({ type: 'resize', width: 800 })\nconsole.log('missing height:', missingField.success ? 'ok' : missingField.error.issues[0].message)",
43
- "name": "Discriminated Union"
44
- },
45
- {
46
- "id": "format-validators",
47
- "code": "import { s } from '@vielzeug/spell'\nimport { isEmail, isUuid } from '@vielzeug/spell/predicates'\n\nconsole.log(isEmail('ada@example.com'))\nconsole.log(isEmail('not-an-email'))\nconsole.log(isUuid('550e8400-e29b-41d4-a716-446655440000'))\nconsole.log(isUuid('short'))\n\nconst UserId = s.string().uuid()\nconsole.log(UserId.safeParse('550e8400-e29b-41d4-a716-446655440000').success)",
48
- "name": "Format Predicates"
49
- },
50
- {
51
- "id": "messages-override",
52
- "code": "import { createParseContext, s } from '@vielzeug/spell'\n\nconst context = createParseContext({\n object: { invalidKeys: () => 'Use only supported fields' },\n})\n\nconsole.log(s.object({ email: s.string().email() }).safeParse({ email: 'ada@example.com', extra: true }, context).success)",
53
- "name": "Request-local messages"
54
- },
55
- {
56
- "id": "nested-objects",
57
- "code": "// Model an API response with a discriminator instead of a loose union.\nimport { s } from '@vielzeug/spell'\n\nconst SearchResponse = s.discriminatedUnion('status', {\n error: s.object({\n message: s.string().min(1),\n status: s.literal('error'),\n }),\n success: s.object({\n results: s.array(s.object({ id: s.string().uuid(), title: s.string().min(1) })).default(() => []),\n status: s.literal('success'),\n }),\n})\n\nconsole.log('Success branch:', SearchResponse.parse({\n status: 'success',\n results: [{ id: '550e8400-e29b-41d4-a716-446655440000', title: 'Spell docs' }],\n}))\n\nconst invalid = SearchResponse.safeParse({ status: 'success', message: 'no results here' })\nconsole.log('Invalid branch accepted:', invalid.success)",
58
- "name": "Variant Responses"
59
- },
60
- {
61
- "id": "number-validation",
62
- "code": "// Enforce money-like numeric constraints for a checkout amount.\nimport { s } from '@vielzeug/spell'\n\nconst CheckoutTotal = s.number().nonNegative().multipleOf(0.01).max(9999)\n\nfor (const value of [129.99, -4, 19.999, 15000]) {\n const result = CheckoutTotal.safeParse(value)\n console.log(value, '=>', result.success ? 'accepted' : result.error.issues[0].message)\n}",
63
- "name": "Number Validation"
64
- },
65
- {
66
- "id": "object-composition",
67
- "code": "import { s } from '@vielzeug/spell';\n\nconst User = s.object({\n email: s.string().email(),\n id: s.string().uuid(),\n name: s.string().min(1),\n});\n\n// Derive shapes first; extend() overrides fields with the same key\nconst Admin = User.extend({ role: s.enum(['owner', 'editor']) });\nconst PublicUser = User.omit('email');\nconst UserPatch = User.pick('email', 'name').partial();\n\nconsole.log(Object.keys(Admin.shape)); // ['email', 'id', 'name', 'role']\nconsole.log(PublicUser.parse({ id: '550e8400-e29b-41d4-a716-446655440000', name: 'Ada' }));\nconsole.log(UserPatch.parse({ name: 'Grace' })); // { name: 'Grace' }\n\n// Checks belong to the final shape: add them after deriving\nconst Signup = User.pick('email')\n .extend({ confirm: s.string(), password: s.string().min(12) })\n .check((value) => value.password === value.confirm || 'Passwords must match');\n\nconsole.log(Signup.safeParse({ confirm: 'x', email: 'ada@example.com', password: 'correct horse battery' }).success); // false\n\n// Deriving from a schema with checks throws, because the check was written for the old shape\ntry {\n Signup.omit('confirm');\n} catch (error) {\n console.log(error.name); // 'SpellDefinitionError'\n}\n",
68
- "name": "Object Composition"
69
- },
70
- {
71
- "id": "object-defaults",
72
- "code": "import { s } from '@vielzeug/spell';\n\nconst ServerConfig = s.object({\n host: s.string().default('localhost'),\n port: s.number().int().positive().default(3000),\n tls: s.boolean().default(false),\n});\n\n// Absent keys take their field default\nconsole.log(ServerConfig.parse({}));\n// { host: 'localhost', port: 3000, tls: false }\n\n// default() on the object itself covers a missing object\nconst AppConfig = s.object({\n debug: s.boolean().default(false),\n server: ServerConfig.default({ host: 'localhost', port: 3000, tls: false }),\n});\n\nconsole.log(AppConfig.parse({}).server.port); // 3000\n\n// Each parse returns a fresh copy of the default value\nconst Tags = s.array(s.string()).default([]);\nconst first = Tags.parse(undefined);\nfirst.push('mutated');\nconsole.log(Tags.parse(undefined)); // []\n\n// Fields without a default stay required\nconsole.log(s.object({ name: s.string() }).safeParse({}).success); // false\n",
73
- "name": "Object Defaults"
74
- },
75
- {
76
- "id": "optional-nullable",
77
- "code": "// required() makes undefined invalid again: it clears optional() and default(), keeping checks and null.\nimport { s } from '@vielzeug/spell'\n\nconst DisplayName = s.string().trim().min(2).optional().default('Guest').nullable()\nconst RequiredDisplayName = DisplayName.required()\n\nconsole.log('default for undefined:', DisplayName.parse(undefined))\nconsole.log('null stays null:', DisplayName.parse(null))\n\nconst short = RequiredDisplayName.safeParse('A')\nconsole.log('short name accepted:', short.success)\n\nconst missing = RequiredDisplayName.safeParse(undefined)\nconsole.log('undefined accepted after required():', missing.success)\n\nconsole.log('null accepted after required():', RequiredDisplayName.parse(null))",
78
- "name": "Optional and Nullable Fields"
79
- },
80
- {
81
- "id": "refinements",
82
- "code": "// check() and checkAsync(): explicit custom domain rules\nimport { s } from '@vielzeug/spell'\n\nconst reserved = new Set(['admin', 'root'])\n\n// check() is synchronous; return a string to fail with that message\nconst Username = s.string().min(3).check((value) =>\n !reserved.has(value) || value + ' is reserved'\n)\n\n// check() receives context for multiple issues or custom error codes\nconst Signup = s.object({ password: s.string().min(8), confirm: s.string() })\n .check((v, ctx) => {\n if (v.password !== v.confirm)\n ctx.addIssue({ code: 'custom', message: 'Passwords must match', path: ['confirm'] })\n })\n\n// check() also covers predicate-only domain rules\nconst EvenPort = s.number().int().min(1).max(65535)\n .check((n) => n % 2 === 0 || 'Port must be even')\n\nfor (const name of ['ad', 'admin', 'grace']) {\n const r = Username.safeParse(name)\n console.log(name, '->', r.success ? 'ok' : r.error.issues[0].message)\n}\n\nconst signupResult = Signup.safeParse({ password: 'secure123', confirm: 'different' })\nconsole.log('signup:', signupResult.success ? 'ok' : signupResult.error.issues[0].message)\n\nfor (const port of [8080, 3001, 443]) {\n const r = EvenPort.safeParse(port)\n console.log('port', port, '->', r.success ? 'ok' : r.error.issues[0].message)\n}",
83
- "name": "Custom Validation"
84
- },
85
- {
86
- "id": "string-validation",
87
- "code": "// Reuse one stateful regex safely across repeated parses in the browser REPL.\nimport { s } from '@vielzeug/spell'\n\nconst HexColor = s.string().regex(/#[0-9a-f]{6}/gy)\n\nfor (const value of ['#ff8800', '#ff8800', 'oops']) {\n const result = HexColor.safeParse(value)\n console.log(value, '=>', result.success)\n}",
88
- "name": "String Validation"
89
- },
90
- {
91
- "id": "wrappers-and-defaults",
92
- "code": "// optional(), nullable(), default(), catch(): missing-value semantics\nimport { s } from '@vielzeug/spell'\n\n// optional: accepts undefined, passes through validation otherwise\nconst Nickname = s.string().min(2).optional().default('Guest')\n\nconsole.log(Nickname.parse(undefined)) // 'Guest'\nconsole.log(Nickname.parse('Ada')) // 'Ada'\n\n// nullable: accepts null explicitly\nconst Bio = s.string().max(200).nullable()\n\nconsole.log(Bio.parse(null)) // null\nconsole.log(Bio.parse('Loves types')) // 'Loves types'\n\n// nullish: accepts both null and undefined\nconst Avatar = s.string().url().nullish()\n\nconsole.log(Avatar.parse(null)) // null\nconsole.log(Avatar.parse(undefined)) // undefined\n\n// required(): strips undefined without removing null\nconst NullableButRequired = s.string().optional().nullable().required()\nconsole.log(NullableButRequired.parse(null)) // null\nconsole.log(NullableButRequired.safeParse(undefined).success) // false\n\n// catch(): returns a fallback when validation fails: never throws\nconst Port = s.number().int().min(1).max(65535).catch(3000)\nconsole.log(Port.parse(8080)) // 8080\nconsole.log(Port.parse('not-a-port')) // 3000",
93
- "name": "Wrappers & Defaults"
94
- }
95
- ],
96
- "typeSignatures": {
97
- "FlatError": "export {\n type FlatError,\n type FlatErrorFirst,\n joinIssuePath,\n SpellDefinitionError,\n SpellError,\n SpellValidationError,\n} from './errors';",
98
- "FlatErrorFirst": "export {\n type FlatError,\n type FlatErrorFirst,\n joinIssuePath,\n SpellDefinitionError,\n SpellError,\n SpellValidationError,\n} from './errors';",
99
- "joinIssuePath": "export {\n type FlatError,\n type FlatErrorFirst,\n joinIssuePath,\n SpellDefinitionError,\n SpellError,\n SpellValidationError,\n} from './errors';",
100
- "SpellDefinitionError": "export {\n type FlatError,\n type FlatErrorFirst,\n joinIssuePath,\n SpellDefinitionError,\n SpellError,\n SpellValidationError,\n} from './errors';",
101
- "SpellError": "export {\n type FlatError,\n type FlatErrorFirst,\n joinIssuePath,\n SpellDefinitionError,\n SpellError,\n SpellValidationError,\n} from './errors';",
102
- "SpellValidationError": "export {\n type FlatError,\n type FlatErrorFirst,\n joinIssuePath,\n SpellDefinitionError,\n SpellError,\n SpellValidationError,\n} from './errors';",
103
- "createParseContext": "export { createParseContext, type DeepPartial, type Messages } from './messages';",
104
- "DeepPartial": "export { createParseContext, type DeepPartial, type Messages } from './messages';",
105
- "Messages": "export { createParseContext, type DeepPartial, type Messages } from './messages';",
106
- "s": "export { s } from './s';",
107
- "Schema": "export { Schema } from './schema';",
108
- "AnySchema": "export {\n type AnySchema,\n type CheckContext,\n ErrorCode,\n type Infer,\n type InferInput,\n type InferOutput,\n type Issue,\n type IssuePath,\n type IssuePathSegment,\n type MessageFn,\n type ParseContext,\n type ParseResult,\n type PatternDescriptor,\n type SchemaDescriptor,\n type SchemaKind,\n type StandardSchemaV1,\n type ValidateResult,\n} from './types';",
109
- "CheckContext": "export {\n type AnySchema,\n type CheckContext,\n ErrorCode,\n type Infer,\n type InferInput,\n type InferOutput,\n type Issue,\n type IssuePath,\n type IssuePathSegment,\n type MessageFn,\n type ParseContext,\n type ParseResult,\n type PatternDescriptor,\n type SchemaDescriptor,\n type SchemaKind,\n type StandardSchemaV1,\n type ValidateResult,\n} from './types';",
110
- "ErrorCode": "export {\n type AnySchema,\n type CheckContext,\n ErrorCode,\n type Infer,\n type InferInput,\n type InferOutput,\n type Issue,\n type IssuePath,\n type IssuePathSegment,\n type MessageFn,\n type ParseContext,\n type ParseResult,\n type PatternDescriptor,\n type SchemaDescriptor,\n type SchemaKind,\n type StandardSchemaV1,\n type ValidateResult,\n} from './types';",
111
- "Infer": "export {\n type AnySchema,\n type CheckContext,\n ErrorCode,\n type Infer,\n type InferInput,\n type InferOutput,\n type Issue,\n type IssuePath,\n type IssuePathSegment,\n type MessageFn,\n type ParseContext,\n type ParseResult,\n type PatternDescriptor,\n type SchemaDescriptor,\n type SchemaKind,\n type StandardSchemaV1,\n type ValidateResult,\n} from './types';",
112
- "InferInput": "export {\n type AnySchema,\n type CheckContext,\n ErrorCode,\n type Infer,\n type InferInput,\n type InferOutput,\n type Issue,\n type IssuePath,\n type IssuePathSegment,\n type MessageFn,\n type ParseContext,\n type ParseResult,\n type PatternDescriptor,\n type SchemaDescriptor,\n type SchemaKind,\n type StandardSchemaV1,\n type ValidateResult,\n} from './types';",
113
- "InferOutput": "export {\n type AnySchema,\n type CheckContext,\n ErrorCode,\n type Infer,\n type InferInput,\n type InferOutput,\n type Issue,\n type IssuePath,\n type IssuePathSegment,\n type MessageFn,\n type ParseContext,\n type ParseResult,\n type PatternDescriptor,\n type SchemaDescriptor,\n type SchemaKind,\n type StandardSchemaV1,\n type ValidateResult,\n} from './types';",
114
- "Issue": "export {\n type AnySchema,\n type CheckContext,\n ErrorCode,\n type Infer,\n type InferInput,\n type InferOutput,\n type Issue,\n type IssuePath,\n type IssuePathSegment,\n type MessageFn,\n type ParseContext,\n type ParseResult,\n type PatternDescriptor,\n type SchemaDescriptor,\n type SchemaKind,\n type StandardSchemaV1,\n type ValidateResult,\n} from './types';",
115
- "IssuePath": "export {\n type AnySchema,\n type CheckContext,\n ErrorCode,\n type Infer,\n type InferInput,\n type InferOutput,\n type Issue,\n type IssuePath,\n type IssuePathSegment,\n type MessageFn,\n type ParseContext,\n type ParseResult,\n type PatternDescriptor,\n type SchemaDescriptor,\n type SchemaKind,\n type StandardSchemaV1,\n type ValidateResult,\n} from './types';",
116
- "IssuePathSegment": "export {\n type AnySchema,\n type CheckContext,\n ErrorCode,\n type Infer,\n type InferInput,\n type InferOutput,\n type Issue,\n type IssuePath,\n type IssuePathSegment,\n type MessageFn,\n type ParseContext,\n type ParseResult,\n type PatternDescriptor,\n type SchemaDescriptor,\n type SchemaKind,\n type StandardSchemaV1,\n type ValidateResult,\n} from './types';",
117
- "MessageFn": "export {\n type AnySchema,\n type CheckContext,\n ErrorCode,\n type Infer,\n type InferInput,\n type InferOutput,\n type Issue,\n type IssuePath,\n type IssuePathSegment,\n type MessageFn,\n type ParseContext,\n type ParseResult,\n type PatternDescriptor,\n type SchemaDescriptor,\n type SchemaKind,\n type StandardSchemaV1,\n type ValidateResult,\n} from './types';",
118
- "ParseContext": "export {\n type AnySchema,\n type CheckContext,\n ErrorCode,\n type Infer,\n type InferInput,\n type InferOutput,\n type Issue,\n type IssuePath,\n type IssuePathSegment,\n type MessageFn,\n type ParseContext,\n type ParseResult,\n type PatternDescriptor,\n type SchemaDescriptor,\n type SchemaKind,\n type StandardSchemaV1,\n type ValidateResult,\n} from './types';",
119
- "ParseResult": "export {\n type AnySchema,\n type CheckContext,\n ErrorCode,\n type Infer,\n type InferInput,\n type InferOutput,\n type Issue,\n type IssuePath,\n type IssuePathSegment,\n type MessageFn,\n type ParseContext,\n type ParseResult,\n type PatternDescriptor,\n type SchemaDescriptor,\n type SchemaKind,\n type StandardSchemaV1,\n type ValidateResult,\n} from './types';",
120
- "PatternDescriptor": "export {\n type AnySchema,\n type CheckContext,\n ErrorCode,\n type Infer,\n type InferInput,\n type InferOutput,\n type Issue,\n type IssuePath,\n type IssuePathSegment,\n type MessageFn,\n type ParseContext,\n type ParseResult,\n type PatternDescriptor,\n type SchemaDescriptor,\n type SchemaKind,\n type StandardSchemaV1,\n type ValidateResult,\n} from './types';",
121
- "SchemaDescriptor": "export {\n type AnySchema,\n type CheckContext,\n ErrorCode,\n type Infer,\n type InferInput,\n type InferOutput,\n type Issue,\n type IssuePath,\n type IssuePathSegment,\n type MessageFn,\n type ParseContext,\n type ParseResult,\n type PatternDescriptor,\n type SchemaDescriptor,\n type SchemaKind,\n type StandardSchemaV1,\n type ValidateResult,\n} from './types';",
122
- "SchemaKind": "export {\n type AnySchema,\n type CheckContext,\n ErrorCode,\n type Infer,\n type InferInput,\n type InferOutput,\n type Issue,\n type IssuePath,\n type IssuePathSegment,\n type MessageFn,\n type ParseContext,\n type ParseResult,\n type PatternDescriptor,\n type SchemaDescriptor,\n type SchemaKind,\n type StandardSchemaV1,\n type ValidateResult,\n} from './types';",
123
- "StandardSchemaV1": "export {\n type AnySchema,\n type CheckContext,\n ErrorCode,\n type Infer,\n type InferInput,\n type InferOutput,\n type Issue,\n type IssuePath,\n type IssuePathSegment,\n type MessageFn,\n type ParseContext,\n type ParseResult,\n type PatternDescriptor,\n type SchemaDescriptor,\n type SchemaKind,\n type StandardSchemaV1,\n type ValidateResult,\n} from './types';",
124
- "ValidateResult": "export {\n type AnySchema,\n type CheckContext,\n ErrorCode,\n type Infer,\n type InferInput,\n type InferOutput,\n type Issue,\n type IssuePath,\n type IssuePathSegment,\n type MessageFn,\n type ParseContext,\n type ParseResult,\n type PatternDescriptor,\n type SchemaDescriptor,\n type SchemaKind,\n type StandardSchemaV1,\n type ValidateResult,\n} from './types';"
125
- }
126
- }
@@ -1,25 +0,0 @@
1
- {
2
- "apiSource": "// Public root surface of @vielzeug/stage. Every public export goes through this file.\n\nexport { StageConfigError, StageDisposedError, StageError, StageUnsupportedError } from './errors.js';\nexport {\n type CreateSurface,\n createStage,\n type PaintContext,\n type Stage,\n type StageController,\n type StageFrameInfo,\n type StageLayerOptions,\n type StageOptions,\n type StageSurface,\n} from './stage.js';\n",
3
- "docs": {
4
- "index": "---\ntitle: 'Stage: Retained-Mode 2D Canvas Engine'\ndescription: 'Retained-mode 2D canvas stage engine with DPR-aware layers, dirty repaints, and PNG export'\npackage: stage\ncategory: utilities\nkeywords: [canvas, rendering, layers, dpr, offscreencanvas, png-export, 2d]\nexports: [createStage, StageError, StageConfigError, StageDisposedError, StageUnsupportedError]\nrelated: [atlas, gesture, ink]\nenvironments: [browser, worker]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"stage\" />\n\n## Why Stage?\n\nA `requestAnimationFrame` loop that redraws everything every frame falls over once a canvas has more than a handful of layers: backgrounds, tiles, tokens, and overlays all repaint even when one token moved. Stage gives you a retained-mode alternative as a headless engine: every layer owns a cached backing surface, only dirty layers repaint, and the composite is one `drawImage` per layer. It handles DPR scaling, world-space transforms (pair it with `@vielzeug/atlas` cameras), and PNG export — with injectable surfaces and schedulers so the whole thing is unit-testable without a GPU.\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/stage\n```\n\n```sh [npm]\nnpm install @vielzeug/stage\n```\n\n```sh [yarn]\nyarn add @vielzeug/stage\n```\n\n:::\n\n## Quick Start\n\n```ts\nimport { createStage } from '@vielzeug/stage';\n\nconst stage = createStage(canvas, {\n dpr: window.devicePixelRatio,\n height: 600,\n layers: [\n { id: 'grid', paint: (ctx, { visibleRect }) => drawGrid(ctx, visibleRect) },\n { id: 'tokens', paint: (ctx) => drawTokens(ctx) },\n ],\n width: 800,\n});\n\nstage.setTransform([2, 0, 0, 2, 40, 10]); // world→screen; DPR applied on top\ntoken.x += 10;\nstage.invalidate('tokens'); // only the tokens layer repaints\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- **`createStage()`**: layered retained-mode renderer with cached per-layer surfaces\n- **Dirty repaints**: invalidate one layer or all; frames coalesce via an injectable scheduler\n- **DPR-aware transforms**: paint in world units, the stage scales by `dpr × matrix`\n- **`StageController`**: one control type shared by main-thread and worker stages\n- **`toBlob()`**: PNG export of the composited canvas, flushing pending frames, with typed unsupported-capability errors\n- **Injectable surfaces**: `createSurface` factory for tests and `OffscreenCanvas` workers\n- **`@vielzeug/stage/worker`**: worker-rendered stages via a transferred `OffscreenCanvas` and a typed scene channel\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\n</div>\n\n## See Also\n\n<div class=\"see-also\">\n\n- [Atlas](/atlas/): cameras, spatial index, and tile grids that feed Stage transforms.\n- [Gesture](/gesture/): pointer drag, pinch, and wheel recognition.\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
5
- "api": "---\ntitle: 'Stage: API Reference'\ndescription: API reference for the Stage retained-mode 2D canvas engine.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution | Common gotcha |\n| ----------------------- | ------------------------------------------------------- | --------- | ----------------------------------------------------------------- |\n| `createStage()` | Retained-mode layered canvas renderer | Sync | Paint callbacks draw in world units; the stage applies the matrix |\n| `StageController` | Control surface shared by main-thread and worker stages | Type | Both modes are assignable to it; mode extras are not |\n| `StageError` | Base class for all stage errors | Sync | Narrow with `instanceof StageError` |\n| `StageConfigError` | Invalid sizes, duplicate/unknown layer ids | Sync | Thrown at call time, in both modes |\n| `StageDisposedError` | Blob export or worker request after disposal | Sync | Worker blob failures carry a `kind` mapped to this class |\n| `StageUnsupportedError` | Missing browser capability (2D context, blob export) | Sync | No silent degradation to a lesser path |\n\n## Package Entry Point\n\n| Import | Purpose |\n| ------------------------ | ------------------------------------------------- |\n| `@vielzeug/stage` | Stage factory, controller type, and error classes |\n| `@vielzeug/stage/worker` | Worker-rendered stages over `OffscreenCanvas` |\n\nGeometry is not re-declared here: `Point`, `Rect`, `Matrix`, and `FrameScheduler` come from\n[`@vielzeug/atlas`](/atlas/api/), which `@vielzeug/stage` depends on.\n\n---\n\n## Core Types\n\n```ts\nimport type { FrameScheduler, Matrix, Rect, Size } from '@vielzeug/atlas';\n\ntype PaintContext = Readonly<{\n /** World→screen matrix (DPR already applied to the context transform). */\n matrix: Matrix;\n /** Visible world-space rect for culling. */\n visibleRect: Rect;\n /** Device pixel ratio in effect. */\n dpr: number;\n /** Frame timestamp from the scheduler. */\n time: number;\n}>;\n\n/** A backing surface a layer paints into. `OffscreenCanvas` on workers. */\ntype StageSurface = {\n width: number;\n height: number;\n getContext: (type: '2d', attributes?: CanvasRenderingContext2DSettings) => unknown;\n};\ntype CreateSurface = (width: number, height: number) => StageSurface;\n\n/**\n * The control surface both stage modes share. A main-thread `Stage` and a\n * `WorkerStage` are interchangeable wherever only control is needed.\n */\ntype StageController = Readonly<{\n resize: (size: Size, dpr?: number) => void;\n setTransform: (matrix: Matrix) => void;\n invalidate: (layerId?: string) => void;\n toBlob: (options?: { type?: string; quality?: number }) => Promise<Blob>;\n dispose: () => void;\n readonly disposed: boolean;\n readonly disposalSignal: AbortSignal;\n [Symbol.dispose]: () => void;\n}>;\n```\n\n`Size` comes from [`@vielzeug/atlas`](/atlas/api/) as well.\n\n---\n\n## `createStage()`\n\n```ts\nfunction createStage(\n canvas: HTMLCanvasElement | OffscreenCanvas,\n options: StageOptions & Readonly<{ width: number; height: number }>,\n): Stage;\n```\n\nCreates a retained-mode stage: every layer owns a cached backing surface, is repainted only when dirty, and all layers are composited onto `canvas` in order each scheduled frame. The canvas backing store is sized `width × dpr` by `height × dpr`.\n\n| Parameter | Type | Description |\n| ----------------------- | -------------------------------------- | ---------------------------------------------------------------------- |\n| `canvas` | `HTMLCanvasElement \\| OffscreenCanvas` | Canvas the stage composites into (visible or transferred) |\n| `options.width` | `number` | CSS width in pixels; must be positive and finite |\n| `options.height` | `number` | CSS height in pixels; must be positive and finite |\n| `options.dpr` | `number?` | Device pixel ratio; defaults to `1` |\n| `options.layers` | `readonly StageLayerOptions[]` | Layers in paint order, fixed at creation; duplicate ids throw |\n| `options.scheduler` | `FrameScheduler?` | Injectable rAF scheduler for deterministic tests |\n| `options.createSurface` | `CreateSurface?` | Backing-surface factory; defaults to `OffscreenCanvas`/document canvas |\n| `options.background` | `string \\| null?` | Color cleared under the layers; defaults to transparent |\n\n**Returns:** `Stage` handle.\n\n**Example**\n\n```ts\nconst stage = createStage(canvas, {\n width: 800,\n height: 600,\n dpr: window.devicePixelRatio,\n layers: [{ id: 'scene', paint: (ctx, { visibleRect }) => drawScene(ctx, visibleRect) }],\n});\nstage.setTransform([2, 0, 0, 2, 40, 10]); // world→screen, CSS pixels\nstage.invalidate('scene');\n```\n\n### `Stage` members\n\n`Stage` extends `StageController` (`resize`, `setTransform`, `invalidate`, `toBlob`, `dispose`, `disposed`, `disposalSignal`, `[Symbol.dispose]`) and adds:\n\n| Member | Description |\n| -------------------------------------------- | -------------------------------------------------------------------------------------- |\n| `render(time?)` | Runs the pending repaint/composite synchronously; `time` defaults to `scheduler.now()` |\n| `visibleRect` | Visible world-space rect derived from the inverse transform |\n| `matrix`, `width`, `height`, `dpr`, `canvas` | Current configuration |\n\n`toBlob()` flushes a pending frame before rasterizing, so it always exports the current frame. Paint callbacks receive a context whose transform is `dpr × matrix`, so they draw in world units. Clear and reset with `ctx.setTransform(1, 0, 0, 1, 0, 0)` only if you must paint in device pixels.\n\n---\n\n## Worker Subpath (`@vielzeug/stage/worker`)\n\n| Export | Description |\n| ------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `createWorkerStage<Scene>(canvas, worker, options)` | Main-thread client: transfers `canvas` to `worker` once, then drives it; a `StageController` plus `ready` and `sendScene(scene: Scene)` |\n| `serveStage<Scene>(scope, setup)` | Worker half: waits for `init`, creates a `createStage` on the transferred `OffscreenCanvas`, and services commands; `setup` returns `{ layers, onScene?, onDispose? }` |\n| `WorkerScope`, `WorkerSelfScope`, `WorkerStage`, `WorkerStageOptions`, `ServeStageSetup`, `StageServer` | Supporting types for both halves |\n\nThe worker owns its layer painters: `serveStage`'s `setup` supplies them, and the main thread never names layers. `onScene(scene, stage)` runs for each forwarded `scene` command and owns repaints — call `stage.invalidate(layerId)` for the layers the payload changed. `server.stage` exposes the created stage whenever you need it.\n\n`Scene` is the application payload type shared by `sendScene` and `onScene`, so neither side casts. Invalid size, DPR, or matrix input throws `StageConfigError` on the main thread, exactly like `createStage`. Worker-side exceptions are surfaced through `reportError`. The message protocol is internal: its version is checked once at the init/ready handshake, and a mismatch rejects `ready` with a `StageError` and disposes the stage.\n\n`createWorkerStage` throws `StageUnsupportedError` when the canvas cannot transfer control (`transferControlToOffscreen` missing). `dispose()` posts a final `dispose` command, rejects in-flight `toBlob()` promises with `StageDisposedError`, aborts `disposalSignal` (terminate the worker from there — the creator owns it), and makes later calls inert.\n\n## Errors\n\n| Class | Thrown when |\n| ----------------------- | ----------------------------------------------------------------- |\n| `StageError` | Base class; catch all stage failures with `instanceof` |\n| `StageConfigError` | Non-positive sizes, non-finite matrices, duplicate/unknown ids |\n| `StageDisposedError` | `toBlob()` after `dispose()`, or worker blob rejected on disposal |\n| `StageUnsupportedError` | No 2D context on a surface, or `canvas.toBlob` missing/failing |\n",
6
- "usage": "---\ntitle: 'Stage: Usage Guide'\ndescription: 'How to drive a @vielzeug/stage layered canvas: layers, transforms, dirty repaints, and export.'\n---\n\n[[toc]]\n\n## Basic Usage\n\n```ts\nimport { createStage } from '@vielzeug/stage';\n\nconst stage = createStage(canvas, {\n width: canvas.clientWidth,\n height: canvas.clientHeight,\n dpr: window.devicePixelRatio,\n layers: [\n { id: 'grid', paint: (ctx, { visibleRect }) => drawGrid(ctx, visibleRect) },\n { id: 'scene', paint: (ctx, { visibleRect }) => drawScene(ctx, visibleRect) },\n { id: 'overlay', paint: (ctx) => drawSelection(ctx) },\n ],\n});\n```\n\nEach layer paints into its own cached backing surface. The stage composites all surfaces onto the visible canvas in registration order whenever a frame is scheduled. Paint callbacks receive a context already transformed by `dpr × matrix`, so they draw in **world units** and can cull against `frame.visibleRect`.\n\nLayers are fixed when the stage is created — the same in both render modes. Hide a layer by returning early from its paint and invalidating it. The stage sizes the canvas backing store; you own the canvas CSS size (set it via CSS or a `ResizeObserver`).\n\n## Driving the Transform\n\nThe stage takes a world→screen matrix in CSS pixels (it applies DPR itself). Pair it with an `@vielzeug/atlas` camera:\n\n```ts\nimport { createCamera } from '@vielzeug/atlas';\n\nconst camera = createCamera({ maxZoom: 16, minZoom: 0.05 });\ncamera.subscribe(() => stage.setTransform(camera.matrix));\n\ncanvas.addEventListener('wheel', (event) => {\n event.preventDefault();\n camera.zoomAt({ x: event.offsetX, y: event.offsetY }, Math.exp(-event.deltaY * 0.0015));\n});\n```\n\n`setTransform()` invalidates every layer — the cached world-space surfaces are no longer valid at the new transform. Compositing stays cheap (one `drawImage` per layer); only the paint callbacks re-run.\n\n## Dirty Repaints\n\nInvalidate the smallest unit that changed:\n\n```ts\ntoken.x += 10;\nstage.invalidate('tokens'); // only the tokens layer repaints next frame\n```\n\nInvalidations within one frame coalesce into a single scheduled frame. Call `stage.render()` to force a synchronous repaint (useful in tests).\n\n## Resize and DPR Changes\n\n```ts\nnew ResizeObserver(([entry]) => {\n stage.resize({ width: entry.contentRect.width, height: entry.contentRect.height }, window.devicePixelRatio);\n}).observe(canvas.parentElement!);\n```\n\n`resize()` resizes the canvas backing store and invalidates all layers; surfaces are reallocated at the new pixel size.\n\n## Exporting a PNG\n\n```ts\nconst blob = await stage.toBlob();\nawait navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })]);\n```\n\n`toBlob()` flushes any pending repaint before rasterizing, so it always captures the current frame — no manual `render()` first. It throws `StageUnsupportedError` when the canvas cannot produce a blob — the stage never silently degrades.\n\n## Testing with Injected Surfaces\n\nInject a fake surface factory and scheduler to unit-test paint behaviour without a GPU:\n\n```ts\nconst frames = { queued: new Set<(t: number) => void>() };\nconst stage = createStage(fakeCanvas, {\n createSurface: (w, h) => fakeSurface(w, h),\n height: 200,\n scheduler: {\n cancelFrame: (id) => frames.queued.delete(id),\n now: () => 0,\n requestFrame: (cb) => {\n frames.queued.add(cb);\n return frames.queued.size;\n },\n },\n width: 400,\n});\n```\n\nThe default factory uses `OffscreenCanvas` when present, else a canvas from the document; in environments with neither, it throws `StageUnsupportedError`.\n\n## Worker Rendering\n\nThe `@vielzeug/stage/worker` subpath renders the composited canvas inside a Web Worker. The main thread transfers an `OffscreenCanvas` once and then drives the stage over an internal message protocol; painters live worker-side. A `WorkerStage` and a main-thread `Stage` share the `StageController` type, so code that only controls a stage works with either.\n\n```ts\n// main.ts\nimport { createWorkerStage } from '@vielzeug/stage/worker';\n\ntype Scene = Readonly<{ col: number; id: string; row: number; type: 'move' }>;\n\nconst worker = new Worker(new URL('./stage.worker.ts', import.meta.url), { type: 'module' });\nconst stage = createWorkerStage<Scene>(canvas, worker, {\n height: 600,\n width: 800,\n});\n// The creator owns the worker: terminate it when the stage is disposed.\nstage.disposalSignal.addEventListener('abort', () => worker.terminate());\n\nawait stage.ready; // the worker created its stage\nstage.setTransform([1, 0, 0, 1, 0, 0]);\nstage.sendScene({ col: 3, id: 'hero', row: 2, type: 'move' });\nconst blob = await stage.toBlob({ type: 'image/png' }); // correlated round-trip\nstage.dispose(); // also rejects any in-flight blob requests\n```\n\n```ts\n// stage.worker.ts\nimport { serveStage } from '@vielzeug/stage/worker';\n\nserveStage<Scene>(self, () => ({\n layers: [{ id: 'scene', paint: (ctx) => ctx.fillRect(0, 0, 800, 600) }],\n onScene: (scene, stage) => {\n applyMove(scene);\n stage.invalidate('scene'); // the handler owns repaints\n },\n}));\n```\n\nNotes:\n\n- The worker owns its painters. `serveStage`'s `setup` returns the `layers` (and optional `onScene`/`onDispose` hooks); the main thread never names layers.\n- The canvas transfer is **one-shot**: `createWorkerStage` calls `transferControlToOffscreen()` on construction. To go back to main-thread rendering, mount a fresh `<canvas>` element.\n- `toBlob()` sends a `blob` command and resolves with the worker's response; requests are correlated by id and reject with `StageDisposedError` if the client is disposed while one is in flight.\n- `sendScene(scene)` forwards your typed payload to the worker's `onScene(scene, stage)` hook — useful for mirroring model state (e.g. token moves) without shipping painters to the main thread. The handler decides which layers to invalidate; nothing repaints automatically.\n- Invalid size, DPR, or matrix input throws `StageConfigError` on the main thread, exactly like `createStage`.\n- Worker-side exceptions are reported through `reportError`, the same path an uncaught main-thread paint error takes. The protocol version is checked once at the init/ready handshake; a stale cached worker rejects `ready` with a `StageError` and disposes the stage.\n\n## Best Practices\n\n- Keep per-layer paint callbacks cheap and cull with `frame.visibleRect`; the stage caches the result, so cost is paid once per invalidation, not per frame.\n- Put rarely-changing content (tile grids, backgrounds) on lower layers so pointer-driven changes only repaint upper layers.\n- Dispose the stage when the view unmounts: `using stage = createStage(...)` or `stage.dispose()`. Disposal cancels scheduled frames and releases every backing surface.\n- Treat `StageUnsupportedError` as a hard capability gap (feature-detect or surface it to the user); there is deliberately no fallback path.\n- In worker mode, invalidate only the layers a scene message changed — `onScene` runs on every forwarded payload.\n",
7
- "examples": "---\ntitle: 'Stage: Examples'\ndescription: Practical examples and recipes for @vielzeug/stage.\n---\n\n## Examples\n\n- [Layered Repaints](./examples/layered-repaints.md)\n"
8
- },
9
- "examples": [],
10
- "typeSignatures": {
11
- "StageConfigError": "export { StageConfigError, StageDisposedError, StageError, StageUnsupportedError } from './errors.js';",
12
- "StageDisposedError": "export { StageConfigError, StageDisposedError, StageError, StageUnsupportedError } from './errors.js';",
13
- "StageError": "export { StageConfigError, StageDisposedError, StageError, StageUnsupportedError } from './errors.js';",
14
- "StageUnsupportedError": "export { StageConfigError, StageDisposedError, StageError, StageUnsupportedError } from './errors.js';",
15
- "CreateSurface": "export {\n type CreateSurface,\n createStage,\n type PaintContext,\n type Stage,\n type StageController,\n type StageFrameInfo,\n type StageLayerOptions,\n type StageOptions,\n type StageSurface,\n} from './stage.js';",
16
- "createStage": "export {\n type CreateSurface,\n createStage,\n type PaintContext,\n type Stage,\n type StageController,\n type StageFrameInfo,\n type StageLayerOptions,\n type StageOptions,\n type StageSurface,\n} from './stage.js';",
17
- "PaintContext": "export {\n type CreateSurface,\n createStage,\n type PaintContext,\n type Stage,\n type StageController,\n type StageFrameInfo,\n type StageLayerOptions,\n type StageOptions,\n type StageSurface,\n} from './stage.js';",
18
- "Stage": "export {\n type CreateSurface,\n createStage,\n type PaintContext,\n type Stage,\n type StageController,\n type StageFrameInfo,\n type StageLayerOptions,\n type StageOptions,\n type StageSurface,\n} from './stage.js';",
19
- "StageController": "export {\n type CreateSurface,\n createStage,\n type PaintContext,\n type Stage,\n type StageController,\n type StageFrameInfo,\n type StageLayerOptions,\n type StageOptions,\n type StageSurface,\n} from './stage.js';",
20
- "StageFrameInfo": "export {\n type CreateSurface,\n createStage,\n type PaintContext,\n type Stage,\n type StageController,\n type StageFrameInfo,\n type StageLayerOptions,\n type StageOptions,\n type StageSurface,\n} from './stage.js';",
21
- "StageLayerOptions": "export {\n type CreateSurface,\n createStage,\n type PaintContext,\n type Stage,\n type StageController,\n type StageFrameInfo,\n type StageLayerOptions,\n type StageOptions,\n type StageSurface,\n} from './stage.js';",
22
- "StageOptions": "export {\n type CreateSurface,\n createStage,\n type PaintContext,\n type Stage,\n type StageController,\n type StageFrameInfo,\n type StageLayerOptions,\n type StageOptions,\n type StageSurface,\n} from './stage.js';",
23
- "StageSurface": "export {\n type CreateSurface,\n createStage,\n type PaintContext,\n type Stage,\n type StageController,\n type StageFrameInfo,\n type StageLayerOptions,\n type StageOptions,\n type StageSurface,\n} from './stage.js';"
24
- }
25
- }
@@ -1,39 +0,0 @@
1
- {
2
- "apiSource": "export { CsvScanner, parseGrid, parseRecords, recordsToCsv, toCsv } from './csv';\nexport { TabulaError, TabulaParseError, TabulaRowError, TabulaValidationError } from './errors';\nexport { createCsvGridStream } from './stream';\nexport { parseTypedRecords } from './typed';\nexport type {\n TabulaOptions,\n TabulaParseOptions,\n TabulaRecordOptions,\n TabulaRecordSerializeOptions,\n TabulaSerializeOptions,\n} from './types';\n",
3
- "docs": {
4
- "index": "---\ntitle: 'Tabula: typed CSV and TSV'\ndescription: 'Typed CSV and TSV: RFC 4180 parser with schema-validated rows, streaming reader, and safe serializer.'\npackage: tabula\ncategory: utilities\nkeywords: [csv, tsv, delimiter, spreadsheet, import, export, parser, serializer, rfc-4180, data-exchange]\nexports: [parseGrid, parseRecords, toCsv, recordsToCsv, createCsvGridStream, parseTypedRecords, CsvScanner]\nrelated: [spell, archive]\nenvironments: [browser, node]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"tabula\" />\n\n## Why Tabula?\n\nCSV is the format every spreadsheet, analytics tool, and finance department speaks — and the\nformat most hand-rolled parsers get subtly wrong: an embedded comma in a quoted title, a\ndouble-quote escape, a CRLF that silently becomes part of a value. Tabula implements RFC 4180\nexactly, with one scanner behind every entry point, so paste-box input, uploaded files, and\nNode streams all parse with identical semantics.\n\n```ts\n// Before: a join that dies on the first comma inside a product name\nconst rows = orders.map((o) => [o.id, o.title, o.total].join(',')); // title: \"Red, Metallic\" → corrupt\n\n// After: quoting, CRLF, and escaping are the library's problem\nimport { parseRecords, recordsToCsv } from '@vielzeug/tabula';\n\nconst csv = recordsToCsv(orders); // every field quoted only when needed, round-trips exactly\n```\n\nRecords are plain objects, and `parseTypedRecords` hands them straight to a\n[Spell](/spell/) standard schema — strings in, typed rows out, with per-line issues aggregated\ninto one error. The streaming reader processes chunks and blobs without ever buffering the\nwhole document.\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/tabula\n```\n\n```sh [npm]\nnpm install @vielzeug/tabula\n```\n\n```sh [yarn]\nyarn add @vielzeug/tabula\n```\n\n:::\n\n## Quick Start\n\n```ts\nimport { parseRecords, recordsToCsv } from '@vielzeug/tabula';\n\nconst grid = parseRecords('id,total\\n7,\"1,200.00\"\\n8,99.50\\n');\n// [{ id: '7', total: '1,200.00' }, { id: '8', total: '99.50' }]\n\nconsole.log(recordsToCsv([{ a: 1, b: 'x,y' }]));\n// a,b\n// 1,\"x,y\"\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- **`parseGrid`**: RFC 4180 scanner into a string grid — BOM stripped, CRLF/CR/LF endings, `\"\"` escapes, configurable delimiter.\n- **`parseRecords`**: first row as keys (or your own `headers`), short rows omit keys instead of inventing `undefined`.\n- **Delimiter auto-detection**: `,`, `;`, and tab are counted outside quotes on the first line — no content sniffing, and pinning `delimiter` skips it.\n- **`toCsv` / `recordsToCsv`**: quotes only when needed, `quoteAll` for spreadsheet paranoia, CRLF by default.\n- **`createCsvGridStream`**: a `TransformStream` of rows for uploads and Node streams; even delimiter auto-detection buffers at most one line.\n- **`parseTypedRecords`**: rows through any Spell/standard-schema validator — one `TabulaValidationError` with every row's line number and issues.\n- **One scanner everywhere**: `CsvScanner` is push-based; sync parse, streams, and typed parsing share the exact same state machine.\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\n</div>\n\n## See Also\n\n<div class=\"see-also\">\n\n- [Spell](/spell/): the schema engine behind `parseTypedRecords`.\n- [Archive](/archive/): stores the files these rows came from.\n- [Tempo](/tempo/): parse and serialize the dates that live in CSV columns.\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
5
- "api": "---\ntitle: 'Tabula: API Reference'\ndescription: 'Public API of @vielzeug/tabula: parsers, serializer, delimiter detection, streaming reader, typed rows, types, and errors.'\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution | Common gotcha |\n| --------------------- | ---------------------------------------------------- | --------- | -------------------------------------------------------------------- |\n| `parseGrid` | RFC 4180 text → string grid | Sync | Blank lines skipped unless `skipEmptyLines: false` |\n| `parseRecords` | First row (or `headers`) as keys | Sync | Short rows omit keys; extra cells are dropped |\n| `toCsv` | Grid → CSV text | Sync | CRLF by default; pass `newline: '\\n'` for LF output |\n| `recordsToCsv` | Records → CSV text with column union | Sync | Without `columns`, order comes from first-seen keys |\n| `createCsvGridStream` | `TransformStream<string, string[]>` for chunked text | Async | The header row is emitted like any other row |\n| `parseTypedRecords` | Records through a standard schema | Sync | Async schemas throw; failures aggregate into `TabulaValidationError` |\n| `CsvScanner` | Push-based state machine behind every parser | Sync | Call `finish()` after the last `push()`; auto-detects when unpinned |\n\n## Package Entry Point\n\n```ts\nimport { parseGrid, parseRecords, recordsToCsv, toCsv } from '@vielzeug/tabula';\n```\n\n## Functions\n\n### parseGrid\n\n```ts\nfunction parseGrid(text: string, options?: TabulaParseOptions): string[][];\n```\n\nParses CSV text into rows of cells. A leading BOM is stripped; `\\r\\n`, `\\r`, and `\\n` all\nterminate records; `\"\"` inside quoted fields is an escaped quote; quotes inside unquoted\nfields are literal (spreadsheet producers emit them constantly). `delimiter` must be a single\ncharacter and defaults to auto-detection: the scanner counts `,`, `;`, and tab outside quotes on\nthe first line and takes the winner (ties go to `,`).\n\n### parseRecords\n\n```ts\nfunction parseRecords(text: string, options?: TabulaRecordOptions): Record<string, string>[];\n```\n\nReads the first row as headers unless `headers` is supplied (then the first row is data).\nExtra cells beyond the header are dropped; missing cells leave the key off the record.\nEmpty `headers` throws `TabulaParseError`.\n\n### toCsv\n\n```ts\nfunction toCsv(rows: Iterable<readonly unknown[]>, options?: TabulaSerializeOptions): string;\n```\n\nSerializes a grid. Fields are quoted only when they contain the delimiter, a quote, `\\r`,\n`\\n`, or leading/trailing spaces — or when `quoteAll` is set. `null`/`undefined` become empty\ncells; other values go through `String()`. Lines end with `\\r\\n` unless `newline` says\notherwise.\n\n### recordsToCsv\n\n```ts\nfunction recordsToCsv(records: Iterable<Record<string, unknown>>, options?: TabulaRecordSerializeOptions): string;\n```\n\nWrites a header row plus one row per record. Columns are `options.columns` or the first-seen\nunion of record keys. Missing keys serialize as empty cells.\n\n### createCsvGridStream\n\n```ts\nfunction createCsvGridStream(options?: TabulaParseOptions): TransformStream<string, string[]>;\n```\n\nTransforms streamed text into completed rows. Until the first newline arrives (needed for\ndelimiter auto-detection unless `delimiter` is pinned) input is buffered by the scanner; after\nthat rows are emitted as they complete.\n\n### parseTypedRecords\n\n```ts\nfunction parseTypedRecords<T>(\n text: string,\n schema: StandardSchemaV1<Record<string, unknown>, T>,\n options?: TabulaRecordOptions,\n): T[];\n```\n\nValidates every record through `schema['~standard'].validate`. Valid rows accumulate;\ninvalid rows produce a `TabulaRowError` with the row's 1-based physical line number, exactly\nas a spreadsheet would show it. All rows are attempted, then failures throw as one `TabulaValidationError`.\n\n### CsvScanner\n\n```ts\nclass CsvScanner {\n constructor(options?: TabulaParseOptions);\n push(text: string, onRow: (row: string[], line: number) => void): void;\n finish(onRow: (row: string[], line: number) => void): void;\n}\n```\n\nThe push-based state machine every parser shares — split a fetch body however you like and\nsemantics stay identical. Without a pinned `delimiter` it holds input until the first line\ncompletes, auto-detects, and starts emitting. `push` may be called with any chunk boundary,\nmid-quote included.\nEach row arrives with the 1-based physical line it started on (quoted newlines and blank\nlines included), which is what `TabulaRowError.line` reports.\n\n## Types\n\n| Type | Purpose |\n| ------------------------------ | -------------------------------------------------- |\n| `TabulaOptions` | `{ delimiter? }` shared by parsers and serializers |\n| `TabulaParseOptions` | `+ { skipEmptyLines? }` (default `true`) |\n| `TabulaRecordOptions` | `+ { headers? }` for headerless documents |\n| `TabulaSerializeOptions` | `{ delimiter?, quoteAll?, newline? }` |\n| `TabulaRecordSerializeOptions` | `+ { columns? }` for explicit column order |\n\n## Errors\n\n| Error | Thrown when |\n| ----------------------- | --------------------------------------------------------------------------------- |\n| `TabulaError` | Base class for every tabula error |\n| `TabulaParseError` | A request cannot be honored (`headers: []`, multi-char `delimiter`, async schema) |\n| `TabulaRowError` | One row failed schema validation (`line`, `issues`) |\n| `TabulaValidationError` | Typed parse finished with any invalid rows (`errors: TabulaRowError[]`) |\n",
6
- "usage": "---\ntitle: 'Tabula: Usage Guide'\ndescription: 'How to use @vielzeug/tabula: parsing grids and records, delimiter detection, serializing, streaming, and schema-typed rows.'\n---\n\n[[toc]]\n\n## Basic Usage\n\nEverything is strings in, strings out — CSV has no types, and tabula does not pretend\notherwise. Parse to a grid when you need positional access, or to records when the first row\nis a header:\n\n```ts\nimport { parseGrid, parseRecords } from '@vielzeug/tabula';\n\nparseGrid('a,b\\n\"x,y\",z\\n');\n// [['a', 'b'], ['x,y', 'z']]\n\nparseRecords('id,total\\n7,\"1,200.00\"\\n');\n// [{ id: '7', total: '1,200.00' }]\n```\n\nA few parser behaviors worth knowing because every hand-rolled parser gets them wrong:\n\n- A BOM is stripped, and `\\r\\n`, `\\r`, and `\\n` all end a record.\n- `\"\"` inside a quoted field is an escaped quote; fields are quoted only as needed on output.\n- A row longer than the header is truncated to the header; a shorter row simply omits keys\n (no surprise `undefined` values in your records).\n- Blank lines are skipped by default; pass `skipEmptyLines: false` to keep them as `['']`.\n\n## Delimiter Detection\n\nEvery parse entry point auto-detects the delimiter unless you pin one: the scanner counts `,`,\n`;`, and tab occurrences outside quotes on the first line and takes the winner (ties go to `,`).\nA paste box and an uploaded `.csv` both just work:\n\n```ts\nimport { parseGrid } from '@vielzeug/tabula';\n\nparseGrid('a;b\\n1;2\\n'); // German Excel export: delimiter is ';'\n```\n\nPin `delimiter` whenever the source is known — it is faster (the parser never counts) and it\nmakes a stray comma in a title harmless.\n\n## Serializing\n\n`toCsv` writes a grid; `recordsToCsv` writes records, taking the column order from explicit\n`columns` or from the first-seen key order. Fields are quoted only when they contain the\ndelimiter, a quote, a newline, or leading/trailing spaces:\n\n```ts\nimport { recordsToCsv, toCsv } from '@vielzeug/tabula';\n\ntoCsv([['note'], ['said \"hi\"']]);\n// note\\r\\n\"said \"\"hi\"\"\"\n\nrecordsToCsv([{ b: 2, a: 1 }], { columns: ['a', 'b'], newline: '\\n' });\n// a,b\\n1,2\n```\n\n`null` and `undefined` serialize as empty cells; everything else goes through `String()`.\nUse `quoteAll: true` when the consumer is a spreadsheet import wizard that guesses column\ntypes from the first rows.\n\n## Streaming\n\n`createCsvGridStream` is a `TransformStream<string, string[]>`: pipe a text stream through it\nand consume rows as they complete. Even when auto-detecting the delimiter it buffers at most\none line, so gigabyte exports never touch memory:\n\n```ts\nimport { createCsvGridStream } from '@vielzeug/tabula';\n\nconst rows = file.stream().pipeThrough(new TextDecoderStream()).pipeThrough(createCsvGridStream());\nfor await (const row of rows) consume(row);\n```\n\nThe header row is emitted like any other row — decide what to do with it at the consumer.\n\n## Typed Rows\n\n`parseTypedRecords` runs every record through a Spell (or any standard-schema) validator and\naggregates failures: one `TabulaValidationError` carrying a `TabulaRowError` per bad row with\nits 1-based line number, so a broken export is reported in full rather than at the first bad\ncell.\n\n```ts\nimport { s } from '@vielzeug/spell';\nimport { parseTypedRecords } from '@vielzeug/tabula';\n\nconst orderSchema = s.object({ id: s.string(), qty: s.coerce.number() });\nconst orders = parseTypedRecords(text, orderSchema); // qty arrives as a number\n```\n\nSchema validation must be synchronous; an async schema throws a `TypeError` immediately\nrather than half-parsing the file.\n\n## Error Handling\n\nAll errors extend `TabulaError`. Parsing is deliberately forgiving of stray quotes\n(spreadsheet producers emit them constantly), so `TabulaParseError` fires only on requests\nthat cannot be honored, such as `headers: []`. Row-level validation failures arrive as one\n`TabulaValidationError` whose `errors` lists a `TabulaRowError` per bad line — report those\nper line, not as one opaque message.\n\n## Best Practices\n\n- Pin `delimiter` and `quote` when the producer is known; auto-detect only for paste boxes and unknown uploads.\n- Feed user imports through `parseTypedRecords` with Spell schemas — CSV hands you strings, and the coercion is where bugs live.\n- Serialize with `recordsToCsv` and explicit `columns` for exports; key insertion order is accidental API otherwise.\n- For files larger than a few MB, stream: `createCsvGridStream` keeps memory flat and shares the exact scanner semantics of `parseGrid`.\n",
7
- "examples": "---\ntitle: 'Tabula: Examples'\ndescription: Practical examples and recipes for @vielzeug/tabula.\n---\n\n## Examples\n\n- [Parse and Serialize](./examples/parse-and-serialize.md)\n- [Typed Import Pipeline](./examples/typed-imports.md)\n"
8
- },
9
- "examples": [
10
- {
11
- "id": "parse-basic",
12
- "code": "import { parseGrid, parseRecords, recordsToCsv } from '@vielzeug/tabula'\n\nconst rows = parseGrid('name;qty\\n\"drill, big\";3\\nhammer;1\\n')\nconsole.log(JSON.stringify(rows))\n\nconst records = parseRecords('id,total\\n7,\"1,200.00\"\\n8,99.50\\n')\nconsole.log(JSON.stringify(records))\n\nconsole.log(recordsToCsv([{ a: 1, b: 'x,y' }], { newline: '\\n' }))",
13
- "name": "Parse - Delimiters, quoting, records"
14
- },
15
- {
16
- "id": "serialize-basic",
17
- "code": "import { toCsv } from '@vielzeug/tabula'\n\nconst csv = toCsv([['note', 'value'], ['said \"hi\"', 'a,b'], ['plain', 42]], { newline: '\\n' })\nconsole.log(csv)\n\nconst tsv = toCsv([['note', 'value'], ['tab\\there', 42]], { delimiter: '\\t', newline: '\\n' })\nconsole.log(tsv)",
18
- "name": "Serialize - Safe quoting and delimiters"
19
- }
20
- ],
21
- "typeSignatures": {
22
- "CsvScanner": "export { CsvScanner, parseGrid, parseRecords, recordsToCsv, toCsv } from './csv';",
23
- "parseGrid": "export { CsvScanner, parseGrid, parseRecords, recordsToCsv, toCsv } from './csv';",
24
- "parseRecords": "export { CsvScanner, parseGrid, parseRecords, recordsToCsv, toCsv } from './csv';",
25
- "recordsToCsv": "export { CsvScanner, parseGrid, parseRecords, recordsToCsv, toCsv } from './csv';",
26
- "toCsv": "export { CsvScanner, parseGrid, parseRecords, recordsToCsv, toCsv } from './csv';",
27
- "TabulaError": "export { TabulaError, TabulaParseError, TabulaRowError, TabulaValidationError } from './errors';",
28
- "TabulaParseError": "export { TabulaError, TabulaParseError, TabulaRowError, TabulaValidationError } from './errors';",
29
- "TabulaRowError": "export { TabulaError, TabulaParseError, TabulaRowError, TabulaValidationError } from './errors';",
30
- "TabulaValidationError": "export { TabulaError, TabulaParseError, TabulaRowError, TabulaValidationError } from './errors';",
31
- "createCsvGridStream": "export { createCsvGridStream } from './stream';",
32
- "parseTypedRecords": "export { parseTypedRecords } from './typed';",
33
- "TabulaOptions": "export type {\n TabulaOptions,\n TabulaParseOptions,\n TabulaRecordOptions,\n TabulaRecordSerializeOptions,\n TabulaSerializeOptions,\n} from './types';",
34
- "TabulaParseOptions": "export type {\n TabulaOptions,\n TabulaParseOptions,\n TabulaRecordOptions,\n TabulaRecordSerializeOptions,\n TabulaSerializeOptions,\n} from './types';",
35
- "TabulaRecordOptions": "export type {\n TabulaOptions,\n TabulaParseOptions,\n TabulaRecordOptions,\n TabulaRecordSerializeOptions,\n TabulaSerializeOptions,\n} from './types';",
36
- "TabulaRecordSerializeOptions": "export type {\n TabulaOptions,\n TabulaParseOptions,\n TabulaRecordOptions,\n TabulaRecordSerializeOptions,\n TabulaSerializeOptions,\n} from './types';",
37
- "TabulaSerializeOptions": "export type {\n TabulaOptions,\n TabulaParseOptions,\n TabulaRecordOptions,\n TabulaRecordSerializeOptions,\n TabulaSerializeOptions,\n} from './types';"
38
- }
39
- }
@@ -1,31 +0,0 @@
1
- {
2
- "apiSource": "// Public root surface of @vielzeug/tandem. Every public export goes through this file.\n\nexport { TandemDisposedError, TandemError } from './errors';\nexport { createSync } from './tandem';\nexport type {\n SyncDeletion,\n SyncEnvelope,\n SyncGateway,\n SyncHandle,\n SyncOptions,\n SyncPort,\n SyncPullResult,\n SyncRecordBase,\n SyncState,\n TandemEvent,\n} from './types';\n",
3
- "docs": {
4
- "index": "---\ntitle: 'Tandem: Offline-first sync engine'\ndescription: Offline-first sync engine with rev baselines, tombstoned deletions, and idle-batched pushes for browser applications.\npackage: tandem\ncategory: sync\nkeywords: [sync, offline, conflict, tombstone, rev, replication, last-write-wins]\nrelated: [vault, postmaster, sentinel, ripple]\nexports: [createSync, SyncPort, SyncGateway, SyncHandle, TandemEvent, TandemError, TandemDisposedError]\nenvironments: [browser, node]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"tandem\" />\n\n## Why Tandem?\n\nA local-first app keeps its records in IndexedDB but must still reach a server: batch bursts of edits into one upload, propagate deletions that a plain pull would resurrect, and reconcile two devices that edited the same record while offline. Tandem drives that round trip against any backend, tracking a per-record write counter so a push carries only what actually changed.\n\n```ts\n// Before\n// Hand-rolled: debounce each save, POST the whole table, hope deletions survive.\nlet timer;\nfunction onSave(record) {\n clearTimeout(timer);\n timer = setTimeout(() => fetch('/sync', { method: 'POST', body: JSON.stringify(allRecords()) }), 3000);\n}\n\n// After\nimport { createSync } from '@vielzeug/tandem';\n\nconst sync = createSync({ gateway, port, idleDelayMs: 3000 });\nsync.changed(); // a local edit happened: the engine batches and pushes dirty records\n```\n\n| Feature | Tandem | RxSync | PowerSync |\n| --------------------------------------- | -------------------------------------------- | ----------------------------------- | ----------------------------------- |\n| Bundle size | <PackageInfo package=\"tandem\" type=\"size\" /> | <ore-icon name=\"x\" size=\"16\" /> | <ore-icon name=\"x\" size=\"16\" /> |\n| Zero runtime dependencies | <ore-icon name=\"check\" size=\"16\" /> | <ore-icon name=\"x\" size=\"16\" /> | <ore-icon name=\"x\" size=\"16\" /> |\n| Backend-agnostic (bring your `port`) | <ore-icon name=\"check\" size=\"16\" /> | <ore-icon name=\"x\" size=\"16\" /> | <ore-icon name=\"x\" size=\"16\" /> |\n| Storage-agnostic (bring your `gateway`) | <ore-icon name=\"check\" size=\"16\" /> | <ore-icon name=\"x\" size=\"16\" /> | <ore-icon name=\"check\" size=\"16\" /> |\n| Tombstoned deletions + rev conflicts | <ore-icon name=\"check\" size=\"16\" /> | <ore-icon name=\"check\" size=\"16\" /> | <ore-icon name=\"check\" size=\"16\" /> |\n\n<div class=\"decision-callout\">\n\n**Use `tandem` when** you already own a local store and a backend and want the sync scheduler: dirty tracking, batching, hide-flows, and conflict reconcile: without adopting a database or a server.\n\n**Consider `PowerSync` when** you want a managed sync service with its own SQLite client and server component rather than a scheduler over your existing storage.\n\n</div>\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/tandem\n```\n\n```sh [npm]\nnpm install @vielzeug/tandem\n```\n\n```sh [yarn]\nyarn add @vielzeug/tandem\n```\n\n:::\n\n## Quick Start\n\nImplement the two seams: a `SyncPort` for the server and a `SyncGateway` for local storage: then start the scheduler. Records are opaque to Tandem; it reads only `id` and `rev`, and every rev comparison is the engine's: the gateway upserts, validates, and tombstones.\n\n```ts\nimport { createSync, type SyncGateway, type SyncPort } from '@vielzeug/tandem';\n\nconst port: SyncPort = {\n pull: (since) => fetch(`/sync?since=${since ?? ''}`).then((r) => r.json()),\n push: async (records, deletions) => {\n const response = await fetch('/sync', { method: 'POST', body: JSON.stringify({ records, deletions }) });\n if (!response.ok) throw new Error(await response.text()); // divergence → the engine pulls to reconcile\n },\n};\n\nconst gateway: SyncGateway = {\n records: () => localRecords.map((record) => ({ entity: 'docs', record })),\n pendingDeletions: () => readTombstones(),\n applyRecords: (pulled) => upsert(pulled), // the engine pre-filters; you validate untrusted records\n applyDeletions: (deletions) => removeLocal(deletions),\n clearDeletions: (deletions) => dropTombstones(deletions),\n loadState: () => readSyncState(),\n saveState: (state) => writeSyncState(state),\n};\n\nconst sync = createSync({ gateway, port });\nsync.tap((event) => console.debug('sync', event)); // observe pushes, pulls, warnings\nmyStore.subscribe(() => sync.changed()); // a local write happened\n\n// On account switch or teardown: after flushing this account's work:\nawait sync.flush();\nsync.dispose();\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- **`createSync()`**: drives a port against a gateway with a serialized push queue.\n- **`SyncPort`**: the server seam: `pull(since)` and `push(records, deletions)`.\n- **`SyncGateway`**: the storage seam: upserts, tombstones, and the persisted baseline: the engine owns every rev comparison.\n- **`rev` baselines**: a record is dirty exactly when its rev is above the last-synced one, across reloads.\n- **`changed()`**: wire it to your write path; the engine debounces a burst into one push.\n- **`flush()`**: a full cycle on demand: pull remote changes, then push dirty records; rejects on failure.\n- **Hide-flows**: flushes with `keepalive` on `pagehide`/`hidden`, runs a full cycle on return to the foreground; `ambient: false` plus `autoStart: false` turn the scheduler into a pull-when-told engine for short-lived connections.\n- **`tap()`**: typed `TandemEvent`s for pushes, pulls, invalid records, and warnings.\n- **Lifecycle-owned**: `dispose()`, `disposed`, `disposalSignal`, and `[Symbol.dispose]`; post-dispose `changed()`/`flush()` fail with `TandemDisposedError`.\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\n</div>\n\n## See Also\n\n<div class=\"see-also\">\n\n- [Vault](/vault/): the typed storage core most gateways wrap; its IndexedDB adapter is a natural `records()`/`applyRecords()` backend.\n- [Postmaster](/postmaster/): the durable outbox half of offline sync; pair it with Tandem for at-least-once mutations alongside state sync.\n- [Sentinel](/sentinel/): subscribable browser state; its network signal can gate when you call `flush()`.\n- [Ripple](/ripple/): signals and effects; `store.subscribe(() => sync.changed())` is the usual wiring.\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
5
- "api": "---\ntitle: 'Tandem: API Reference'\ndescription: Factory, port and gateway contracts, events, and types for Tandem.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution mode | Common gotcha |\n| -------------- | ------------------------------------------ | ------------------------ | ----------------------------------------------------------- |\n| `createSync()` | Scheduler driving a port against a gateway | Sync (queues async work) | Boot runs pull-then-push; dispose before switching accounts |\n\n## Package Entry Point\n\n| Import | Purpose |\n| ------------------ | --------------------------------------------------------------------------------------------- |\n| `@vielzeug/tandem` | `createSync`, `TandemError`, `TandemDisposedError`, port/gateway contracts, events, and types |\n\n## Factories\n\n### `createSync()`\n\n```ts\nfunction createSync<TRecord extends SyncRecordBase = SyncRecordBase>(options: SyncOptions<TRecord>): SyncHandle;\n```\n\nStarts a sync scheduler: it loads the persisted baseline, pulls remote changes, pushes anything dirty, then flushes on `changed()`, on tab hide, and on foreground return. `autoStart: false` defers the opening cycle to the first explicit `flush()`; `ambient: false` drops the tab-lifecycle hooks.\n\n| Parameter | Type | Description |\n| --------------------- | ---------------------- | ------------------------------------------------------------------ |\n| `options.ambient` | `boolean \\| undefined` | Wire tab hide/close and foreground return to sync (default `true`) |\n| `options.autoStart` | `boolean \\| undefined` | Run a full cycle on creation (default `true`) |\n| `options.gateway` | `SyncGateway<TRecord>` | The device's storage seam |\n| `options.idleDelayMs` | `number \\| undefined` | Quiet period before a flush (default `3000`) |\n| `options.port` | `SyncPort<TRecord>` | The server seam |\n\n**Returns** a `SyncHandle`. Ambient flushes never reject: they surface failures as `warning` events through `tap()`. An explicit `flush()` rejects when its cycle fails.\n\n**Example**\n\n```ts\nimport { createSync } from '@vielzeug/tandem';\n\nconst sync = createSync({ gateway, idleDelayMs: 1500, port });\nsync.changed();\nawait sync.flush();\nsync.dispose();\n```\n\n#### `SyncHandle` methods\n\n| Member | Description |\n| ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------- |\n| `changed()` | Notes a local change and (re)starts the idle flush timer; throws `TandemDisposedError` after `dispose` |\n| `dispose()` | Stops the scheduler, clears the timer, removes document/window listeners |\n| `disposed` | `true` once disposed |\n| `disposalSignal` | `AbortSignal` aborted on dispose |\n| `flush()` | Runs a full cycle: pull, then push; resolves when it completes, rejects when it fails, and rejects with `TandemDisposedError` after `dispose` |\n| `tap(handler, options?)` | Observes `TandemEvent`s; returns an unsubscribe function |\n| `[Symbol.dispose]()` | Calls `dispose()` for `using` scopes |\n\n## Contracts\n\n### `SyncPort`\n\nThe server seam. `pull(since)` returns remote records, remote deletions, and the next cursor. `push(records, deletions, options)` sends local changes; reject it when the server diverged so the engine pulls to reconcile. `options.keepalive` marks a flush that must survive the tab closing.\n\n### `SyncGateway`\n\nThe storage seam. The engine owns every rev comparison: it calls your gateway with the decisions already made.\n\n| Member | Contract |\n| --------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |\n| `records()` | This device's own records, remote mirrors excluded; sync or async, so a disk-backed gateway can read from storage instead of holding a mirror |\n| `pendingDeletions()` | Tombstones the server has not acknowledged |\n| `applyRecords(records)` | Upsert the given records: already filtered to what the server is ahead on; return the ids that failed validation |\n| `applyDeletions(deletions)` | Remove records deleted remotely |\n| `clearDeletions(deletions)` | Drop the given tombstones a successful push carried |\n| `loadState()` | The persisted `SyncState`, or `null` on a fresh device |\n| `saveState(state)` | Persist the baseline after a completed pull or push |\n\n## Events\n\n### `TandemEvent`\n\n```ts\ntype TandemEvent =\n | { readonly records: number; readonly type: 'pull' }\n | { readonly records: number; readonly type: 'push' }\n | { readonly message: string; readonly skipped: readonly string[]; readonly type: 'invalid' }\n | { readonly error: unknown; readonly message: string; readonly type: 'warning' }\n | { readonly type: 'dispose' };\n```\n\n`invalid` reports record ids `applyRecords` refused; `warning` reports a rejected push or transport failure and carries the original cause in `error` beside its `message`; `pull` and `push` report the record counts applied and pushed. `dispose` fires once, before tappers are cleared.\n\n## Types\n\n### `SyncRecordBase`\n\n```ts\ninterface SyncRecordBase {\n readonly id: string;\n readonly rev: number;\n}\n```\n\nThe only shape Tandem reads from a record: identity and a write counter. `rev` is required: the dirty model is a rev comparison, so every synced record carries one from birth.\n\n### `SyncEnvelope`\n\n```ts\ninterface SyncEnvelope<TRecord extends SyncRecordBase = SyncRecordBase> {\n readonly entity: string;\n readonly record: TRecord;\n}\n```\n\nA record paired with the entity (table or kind) it belongs to.\n\n### `SyncDeletion`\n\n```ts\ninterface SyncDeletion {\n readonly deletedAt?: string;\n readonly entity: string;\n readonly id: string;\n}\n```\n\nA tombstone: a deletion that travels to the server on the next push. `deletedAt` is set by whoever recorded the deletion and the engine never reads it: include it when your server wants the timestamp, omit it otherwise.\n\n### `SyncState`\n\n```ts\ninterface SyncState {\n cursor: string | null;\n revs: Record<string, number>;\n}\n```\n\nThe persisted baseline. `revs` maps `\"${entity}:${id}\"` to the newest rev the server has seen.\n\n### `SyncPullResult`\n\n```ts\ninterface SyncPullResult<TRecord extends SyncRecordBase = SyncRecordBase> {\n readonly cursor: string | null;\n readonly deletions: readonly SyncDeletion[];\n readonly records: readonly SyncEnvelope<TRecord>[];\n}\n```\n\n### `SyncOptions`\n\n```ts\ninterface SyncOptions<TRecord extends SyncRecordBase = SyncRecordBase> {\n ambient?: boolean;\n autoStart?: boolean;\n gateway: SyncGateway<TRecord>;\n idleDelayMs?: number;\n port: SyncPort<TRecord>;\n}\n```\n\n## Errors\n\n### `TandemError`\n\n```ts\nclass TandemError extends Error {}\n```\n\nBase class for every error Tandem throws; `instanceof TandemError` catches them all in one branch.\n\n### `TandemDisposedError`\n\n```ts\nclass TandemDisposedError extends TandemError {}\n```\n\nThrown by `changed()` and rejected by `flush()` after `dispose()`. A scheduler that stops silently is a sync engine's worst failure: the device keeps editing while nothing uploads, so a leaked handle fails loudly instead.\n\nBeyond disposal, Tandem defines no error classes. A rejected `push` is expected input, not a failure: the engine pulls to reconcile and reports it as a `warning` event. `flush()` additionally rejects with the underlying port or gateway error; dirty records survive the failure and retry on the next cycle.\n",
6
- "usage": "---\ntitle: 'Tandem: Usage Guide'\ndescription: 'How to drive offline sync with @vielzeug/tandem: ports, gateways, rev baselines, tombstones, and reconciliation.'\n---\n\n[[toc]]\n\n## Basic Usage\n\nTandem sits between your storage and your server. You implement two interfaces and call `createSync`; the engine handles batching, dirty tracking, hide-flows, and conflict reconcile.\n\n```ts\nimport { createSync, type SyncGateway, type SyncPort } from '@vielzeug/tandem';\n\ninterface Doc {\n id: string;\n rev: number;\n title: string;\n}\n\nconst port: SyncPort<Doc> = {\n async pull(since) {\n return fetch(`/sync/pull?since=${since ?? ''}`).then((response) => response.json());\n },\n async push(records, deletions, options) {\n const response = await fetch('/sync/push', {\n body: JSON.stringify({ records, deletions }),\n headers: { 'Content-Type': 'application/json' },\n keepalive: options?.keepalive,\n method: 'POST',\n });\n if (!response.ok) throw new Error(`server diverged: ${await response.text()}`);\n },\n};\n\nconst gateway: SyncGateway<Doc> = {\n records: () => docs.map((record) => ({ entity: 'docs', record })),\n pendingDeletions: () => readTombstones(),\n async applyRecords(pulled) {\n // The engine already filtered these to records the server is ahead on;\n // validate the untrusted remotes and upsert the rest.\n const skipped: string[] = [];\n for (const { record } of pulled) {\n if (!isValid(record)) skipped.push(record.id);\n else upsert(record);\n }\n return skipped;\n },\n applyDeletions: (deletions) => Promise.all(deletions.map((d) => remove(d.id))),\n clearDeletions: (deletions) => Promise.all(deletions.map((d) => dropTombstone(d.id))),\n loadState: () => readRow('syncState'),\n saveState: (state) => writeRow('syncState', state),\n};\n\nconst sync = createSync<Doc>({ gateway, port });\n```\n\n## Track Dirty Records with Revs\n\nTandem never diffs record contents. Each record carries a `rev` counting its committed writes, and the gateway persists a baseline of the newest rev the server has seen. A record is dirty exactly when its current rev is above that baseline.\n\n```ts\n// Your write path bumps the rev on every committed change.\nfunction saveDoc(id: string, patch: Partial<Doc>): void {\n const current = docs.find((doc) => doc.id === id)!;\n upsert({ ...current, ...patch, rev: current.rev + 1 });\n sync.changed(); // schedule a flush\n}\n```\n\nBecause the baseline is persisted, dirtiness survives a reload: a record edited while offline is still above the baseline when the app restarts, and the boot sequence pushes it. The engine never asks your gateway to compare revs: ahead, dirty, and deletion precedence are all its decisions.\n\n## Propagate Deletions with Tombstones\n\nA plain pull cannot carry a deletion: the record is gone. Record a tombstone when you delete locally; Tandem pushes it and clears it only once the server acknowledges.\n\n```ts\nfunction deleteDoc(id: string): void {\n remove(id);\n writeTombstone({ deletedAt: new Date().toISOString(), entity: 'docs', id });\n sync.changed();\n}\n```\n\nA remote deletion loses to a local record with unpushed changes: if your local rev is above the baseline, Tandem keeps your edit and pushes it instead of applying the deletion. The guard runs both ways: a pulled record whose id is locally tombstoned, or deleted in the same pull, never applies, so a backend without an incremental cursor cannot resurrect your deletions.\n\n## Batch Changes and Flush\n\nCall `changed()` on every local write. The engine debounces a burst into one push after `idleDelayMs` (default 3000), and serializes pushes so two never overlap.\n\n```ts\nconst sync = createSync({ gateway, idleDelayMs: 1500, port });\n\n// Force a full cycle now: on a save button, or before navigating away.\ntry {\n await sync.flush();\n} catch {\n // the cycle failed: edits stay local and dirty; the next cycle retries them\n}\n```\n\n`flush()` pulls remote changes and then pushes dirty records, so it is also the wiring point for a returning network connection. It rejects when either half fails; the records stay dirty and the next cycle retries them. After `dispose()`, `flush()` rejects with `TandemDisposedError` and `changed()` throws it: a leaked scheduler fails loudly instead of silently stopping. If your reactive wiring can fire after disposal, unsubscribe from your store before disposing the handle, or guard with `sync.disposed`.\n\nTandem also flushes on its own: it pushes with `keepalive: true` when the tab hides or closes, and runs a full cycle when the tab returns to the foreground. Serve the keepalive push with `navigator.sendBeacon` or a `keepalive` fetch so it survives the tab closing.\n\nFor a connection that cannot survive an ambient flush, both behaviors are options: `ambient: false` drops the tab-lifecycle hooks, and `autoStart: false` defers the opening cycle to your first `flush()` call. The boot job still loads the persisted baseline, so dirt detection works from the first tick:\n\n```ts\nconst sync = createSync({ ambient: false, autoStart: false, gateway, port });\n\n// Pull and push only when the app says the connection is ready:\nawait sync.flush();\n```\n\n## Reconcile a Rejected Push\n\nWhen the server is ahead of the lineage you pushed, reject the push. Tandem immediately pulls to reconcile, then the next flush retries with the merged state. Ambient flushes (debounce, hide) report the failure as a `warning` event; `flush()` additionally rejects with the port's error.\n\n```ts\nasync push(records, deletions) {\n const response = await fetch('/sync/push', { body: JSON.stringify({ records, deletions }), method: 'POST' });\n if (response.status === 409) throw new Error('server ahead'); // triggers a reconcile pull\n}\n```\n\n## Observe with tap()\n\n`tap()` is the observation seam: pushes, pulls, refused records, and warnings. Handler errors are swallowed, so an observer never breaks sync.\n\n```ts\nconst unsubscribe = sync.tap((event) => {\n switch (event.type) {\n case 'push':\n case 'pull':\n console.debug(`sync ${event.type}: ${event.records} records`);\n break;\n case 'invalid':\n console.warn(event.message, event.skipped);\n break;\n case 'warning':\n console.warn(event.message, event.error); // push rejected, network failure, etc.\n break;\n }\n});\n```\n\n## Lifecycle and Disposal\n\nDispose before switching accounts: the baseline is per-account state and a running scheduler would push into the wrong port.\n\n```ts\nconst sync = createSync({ gateway, port });\n// ...\nsync.dispose(); // stops the scheduler, clears the timer, removes document/window listeners\n```\n\n`disposed` and `disposalSignal` report the state; `[Symbol.dispose]` lets you scope it with `using`.\n\n```ts\n{\n using sync = createSync({ gateway, port });\n sync.changed();\n} // disposed here\n```\n\n## Testing\n\nDrive the engine against in-memory doubles. A `SyncPort` double records pushes and returns scripted pulls; a `SyncGateway` double is a record array plus a tombstone list plus a state row.\n\n```ts\nimport { createSync } from '@vielzeug/tandem';\n\nconst pushes: unknown[][] = [];\nconst port: SyncPort = {\n pull: async () => ({ cursor: null, deletions: [], records: [] }),\n push: async (records, deletions) => void pushes.push([records, deletions]),\n};\n\nconst sync = createSync({ gateway: fakeGateway, idleDelayMs: 10, port });\nawait vi.waitFor(() => expect(pushes.length).toBe(1)); // startup push\nsync.dispose();\n```\n\n## Framework Integration\n\nTandem is framework-neutral. Wire `changed()` to your reactive layer and `dispose()` to the component or scope lifecycle.\n\n::: code-group\n\n```ts [Vue 3]\nimport { onScopeDispose, watch } from 'vue';\n\nconst sync = createSync({ gateway, port });\nwatch(store.records, () => sync.changed(), { deep: true });\nonScopeDispose(() => sync.dispose());\n```\n\n```tsx [React]\nimport { useEffect, useRef } from 'react';\n\nconst syncRef = useRef(createSync({ gateway, port }));\nuseEffect(() => {\n const sync = syncRef.current;\n return () => sync.dispose();\n}, []);\n```\n\n```svelte [Svelte]\n<script lang=\"ts\">\n import { onDestroy } from 'svelte';\n const sync = createSync({ gateway, port });\n $effect(() => { $records; sync.changed(); });\n onDestroy(() => sync.dispose());\n</script>\n```\n\n:::\n\n## Working with Other Vielzeug Libraries\n\n- **Vault**: the usual `gateway` backend. Its IndexedDB adapter stores records and the sync-state row; `records()` reads them from storage (it may be async), `applyRecords()` writes through the codec.\n- **Postmaster**: complementary, not overlapping. Postmaster guarantees at-least-once delivery of discrete mutations; Tandem keeps whole-record state in step. Apps that need both run them side by side.\n- **Sentinel**: subscribe to `createNetwork()` and call `sync.flush()` when the connection returns; the cycle pulls and pushes, so remote changes land without waiting for the next foreground return.\n- **Ripple**: `store.subscribe(() => sync.changed())` is the idiomatic wiring for a signal-backed store.\n\n## Best Practices\n\n- Bump `rev` on every committed write: the whole dirty model depends on it.\n- Validate remote records in `applyRecords()` and return the ids you refuse; never trust a pulled record.\n- Keep `records()` free of remote session mirrors: it must return only this device's own records.\n- Dispose on account switch; a stale scheduler pushes into the wrong port.\n- Serve `keepalive` pushes with `sendBeacon` or a `keepalive` fetch so they survive tab close.\n- Reject a push on divergence instead of silently overwriting; let the reconcile pull merge.\n- Persist the sync-state row per account, alongside the records it describes.\n- Call `flush()` before actions that assume both sides are current, such as a share or export, and handle its rejection.\n",
7
- "examples": "---\ntitle: 'Tandem: Examples'\ndescription: Offline sync recipes for two-device editing, deletions, and account switching.\n---\n\n## Examples\n\n- [Sync a Vault Store](./examples/sync-a-vault-store.md)\n- [Make Store Commands Undoable](./examples/make-store-commands-undoable.md)\n- [Keep Deletions from Resurrecting](./examples/keep-deletions-from-resurrecting.md)\n- [Switch Accounts Safely](./examples/switch-accounts-safely.md)\n"
8
- },
9
- "examples": [
10
- {
11
- "id": "create-sync",
12
- "code": "import { createSync } from '@vielzeug/tandem'\n\n// Two in-memory doubles stand in for the device store and the server.\nlet docs = [{ id: 'a', rev: 0, title: 'First doc' }]\nlet tombstones = []\nlet storedState = null\nconst server = []\n\nconst gateway = {\n records: () => docs.map((record) => ({ entity: 'docs', record })),\n pendingDeletions: async () => [...tombstones],\n async applyRecords(pulled) {\n // The engine already filtered these to records the server is ahead on.\n for (const { record } of pulled) {\n docs = [...docs.filter((d) => d.id !== record.id), record]\n }\n return []\n },\n async applyDeletions(deletions) {\n for (const { id } of deletions) docs = docs.filter((d) => d.id !== id)\n },\n async clearDeletions(deletions) {\n tombstones = tombstones.filter((t) => !deletions.some((d) => d.id === t.id))\n },\n loadState: async () => storedState,\n saveState: async (state) => { storedState = structuredClone(state) },\n}\n\nconst port = {\n pull: async () => ({ cursor: null, deletions: [], records: [] }),\n push: async (records, deletions) => {\n server.push({ records: [...records], deletions: [...deletions] })\n },\n}\n\nconst sync = createSync({ gateway, idleDelayMs: 20, port })\nsync.tap((event) => console.log('event:', event.type))\n\nawait new Promise((r) => setTimeout(r, 50)) // boot: load baseline, pull, push the seed\nconsole.log('after boot:', server.length) // 1\n\n// A burst of edits becomes ONE push: bump the rev, then announce the change.\nfor (let i = 1; i <= 3; i++) {\n docs = docs.map((d) => (d.id === 'a' ? { ...d, rev: d.rev + 1, title: `v${i}` } : d))\n sync.changed()\n}\n\nawait new Promise((r) => setTimeout(r, 120))\nconsole.log('pushes:', server.length) // 2: one flush for three edits\nconsole.log('pushed rev:', server.at(-1).records[0].record.rev) // 3: one upload carries all of them\nsync.dispose()",
13
- "name": "createSync - Batched Pushes"
14
- }
15
- ],
16
- "typeSignatures": {
17
- "TandemDisposedError": "export { TandemDisposedError, TandemError } from './errors';",
18
- "TandemError": "export { TandemDisposedError, TandemError } from './errors';",
19
- "createSync": "export { createSync } from './tandem';",
20
- "SyncDeletion": "export type {\n SyncDeletion,\n SyncEnvelope,\n SyncGateway,\n SyncHandle,\n SyncOptions,\n SyncPort,\n SyncPullResult,\n SyncRecordBase,\n SyncState,\n TandemEvent,\n} from './types';",
21
- "SyncEnvelope": "export type {\n SyncDeletion,\n SyncEnvelope,\n SyncGateway,\n SyncHandle,\n SyncOptions,\n SyncPort,\n SyncPullResult,\n SyncRecordBase,\n SyncState,\n TandemEvent,\n} from './types';",
22
- "SyncGateway": "export type {\n SyncDeletion,\n SyncEnvelope,\n SyncGateway,\n SyncHandle,\n SyncOptions,\n SyncPort,\n SyncPullResult,\n SyncRecordBase,\n SyncState,\n TandemEvent,\n} from './types';",
23
- "SyncHandle": "export type {\n SyncDeletion,\n SyncEnvelope,\n SyncGateway,\n SyncHandle,\n SyncOptions,\n SyncPort,\n SyncPullResult,\n SyncRecordBase,\n SyncState,\n TandemEvent,\n} from './types';",
24
- "SyncOptions": "export type {\n SyncDeletion,\n SyncEnvelope,\n SyncGateway,\n SyncHandle,\n SyncOptions,\n SyncPort,\n SyncPullResult,\n SyncRecordBase,\n SyncState,\n TandemEvent,\n} from './types';",
25
- "SyncPort": "export type {\n SyncDeletion,\n SyncEnvelope,\n SyncGateway,\n SyncHandle,\n SyncOptions,\n SyncPort,\n SyncPullResult,\n SyncRecordBase,\n SyncState,\n TandemEvent,\n} from './types';",
26
- "SyncPullResult": "export type {\n SyncDeletion,\n SyncEnvelope,\n SyncGateway,\n SyncHandle,\n SyncOptions,\n SyncPort,\n SyncPullResult,\n SyncRecordBase,\n SyncState,\n TandemEvent,\n} from './types';",
27
- "SyncRecordBase": "export type {\n SyncDeletion,\n SyncEnvelope,\n SyncGateway,\n SyncHandle,\n SyncOptions,\n SyncPort,\n SyncPullResult,\n SyncRecordBase,\n SyncState,\n TandemEvent,\n} from './types';",
28
- "SyncState": "export type {\n SyncDeletion,\n SyncEnvelope,\n SyncGateway,\n SyncHandle,\n SyncOptions,\n SyncPort,\n SyncPullResult,\n SyncRecordBase,\n SyncState,\n TandemEvent,\n} from './types';",
29
- "TandemEvent": "export type {\n SyncDeletion,\n SyncEnvelope,\n SyncGateway,\n SyncHandle,\n SyncOptions,\n SyncPort,\n SyncPullResult,\n SyncRecordBase,\n SyncState,\n TandemEvent,\n} from './types';"
30
- }
31
- }