@schema-engine/layout 0.0.0-stage → 0.5.0

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 (53) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +57 -2
  3. package/dist/index.d.ts +37 -0
  4. package/dist/index.js +4 -0
  5. package/dist/index.js.map +7 -0
  6. package/dist/lib/appearance.d.ts +204 -0
  7. package/dist/lib/appearance.js +2 -0
  8. package/dist/lib/appearance.js.map +7 -0
  9. package/dist/lib/deep-readonly.d.ts +10 -0
  10. package/dist/lib/deep-readonly.js +0 -0
  11. package/dist/lib/deep-readonly.js.map +7 -0
  12. package/dist/lib/grid-placement.d.ts +107 -0
  13. package/dist/lib/grid-placement.js +1 -0
  14. package/dist/lib/grid-placement.js.map +7 -0
  15. package/dist/lib/grid-styles.d.ts +178 -0
  16. package/dist/lib/grid-styles.js +2 -0
  17. package/dist/lib/grid-styles.js.map +7 -0
  18. package/dist/lib/layout-issue.d.ts +12 -0
  19. package/dist/lib/layout-issue.js +0 -0
  20. package/dist/lib/layout-issue.js.map +7 -0
  21. package/dist/lib/layout-theme.d.ts +94 -0
  22. package/dist/lib/layout-theme.js +4 -0
  23. package/dist/lib/layout-theme.js.map +7 -0
  24. package/dist/recipes/bind-recipe.d.ts +12 -0
  25. package/dist/recipes/bind-recipe.js +1 -0
  26. package/dist/recipes/bind-recipe.js.map +7 -0
  27. package/dist/recipes/define-recipe-spec.d.ts +49 -0
  28. package/dist/recipes/define-recipe-spec.js +1 -0
  29. package/dist/recipes/define-recipe-spec.js.map +7 -0
  30. package/dist/recipes/merge-slot-defaults.d.ts +8 -0
  31. package/dist/recipes/merge-slot-defaults.js +1 -0
  32. package/dist/recipes/merge-slot-defaults.js.map +7 -0
  33. package/dist/recipes/protocol.d.ts +69 -0
  34. package/dist/recipes/protocol.js +1 -0
  35. package/dist/recipes/protocol.js.map +7 -0
  36. package/dist/recipes/resolve-recipe-view.d.ts +52 -0
  37. package/dist/recipes/resolve-recipe-view.js +1 -0
  38. package/dist/recipes/resolve-recipe-view.js.map +7 -0
  39. package/dist/recipes/types.d.ts +53 -0
  40. package/dist/recipes/types.js +0 -0
  41. package/dist/recipes/types.js.map +7 -0
  42. package/dist/recipes/view-model.d.ts +20 -0
  43. package/dist/recipes/view-model.js +1 -0
  44. package/dist/recipes/view-model.js.map +7 -0
  45. package/dist/schemas/appearance.d.ts +57 -0
  46. package/dist/schemas/appearance.js +1 -0
  47. package/dist/schemas/appearance.js.map +7 -0
  48. package/dist/schemas/grid.d.ts +666 -0
  49. package/dist/schemas/grid.js +1 -0
  50. package/dist/schemas/grid.js.map +7 -0
  51. package/package.json +75 -3
  52. package/skill/SKILL.md +79 -0
  53. package/skill/reference/layout.md +48 -0
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/lib/appearance.ts", "../../src/recipes/merge-slot-defaults.ts", "../../src/recipes/resolve-recipe-view.ts"],
4
+ "sourcesContent": ["import {\n\tcreateRegistry,\n\ttype BaseRegistration,\n\ttype ReadOnlyRegistry,\n\ttype RegistrationMetadata,\n} from '@schema-engine/registry';\nimport * as z from 'zod/mini';\nimport type { LayoutIssue } from './layout-issue';\nimport type { LayoutTheme, LayoutThemeCompilerOptions } from './layout-theme';\n\n/**\n * Appearance axes a document picks values on and renderers emit as data attributes.\n *\n * @remarks\n * An axis is one independent dimension of appearance, with two to five named values. Each value\n * stands for a set of semantic CSS tokens, which components read; components never read an axis\n * value. The theme declares the axes ({@link defineAxis}, stored in a registry), a registration\n * declares which axes it responds to, and a document picks values that pass down.\n *\n * A domain checks the pick against the vocabulary and the owner's declared axes\n * ({@link checkAppearance}), merges it with the pick it inherits ({@link mergeAppearance}), and a\n * renderer emits the result as `data-se-<axis>=\"<value>\"` ({@link getAppearanceAttributes}).\n * Walking the document tree to inherit picks belongs to the domain, because only it knows the\n * tree's shape.\n *\n * Compile once, where the theme is built ({@link createLayoutTheme} does, with the grid). Token rules are\n * emitted inside `:where()`, so they add no specificity and an author's `className` always wins; they\n * are scoped to the theme by `data-se-theme` and the nearest theme above an element wins, so two themes\n * with different tokens cannot overwrite each other ({@link getAppearanceCss} has the details).\n */\n\n/** Custom properties a value stands for, keyed `--name`. */\nexport type AppearanceTokens = Readonly<Record<`--${string}`, string | number>>;\n\n/** A pick of one value per axis. */\nexport type AppearanceSelection = Readonly<Record<string, string>>;\n\n/**\n * An appearance axis, stored in a registry like every other registration.\n *\n * @remarks\n * `schema` is a Standard Schema that accepts exactly the value names, which satisfies the\n * registry's build check and is what a catalog or JSON Schema export lists. {@link defineAxis}\n * produces it.\n */\nexport interface AxisRegistration<\n\tTName extends string = string,\n\tTValue extends string = string,\n> extends BaseRegistration<unknown, RegistrationMetadata> {\n\treadonly $type: TName;\n\t/** Each value name and the semantic tokens it stands for. */\n\treadonly values: Readonly<Record<TValue, AppearanceTokens>>;\n\t/**\n\t * The value that stands for no pick.\n\t *\n\t * @remarks\n\t * A component's own CSS fallbacks are the look of this value, so a document that picks it looks\n\t * like one that picks nothing. To make that true under an inherited pick, a default value that\n\t * leaves the tokens to the component sets them to `initial`: a custom property set to `initial`\n\t * makes `var(--token, fallback)` use its fallback, so a step that picks `default` inside a\n\t * `compact` form undoes the compact tokens.\n\t */\n\treadonly default: TValue;\n}\n\n/** Any axis registration, whatever its name and values. */\nexport type AnyAxisRegistration = AxisRegistration;\n\n/** A registry of axes, as {@link createLayoutTheme} builds it. */\nexport type AxisRegistry = ReadOnlyRegistry<AnyAxisRegistration>;\n\n/** Input to {@link defineAxis}. */\nexport interface AxisDefinition<TName extends string, TValues extends Readonly<Record<string, AppearanceTokens>>> {\n\t/** The axis name, which becomes the `data-se-<axis>` attribute and the key of a pick. */\n\treadonly $type: TName;\n\t/** Each value name and the semantic tokens it stands for. Two to five values. */\n\treadonly values: TValues;\n\t/** One of the value names. */\n\treadonly default: keyof TValues & string;\n\treadonly metadata: RegistrationMetadata;\n}\n\nconst AXIS_NAME = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;\nconst VALUE_NAME = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;\nconst UNSAFE_TOKEN_VALUE = /[{};<]|\\/\\*/;\nconst MIN_AXIS_VALUES = 2;\nconst MAX_AXIS_VALUES = 5;\n\n/**\n * Throws when an axis name is one a domain reserves.\n *\n * @remarks The one place the message lives, shared by the compiler and by {@link assertAxesNotReserved}.\n */\nexport function assertAxisNotReserved(axisName: string, reserved: ReadonlySet<string>): void {\n\tif (reserved.has(axisName)) {\n\t\tthrow new Error(`Invalid appearance axis name '${axisName}': data-se-${axisName} is reserved by the renderer.`);\n\t}\n}\n\n/**\n * Throws when an axis is not a usable one: a bad name, fewer than two or more than five values, a\n * value that would break a selector, a token that is not a custom property, or a `default` that is\n * not a value.\n *\n * @remarks\n * Axis names become `data-se-<axis>` attribute names and values go into attribute selectors, so\n * both are restricted to plain identifiers. {@link defineAxis} and the compiler both run this, so an\n * object that did not come from `defineAxis` is held to the same rules.\n */\nfunction assertValidAxis(axis: AnyAxisRegistration): void {\n\tconst name = axis.$type;\n\tif (!AXIS_NAME.test(name)) {\n\t\tthrow new Error(\n\t\t\t`Invalid appearance axis name '${name}': use lowercase letters, digits and hyphens, starting with a letter.`,\n\t\t);\n\t}\n\tconst entries = Object.entries(axis.values);\n\tif (entries.length < MIN_AXIS_VALUES || entries.length > MAX_AXIS_VALUES) {\n\t\tthrow new Error(\n\t\t\t`Invalid appearance axis '${name}': an axis has ${MIN_AXIS_VALUES} to ${MAX_AXIS_VALUES} values, found ${entries.length}. A raw value is a token override, not an axis value.`,\n\t\t);\n\t}\n\tif (!Object.hasOwn(axis.values, axis.default)) {\n\t\tthrow new Error(\n\t\t\t`Invalid appearance axis '${name}': default '${axis.default}' is not one of its values (${entries.map(([value]) => value).join(', ')}).`,\n\t\t);\n\t}\n\tfor (const [value, tokens] of entries) {\n\t\tif (!VALUE_NAME.test(value)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Invalid appearance value '${value}' on axis '${name}': use letters, digits, hyphens and underscores.`,\n\t\t\t);\n\t\t}\n\t\tfor (const [token, tokenValue] of Object.entries(tokens)) {\n\t\t\tif (!token.startsWith('--') || token.length < 3) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Invalid appearance token '${token}' on '${name}.${value}': tokens are CSS custom properties and start with '--'.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (UNSAFE_TOKEN_VALUE.test(String(tokenValue))) {\n\t\t\t\tthrow new Error(`Invalid appearance token value for '${token}' on '${name}.${value}'.`);\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * Defines an appearance axis: one independent dimension of appearance with a small closed set of\n * named values.\n *\n * @remarks\n * Each value stands for a set of semantic CSS custom properties (`--se-space`, `--se-shadow`) that\n * components read; components never read the axis value. A token names a role, not a component, so\n * it means the same on every component that reads it. A value that sets a token to `initial`\n * hands it back to the component's own fallback. Appearance only: structure is slot config or the grid.\n *\n * The axis carries a Standard Schema that accepts exactly its value names. Throws on an axis with\n * a name that is not a lowercase identifier, fewer than 2 or more than 5 values, a value name that\n * would break a selector, a token that is not a custom property or has an unsafe value, or a\n * `default` that is not one of the values.\n */\nexport function defineAxis<\n\tconst TName extends string,\n\tconst TValues extends Readonly<Record<string, AppearanceTokens>>,\n>(definition: AxisDefinition<TName, TValues>): AxisRegistration<TName, keyof TValues & string> {\n\tconst axis: AxisRegistration<TName, keyof TValues & string> = {\n\t\t$type: definition.$type,\n\t\tvalues: definition.values,\n\t\tdefault: definition.default,\n\t\tmetadata: definition.metadata,\n\t\tschema: z\n\t\t\t.enum(Object.keys(definition.values) as [string, ...string[]])\n\t\t\t.check(z.describe(definition.metadata.description ?? definition.metadata.name)),\n\t};\n\tassertValidAxis(axis);\n\treturn Object.freeze(axis);\n}\n\nconst sizeAxis = defineAxis({\n\t$type: 'size',\n\tmetadata: {\n\t\tname: 'Size',\n\t\tdescription: 'How much room components take: spacing, type size, control height and readable width.',\n\t},\n\tdefault: 'default',\n\tvalues: {\n\t\tcompact: {\n\t\t\t'--se-space': 'var(--se-space-compact, var(--se-renderer-space-compact, 1rem))',\n\t\t\t'--se-font-size': '0.875rem',\n\t\t\t'--se-measure': '24rem',\n\t\t\t'--se-control-height':\n\t\t\t\t'var(--se-control-height-compact, var(--se-renderer-control-height-compact, 1.75rem))',\n\t\t},\n\t\tdefault: {\n\t\t\t'--se-space': 'initial',\n\t\t\t'--se-font-size': 'initial',\n\t\t\t'--se-measure': 'initial',\n\t\t\t'--se-control-height': 'initial',\n\t\t},\n\t\tcomfortable: {\n\t\t\t'--se-space': 'var(--se-space-comfortable, var(--se-renderer-space-comfortable, 2rem))',\n\t\t\t'--se-font-size': '1.0625rem',\n\t\t\t'--se-measure': '32rem',\n\t\t\t'--se-control-height':\n\t\t\t\t'var(--se-control-height-comfortable, var(--se-renderer-control-height-comfortable, 2.25rem))',\n\t\t},\n\t},\n});\n\nconst surfaceAxis = defineAxis({\n\t$type: 'surface',\n\tmetadata: {\n\t\tname: 'Surface',\n\t\tdescription: 'How a container sets itself apart: border, shadow and background.',\n\t},\n\tdefault: 'elevated',\n\tvalues: {\n\t\tflat: {\n\t\t\t'--se-border-width': '0',\n\t\t\t'--se-shadow': 'none',\n\t\t\t'--se-surface-background': 'initial',\n\t\t},\n\t\toutlined: {\n\t\t\t'--se-border-width': '1px',\n\t\t\t'--se-shadow': 'none',\n\t\t\t'--se-surface-background': 'initial',\n\t\t},\n\t\televated: {\n\t\t\t'--se-border-width': 'initial',\n\t\t\t'--se-shadow': 'initial',\n\t\t\t'--se-surface-background': 'initial',\n\t\t},\n\t},\n});\n\n/**\n * The axes every layout theme starts from: `size` (compact, default, comfortable) and `surface`\n * (flat, outlined, elevated).\n *\n * @remarks\n * The tokens are renderer-neutral and name no host theme; `size` reads hooks an author sets (`--se-space-compact`,\n * `--se-control-height-compact` and their `comfortable` twins), then the `--se-renderer-*` twin of each, which a renderer sets from its theme, then a neutral value. `size.default` and the background of\n * `surface.elevated` are `initial`, which hands the token back to the component's own fallback, so\n * a renderer's fallbacks, which it maps to its host theme, stay in force and `size: default`\n * looks like no pick, also inside a `compact` form. Override an axis by listing another\n * with the same `$type` after these: `createLayoutTheme({ appearance: [...builtInAxes, mine] })`.\n */\nexport const builtInAxes = [sizeAxis, surfaceAxis] as const;\n\n/** The value names of an axis registration. */\ntype AxisValueNames<TAxis> = TAxis extends AxisRegistration<string, infer V> ? V : never;\n\ntype Flatten<T> = { [K in keyof T]: T[K] & string };\n\ntype AxesOfTuple<TAxes extends readonly AnyAxisRegistration[]> = TAxes extends readonly [\n\t...infer Rest extends readonly AnyAxisRegistration[],\n\tinfer Last extends AnyAxisRegistration,\n]\n\t? Omit<AxesOfTuple<Rest>, Last['$type']> & { [K in Last['$type']]: AxisValueNames<Last> }\n\t: unknown;\n\n/**\n * Axis-to-value-union map of a theme: the axes a host lists in `appearance`, the last of a name winning.\n *\n * @remarks Typed authoring narrows a pick to these literals. `TAxes` should be a const-inferred list;\n * a list that is not a tuple, or a member typed as a plain `AnyAxisRegistration` (name `string`),\n * widens to any axis name and any value.\n */\nexport type ResolvedAppearanceAxes<TAxes extends readonly AnyAxisRegistration[] = typeof builtInAxes> =\n\tnumber extends TAxes['length'] ? Record<string, string> : Flatten<AxesOfTuple<TAxes>>;\n\n/** Built-in axes and their values, as literal types, for typed authoring. */\nexport type BuiltInAppearanceAxes = ResolvedAppearanceAxes;\n\n/** The axes an element or a recipe slot declares it supports. */\nexport type AppearanceAxisList = readonly string[];\n\n/** The axes each slot of a recipe supports, keyed by slot name. */\nexport type SlotAppearanceAxes<TSlot extends PropertyKey = string> = { [K in TSlot]?: AppearanceAxisList };\n\n/** Authoring shape of a pick: any declared axis, restricted to its values. */\nexport type AppearanceInput<TAxes extends Record<string, string>> = { readonly [A in keyof TAxes]?: TAxes[A] };\n\n/** A theme's compiled appearance vocabulary. */\nexport interface CompiledAppearance {\n\t/** The axes, last registration of a `$type` winning, in first-registration order. */\n\treadonly registry: AxisRegistry;\n\t/** Axis name to its closed value list. */\n\treadonly axes: Readonly<Record<string, readonly string[]>>;\n}\n\n/**\n * The token rules of a compiled appearance, scoped to the layout theme with the given id.\n *\n * @remarks\n * Every rule sits inside `:where()`, so it adds no specificity and an author's class always wins.\n * Every grid and item carries `data-se-theme`, so a form of theme B inside a grid item of theme A\n * has both themes above it; the nearest theme's rule must be the one that matches, whatever the\n * order of the stylesheets. Empty when no value declares tokens. Two sets of rules say so:\n *\n * 1. Plain rules, which match an element that carries the theme and the pick together, or a\n * descendant of the theme's root with no element of another theme between. They need only\n * `:where()` and complex selectors in `:not()`, so they hold in server-rendered output in every\n * browser the renderers support. They cannot say \"no other theme between\" for a theme re-entered\n * below another theme (A in B in A): its descendants match no plain rule, so they inherit the\n * custom properties of the nearest element that did.\n * 2. `@scope` rules, emitted after the plain ones in one block: the theme's roots down to the nearest\n * element of another theme. A browser without `@scope` drops the block and keeps the plain rules;\n * one with it is exact, A in B in A included. About 1.1 KB per theme with the built-in axes.\n *\n * The `@scope` rules change one cascade detail: scope proximity outranks source order, and an\n * unscoped rule is the farthest from any root. A zero-specificity author rule such as `:where(.x)`\n * therefore loses to a token rule in a browser with `@scope`, where it won on order alone before;\n * a class with any specificity still wins.\n */\nexport function getAppearanceCss(appearance: CompiledAppearance, themeId: string): string {\n\tconst plain: string[] = [];\n\tconst scoped: string[] = [];\n\tconst scope = `[data-se-theme=\"${themeId}\"]`;\n\tconst foreign = `[data-se-theme]:not(${scope})`;\n\tfor (const axis of appearance.registry.all()) {\n\t\tfor (const [value, tokens] of Object.entries(axis.values)) {\n\t\t\tconst declarations = Object.entries(tokens).map(([token, tokenValue]) => `${token}:${tokenValue};`);\n\t\t\tif (declarations.length === 0) continue;\n\t\t\tconst block = `{${declarations.join('')}}`;\n\t\t\tconst match = `[data-se-${axis.$type}=\"${value}\"]`;\n\t\t\tconst descendant = `${scope} ${match}:not(${foreign},${scope} ${foreign} *)`;\n\t\t\tplain.push(`:where(${scope}${match},${descendant})${block}`);\n\t\t\tscoped.push(`:where(:scope${match},${match})${block}`);\n\t\t}\n\t}\n\tif (scoped.length === 0) return '';\n\treturn [...plain, `@scope (${scope}) to (${foreign}){${scoped.join('')}}`].join('\\n');\n}\n\n/**\n * Compiles a list of axes into the theme's appearance vocabulary.\n *\n * @param axes - The axes of the theme; defaults to {@link builtInAxes}. A later axis with the same\n * `$type` replaces the earlier one, so `[...builtInAxes, mine]` overrides.\n *\n * @remarks\n * Stores the axes with `createRegistry`, so each needs a Standard Schema, and holds every winner to\n * the rules {@link defineAxis} states. Throws on an invalid axis and on one named in `reservedNames`.\n */\nexport function compileAppearance(\n\taxes: readonly AnyAxisRegistration[] = builtInAxes,\n\tcompiler: LayoutThemeCompilerOptions = {},\n): CompiledAppearance {\n\tconst registry = createRegistry<AnyAxisRegistration>('Axis', axes);\n\tconst reserved = new Set(compiler.reservedNames);\n\tfor (const axis of registry.all()) {\n\t\tassertValidAxis(axis);\n\t\tassertAxisNotReserved(axis.$type, reserved);\n\t}\n\treturn Object.freeze({\n\t\tregistry,\n\t\taxes: Object.freeze(\n\t\t\tObject.fromEntries(registry.all().map((axis) => [axis.$type, Object.freeze(Object.keys(axis.values))])),\n\t\t),\n\t});\n}\n\n/**\n * The `data-se-<axis>` attributes for a resolved selection.\n *\n * @remarks A renderer spreads this on every element that carries a pick.\n */\nexport function getAppearanceAttributes(appearance: AppearanceSelection | undefined): Record<string, string> {\n\tconst attributes: Record<string, string> = {};\n\tfor (const [axis, value] of Object.entries(appearance ?? {})) attributes[`data-se-${axis}`] = value;\n\treturn attributes;\n}\n\n/**\n * A child's picks laid over the picks it inherits: the child's value wins per axis.\n *\n * @remarks Pure merge; checking that the child's axes are valid is {@link checkAppearance}'s job.\n */\nexport function mergeAppearance(\n\tinherited: AppearanceSelection | undefined,\n\town: AppearanceSelection | undefined,\n): Record<string, string> {\n\treturn { ...inherited, ...own };\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/**\n * Checks an authored pick against the vocabulary and, when given, the axes its owner supports.\n *\n * @param subject Names the owner in a message, for example `Element 'fieldSet'`.\n * @param supported The axes the owner declares; an owner that declares none passes `[]`. Omit it for an owner that accepts every axis.\n * @returns One issue per problem, with a path relative to the authored pick (`['appearance', axis]`), and the valid picks.\n */\nexport function checkAppearance(\n\tauthored: unknown,\n\toptions: { axes: LayoutTheme['axes']; subject: string; supported?: readonly string[] },\n): { issues: LayoutIssue[]; appearance: Record<string, string> } {\n\tconst issues: LayoutIssue[] = [];\n\tconst appearance: Record<string, string> = {};\n\tif (authored === undefined) return { issues, appearance };\n\tif (!isRecord(authored)) {\n\t\treturn {\n\t\t\tissues: [{ path: ['appearance'], message: 'Expected an object of axis names to values.' }],\n\t\t\tappearance,\n\t\t};\n\t}\n\tconst declared = Object.keys(options.axes).join(', ');\n\tfor (const [axis, value] of Object.entries(authored)) {\n\t\tconst values = Object.hasOwn(options.axes, axis) ? options.axes[axis] : undefined;\n\t\tif (!values) {\n\t\t\tissues.push({ path: ['appearance', axis], message: `Unknown axis '${axis}'. Declared axes: ${declared}.` });\n\t\t\tcontinue;\n\t\t}\n\t\tif (options.supported !== undefined && !options.supported.includes(axis)) {\n\t\t\tconst supported = options.supported.length > 0 ? options.supported.join(', ') : '(none)';\n\t\t\tissues.push({\n\t\t\t\tpath: ['appearance', axis],\n\t\t\t\tmessage: `${options.subject} does not support the axis '${axis}'. Supported axes: ${supported}.`,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (typeof value !== 'string') {\n\t\t\tissues.push({ path: ['appearance', axis], message: `Expected one of ${values.join(', ')}.` });\n\t\t\tcontinue;\n\t\t}\n\t\tif (!values.includes(value)) {\n\t\t\tissues.push({\n\t\t\t\tpath: ['appearance', axis],\n\t\t\t\tmessage: `'${value}' is not a value of '${axis}'. Allowed: ${values.join(', ')}.`,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tappearance[axis] = value;\n\t}\n\treturn { issues, appearance };\n}\n\n/** Keeps the axes an owner supports. An owner that declares none keeps none. */\nexport function pickSupportedAppearance(\n\tselection: AppearanceSelection,\n\tsupported: readonly string[] | undefined,\n): Record<string, string> {\n\tconst picked: Record<string, string> = {};\n\tfor (const axis of supported ?? []) {\n\t\tconst value = selection[axis];\n\t\tif (value !== undefined) picked[axis] = value;\n\t}\n\treturn picked;\n}\n", "/**\n * @remarks\n * Duplicates the helper the forms package keeps for its own deep operations on purpose: this\n * package cannot import forms.\n */\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n\tif (typeof value !== 'object' || value === null) return false;\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === Object.prototype || prototype === null;\n}\n\nfunction mergeDeep(base: unknown, override: unknown): unknown {\n\tif (override === undefined) return base;\n\tif (!isPlainObject(base) || !isPlainObject(override)) return override;\n\tconst merged: Record<string, unknown> = { ...base };\n\tfor (const [key, value] of Object.entries(override)) {\n\t\tmerged[key] = mergeDeep(base[key], value);\n\t}\n\treturn merged;\n}\n\n/**\n * Lays a view's slot config over the recipe's `slotDefaults`, deep for plain objects.\n *\n * @remarks\n * Runs before the view schema parses, so schema defaults fill only what neither the author\n * nor the recipe set. Arrays and other non-plain values replace the default whole. A key the author sets to `undefined` keeps the recipe default.\n */\nexport function mergeSlotDefaults(\n\tview: Record<string, unknown>,\n\tslotDefaults: Record<string, unknown> | undefined,\n): Record<string, unknown> {\n\tif (!slotDefaults) return view;\n\tconst merged = { ...view };\n\tfor (const [slot, defaults] of Object.entries(slotDefaults)) {\n\t\tmerged[slot] = mergeDeep(defaults, view[slot]);\n\t}\n\treturn merged;\n}\n", "import type { StandardSchemaV1 } from '@standard-schema/spec';\nimport { checkAppearance, mergeAppearance, pickSupportedAppearance, type SlotAppearanceAxes } from '../lib/appearance';\nimport type { LayoutIssue } from '../lib/layout-issue';\nimport type { LayoutTheme } from '../lib/layout-theme';\nimport { mergeSlotDefaults } from './merge-slot-defaults';\n\n/** Appearance picks a view inherits: the theme's vocabulary, and what the containing document picked. */\nexport interface RecipeViewScope {\n\treadonly axes: LayoutTheme['axes'];\n\treadonly inherited: Readonly<Record<string, string>>;\n}\n\n/** The part of a recipe registration that resolving a view reads. */\nexport interface RecipeViewSource {\n\treadonly $type: string;\n\treadonly slots: readonly string[];\n\treadonly schema: StandardSchemaV1;\n\treadonly slotDefaults?: Readonly<Record<string, unknown>>;\n\treadonly appearanceAxes?: SlotAppearanceAxes;\n}\n\n/** An authored view: the recipe's `$type` and the config of its slots. */\nexport type RecipeViewInput = Readonly<Record<string, unknown>> & { readonly $type: string };\n\n/**\n * What {@link resolveRecipeView} found.\n *\n * @remarks\n * `view` is present when the schema parsed and kept its `$type`; it can still come with `issues`\n * (an appearance pick that is not valid, or a key the recipe does not declare). `schemaIssues` is\n * present, with no `view`, when the schema rejected the view: the caller formats them, since only\n * the domain knows how it reports a schema's issues.\n */\nexport interface ResolvedRecipeView {\n\t/** One issue per problem, with a path relative to the view (`[slot, 'appearance', axis]`, `[key]`). */\n\tissues: LayoutIssue[];\n\tview?: Record<string, unknown>;\n\tschemaIssues?: StandardSchemaV1.Issue[];\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n\tif (typeof value !== 'object' || value === null) return false;\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === Object.prototype || prototype === null;\n}\n\nfunction withoutAppearance(config: Record<string, unknown>): Record<string, unknown> {\n\tif (!('appearance' in config)) return config;\n\tconst { appearance: _authored, ...rest } = config;\n\treturn rest;\n}\n\nfunction parseSync(schema: StandardSchemaV1, value: unknown): StandardSchemaV1.Result<unknown> {\n\tconst result = schema['~standard'].validate(value);\n\tif (result && typeof (result as Promise<unknown>).then === 'function') {\n\t\tthrow new Error('Async Standard Schema validation is not supported in this context');\n\t}\n\tif (result === null || typeof result !== 'object') {\n\t\tthrow new Error('Standard Schema validation returned an invalid result');\n\t}\n\treturn result as StandardSchemaV1.Result<unknown>;\n}\n\n/**\n * Resolves the view a document selects for a recipe: the recipe defaults laid under the author's\n * slot config, each slot's appearance, the schema parse, and the keys the recipe does not declare.\n *\n * @param recipe - The winning registration the view's `$type` selects\n * @param view - The authored view; not changed\n * @param scope - The picks the view inherits from its document\n *\n * @remarks\n * Slot appearance follows the recipe's inheritance rule: the document's picks reach a slot for the\n * axes the recipe declares on it, and the slot's own pick wins. The authored `appearance` key is\n * removed before the slot schema parses, so a schema only has to type it, and the resolved\n * selection is written back on the slot when it is not empty. Domain rules that need the document\n * (a kind that wants one step, a default recipe) stay with the domain's validator.\n */\nexport function resolveRecipeView(\n\trecipe: RecipeViewSource,\n\tview: RecipeViewInput,\n\tscope: RecipeViewScope,\n): ResolvedRecipeView {\n\tconst issues: LayoutIssue[] = [];\n\tconst stripped: Record<string, unknown> = { ...view };\n\tconst resolved: Record<string, Record<string, string>> = {};\n\tfor (const slot of recipe.slots) {\n\t\tconst authoredSlot = view[slot];\n\t\tconst supported = recipe.appearanceAxes?.[slot] ?? [];\n\t\tconst checked = checkAppearance(isPlainRecord(authoredSlot) ? authoredSlot.appearance : undefined, {\n\t\t\taxes: scope.axes,\n\t\t\tsubject: `Slot '${slot}' of recipe '${recipe.$type}'`,\n\t\t\tsupported,\n\t\t});\n\t\tissues.push(...checked.issues.map((issue) => ({ ...issue, path: [slot, ...issue.path] })));\n\t\tconst selection = pickSupportedAppearance(mergeAppearance(scope.inherited, checked.appearance), supported);\n\t\tif (Object.keys(selection).length > 0) resolved[slot] = selection;\n\t\tif (isPlainRecord(authoredSlot)) stripped[slot] = withoutAppearance(authoredSlot);\n\t}\n\n\tconst parsed = parseSync(recipe.schema, mergeSlotDefaults(stripped, recipe.slotDefaults));\n\tif (parsed.issues !== undefined) return { issues, schemaIssues: [...parsed.issues] };\n\tconst output = parsed.value;\n\tif (typeof output !== 'object' || output === null || !('$type' in output) || typeof output.$type !== 'string') {\n\t\tissues.push({\n\t\t\tpath: ['$type'],\n\t\t\tmessage: `Invalid view configuration for recipe '${recipe.$type}': parsed output is missing $type.`,\n\t\t});\n\t\treturn { issues };\n\t}\n\n\tconst allowedSlots = new Set<string>(recipe.slots);\n\tfor (const key of Object.keys(view)) {\n\t\tif (key !== '$type' && !allowedSlots.has(key)) {\n\t\t\tissues.push({\n\t\t\t\tpath: [key],\n\t\t\t\tmessage: `Recipe '${recipe.$type}' does not accept view key '${key}'. Allowed: ${[...allowedSlots].join(', ') || '(none)'}.`,\n\t\t\t});\n\t\t}\n\t}\n\n\tconst next: Record<string, unknown> = { ...output };\n\tfor (const [slot, selection] of Object.entries(resolved)) {\n\t\tconst slotConfig = (output as Record<string, unknown>)[slot];\n\t\tif (isPlainRecord(slotConfig)) next[slot] = { ...slotConfig, appearance: selection };\n\t}\n\treturn { issues, view: next };\n}\n"],
5
+ "mappings": "AAAA,OACC,kBAAAA,MAIM,0BACP,UAAYC,MAAO,WA4EnB,IAAMC,EAAY,kCACZC,EAAa,8BACbC,EAAqB,cACrBC,EAAkB,EAClBC,EAAkB,EAuBxB,SAASC,EAAgBC,EAAiC,CACzD,IAAMC,EAAOD,EAAK,MAClB,GAAI,CAACE,EAAU,KAAKD,CAAI,EACvB,MAAM,IAAI,MACT,iCAAiCA,CAAI,uEACtC,EAED,IAAME,EAAU,OAAO,QAAQH,EAAK,MAAM,EAC1C,GAAIG,EAAQ,OAASC,GAAmBD,EAAQ,OAASE,EACxD,MAAM,IAAI,MACT,4BAA4BJ,CAAI,kBAAkBG,CAAe,OAAOC,CAAe,kBAAkBF,EAAQ,MAAM,uDACxH,EAED,GAAI,CAAC,OAAO,OAAOH,EAAK,OAAQA,EAAK,OAAO,EAC3C,MAAM,IAAI,MACT,4BAA4BC,CAAI,eAAeD,EAAK,OAAO,+BAA+BG,EAAQ,IAAI,CAAC,CAACG,CAAK,IAAMA,CAAK,EAAE,KAAK,IAAI,CAAC,IACrI,EAED,OAAW,CAACA,EAAOC,CAAM,IAAKJ,EAAS,CACtC,GAAI,CAACK,EAAW,KAAKF,CAAK,EACzB,MAAM,IAAI,MACT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ME", "token", "tokenValue", "UNSAFE_TOKEN_VALUE", "defineAxis", "definition", "sizeAxis", "surfaceAxis", "mergeAppearance", "inherited", "own", "isRecord", "value", "checkAppearance", "authored", "options", "issues", "appearance", "declared", "axis", "values", "supported", "pickSupportedAppearance", "selection", "picked", "isPlainObject", "value", "prototype", "mergeDeep", "base", "override", "merged", "key", "mergeSlotDefaults", "view", "slotDefaults", "slot", "defaults", "isPlainRecord", "value", "prototype", "withoutAppearance", "config", "_authored", "rest", "parseSync", "schema", "result", "resolveRecipeView", "recipe", "view", "scope", "issues", "stripped", "resolved", "slot", "authoredSlot", "supported", "checked", "checkAppearance", "issue", "selection", "pickSupportedAppearance", "mergeAppearance", "parsed", "mergeSlotDefaults", "output", "allowedSlots", "key", "next", "slotConfig"]
7
+ }
@@ -0,0 +1,53 @@
1
+ import type * as z from 'zod/mini';
2
+ import type { BaseRegistration, ComponentMetadata } from '@schema-engine/registry';
3
+ import type { SlotAppearanceAxes } from '../lib/appearance';
4
+ export interface RecipeMetadata extends ComponentMetadata {
5
+ category?: string;
6
+ }
7
+ export type ProtocolRecipeSlotSchemas<TSlot extends string = string> = Partial<Record<TSlot, z.ZodMiniType>>;
8
+ /**
9
+ * Slot config applied beneath a view's own slot config, typed as the input of each declared slot schema.
10
+ *
11
+ * @remarks
12
+ * Undeclared slots and misspelled keys are compile errors; `defineProtocolRecipeSpec` also parses each
13
+ * default against its slot schema.
14
+ */
15
+ export type RecipeSlotDefaults<TSlots extends Partial<Record<string, z.ZodMiniType>>> = {
16
+ [K in keyof TSlots]?: TSlots[K] extends z.ZodMiniType ? z.input<TSlots[K]> : never;
17
+ };
18
+ export interface ProtocolRecipeSpec<TSlot extends string = string, TKind extends string = string, TType extends string = string, TSchema extends z.ZodMiniType = z.ZodMiniType, TSlots extends ProtocolRecipeSlotSchemas<TSlot> = ProtocolRecipeSlotSchemas<TSlot>> {
19
+ $type: TType;
20
+ kind: TKind;
21
+ slots: TSlot[];
22
+ slotSchemas: TSlots;
23
+ slotDefaults?: RecipeSlotDefaults<TSlots>;
24
+ /**
25
+ * Appearance axes each slot supports (`{ shell: ['size', 'surface'] }`); undeclared axes fail validation on that slot.
26
+ *
27
+ * @remarks
28
+ * A slot that declares axes must accept an `appearance` key in its schema, so authored
29
+ * configs type-check and the JSON Schema lists it. A validator that resolves the view (forms: `validateForm`) does not
30
+ * pass the key to the slot schema when it parses it, and writes the resolved selection back, so a renderer reading the
31
+ * normalized slot sees it.
32
+ */
33
+ appearanceAxes?: SlotAppearanceAxes<keyof TSlots>;
34
+ metadata: RecipeMetadata;
35
+ schema: TSchema;
36
+ }
37
+ /**
38
+ * A spec bound to a render payload, as registered in a domain's recipe registry.
39
+ *
40
+ * @remarks
41
+ * `render` is whatever the domain's renderers need (shell and slot components); this package never
42
+ * reads it.
43
+ */
44
+ export interface ProtocolRecipeRegistration<TSlot extends string = string, TKind extends string = string, TType extends string = string, TSchema extends BaseRegistration['schema'] = BaseRegistration['schema'], TRender = unknown> extends BaseRegistration {
45
+ $type: TType;
46
+ kind: TKind;
47
+ slots: TSlot[];
48
+ schema: TSchema;
49
+ metadata: RecipeMetadata;
50
+ slotDefaults?: Partial<Record<TSlot, Record<string, unknown>>>;
51
+ appearanceAxes?: SlotAppearanceAxes<TSlot>;
52
+ render: TRender;
53
+ }
File without changes
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": [],
4
+ "sourcesContent": [],
5
+ "mappings": "",
6
+ "names": []
7
+ }
@@ -0,0 +1,20 @@
1
+ import type * as z from 'zod/mini';
2
+ /**
3
+ * What every recipe renderer receives, whatever the domain: the recipe's kind and the resolved view.
4
+ *
5
+ * @remarks
6
+ * A domain extends it with what its renderers also need, for example the steps of a form.
7
+ */
8
+ export interface RecipeViewModel<TKind extends string = string> {
9
+ kind: TKind;
10
+ viewConfig: Record<string, unknown>;
11
+ }
12
+ /**
13
+ * Reads one slot's complete config from a resolved view.
14
+ *
15
+ * @remarks
16
+ * `schema` only types the result. The view is already complete, and parsing it again with the
17
+ * block's own strict schema would reject a custom recipe whose slot schema extends the block's
18
+ * with extra keys.
19
+ */
20
+ export declare function readSlotConfig<TSchema extends z.ZodMiniType>(viewConfig: Record<string, unknown>, slot: string, _schema: TSchema): z.output<TSchema>;
@@ -0,0 +1 @@
1
+ function t(e,n,i){return e[n]}export{t as readSlotConfig};
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/recipes/view-model.ts"],
4
+ "sourcesContent": ["import type * as z from 'zod/mini';\n\n/**\n * What every recipe renderer receives, whatever the domain: the recipe's kind and the resolved view.\n *\n * @remarks\n * A domain extends it with what its renderers also need, for example the steps of a form.\n */\nexport interface RecipeViewModel<TKind extends string = string> {\n\tkind: TKind;\n\tviewConfig: Record<string, unknown>;\n}\n\n/**\n * Reads one slot's complete config from a resolved view.\n *\n * @remarks\n * `schema` only types the result. The view is already complete, and parsing it again with the\n * block's own strict schema would reject a custom recipe whose slot schema extends the block's\n * with extra keys.\n */\nexport function readSlotConfig<TSchema extends z.ZodMiniType>(\n\tviewConfig: Record<string, unknown>,\n\tslot: string,\n\t_schema: TSchema,\n): z.output<TSchema> {\n\treturn viewConfig[slot] as z.output<TSchema>;\n}\n"],
5
+ "mappings": "AAqBO,SAASA,EACfC,EACAC,EACAC,EACoB,CACpB,OAAOF,EAAWC,CAAI,CACvB",
6
+ "names": ["readSlotConfig", "viewConfig", "slot", "_schema"]
7
+ }
@@ -0,0 +1,57 @@
1
+ import * as z from 'zod/mini';
2
+ import type { AxisRegistry } from '../lib/appearance.js';
3
+ /**
4
+ * A pick of named appearance values, one per axis: `{ size: 'compact' }`.
5
+ *
6
+ * @remarks
7
+ * The shape is open because the axes belong to the theme (`createLayoutTheme({ appearance })`). A
8
+ * domain checks each axis and value against the theme's vocabulary and the owner's declared axes.
9
+ */
10
+ export declare const AppearanceConfigSchema: z.ZodMiniRecord<z.ZodMiniString<string>, z.ZodMiniString<string>>;
11
+ export type AppearanceConfig = z.infer<typeof AppearanceConfigSchema>;
12
+ /**
13
+ * The pick schema of one theme: each axis is an optional enum of its values, and any other axis is
14
+ * rejected.
15
+ *
16
+ * @param supported Restricts the schema to the axes one owner declares; omit it for an owner that
17
+ * accepts every axis of the theme (the document and its steps). An empty list is a closed object
18
+ * with no axes. A name the theme does not hold is skipped, since an engine rejects it when it builds.
19
+ *
20
+ * @remarks
21
+ * Built for a JSON Schema export, so an editor autocompletes `appearance.size`. The enums are fresh
22
+ * schemas rather than the axes' own, so the export inlines them instead of referencing a catalog
23
+ * entry. It is built from the same registry and declarations `checkAppearance` validates against.
24
+ */
25
+ export declare function createAppearanceSchema(axes: AxisRegistry, supported?: readonly string[]): z.ZodMiniObject<{
26
+ [x: string]: z.ZodMiniOptional<z.ZodMiniEnum<{
27
+ [x: string]: string;
28
+ }>>;
29
+ }, z.core.$strict>;
30
+ /**
31
+ * Sets the `appearance` key of an object schema to the closed schema of the axes its owner
32
+ * declares, for a JSON Schema export.
33
+ *
34
+ * @param supported The owner's declared axes (`appearanceAxes`); omit it for an owner that declares none,
35
+ * which gets a closed object with no axes.
36
+ *
37
+ * @remarks
38
+ * Validation strips an authored `appearance` before it parses the owner's own schema and checks the
39
+ * pick against the declared axes (`checkAppearance`), on every owner whatever its schema says. So the
40
+ * key is set whether or not the schema has one, and replaces an open one. This keeps the export from
41
+ * drifting from validation. A pipe is rewritten on its input, so a transform after the object stays.
42
+ * A schema that is not an object, a pipe of one or a prefault of one (a lazy schema, for example) is
43
+ * returned unchanged. The result is for export only: parse with the original.
44
+ */
45
+ export declare function withAppearanceAxes(schema: z.ZodMiniType, axes: AxisRegistry, supported?: readonly string[]): z.ZodMiniType;
46
+ /**
47
+ * Applies {@link withAppearanceAxes} to each slot of a recipe's view schema, with the axes the
48
+ * recipe declares for that slot.
49
+ *
50
+ * @param slotAxes The recipe's `appearanceAxes`; a slot it does not list declares none.
51
+ *
52
+ * @remarks
53
+ * Expects the shape `defineProtocolRecipeSpec` builds: a strict object whose slots are objects
54
+ * wrapped in `prefault`. Validation resolves the appearance of every slot, so every slot gets the
55
+ * key. Any other shape is returned unchanged.
56
+ */
57
+ export declare function withSlotAppearanceAxes(schema: z.ZodMiniType, axes: AxisRegistry, slotAxes?: Readonly<Record<string, readonly string[] | undefined>>): z.ZodMiniType;
@@ -0,0 +1 @@
1
+ import*as n from"zod/mini";var g=n.record(n.string(),n.string());function a(e,t){let i=e.all().filter(r=>t===void 0||t.includes(r.$type)).map(r=>[r.$type,n.optional(n.enum(Object.keys(r.values)))]);return n.strictObject(Object.fromEntries(i))}function c(e){return"check"in e&&typeof e.check=="function"}function f(e){return e._zod.def.type==="object"}function u(e){return e._zod.def.type==="pipe"}function z(e){return e._zod.def.type==="prefault"}function d(e,t){if(f(e))return n.safeExtend(e,{appearance:t});if(u(e)){let{in:i,out:r}=e._zod.def;if(!c(i))return e;let o=d(i,t);return o===i?e:n.pipe(o,r)}if(z(e)){let{innerType:i,defaultValue:r}=e._zod.def;if(!c(i))return e;let o=d(i,t);return o===i?e:n.prefault(o,r)}return e}function y(e,t){return n.optional(a(e,t)).check(n.describe("Named appearance values, one per declared axis"))}function l(e,t,i=[]){return d(e,y(t,i))}function x(e,t,i={}){if(!f(e))return e;let r={};for(let[o,p]of Object.entries(e._zod.def.shape)){if(!c(p))continue;let s=l(p,t,i[o]);s!==p&&(r[o]=s)}return Object.keys(r).length===0?e:n.safeExtend(e,r)}export{g as AppearanceConfigSchema,a as createAppearanceSchema,l as withAppearanceAxes,x as withSlotAppearanceAxes};
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/schemas/appearance.ts"],
4
+ "sourcesContent": ["import * as z from 'zod/mini';\nimport type { AxisRegistry } from '@/lib/appearance';\n\n/**\n * A pick of named appearance values, one per axis: `{ size: 'compact' }`.\n *\n * @remarks\n * The shape is open because the axes belong to the theme (`createLayoutTheme({ appearance })`). A\n * domain checks each axis and value against the theme's vocabulary and the owner's declared axes.\n */\nexport const AppearanceConfigSchema = z.record(z.string(), z.string());\n\nexport type AppearanceConfig = z.infer<typeof AppearanceConfigSchema>;\n\n/**\n * The pick schema of one theme: each axis is an optional enum of its values, and any other axis is\n * rejected.\n *\n * @param supported Restricts the schema to the axes one owner declares; omit it for an owner that\n * accepts every axis of the theme (the document and its steps). An empty list is a closed object\n * with no axes. A name the theme does not hold is skipped, since an engine rejects it when it builds.\n *\n * @remarks\n * Built for a JSON Schema export, so an editor autocompletes `appearance.size`. The enums are fresh\n * schemas rather than the axes' own, so the export inlines them instead of referencing a catalog\n * entry. It is built from the same registry and declarations `checkAppearance` validates against.\n */\nexport function createAppearanceSchema(axes: AxisRegistry, supported?: readonly string[]) {\n\tconst entries = axes\n\t\t.all()\n\t\t.filter((axis) => supported === undefined || supported.includes(axis.$type))\n\t\t.map((axis) => [axis.$type, z.optional(z.enum(Object.keys(axis.values) as [string, ...string[]]))] as const);\n\treturn z.strictObject(Object.fromEntries(entries));\n}\n\n/**\n * @remarks\n * Only narrows the members of a schema's definition, which Zod types as the core base. A classic\n * Zod schema passes too, since it has the same methods, and is rewritten the same way.\n */\nfunction isMiniSchema(schema: z.core.$ZodType): schema is z.ZodMiniType {\n\treturn 'check' in schema && typeof schema.check === 'function';\n}\n\nfunction isObjectSchema(schema: z.ZodMiniType): schema is z.ZodMiniObject {\n\treturn schema._zod.def.type === 'object';\n}\n\nfunction isPipeSchema(schema: z.ZodMiniType): schema is z.ZodMiniPipe {\n\treturn schema._zod.def.type === 'pipe';\n}\n\nfunction isPrefaultSchema(schema: z.ZodMiniType): schema is z.ZodMiniPrefault {\n\treturn schema._zod.def.type === 'prefault';\n}\n\n/**\n * Sets the `appearance` key on the object a schema parses, looking through a pipe (its input) and\n * a prefault (its inner schema). Any other schema comes back as it is.\n */\nfunction setAppearance(schema: z.ZodMiniType, appearance: z.ZodMiniType): z.ZodMiniType {\n\tif (isObjectSchema(schema)) return z.safeExtend(schema, { appearance });\n\tif (isPipeSchema(schema)) {\n\t\tconst { in: input, out } = schema._zod.def;\n\t\tif (!isMiniSchema(input)) return schema;\n\t\tconst next = setAppearance(input, appearance);\n\t\treturn next === input ? schema : z.pipe(next, out);\n\t}\n\tif (isPrefaultSchema(schema)) {\n\t\tconst { innerType, defaultValue } = schema._zod.def;\n\t\tif (!isMiniSchema(innerType)) return schema;\n\t\tconst next = setAppearance(innerType, appearance);\n\t\treturn next === innerType ? schema : z.prefault(next, defaultValue);\n\t}\n\treturn schema;\n}\n\nfunction declaredAppearance(axes: AxisRegistry, supported: readonly string[]) {\n\treturn z\n\t\t.optional(createAppearanceSchema(axes, supported))\n\t\t.check(z.describe('Named appearance values, one per declared axis'));\n}\n\n/**\n * Sets the `appearance` key of an object schema to the closed schema of the axes its owner\n * declares, for a JSON Schema export.\n *\n * @param supported The owner's declared axes (`appearanceAxes`); omit it for an owner that declares none,\n * which gets a closed object with no axes.\n *\n * @remarks\n * Validation strips an authored `appearance` before it parses the owner's own schema and checks the\n * pick against the declared axes (`checkAppearance`), on every owner whatever its schema says. So the\n * key is set whether or not the schema has one, and replaces an open one. This keeps the export from\n * drifting from validation. A pipe is rewritten on its input, so a transform after the object stays.\n * A schema that is not an object, a pipe of one or a prefault of one (a lazy schema, for example) is\n * returned unchanged. The result is for export only: parse with the original.\n */\nexport function withAppearanceAxes(\n\tschema: z.ZodMiniType,\n\taxes: AxisRegistry,\n\tsupported: readonly string[] = [],\n): z.ZodMiniType {\n\treturn setAppearance(schema, declaredAppearance(axes, supported));\n}\n\n/**\n * Applies {@link withAppearanceAxes} to each slot of a recipe's view schema, with the axes the\n * recipe declares for that slot.\n *\n * @param slotAxes The recipe's `appearanceAxes`; a slot it does not list declares none.\n *\n * @remarks\n * Expects the shape `defineProtocolRecipeSpec` builds: a strict object whose slots are objects\n * wrapped in `prefault`. Validation resolves the appearance of every slot, so every slot gets the\n * key. Any other shape is returned unchanged.\n */\nexport function withSlotAppearanceAxes(\n\tschema: z.ZodMiniType,\n\taxes: AxisRegistry,\n\tslotAxes: Readonly<Record<string, readonly string[] | undefined>> = {},\n): z.ZodMiniType {\n\tif (!isObjectSchema(schema)) return schema;\n\tconst replaced: Record<string, z.ZodMiniType> = {};\n\tfor (const [slot, slotSchema] of Object.entries(schema._zod.def.shape)) {\n\t\tif (!isMiniSchema(slotSchema)) continue;\n\t\tconst next = withAppearanceAxes(slotSchema, axes, slotAxes[slot]);\n\t\tif (next !== slotSchema) replaced[slot] = next;\n\t}\n\tif (Object.keys(replaced).length === 0) return schema;\n\treturn z.safeExtend(schema, replaced);\n}\n"],
5
+ "mappings": "AAAA,UAAYA,MAAO,WAUZ,IAAMC,EAA2B,SAAS,SAAO,EAAK,SAAO,CAAC,EAiB9D,SAASC,EAAuBC,EAAoBC,EAA+B,CACzF,IAAMC,EAAUF,EACd,IAAI,EACJ,OAAQG,GAASF,IAAc,QAAaA,EAAU,SAASE,EAAK,KAAK,CAAC,EAC1E,IAAKA,GAAS,CAACA,EAAK,MAAS,WAAW,OAAK,OAAO,KAAKA,EAAK,MAAM,CAA0B,CAAC,CAAC,CAAU,EAC5G,OAAS,eAAa,OAAO,YAAYD,CAAO,CAAC,CAClD,CAOA,SAASE,EAAaC,EAAkD,CACvE,MAAO,UAAWA,GAAU,OAAOA,EAAO,OAAU,UACrD,CAEA,SAASC,EAAeD,EAAkD,CACzE,OAAOA,EAAO,KAAK,IAAI,OAAS,QACjC,CAEA,SAASE,EAAaF,EAAgD,CACrE,OAAOA,EAAO,KAAK,IAAI,OAAS,MACjC,CAEA,SAASG,EAAiBH,EAAoD,CAC7E,OAAOA,EAAO,KAAK,IAAI,OAAS,UACjC,CAMA,SAASI,EAAcJ,EAAuBK,EAA0C,CACvF,GAAIJ,EAAeD,CAAM,EAAG,OAAS,aAAWA,EAAQ,CAAE,WAAAK,CAAW,CAAC,EACtE,GAAIH,EAAaF,CAAM,EAAG,CACzB,GAAM,CAAE,GAAIM,EAAO,IAAAC,CAAI,EAAIP,EAAO,KAAK,IACvC,GAAI,CAACD,EAAaO,CAAK,EAAG,OAAON,EACjC,IAAMQ,EAAOJ,EAAcE,EAAOD,CAAU,EAC5C,OAAOG,IAASF,EAAQN,EAAW,OAAKQ,EAAMD,CAAG,CAClD,CACA,GAAIJ,EAAiBH,CAAM,EAAG,CAC7B,GAAM,CAAE,UAAAS,EAAW,aAAAC,CAAa,EAAIV,EAAO,KAAK,IAChD,GAAI,CAACD,EAAaU,CAAS,EAAG,OAAOT,EACrC,IAAMQ,EAAOJ,EAAcK,EAAWJ,CAAU,EAChD,OAAOG,IAASC,EAAYT,EAAW,WAASQ,EAAME,CAAY,CACnE,CACA,OAAOV,CACR,CAEA,SAASW,EAAmBhB,EAAoBC,EAA8B,CAC7E,OACE,WAASF,EAAuBC,EAAMC,CAAS,CAAC,EAChD,MAAQ,WAAS,gDAAgD,CAAC,CACrE,CAiBO,SAASgB,EACfZ,EACAL,EACAC,EAA+B,CAAC,EAChB,CAChB,OAAOQ,EAAcJ,EAAQW,EAAmBhB,EAAMC,CAAS,CAAC,CACjE,CAaO,SAASiB,EACfb,EACAL,EACAmB,EAAoE,CAAC,EACrD,CAChB,GAAI,CAACb,EAAeD,CAAM,EAAG,OAAOA,EACpC,IAAMe,EAA0C,CAAC,EACjD,OAAW,CAACC,EAAMC,CAAU,IAAK,OAAO,QAAQjB,EAAO,KAAK,IAAI,KAAK,EAAG,CACvE,GAAI,CAACD,EAAakB,CAAU,EAAG,SAC/B,IAAMT,EAAOI,EAAmBK,EAAYtB,EAAMmB,EAASE,CAAI,CAAC,EAC5DR,IAASS,IAAYF,EAASC,CAAI,EAAIR,EAC3C,CACA,OAAI,OAAO,KAAKO,CAAQ,EAAE,SAAW,EAAUf,EACtC,aAAWA,EAAQe,CAAQ,CACrC",
6
+ "names": ["z", "AppearanceConfigSchema", "createAppearanceSchema", "axes", "supported", "entries", "axis", "isMiniSchema", "schema", "isObjectSchema", "isPipeSchema", "isPrefaultSchema", "setAppearance", "appearance", "input", "out", "next", "innerType", "defaultValue", "declaredAppearance", "withAppearanceAxes", "withSlotAppearanceAxes", "slotAxes", "replaced", "slot", "slotSchema"]
7
+ }