@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.
- package/LICENSE +21 -0
- package/README.md +57 -2
- package/dist/index.d.ts +37 -0
- package/dist/index.js +4 -0
- package/dist/index.js.map +7 -0
- package/dist/lib/appearance.d.ts +204 -0
- package/dist/lib/appearance.js +2 -0
- package/dist/lib/appearance.js.map +7 -0
- package/dist/lib/deep-readonly.d.ts +10 -0
- package/dist/lib/deep-readonly.js +0 -0
- package/dist/lib/deep-readonly.js.map +7 -0
- package/dist/lib/grid-placement.d.ts +107 -0
- package/dist/lib/grid-placement.js +1 -0
- package/dist/lib/grid-placement.js.map +7 -0
- package/dist/lib/grid-styles.d.ts +178 -0
- package/dist/lib/grid-styles.js +2 -0
- package/dist/lib/grid-styles.js.map +7 -0
- package/dist/lib/layout-issue.d.ts +12 -0
- package/dist/lib/layout-issue.js +0 -0
- package/dist/lib/layout-issue.js.map +7 -0
- package/dist/lib/layout-theme.d.ts +94 -0
- package/dist/lib/layout-theme.js +4 -0
- package/dist/lib/layout-theme.js.map +7 -0
- package/dist/recipes/bind-recipe.d.ts +12 -0
- package/dist/recipes/bind-recipe.js +1 -0
- package/dist/recipes/bind-recipe.js.map +7 -0
- package/dist/recipes/define-recipe-spec.d.ts +49 -0
- package/dist/recipes/define-recipe-spec.js +1 -0
- package/dist/recipes/define-recipe-spec.js.map +7 -0
- package/dist/recipes/merge-slot-defaults.d.ts +8 -0
- package/dist/recipes/merge-slot-defaults.js +1 -0
- package/dist/recipes/merge-slot-defaults.js.map +7 -0
- package/dist/recipes/protocol.d.ts +69 -0
- package/dist/recipes/protocol.js +1 -0
- package/dist/recipes/protocol.js.map +7 -0
- package/dist/recipes/resolve-recipe-view.d.ts +52 -0
- package/dist/recipes/resolve-recipe-view.js +1 -0
- package/dist/recipes/resolve-recipe-view.js.map +7 -0
- package/dist/recipes/types.d.ts +53 -0
- package/dist/recipes/types.js +0 -0
- package/dist/recipes/types.js.map +7 -0
- package/dist/recipes/view-model.d.ts +20 -0
- package/dist/recipes/view-model.js +1 -0
- package/dist/recipes/view-model.js.map +7 -0
- package/dist/schemas/appearance.d.ts +57 -0
- package/dist/schemas/appearance.js +1 -0
- package/dist/schemas/appearance.js.map +7 -0
- package/dist/schemas/grid.d.ts +666 -0
- package/dist/schemas/grid.js +1 -0
- package/dist/schemas/grid.js.map +7 -0
- package/package.json +75 -3
- package/skill/SKILL.md +79 -0
- package/skill/reference/layout.md +48 -0
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/lib/appearance.ts", "../../src/schemas/grid.ts", "../../src/lib/grid-placement.ts", "../../src/lib/grid-styles.ts", "../../src/lib/layout-theme.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", "import * as z from 'zod/mini';\n\n/**\n * Semantic gap tokens for grid layouts.\n *\n * @remarks\n * Tokens are indirections to overridable CSS variables: the renderer emits\n * `var(--se-grid-gap-<token>)`, so hosts restyle every grid by overriding the\n * token at `:root`. Raw CSS strings (e.g. `'1.5rem'`) are the one-off escape\n * hatch.\n */\nexport const GridGapTokens = ['none', 'compact', 'default', 'loose', 'wide'] as const;\n\nexport type GridGapToken = (typeof GridGapTokens)[number];\n\n/**\n * Semantic gap token or a raw CSS length.\n *\n * @remarks\n * The enum branch is redundant for validation \u2014 the string branch accepts the\n * same values \u2014 and `z.infer` collapses the union to `string`. It is kept\n * because `z.toJSONSchema` emits it as `anyOf: [{enum: [...]}, {type: string}]`,\n * which is how the token vocabulary reaches registry and docs consumers.\n */\nexport const GridGapValueSchema = z\n\t.union([z.enum(GridGapTokens), z.string()])\n\t.check(z.describe('Semantic gap token (none | compact | default | loose | wide) or a raw CSS length.'));\n\n/**\n * Words that are not valid grid area names: `grid-area` reads `auto` and `span`\n * as placement keywords, the CSS-wide keywords reset a declaration, and `none`\n * and `default` are excluded from a `<custom-ident>` by the CSS grammar.\n */\nconst RESERVED_AREA_NAMES = [\n\t'auto',\n\t'span',\n\t'none',\n\t'default',\n\t'inherit',\n\t'initial',\n\t'unset',\n\t'revert',\n\t'revert-layer',\n];\n\n/**\n * A word as a pattern that matches it in any letter case.\n *\n * @remarks\n * Spelled with character classes instead of an `i` flag because the JSON Schema\n * export keeps only a regex's source, so a flag would be lost and editors would\n * accept `AUTO` and reject `Street`.\n */\nfunction anyCase(word: string): string {\n\treturn word\n\t\t.split('')\n\t\t.map((char) => (/[a-z]/i.test(char) ? `[${char.toLowerCase()}${char.toUpperCase()}]` : char))\n\t\t.join('');\n}\n\nconst AREA_NAME_SOURCE = `(?!(?:${RESERVED_AREA_NAMES.map(anyCase).join('|')})(?![\\\\w-]))-?[_a-zA-Z][_a-zA-Z0-9-]*`;\n\n/**\n * Name of a grid area: an ASCII CSS identifier that is not a reserved word.\n *\n * @remarks\n * Names are written into a custom property that the stylesheet reads as CSS, so\n * the pattern is the injection guard. Nothing outside `[A-Za-z0-9_-]` can reach the\n * property, which rules out quotes, semicolons, braces and whitespace.\n */\nconst GridAreaNameSchema = z\n\t.string()\n\t.check(\n\t\tz.regex(new RegExp(`^${AREA_NAME_SOURCE}$`), 'Area names are CSS identifiers such as \"header\" or \"side-2\".'),\n\t\tz.describe('Name of a cell group in the grid template: a CSS identifier such as \"header\" or \"side-2\".'),\n\t);\n\n/** A value per cascade slot (`default`, `sm` ... `2xl`), each optional. */\nfunction perBreakpoint<T extends z.ZodMiniType>(schema: T) {\n\treturn z.strictObject({\n\t\tdefault: z.optional(schema),\n\t\tsm: z.optional(schema),\n\t\tmd: z.optional(schema),\n\t\tlg: z.optional(schema),\n\t\txl: z.optional(schema),\n\t\t'2xl': z.optional(schema),\n\t});\n}\n\nfunction responsiveSchema<T extends z.ZodMiniType>(schema: T) {\n\treturn z.optional(perBreakpoint(schema));\n}\n\n/** One row of a template: area names or `.` for an empty cell, separated by spaces. */\nconst GridAreaRowSchema = z\n\t.string()\n\t.check(\n\t\tz.regex(\n\t\t\tnew RegExp(`^\\\\s*(?:\\\\.+|${AREA_NAME_SOURCE})(?:\\\\s+(?:\\\\.+|${AREA_NAME_SOURCE}))*\\\\s*$`),\n\t\t\t'A grid areas row lists area names (CSS identifiers) or \".\" for an empty cell, separated by spaces.',\n\t\t),\n\t);\n\nconst GridAreaRowsSchema = z.array(GridAreaRowSchema).check(z.minLength(1));\n\n/**\n * A drawn layout: rows of area names, optionally per breakpoint.\n *\n * @remarks\n * The column count comes from the rows, so a grid with `areas` sets no\n * `columns`. Rows of one template must be the same length and each name must\n * fill a rectangle; the domain validator checks both, as CSS drops a template that\n * breaks either.\n */\nconst GridAreasSchema = z\n\t.union([GridAreaRowsSchema, perBreakpoint(GridAreaRowsSchema)])\n\t.check(\n\t\tz.describe(\n\t\t\t'Rows of area names separated by spaces (\".\" is an empty cell), or a record of them per breakpoint (default, sm ... 2xl).',\n\t\t),\n\t);\n\nconst GridLayoutPropertiesSchema = z.strictObject({\n\tareas: z.optional(GridAreasSchema),\n\tcolumns: z.optional(z.union([z.number(), z.literal('auto')])),\n\tgap: z.optional(GridGapValueSchema),\n\tgapX: z.optional(GridGapValueSchema),\n\tgapY: z.optional(GridGapValueSchema),\n\tminColumnWidth: z.optional(z.string()),\n\tjustifyItems: z.optional(z.enum(['start', 'end', 'center', 'stretch'])),\n\talignItems: z.optional(z.enum(['start', 'end', 'center', 'stretch'])),\n\tplaceItems: z.optional(z.string()),\n\tjustifyContent: z.optional(\n\t\tz.enum(['start', 'end', 'center', 'stretch', 'space-around', 'space-between', 'space-evenly']),\n\t),\n\talignContent: z.optional(\n\t\tz.enum(['start', 'end', 'center', 'stretch', 'space-around', 'space-between', 'space-evenly']),\n\t),\n\tplaceContent: z.optional(z.string()),\n});\n\nexport const GridBreakpointConfigSchema = z.pick(GridLayoutPropertiesSchema, {\n\tcolumns: true,\n\tgap: true,\n\tgapX: true,\n\tgapY: true,\n\tminColumnWidth: true,\n});\n\nexport const GridLayoutConfigSchema = z.extend(GridLayoutPropertiesSchema, {\n\tresponsive: responsiveSchema(GridBreakpointConfigSchema),\n});\n\n/**\n * Named item widths, as shares of the row.\n *\n * @remarks\n * A grid whose items use `width` or `offset` is laid out on 12 tracks, so\n * every name is a whole number of tracks: `full` 12, `three-quarters` 9,\n * `two-thirds` 8, `half` 6, `third` 4, `quarter` 3. An item that sets no width\n * fills the row.\n */\nexport const GridWidthNames = ['full', 'three-quarters', 'two-thirds', 'half', 'third', 'quarter'] as const;\n\nexport type GridWidthName = (typeof GridWidthNames)[number];\n\n/** Named offsets: the widths that are a fraction of the row, without `full`. */\nexport const GridOffsetNames = ['three-quarters', 'two-thirds', 'half', 'third', 'quarter'] as const;\n\nexport type GridOffsetName = (typeof GridOffsetNames)[number];\n\nconst ElementGridPropertiesSchema = z.strictObject({\n\tarea: z\n\t\t.optional(GridAreaNameSchema)\n\t\t.check(z.describe('Name of the cell group this item fills in the grid areas template.')),\n\twidth: z\n\t\t.optional(z.enum(GridWidthNames))\n\t\t.check(z.describe(`Named share of the row (${GridWidthNames.join(' | ')}).`)),\n\toffset: z\n\t\t.optional(z.enum(GridOffsetNames))\n\t\t.check(z.describe(`Named empty space before the item (${GridOffsetNames.join(' | ')}).`)),\n\tcolumn: z.optional(z.union([z.number(), z.string()])),\n\trow: z.optional(z.union([z.number(), z.string()])),\n\tjustifySelf: z.optional(z.enum(['start', 'end', 'center', 'stretch'])),\n\talignSelf: z.optional(z.enum(['start', 'end', 'center', 'stretch'])),\n\tplaceSelf: z.optional(z.string()),\n\tmarginBlockStart: z\n\t\t.optional(GridGapValueSchema)\n\t\t.check(z.describe('Extra space before this element, on top of the grid row gap.')),\n\tmarginBlockEnd: z\n\t\t.optional(GridGapValueSchema)\n\t\t.check(z.describe('Extra space after this element, on top of the grid row gap.')),\n});\n\nexport const ItemGridBreakpointSchema = z.extend(z.omit(ElementGridPropertiesSchema, { placeSelf: true }), {\n\thidden: z.optional(z.boolean()),\n});\n\nexport const ElementGridConfigSchema = z.extend(ElementGridPropertiesSchema, {\n\tresponsive: responsiveSchema(ItemGridBreakpointSchema),\n});\n\nexport type GridBreakpointConfig = z.infer<typeof GridBreakpointConfigSchema>;\nexport type ItemGridBreakpointConfig = z.infer<typeof ItemGridBreakpointSchema>;\nexport type ElementGridConfig = z.infer<typeof ElementGridConfigSchema>;\nexport type GridLayoutConfig = z.infer<typeof GridLayoutConfigSchema>;\n", "import type { GridBreakpointConfig, GridOffsetName, GridWidthName } from '@/schemas/grid';\nimport type { LayoutIssue } from './layout-issue';\n\n/**\n * Reads of an element's grid placement shared by the stylesheet emitter and\n * validation, so the cascade the author is checked against is the one emitted.\n *\n * @remarks\n * Elements arrive as `unknown` because they are read before, or without, a\n * registered schema narrowing them: a registration may declare `grid` loosely.\n */\n\nexport const BREAKPOINT_ORDER = ['sm', 'md', 'lg', 'xl', '2xl'] as const;\n\n/** Named breakpoint tokens. Thresholds are configured on the layout theme's `grid` option. */\nexport type GridBreakpointToken = (typeof BREAKPOINT_ORDER)[number];\n\nexport type CascadeSlot = 'default' | GridBreakpointToken;\n\n/** Every slot of the cascade, narrowest first. */\nexport const CASCADE_SLOTS: readonly CascadeSlot[] = ['default', ...BREAKPOINT_ORDER];\n\n/** Tracks a grid has once its items use named widths. */\nexport const WIDTH_TRACKS = 12;\n\nexport const WIDTH_SPANS: Readonly<Record<GridWidthName, number>> = {\n\tfull: 12,\n\t'three-quarters': 9,\n\t'two-thirds': 8,\n\thalf: 6,\n\tthird: 4,\n\tquarter: 3,\n};\n\n/**\n * Grid keys that define the template, and so cannot meet named widths.\n *\n * @remarks\n * Typed against the breakpoint schema so a renamed key fails to compile here.\n */\nexport const GRID_TEMPLATE_KEYS = [\n\t'columns',\n\t'minColumnWidth',\n] as const satisfies readonly (keyof GridBreakpointConfig)[];\n\n/** The width and offset an item has authored so far, carried through the cascade. */\nexport interface NamedPlacement {\n\twidth?: GridWidthName;\n\toffset?: GridOffsetName;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === 'object' && value !== null;\n}\n\n/**\n * An element's grid entries in cascade order: the top level, `responsive.default`,\n * then each breakpoint that is set.\n */\nexport function elementGridSlots(element: unknown): Array<{ slot: CascadeSlot; entry: Record<string, unknown> }> {\n\tif (!isRecord(element) || !isRecord(element.grid)) return [];\n\tconst grid = element.grid;\n\tconst slots: Array<{ slot: CascadeSlot; entry: Record<string, unknown> }> = [{ slot: 'default', entry: grid }];\n\tconst responsive = grid.responsive;\n\tif (!isRecord(responsive)) return slots;\n\tfor (const slot of CASCADE_SLOTS) {\n\t\tconst entry = responsive[slot];\n\t\tif (isRecord(entry)) slots.push({ slot, entry });\n\t}\n\treturn slots;\n}\n\n/** Keys an element's `grid` config sets to a value, at the top level or in any breakpoint. */\nexport function elementGridKeys(element: unknown): ReadonlySet<string> {\n\tconst keys = new Set<string>();\n\tfor (const { entry } of elementGridSlots(element)) {\n\t\tfor (const [key, value] of Object.entries(entry)) {\n\t\t\tif (key !== 'responsive' && value !== undefined) keys.add(key);\n\t\t}\n\t}\n\treturn keys;\n}\n\nexport function elementUsesGridWidths(element: unknown): boolean {\n\tconst keys = elementGridKeys(element);\n\treturn keys.has('width') || keys.has('offset');\n}\n\nexport function usesGridWidths(elements: readonly unknown[]): boolean {\n\treturn elements.some(elementUsesGridWidths);\n}\n\n/** Updates `carried` with the width and offset a slot authored; the other keeps its earlier value. */\nexport function carryNamedPlacement(carried: NamedPlacement, entry: NamedPlacement): void {\n\tcarried.width = entry.width ?? carried.width;\n\tcarried.offset = entry.offset ?? carried.offset;\n}\n\n/**\n * The first slot where an element's offset and width together pass the grid's\n * tracks, with the tracks they span, or `undefined` when none does.\n *\n * @remarks\n * Follows the same carry-over as emission: a slot that sets one of the pair is\n * checked against the other as the narrower slots left it, so two slots that\n * each look valid can still overflow together.\n */\nexport function namedPlacementOverflow(element: unknown): { slot: CascadeSlot; tracks: number } | undefined {\n\tconst carried: NamedPlacement = {};\n\tfor (const { slot, entry } of elementGridSlots(element)) {\n\t\tif (entry.width === undefined && entry.offset === undefined) continue;\n\t\tcarryNamedPlacement(carried, entry as NamedPlacement);\n\t\tif (carried.width === undefined || carried.offset === undefined) continue;\n\t\tconst tracks = (WIDTH_SPANS[carried.width] ?? 0) + (WIDTH_SPANS[carried.offset] ?? 0);\n\t\tif (tracks > WIDTH_TRACKS) return { slot, tracks };\n\t}\n\treturn undefined;\n}\n\n/** The cells of each row of a template; `.` marks an empty cell. */\nexport type GridAreaRows = readonly (readonly string[])[];\n\n/** Templates by the slot that sets them. */\nexport type GridAreaTemplates = Partial<Record<CascadeSlot, GridAreaRows>>;\n\nconst EMPTY_CELL = '.';\n\nfunction splitRow(row: unknown): string[] {\n\tif (typeof row !== 'string') return [];\n\treturn row\n\t\t.trim()\n\t\t.split(/\\s+/)\n\t\t.filter(Boolean)\n\t\t.map((cell) => (/^\\.+$/.test(cell) ? EMPTY_CELL : cell));\n}\n\nfunction toRows(rows: unknown): GridAreaRows | undefined {\n\treturn Array.isArray(rows) ? rows.map(splitRow) : undefined;\n}\n\n/**\n * The templates a grid's `areas` sets, by slot. An array is the `default` template.\n *\n * @remarks\n * A run of dots is one empty cell, normalised to a single `.`, so a template\n * compares and emits the same however the author spaced it.\n */\nexport function gridAreaTemplates(grid: unknown): GridAreaTemplates {\n\tif (!isRecord(grid) || grid.areas === undefined) return {};\n\tif (Array.isArray(grid.areas)) {\n\t\tconst rows = toRows(grid.areas);\n\t\treturn rows ? { default: rows } : {};\n\t}\n\tif (!isRecord(grid.areas)) return {};\n\tconst templates: GridAreaTemplates = {};\n\tfor (const slot of CASCADE_SLOTS) {\n\t\tconst rows = toRows(grid.areas[slot]);\n\t\tif (rows) templates[slot] = rows;\n\t}\n\treturn templates;\n}\n\n/** Whether a grid draws its layout with `areas`. */\nexport function gridUsesAreas(grid: unknown): boolean {\n\treturn Object.keys(gridAreaTemplates(grid)).length > 0;\n}\n\n/** Area names a template uses, in order of first appearance. */\nexport function areaNames(rows: GridAreaRows): string[] {\n\tconst names = new Set<string>();\n\tfor (const row of rows) {\n\t\tfor (const cell of row) if (cell !== EMPTY_CELL) names.add(cell);\n\t}\n\treturn [...names];\n}\n\n/** The `grid-template-areas` value for a template: one quoted string per row. */\nexport function areasTemplateValue(rows: GridAreaRows): string {\n\treturn rows.map((row) => `\"${row.join(' ')}\"`).join(' ');\n}\n\n/**\n * The area an element authored at each slot it sets one. Within a slot,\n * `responsive.default` beats the top level, as in emission.\n */\nexport function elementAreaSlots(element: unknown): Partial<Record<CascadeSlot, string>> {\n\tconst areas: Partial<Record<CascadeSlot, string>> = {};\n\tfor (const { slot, entry } of elementGridSlots(element)) {\n\t\tif (typeof entry.area === 'string') areas[slot] = entry.area;\n\t}\n\treturn areas;\n}\n\n/** Whether an element hides itself at each slot it sets `hidden`, in cascade order within a slot. */\nexport function elementHiddenSlots(element: unknown): Partial<Record<CascadeSlot, boolean>> {\n\tconst hidden: Partial<Record<CascadeSlot, boolean>> = {};\n\tfor (const { slot, entry } of elementGridSlots(element)) {\n\t\tif (typeof entry.hidden === 'boolean') hidden[slot] = entry.hidden;\n\t}\n\treturn hidden;\n}\n\n/**\n * What each slot resolves to: the value set at that slot, else the last one a\n * narrower slot set.\n *\n * @remarks\n * Emission falls back through narrower slots in the stylesheet, so validation\n * reads templates and areas the same way to check what a viewport gets.\n */\nexport function cascadeValues<T>(\n\tauthored: Partial<Record<CascadeSlot, T>>,\n): Array<{ slot: CascadeSlot; value: T | undefined }> {\n\tlet carried: T | undefined;\n\treturn CASCADE_SLOTS.map((slot) => {\n\t\tcarried = authored[slot] ?? carried;\n\t\treturn { slot, value: carried };\n\t});\n}\n\nfunction cellCount(count: number): string {\n\treturn `${count} ${count === 1 ? 'cell' : 'cells'}`;\n}\n\nfunction isRectangle(rows: GridAreaRows, name: string): boolean {\n\tconst cells: Array<[row: number, column: number]> = [];\n\trows.forEach((row, rowIndex) =>\n\t\trow.forEach((cell, columnIndex) => {\n\t\t\tif (cell === name) cells.push([rowIndex, columnIndex]);\n\t\t}),\n\t);\n\tconst rowsUsed = cells.map(([row]) => row);\n\tconst columnsUsed = cells.map(([, column]) => column);\n\tconst height = Math.max(...rowsUsed) - Math.min(...rowsUsed) + 1;\n\tconst width = Math.max(...columnsUsed) - Math.min(...columnsUsed) + 1;\n\treturn height * width === cells.length;\n}\n\n/**\n * Why CSS would drop a template: rows of unequal length, or an area whose cells\n * do not fill a rectangle.\n *\n * @param grid A grid config; one that sets no `areas` has no issue.\n *\n * @remarks\n * Each issue's `path` is relative to the grid: `['areas']` for the array form of the default\n * template, else `['areas', slot]`. Rows of unequal length stop the check for that template, as no\n * area can be located in a ragged one.\n */\nexport function areaTemplateIssues(grid: unknown): LayoutIssue[] {\n\tconst templates = gridAreaTemplates(grid);\n\tconst arrayForm = isRecord(grid) && Array.isArray(grid.areas);\n\tconst issues: LayoutIssue[] = [];\n\tfor (const slot of CASCADE_SLOTS) {\n\t\tconst rows = templates[slot];\n\t\tif (!rows) continue;\n\t\tconst path = arrayForm ? ['areas'] : ['areas', slot];\n\t\tconst width = rows[0]?.length ?? 0;\n\t\tconst ragged = rows.findIndex((row) => row.length !== width);\n\t\tif (ragged !== -1) {\n\t\t\tissues.push({\n\t\t\t\tpath,\n\t\t\t\tmessage: `row ${ragged + 1} has ${cellCount(rows[ragged]?.length ?? 0)} but row 1 has ${width}.`,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tfor (const name of areaNames(rows)) {\n\t\t\tif (!isRectangle(rows, name)) {\n\t\t\t\tissues.push({\n\t\t\t\t\tpath,\n\t\t\t\t\tmessage: `area '${name}' is not rectangular; CSS drops the whole template unless every area fills a rectangle.`,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\treturn issues;\n}\n", "import type { ElementGridConfig, GridGapToken, GridLayoutConfig, GridOffsetName, GridWidthName } from '@/schemas/grid';\nimport type { DeepReadonly } from '@/lib/deep-readonly';\nimport { GridGapTokens } from '@/schemas/grid';\nimport {\n\tareasTemplateValue,\n\tBREAKPOINT_ORDER,\n\tcarryNamedPlacement,\n\tCASCADE_SLOTS,\n\tgridAreaTemplates,\n\tusesGridWidths,\n\tWIDTH_SPANS,\n\tWIDTH_TRACKS,\n\ttype CascadeSlot,\n\ttype GridBreakpointToken,\n\ttype NamedPlacement,\n} from '@/lib/grid-placement';\n\n/**\n * Maps authored grid values to theme-scoped CSS variables.\n *\n * @remarks\n * The theme owns the grid vocabulary: breakpoint thresholds, gap tokens,\n * and the default minimum column width. The document owns layout intent:\n * columns, responsive changes, gap selection, item placement.\n *\n * Compile once, with the rest of the layout theme ({@link createLayoutTheme}); renderers\n * emit the resulting stylesheet and per-container CSS variables inline. Breakpoint\n * behavior lives entirely in the generated media queries \u2014 no runtime\n * observers, and layout is correct with JavaScript disabled.\n *\n * Cascade contract for sparse responsive entries (see tests): initialize from\n * top-level values, apply `responsive.default`, then each successive\n * breakpoint. Within an entry, axis-specific gaps (`gapX`/`gapY`) beat the\n * entry's general `gap`.\n *\n * `place-*` shorthands are resolved into their axis longhands here rather than\n * emitted as CSS. A shorthand declaration would have to follow the longhands\n * in the generated rule and would then reset them, so authored `justifyItems`\n * or `justifySelf` could never take effect. Resolving in one place also lets\n * `placeSelf` join the responsive cascade for free.\n *\n * Only authored values are emitted, as custom properties (not camelCase CSS\n * keys) so the return type is a `--*` record assignable to React\n * `CSSProperties` and to inline `style` attributes without a cast. Neutral\n * defaults, the breakpoint cascade, and the resets that stop a nested grid\n * inheriting its parent's placement all live in the generated stylesheet.\n */\n\n/**\n * Inline style consisting only of CSS custom properties.\n *\n * @remarks\n * React 19 `CSSProperties` indexes `--${string}`; a `string` index does not,\n * which is why earlier `Record<string, string>` returns needed a cast.\n */\nexport type CssVariables = {\n\t[property: `--${string}`]: string | undefined;\n};\n\nexport interface GridThemeOptions {\n\t/**\n\t * Breakpoint thresholds in CSS lengths (`rem` recommended for zoom).\n\t * Overrides only the named token; the rest keep library defaults.\n\t *\n\t * @remarks\n\t * Configured thresholds must preserve named cascade order\n\t * (`sm \u2264 md \u2264 lg \u2264 xl \u2264 2xl`). `rem`/`em` values are compared at a 16px\n\t * root so mixed units cannot invert the sequence.\n\t */\n\tbreakpoints?: Partial<Record<GridBreakpointToken, string>>;\n\t/** Gap token definitions as CSS values, overriding only the named tokens. */\n\tgap?: GridGapScale;\n\t/** Default minimum column width used by `columns: 'auto'` grids. */\n\tminColumnWidth?: string;\n\t/**\n\t * Token values that change from a breakpoint up.\n\t *\n\t * @remarks\n\t * Breakpoint-major, like a document's own `responsive`: one entry per width\n\t * listing the tokens that change there, rather than one entry per token\n\t * listing its widths. Base values stay in `gap`, so there is no `default`\n\t * entry here \u2014 and no collision between the `default` *token* and a\n\t * `default` *slot*.\n\t *\n\t * Tokens are axis-agnostic: a document picks which token each axis uses via\n\t * `gapX`/`gapY`, so a theme never declares an axis.\n\t *\n\t * ```ts\n\t * grid: {\n\t * gap: { default: '1rem', loose: '1.5rem' },\n\t * responsive: {\n\t * md: { default: '1.25rem' },\n\t * lg: { default: '1.5rem', loose: '2rem' },\n\t * },\n\t * }\n\t * ```\n\t */\n\tresponsive?: Partial<Record<GridBreakpointToken, GridGapScale>>;\n}\n\n/** Gap token values at one width. Unlisted tokens keep the value from the next narrower width. */\nexport type GridGapScale = Partial<Record<GridGapToken, string>>;\n\nexport interface NormalizedGridTheme {\n\treadonly breakpoints: Readonly<Record<GridBreakpointToken, string>>;\n\treadonly gap: Readonly<Record<GridGapToken, string>>;\n\t/** Token overrides per breakpoint; only the tokens a width changes. */\n\treadonly responsive: Readonly<Partial<Record<GridBreakpointToken, Readonly<GridGapScale>>>>;\n\treadonly minColumnWidth: string;\n}\n\nconst DEFAULT_BREAKPOINTS: Record<GridBreakpointToken, string> = {\n\tsm: '40rem',\n\tmd: '48rem',\n\tlg: '64rem',\n\txl: '80rem',\n\t'2xl': '96rem',\n};\n\nconst DEFAULT_GAP: Record<GridGapToken, string> = {\n\tnone: '0',\n\tcompact: '0.5rem',\n\tdefault: 'var(--space-stack, 1rem)',\n\tloose: 'var(--space-block-lg, 1.5rem)',\n\twide: 'var(--space-block-xl, 2rem)',\n};\n\nconst DEFAULT_MIN_COLUMN_WIDTH = '15.625rem';\n\n/**\n * Public gap tokens. Hosts override these at `:root` to restyle every grid.\n *\n * @remarks\n * The theme must never declare these on an element: an element's own\n * declaration beats an inherited one, which would make the documented `:root`\n * override a no-op. The theme's value is declared under\n * {@link gapBaseVariable} instead and reached through a `var()` fallback.\n *\n * A host override therefore replaces the token at *every* width, including one\n * a theme ramps through `responsive` \u2014 the public token is the first `var()`\n * argument and a ramp only ever redeclares the fallback. A host that wants its\n * own rhythm declares its own media queries.\n */\nconst GAP_TOKEN_VARIABLES: Record<GridGapToken, `--${string}`> = {\n\tnone: '--se-grid-gap-none',\n\tcompact: '--se-grid-gap-compact',\n\tdefault: '--se-grid-gap-default',\n\tloose: '--se-grid-gap-loose',\n\twide: '--se-grid-gap-wide',\n};\n\n/** Theme default for a gap token, shadowed by the public token when a host sets it. */\nfunction gapBaseVariable(token: GridGapToken): `--${string}` {\n\treturn `--se-grid-gap-base-${token}`;\n}\n\n/** A gap token as CSS: the host's override if present, else the theme default. */\nfunction gapTokenValue(token: GridGapToken): string {\n\treturn `var(${GAP_TOKEN_VARIABLES[token]}, var(${gapBaseVariable(token)}))`;\n}\n\nconst DEFAULT_GAP_CSS = gapTokenValue('default');\n\n/**\n * Display a visible item falls back to.\n *\n * @remarks\n * The item rule outranks a component's own `display` (class plus attribute\n * beats a lone class), so a host that needs its own layout sets\n * `--se-item-display-mode` rather than `display`. Responsive `hidden` then\n * toggles between `none` and that mode instead of forcing `block`.\n */\nconst ITEM_DISPLAY_MODE = 'var(--se-item-display-mode, block)';\n\n/** Root font size used when comparing `rem`/`em` breakpoint thresholds. */\nconst ROOT_FONT_PX = 16;\n\ntype CssLengthUnit = 'px' | 'rem' | 'em';\n\n/** CSS property, its variable base name, and the value used when unauthored. */\ntype ResponsiveProperty = readonly [property: string, variable: string, fallback: string];\n\nfunction deepFreeze<T extends object>(value: T): T {\n\tObject.freeze(value);\n\tfor (const child of Object.values(value)) {\n\t\tif (child !== null && typeof child === 'object' && !Object.isFrozen(child)) {\n\t\t\tdeepFreeze(child);\n\t\t}\n\t}\n\treturn value;\n}\n\n/** Drops empty entries so an unramped theme normalizes to `{}` and emits nothing extra. */\nfunction resolveResponsiveGap(\n\toverrides?: Partial<Record<GridBreakpointToken, GridGapScale>>,\n): Partial<Record<GridBreakpointToken, GridGapScale>> {\n\tconst resolved: Partial<Record<GridBreakpointToken, GridGapScale>> = {};\n\tfor (const breakpoint of BREAKPOINT_ORDER) {\n\t\tconst entry = overrides?.[breakpoint];\n\t\tconst tokens = GridGapTokens.filter((token) => entry?.[token] !== undefined);\n\t\tif (tokens.length > 0) {\n\t\t\tresolved[breakpoint] = Object.fromEntries(tokens.map((token) => [token, entry![token]])) as GridGapScale;\n\t\t}\n\t}\n\treturn resolved;\n}\n\n/**\n * Resolves the immutable grid theme from the `grid` option of a layout theme.\n *\n * @remarks\n * Threshold overrides replace only the named breakpoint; the rest keep\n * library defaults. Thresholds accept `px`/`rem`/`em` lengths and must\n * preserve named cascade order. `rem`/`em` compare at a 16px root.\n * Media queries follow viewport width \u2014 a grid inside a narrow sidebar\n * still receives the desktop rules of the wide screen it lives on.\n */\nexport function resolveGridTheme(options?: GridThemeOptions): NormalizedGridTheme {\n\tconst breakpoints = { ...DEFAULT_BREAKPOINTS, ...options?.breakpoints };\n\tconst gap = { ...DEFAULT_GAP, ...options?.gap };\n\tconst responsive = resolveResponsiveGap(options?.responsive);\n\tconst minColumnWidth = options?.minColumnWidth ?? DEFAULT_MIN_COLUMN_WIDTH;\n\tassertBreakpointOrder(breakpoints);\n\treturn deepFreeze({\n\t\tbreakpoints,\n\t\tgap,\n\t\tresponsive,\n\t\tminColumnWidth,\n\t});\n}\n\nfunction isCssLengthUnit(unit: string | undefined): unit is CssLengthUnit {\n\treturn unit === 'px' || unit === 'rem' || unit === 'em';\n}\n\nfunction thresholdToPx(token: GridBreakpointToken, threshold: string): number {\n\tconst match = /^(\\d+(?:\\.\\d+)?)(px|rem|em)$/.exec(threshold);\n\tconst rawUnit = match?.[2];\n\tif (!match || !isCssLengthUnit(rawUnit)) {\n\t\tthrow new Error(`Grid theme breakpoint '${token}' must be a px, rem, or em length; received '${threshold}'.`);\n\t}\n\tconst value = Number(match[1]);\n\treturn rawUnit === 'px' ? value : value * ROOT_FONT_PX;\n}\n\nfunction assertBreakpointOrder(breakpoints: Record<GridBreakpointToken, string>): void {\n\tlet previousPx = Number.NEGATIVE_INFINITY;\n\tlet previousToken: GridBreakpointToken | undefined;\n\tfor (const token of BREAKPOINT_ORDER) {\n\t\tconst threshold = breakpoints[token];\n\t\tconst px = thresholdToPx(token, threshold);\n\t\tif (previousToken !== undefined && px < previousPx) {\n\t\t\tthrow new Error(\n\t\t\t\t`Grid theme breakpoints must preserve cascade order sm \u2264 md \u2264 lg \u2264 xl \u2264 2xl (rem/em compared at ${ROOT_FONT_PX}px root); '${token}' (${threshold}) is smaller than '${previousToken}' (${breakpoints[previousToken]}).`,\n\t\t\t);\n\t\t}\n\t\tpreviousPx = px;\n\t\tpreviousToken = token;\n\t}\n}\n\n/**\n * Responsive gap overrides as ordered pairs, independent of authored key order.\n *\n * @remarks\n * These come from consumer options, so `{ md, lg }` and `{ lg, md }` describe\n * one theme with different `JSON.stringify` output. Hashing that directly would\n * mint two ids for the same theme and emit its stylesheet twice under different\n * scopes, defeating the sharing of one compiled theme.\n */\nfunction canonicalResponsiveGap(\n\tresponsive: Readonly<Partial<Record<GridBreakpointToken, Readonly<GridGapScale>>>>,\n): Array<[string, Array<[string, string]>]> {\n\treturn BREAKPOINT_ORDER.flatMap((breakpoint) => {\n\t\tconst entry = responsive[breakpoint];\n\t\tif (!entry) return [];\n\t\tconst tokens = GridGapTokens.flatMap((token) => {\n\t\t\tconst value = entry[token];\n\t\t\treturn value === undefined ? [] : [[token, value] as [string, string]];\n\t\t});\n\t\treturn [[breakpoint, tokens] as [string, Array<[string, string]>]];\n\t});\n}\n\n/** The normalized grid theme in a stable shape, for hashing into a layout theme id. */\nexport function canonicalGridTheme(theme: NormalizedGridTheme) {\n\treturn {\n\t\tbreakpoints: theme.breakpoints,\n\t\tgap: theme.gap,\n\t\tresponsive: canonicalResponsiveGap(theme.responsive),\n\t\tminColumnWidth: theme.minColumnWidth,\n\t};\n}\n\n/**\n * Class a grid container carries, and the stylesheet's hook for it.\n *\n * @remarks\n * Neutral on purpose: a domain's renderer adds this beside its own class,\n * so a step, a page section and a container of any domain share one set of rules. The stylesheet\n * keys on this class, {@link GRID_ITEM_CLASS} and `[data-se-theme]` only, with no alias for a\n * domain's own class.\n */\nexport const GRID_CLASS = 'se-grid';\n\n/** Class an element placed in a grid carries, and the stylesheet's hook for it. See {@link GRID_CLASS}. */\nexport const GRID_ITEM_CLASS = 'se-grid-item';\n\n/**\n * Grid container properties that change per breakpoint.\n *\n * @remarks\n * One table drives the base rule, every media query, and the inheritance\n * resets, so a property cannot be declared at one width and forgotten at\n * another.\n */\nconst GRID_PROPERTIES: readonly ResponsiveProperty[] = [\n\t['grid-template-columns', 'se-grid-template', 'repeat(1, minmax(0, 1fr))'],\n\t['grid-template-areas', 'se-grid-areas', 'none'],\n\t['row-gap', 'se-grid-gap-y', DEFAULT_GAP_CSS],\n\t['column-gap', 'se-grid-gap-x', DEFAULT_GAP_CSS],\n];\n\n/**\n * Placement an item takes when it sets none, declared on its grid.\n *\n * @remarks\n * A grid whose items use named widths has 12 tracks, so an item that sets no\n * width would otherwise fall into one of them. The grid declares `1 / -1` here\n * and the item's `grid-column` falls back to it, which keeps the rule in the\n * stylesheet. The grid rule resets it so a nested grid does not inherit its\n * parent's default.\n */\nconst DEFAULT_COLUMN_VARIABLE = '--se-grid-default-column';\n\n/**\n * Item placement properties that change per breakpoint.\n *\n * @remarks\n * `justify-self`/`align-self` fall back to `auto`, which defers to the grid's\n * own `justify-items`/`align-items`. Any other fallback would silently beat\n * grid-level alignment on every item.\n */\nconst ITEM_PROPERTIES: readonly ResponsiveProperty[] = [\n\t['display', 'se-item-display', ITEM_DISPLAY_MODE],\n\t['grid-column', 'se-item-grid-column', `var(${DEFAULT_COLUMN_VARIABLE}, auto)`],\n\t['grid-row', 'se-item-grid-row', 'auto'],\n\t['justify-self', 'se-item-justify-self', 'auto'],\n\t['align-self', 'se-item-align-self', 'auto'],\n\t['margin-block-start', 'se-item-margin-block-start', '0'],\n\t['margin-block-end', 'se-item-margin-block-end', '0'],\n];\n\n/** Grid alignment, authored once for all widths. */\nconst GRID_ALIGNMENT_PROPERTIES: readonly ResponsiveProperty[] = [\n\t['justify-items', 'se-grid-justify-items', 'normal'],\n\t['align-items', 'se-grid-align-items', 'normal'],\n\t['justify-content', 'se-grid-justify-content', 'normal'],\n\t['align-content', 'se-grid-align-content', 'start'],\n];\n\n/** Removes the space after each comma of a stylesheet-only fallback, which `var()` ignores. */\nfunction tight(fallback: string): string {\n\treturn fallback.replaceAll(', ', ',');\n}\n\n/**\n * Name of the stylesheet-private custom property that gates one cascade slot of one table row.\n *\n * @remarks\n * A gate is declared inside the slot's media query as a copy of the public slot variable, so\n * outside that query it is the guaranteed-invalid value and the `var()` chain skips it. The names\n * are private to the stylesheet (a form never writes them, and they carry no contract) and carry\n * the theme id: custom properties inherit, so a gate named alike in two themes would let a theme\n * with a wider threshold read the gate its ancestor's narrower query declared. Within one theme\n * every element the rules reach declares its own gates wherever the query applies, so no reset\n * is needed.\n *\n * Read a name in devtools as theme id, table (`g` grid, `i` item), the property's row in that\n * table, and the breakpoint token: `--l1abc-i1md` is the `md` gate of the item `grid-column`.\n */\nfunction gateName(themeId: string, table: string, row: number, slot: GridBreakpointToken): string {\n\treturn `--${themeId}-${table}${row}${slot}`;\n}\n\n/**\n * `var(--g-2xl, var(--g-xl, ... var(--x, fallback)))`: the widest slot whose media query applies wins.\n *\n * @remarks\n * The chain is written once, in the base rule. A slot's gate is declared only inside its media\n * query (see {@link gateName}), so the cascade across widths costs one short declaration per slot\n * instead of restating the whole chain in every query. An unset slot resolves to the nearest\n * narrower one, so a renderer emits only the breakpoints an author wrote.\n */\nfunction cascadingVar(themeId: string, table: string, row: number, variable: string, fallback: string): string {\n\tlet value = `var(--${variable},${tight(fallback)})`;\n\tfor (const slot of BREAKPOINT_ORDER) {\n\t\tvalue = `var(${gateName(themeId, table, row, slot)},${value})`;\n\t}\n\treturn value;\n}\n\nfunction declarations(themeId: string, table: string, properties: readonly ResponsiveProperty[]): string {\n\treturn properties\n\t\t.map(\n\t\t\t([property, variable, fallback], row) =>\n\t\t\t\t`${property}:${cascadingVar(themeId, table, row, variable, fallback)};`,\n\t\t)\n\t\t.join('');\n}\n\n/** Alignment is authored once for all widths, so it has no slots and no gates. */\nfunction flatDeclarations(properties: readonly ResponsiveProperty[]): string {\n\treturn properties\n\t\t.map(([property, variable, fallback]) => `${property}:var(--${variable},${tight(fallback)});`)\n\t\t.join('');\n}\n\n/** One slot's gates: each property's public slot variable, copied inside the slot's media query. */\nfunction gates(\n\tthemeId: string,\n\ttable: string,\n\tproperties: readonly ResponsiveProperty[],\n\tslot: GridBreakpointToken,\n): string {\n\treturn properties\n\t\t.map(([, variable], row) => `${gateName(themeId, table, row, slot)}:var(--${variable}-${slot});`)\n\t\t.join('');\n}\n\n/**\n * Resets every slot so custom properties do not inherit past a host.\n *\n * @remarks\n * Custom properties inherit, so a nested grid or item would otherwise pick up\n * its ancestor's placement. `initial` makes `var()` fall through to the chain\n * above, and an inline value on the same element still wins the cascade.\n * Only a table with slots resets them: alignment is authored once for all widths, so its\n * slot variables are never written and never read.\n */\nfunction inheritanceResets(properties: readonly ResponsiveProperty[], withSlots: boolean): string {\n\treturn properties\n\t\t.flatMap(([, variable]) => [\n\t\t\t`--${variable}`,\n\t\t\t...(withSlots ? BREAKPOINT_ORDER.map((slot) => `--${variable}-${slot}`) : []),\n\t\t])\n\t\t.map((name) => `${name}:initial;`)\n\t\t.join('');\n}\n\n/**\n * Generates the theme-scoped stylesheet.\n *\n * @remarks\n * Rules are scoped under `[data-se-theme=\"<id>\"]`, which the renderer\n * places on every grid container and item, so two themes that differ\n * cannot overwrite each other. Item rules are scoped under the item that\n * carries the theme attribute so nested grids do not leak styles across themes.\n * Selectors use only {@link GRID_CLASS}, {@link GRID_ITEM_CLASS} and that attribute.\n *\n * Each responsive property is declared once, in the base rule, as a `var()` chain over the\n * slot gates ({@link gateName}); a media query only declares the gates of its slot.\n *\n * @param theme The resolved grid vocabulary.\n * @param themeId The id of the layout theme the rules are scoped to.\n */\nexport function getGridThemeCss(theme: NormalizedGridTheme, themeId: string): string {\n\tconst scope = `[data-se-theme=\"${themeId}\"]`;\n\tconst gridScope = `.${GRID_CLASS}${scope}`;\n\tconst itemScope = `.${GRID_ITEM_CLASS}${scope}`;\n\tconst tokens = GridGapTokens.map((token) => `${gapBaseVariable(token)}:${theme.gap[token]};`).join('');\n\tconst lines: string[] = [\n\t\t`${scope}{${tokens}}`,\n\t\t`${gridScope}{${inheritanceResets(GRID_PROPERTIES, true)}${inheritanceResets(GRID_ALIGNMENT_PROPERTIES, false)}${DEFAULT_COLUMN_VARIABLE}:initial;display:grid;${declarations(themeId, 'g', GRID_PROPERTIES)}${flatDeclarations(GRID_ALIGNMENT_PROPERTIES)}}`,\n\t\t`${itemScope}{${inheritanceResets(ITEM_PROPERTIES, true)}${declarations(themeId, 'i', ITEM_PROPERTIES)}}`,\n\t];\n\tfor (const breakpoint of BREAKPOINT_ORDER) {\n\t\tconst ramped = theme.responsive[breakpoint];\n\t\tconst rampedTokens = ramped\n\t\t\t? GridGapTokens.filter((token) => ramped[token] !== undefined)\n\t\t\t\t\t.map((token) => `${gapBaseVariable(token)}:${ramped[token]};`)\n\t\t\t\t\t.join('')\n\t\t\t: '';\n\t\tlines.push(\n\t\t\t`@media (min-width:${theme.breakpoints[breakpoint]}){${rampedTokens ? `${scope}{${rampedTokens}}` : ''}${gridScope}{${gates(themeId, 'g', GRID_PROPERTIES, breakpoint)}}${itemScope}{${gates(themeId, 'i', ITEM_PROPERTIES, breakpoint)}}}`,\n\t\t);\n\t}\n\treturn lines.join('\\n');\n}\n\nfunction isGridGapToken(value: string): value is GridGapToken {\n\tfor (const token of GridGapTokens) {\n\t\tif (token === value) return true;\n\t}\n\treturn false;\n}\n\n/**\n * Maps an authored gap value (semantic token or raw CSS value) to its\n * variable reference or literal.\n */\nfunction resolveGridGap(value: string | undefined): string | undefined {\n\tif (value === undefined) return undefined;\n\tif (isGridGapToken(value)) {\n\t\treturn gapTokenValue(value);\n\t}\n\treturn value;\n}\n\n/** Keywords that qualify the position keyword that follows them. */\nconst AXIS_QUALIFIERS = new Set(['safe', 'unsafe', 'first', 'last']);\n\n/**\n * Splits a `place-*` shorthand into `[align, justify]` per the CSS grammar.\n *\n * @remarks\n * The shorthand is align-first and a single axis value sets both axes \u2014 but an\n * axis value can be two keywords, an overflow position (`safe`/`unsafe`) or a\n * baseline modifier (`first`/`last`) plus its position. So `safe center` is one\n * value for both axes, while `center start` is one value per axis. Splitting on\n * whitespace alone would emit `align-self: safe`, which is not valid CSS.\n */\nfunction splitPlaceShorthand(value: string | undefined): [string | undefined, string | undefined] {\n\tif (value === undefined) return [undefined, undefined];\n\tconst tokens = value.trim().split(/\\s+/).filter(Boolean);\n\tif (tokens.length === 0) return [undefined, undefined];\n\tconst alignLength = AXIS_QUALIFIERS.has(tokens[0] as string) && tokens.length > 1 ? 2 : 1;\n\tconst align = tokens.slice(0, alignLength).join(' ');\n\tconst justify = alignLength < tokens.length ? tokens.slice(alignLength).join(' ') : align;\n\treturn [align, justify];\n}\n\nfunction toGridTemplate(columns: number | 'auto', minColumnWidth: string): string {\n\tif (columns === 'auto') {\n\t\treturn `repeat(auto-fit, minmax(min(${minColumnWidth}, 100%), 1fr))`;\n\t}\n\treturn `repeat(${columns}, minmax(0, 1fr))`;\n}\n\nfunction customProperty(name: string, slot: CascadeSlot): `--${string}` {\n\treturn slot === 'default' ? `--${name}` : `--${name}-${slot}`;\n}\n\n/** Layout values a single cascade slot may set; the top-level config is the `default` slot. */\ninterface GridEntry {\n\tcolumns?: number | 'auto';\n\tminColumnWidth?: string;\n\tgap?: string;\n\tgapX?: string;\n\tgapY?: string;\n}\n\n/** Placement a single cascade slot may set; the top-level config is the `default` slot. */\ninterface GridItemEntry {\n\tarea?: string;\n\twidth?: GridWidthName;\n\toffset?: GridOffsetName;\n\tcolumn?: number | string;\n\trow?: number | string;\n\tjustifySelf?: string;\n\talignSelf?: string;\n\thidden?: boolean;\n\tmarginBlockStart?: string;\n\tmarginBlockEnd?: string;\n}\n\nfunction emitGapEntry(variables: CssVariables, slot: CascadeSlot, entry: GridEntry | undefined): void {\n\tif (!entry) return;\n\tconst entryGap = resolveGridGap(entry.gap);\n\tconst gapX = resolveGridGap(entry.gapX) ?? entryGap;\n\tconst gapY = resolveGridGap(entry.gapY) ?? entryGap;\n\tif (gapY !== undefined) variables[customProperty('se-grid-gap-y', slot)] = gapY;\n\tif (gapX !== undefined) variables[customProperty('se-grid-gap-x', slot)] = gapX;\n}\n\n/**\n * Resolves a grid against the theme into one inline style record.\n *\n * @remarks\n * Only values an author wrote are emitted; the generated stylesheet falls back\n * through the narrower breakpoints, so an unconfigured grid carries no inline\n * style. `columns` and `minColumnWidth` are the one coupled pair \u2014 they share a\n * single template \u2014 so they are the only values carried across slots. Axis\n * properties win over the matching `placeItems`/`placeContent` shorthand.\n *\n * When `elements` (the items this grid places) use named widths, the grid\n * gets 12 tracks and a `1 / -1` default placement for items that set no width. Validation keeps that from meeting `columns`.\n *\n * A grid with `areas` gets the template of each slot that sets one: the quoted\n * rows as `--se-grid-areas` and the track count they draw as `--se-grid-template`,\n * derived from the rows rather than authored, as with named widths.\n */\nexport function getGridVariables(\n\tgrid: DeepReadonly<GridLayoutConfig> | undefined,\n\ttheme: NormalizedGridTheme,\n\telements: readonly unknown[],\n): CssVariables {\n\tconst variables: CssVariables = {};\n\n\tconst [placeAlignItems, placeJustifyItems] = splitPlaceShorthand(grid?.placeItems);\n\tconst [placeAlignContent, placeJustifyContent] = splitPlaceShorthand(grid?.placeContent);\n\tconst alignment: Record<string, string | undefined> = {\n\t\t'--se-grid-justify-items': grid?.justifyItems ?? placeJustifyItems,\n\t\t'--se-grid-align-items': grid?.alignItems ?? placeAlignItems,\n\t\t'--se-grid-justify-content': grid?.justifyContent ?? placeJustifyContent,\n\t\t'--se-grid-align-content': grid?.alignContent ?? placeAlignContent,\n\t};\n\tfor (const [name, value] of Object.entries(alignment)) {\n\t\tif (value !== undefined) variables[name as `--${string}`] = value;\n\t}\n\n\tlet columns: number | 'auto' = 1;\n\tlet minColumnWidth = theme.minColumnWidth;\n\tconst emitTemplate = (slot: CascadeSlot, entry: GridEntry | undefined): void => {\n\t\tif (!entry) return;\n\t\tif (entry.columns === undefined && entry.minColumnWidth === undefined) return;\n\t\tif (entry.columns !== undefined) columns = entry.columns;\n\t\tif (entry.minColumnWidth !== undefined) minColumnWidth = entry.minColumnWidth;\n\t\tvariables[customProperty('se-grid-template', slot)] = toGridTemplate(columns, minColumnWidth);\n\t};\n\n\tif (usesGridWidths(elements)) {\n\t\tvariables['--se-grid-template'] = `repeat(${WIDTH_TRACKS}, minmax(0, 1fr))`;\n\t\tvariables[DEFAULT_COLUMN_VARIABLE] = '1 / -1';\n\t}\n\n\tconst templates = gridAreaTemplates(grid);\n\tfor (const slot of CASCADE_SLOTS) {\n\t\tconst rows = templates[slot];\n\t\tif (!rows) continue;\n\t\tvariables[customProperty('se-grid-areas', slot)] = areasTemplateValue(rows);\n\t\tvariables[customProperty('se-grid-template', slot)] = toGridTemplate(\n\t\t\trows[0]?.length ?? 1,\n\t\t\ttheme.minColumnWidth,\n\t\t);\n\t}\n\n\tconst responsive = grid?.responsive;\n\temitTemplate('default', grid);\n\temitTemplate('default', responsive?.default);\n\temitGapEntry(variables, 'default', grid);\n\temitGapEntry(variables, 'default', responsive?.default);\n\n\tfor (const breakpoint of BREAKPOINT_ORDER) {\n\t\temitTemplate(breakpoint, responsive?.[breakpoint]);\n\t\temitGapEntry(variables, breakpoint, responsive?.[breakpoint]);\n\t}\n\treturn variables;\n}\n\n/**\n * `grid-column` for a width and offset.\n *\n * @remarks\n * Both names resolve into one declaration, so a slot that authors only one of\n * them is emitted together with the other as the narrower slots left it \u2014\n * the same coupling `columns` and `minColumnWidth` have for the grid template.\n * An offset with no width runs to the end of the row.\n */\nfunction namedColumn({ width, offset }: NamedPlacement): string {\n\tconst start = offset === undefined ? undefined : WIDTH_SPANS[offset] + 1;\n\tif (width === undefined) return start === undefined ? 'auto' : `${start} / -1`;\n\tconst span = `span ${WIDTH_SPANS[width]}`;\n\treturn start === undefined ? span : `${start} / ${span}`;\n}\n\nfunction formatGridLine(value: number | string): string {\n\treturn typeof value === 'number' ? String(value) : value;\n}\n\nfunction emitItemEntry(\n\tvariables: CssVariables,\n\tslot: CascadeSlot,\n\tentry: GridItemEntry | undefined,\n\tnamed: NamedPlacement = {},\n): void {\n\tif (!entry) return;\n\tif (entry.width !== undefined || entry.offset !== undefined) {\n\t\tcarryNamedPlacement(named, entry);\n\t\tvariables[customProperty('se-item-grid-column', slot)] = namedColumn(named);\n\t}\n\tif (entry.area !== undefined) {\n\t\tvariables[customProperty('se-item-grid-column', slot)] = entry.area;\n\t\tvariables[customProperty('se-item-grid-row', slot)] = entry.area;\n\t}\n\tif (entry.column !== undefined) {\n\t\tvariables[customProperty('se-item-grid-column', slot)] = formatGridLine(entry.column);\n\t}\n\tif (entry.row !== undefined) variables[customProperty('se-item-grid-row', slot)] = formatGridLine(entry.row);\n\tif (entry.justifySelf !== undefined) variables[customProperty('se-item-justify-self', slot)] = entry.justifySelf;\n\tif (entry.alignSelf !== undefined) variables[customProperty('se-item-align-self', slot)] = entry.alignSelf;\n\tconst marginBlockStart = resolveGridGap(entry.marginBlockStart);\n\tif (marginBlockStart !== undefined) {\n\t\tvariables[customProperty('se-item-margin-block-start', slot)] = marginBlockStart;\n\t}\n\tconst marginBlockEnd = resolveGridGap(entry.marginBlockEnd);\n\tif (marginBlockEnd !== undefined) {\n\t\tvariables[customProperty('se-item-margin-block-end', slot)] = marginBlockEnd;\n\t}\n\tif (entry.hidden !== undefined) {\n\t\tvariables[customProperty('se-item-display', slot)] = entry.hidden ? 'none' : ITEM_DISPLAY_MODE;\n\t}\n}\n\n/**\n * Resolves a single element's grid placement and spacing into inline style variables.\n *\n * @remarks\n * Each slot emits exactly what its entry authored \u2014 no value is carried across\n * breakpoints, because the generated stylesheet already falls back through the\n * narrower slots. The one exception is `width` and `offset`, which share the\n * single `grid-column` declaration (see {@link namedColumn}). An `area` is one\n * name written to both `grid-column` and `grid-row`, where a lone name reads as\n * that area's start and end lines. An element without a `grid` config produces\n * no inline style.\n * `placeSelf` is applied before the axis properties, so those win.\n *\n * `marginBlockStart`/`marginBlockEnd` accept the same gap tokens as the grid, so\n * a one-off rhythm around a non-input element reads in the same vocabulary as\n * the grid's spacing. They ride the shared item property table rather than a\n * separate mechanism, which is what gives them the breakpoint cascade and the\n * inheritance resets for free \u2014 and keeps a single system owning the block axis\n * instead of two fighting over it.\n */\nexport function getGridItemVariables(grid?: ElementGridConfig): CssVariables {\n\tconst variables: CssVariables = {};\n\tconst [alignSelf, justifySelf] = splitPlaceShorthand(grid?.placeSelf);\n\n\tconst named: NamedPlacement = {};\n\temitItemEntry(variables, 'default', { alignSelf, justifySelf });\n\temitItemEntry(variables, 'default', grid, named);\n\temitItemEntry(variables, 'default', grid?.responsive?.default, named);\n\n\tfor (const breakpoint of BREAKPOINT_ORDER) {\n\t\temitItemEntry(variables, breakpoint, grid?.responsive?.[breakpoint], named);\n\t}\n\treturn variables;\n}\n", "import {\n\tassertAxisNotReserved,\n\tcompileAppearance,\n\tgetAppearanceCss,\n\ttype AnyAxisRegistration,\n\ttype AxisRegistry,\n\ttype CompiledAppearance,\n\ttype ResolvedAppearanceAxes,\n\ttype builtInAxes,\n} from '@/lib/appearance';\nimport {\n\tcanonicalGridTheme,\n\tgetGridThemeCss,\n\tresolveGridTheme,\n\ttype GridThemeOptions,\n\ttype NormalizedGridTheme,\n} from '@/lib/grid-styles';\n\n/** What an author writes: the grid vocabulary and the appearance vocabulary of one theme. */\nexport interface LayoutThemeOptions<\n\tTAppearance extends readonly AnyAxisRegistration[] = readonly AnyAxisRegistration[],\n> {\n\t/** Breakpoint thresholds, gap tokens and the default minimum column width. */\n\treadonly grid?: GridThemeOptions;\n\t/**\n\t * The axes a document picks values on, built with `defineAxis`. Defaults to {@link builtInAxes}.\n\t *\n\t * @remarks\n\t * A later axis with the same `$type` replaces the earlier one, so `[...builtInAxes, myAxis]` adds\n\t * an axis and overrides a built-in one. A list without the built-ins has none of them.\n\t */\n\treadonly appearance?: TAppearance;\n}\n\n/** Inputs to {@link createLayoutTheme} that come from the domain rather than the author. */\nexport interface LayoutThemeCompilerOptions {\n\t/**\n\t * Suffixes of the `data-se-*` attributes the domain's renderers already write, which an axis cannot reuse.\n\t *\n\t * @remarks\n\t * `getAppearanceAttributes` spreads after a renderer's own attributes on the same elements, so\n\t * an axis named like one would overwrite it. Each domain lists its own, so this package hard-codes none.\n\t */\n\treadonly reservedNames?: readonly string[];\n}\n\n/**\n * A compiled layout theme: the grid vocabulary and the appearance vocabulary, with one id and one\n * stylesheet.\n *\n * @remarks\n * Produced once by {@link createLayoutTheme}, frozen, and safe to share between consumers: engines\n * built on the same theme carry the same `data-se-theme` and the same stylesheet content.\n * A renderer puts `id` on the elements the stylesheet should reach, as `data-se-theme`, and\n * emits `css` for each form it renders: React hoists equal stylesheets to one element, while\n * Radiant inlines an identical copy per form, by design.\n */\nexport interface LayoutTheme<TAxes extends Record<string, string> = Record<string, string>> {\n\t/** Identity of the whole theme; the value of `data-se-theme` and the scope of every rule in `css`. */\n\treadonly id: string;\n\t/** The resolved grid vocabulary. */\n\treadonly grid: NormalizedGridTheme;\n\t/** Appearance axis name to its closed value list. */\n\treadonly axes: Readonly<{ [A in keyof TAxes]: readonly TAxes[A][] }>;\n\t/** The theme's axes as registrations: values, tokens, default and metadata. */\n\treadonly appearance: AxisRegistry;\n\t/** The stylesheet for grid and appearance together, scoped by `[data-se-theme=\"<id>\"]`. */\n\treadonly css: string;\n}\n\n/** What an engine accepts as its `layout` option: a compiled theme, or options to compile one. */\nexport type LayoutInput = LayoutTheme | LayoutThemeOptions;\n\n/**\n * Axis-to-value-union map a layout input gives an engine, for typed authoring.\n *\n * @remarks A compiled theme carries its axes; inline options give the built-in axes extended by `appearance`.\n */\nexport type LayoutAxes<TLayout> = TLayout extends { readonly axes: infer TAxes }\n\t? { [A in keyof TAxes]: TAxes[A] extends readonly (infer V extends string)[] ? V : never }\n\t: TLayout extends { readonly appearance: infer TAppearance extends readonly AnyAxisRegistration[] }\n\t\t? ResolvedAppearanceAxes<TAppearance>\n\t\t: ResolvedAppearanceAxes;\n\n/**\n * The brand every compiled theme carries, a non-enumerable property keyed by a registry symbol.\n *\n * @remarks\n * The key comes from `Symbol.for`, so a theme from a second copy of this module (a duplicate\n * install, or a page and a form bundled apart) is still recognised, and a theme keeps its id and\n * axes wherever it is passed. The property is non-enumerable and symbol-keyed, so a spread copy\n * and a JSON copy lose it: a copy is not a theme. A theme holds the axis registry, whose functions\n * a structured clone cannot copy, so `structuredClone(theme)` throws a `DataCloneError`.\n */\nconst LAYOUT_THEME_BRAND = Symbol.for('@schema-engine/layout/theme');\n\n/**\n * Whether a value is a theme made by {@link createLayoutTheme}, as opposed to options for one.\n *\n * @remarks A copy of a theme is not one: only the object the compiler returned carries the brand.\n */\nexport function isLayoutTheme(value: unknown): value is LayoutTheme {\n\treturn typeof value === 'object' && value !== null && Reflect.get(value, LAYOUT_THEME_BRAND) === true;\n}\n\n/**\n * The one hash behind a theme id: djb2 over the serialized theme, in base 36.\n *\n * @remarks A theme id is only ever minted by {@link createLayoutTheme}.\n */\nfunction hashThemeId(serialized: string): string {\n\tlet hash = 5381;\n\tfor (let index = 0; index < serialized.length; index += 1) {\n\t\thash = ((hash << 5) + hash + serialized.charCodeAt(index)) | 0;\n\t}\n\treturn `l${(hash >>> 0).toString(36)}`;\n}\n\nfunction canonicalAppearance(appearance: CompiledAppearance) {\n\treturn appearance.registry.all().map((axis) => [axis.$type, axis.default, Object.entries(axis.values)]);\n}\n\n/**\n * Compiles a grid vocabulary and an appearance vocabulary into one frozen theme.\n *\n * @remarks\n * The single construction boundary: one id, one stylesheet, one `data-se-theme` attribute. Options\n * that describe the same theme give the same id, whatever the key order of the grid's responsive\n * entries, so engines built from equal options share a stylesheet.\n *\n * Throws on a grid or axis that is invalid, and on an appearance axis named in\n * `reservedNames`: each domain lists the `data-se-*` attributes its renderers already write, so\n * this package hard-codes none.\n */\nexport function createLayoutTheme<const TAppearance extends readonly AnyAxisRegistration[] = typeof builtInAxes>(\n\toptions?: LayoutThemeOptions<TAppearance>,\n\tcompiler: LayoutThemeCompilerOptions = {},\n): LayoutTheme<ResolvedAppearanceAxes<TAppearance>> {\n\tconst grid = resolveGridTheme(options?.grid);\n\tconst appearance = compileAppearance(options?.appearance, compiler);\n\tconst id = hashThemeId(\n\t\tJSON.stringify({ grid: canonicalGridTheme(grid), appearance: canonicalAppearance(appearance) }),\n\t);\n\tconst css = [getGridThemeCss(grid, id), getAppearanceCss(appearance, id)].filter(Boolean).join('\\n');\n\tconst theme = { id, grid, axes: appearance.axes, appearance: appearance.registry, css };\n\tObject.defineProperty(theme, LAYOUT_THEME_BRAND, { value: true, enumerable: false });\n\tObject.freeze(theme);\n\treturn theme as unknown as LayoutTheme<ResolvedAppearanceAxes<TAppearance>>;\n}\n\nlet cachedDefaultLayoutTheme: LayoutTheme<ResolvedAppearanceAxes> | undefined;\n\n/** Frozen library-default theme; shared by engines built without a `layout` option. */\nexport function getDefaultLayoutTheme(): LayoutTheme<ResolvedAppearanceAxes> {\n\tcachedDefaultLayoutTheme ??= createLayoutTheme();\n\treturn cachedDefaultLayoutTheme;\n}\n\n/**\n * Throws when a compiled theme declares an appearance axis a domain reserves.\n *\n * @remarks\n * {@link createLayoutTheme} checks `reservedNames` as it compiles, but a theme compiled elsewhere\n * (or for another domain) reaches an engine without that check, so the engine runs this on it.\n */\nexport function assertAxesNotReserved(theme: LayoutTheme, reservedNames: readonly string[]): void {\n\tconst reserved = new Set(reservedNames);\n\tfor (const axis of Object.keys(theme.axes)) assertAxisNotReserved(axis, reserved);\n}\n"],
|
|
5
|
+
"mappings": "AAAA,OACC,kBAAAA,MAIM,0BACP,UAAYC,MAAO,WA4EnB,IAAMC,GAAY,kCACZC,GAAa,8BACbC,GAAqB,cACrBC,EAAkB,EAClBC,EAAkB,EAOjB,SAASC,EAAsBC,EAAkBC,EAAqC,CAC5F,GAAIA,EAAS,IAAID,CAAQ,EACx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vDD,GAASA,GAAQ,GAAKA,EAAOD,EAAW,WAAWE,CAAK,EAAK,EAE9D,MAAO,KAAKD,IAAS,GAAG,SAAS,EAAE,CAAC,EACrC,CAEA,SAASE,GAAoBC,EAAgC,CAC5D,OAAOA,EAAW,SAAS,IAAI,EAAE,IAAKC,GAAS,CAACA,EAAK,MAAOA,EAAK,QAAS,OAAO,QAAQA,EAAK,MAAM,CAAC,CAAC,CACvG,CAcO,SAASC,GACfC,EACAC,EAAuC,CAAC,EACW,CACnD,IAAMC,EAAOC,EAAiBH,GAAS,IAAI,EACrCH,EAAaO,EAAkBJ,GAAS,WAAYC,CAAQ,EAC5DI,EAAKb,GACV,KAAK,UAAU,CAAE,KAAMc,EAAmBJ,CAAI,EAAG,WAAYN,GAAoBC,CAAU,CAAE,CAAC,CAC/F,EACMU,EAAM,CAACC,EAAgBN,EAAMG,CAAE,EAAGI,EAAiBZ,EAAYQ,CAAE,CAAC,EAAE,OAAO,OAAO,EAAE,KAAK;AAAA,CAAI,EAC7FK,EAAQ,CAAE,GAAAL,EAAI,KAAAH,EAAM,KAAML,EAAW,KAAM,WAAYA,EAAW,SAAU,IAAAU,CAAI,EACtF,cAAO,eAAeG,EAAOrB,EAAoB,CAAE,MAAO,GAAM,WAAY,EAAM,CAAC,EACnF,OAAO,OAAOqB,CAAK,EACZA,CACR,CAEA,IAAIC,EAGG,SAASC,IAA6D,CAC5E,OAAAD,IAA6BZ,GAAkB,EACxCY,CACR,CASO,SAASE,GAAsBH,EAAoBI,EAAwC,CACjG,IAAMC,EAAW,IAAI,IAAID,CAAa,EACtC,QAAWhB,KAAQ,OAAO,KAAKY,EAAM,IAAI,EAAGM,EAAsBlB,EAAMiB,CAAQ,CACjF",
|
|
6
|
+
"names": ["createRegistry", "z", "AXIS_NAME", "VALUE_NAME", "UNSAFE_TOKEN_VALUE", "MIN_AXIS_VALUES", "MAX_AXIS_VALUES", "assertAxisNotReserved", "axisName", "reserved", "assertValidAxis", "axis", "name", "entries", "value", "tokens", "token", "tokenValue", "defineAxis", "definition", "sizeAxis", "surfaceAxis", "builtInAxes", "getAppearanceCss", "appearance", "themeId", "plain", "scoped", "scope", "foreign", "declarations", "block", "match", "descendant", "compileAppearance", "axes", "compiler", "registry", "z", "GridGapTokens", "GridGapValueSchema", "RESERVED_AREA_NAMES", "anyCase", "word", "char", "AREA_NAME_SOURCE", "GridAreaNameSchema", "perBreakpoint", "schema", "responsiveSchema", "GridAreaRowSchema", "GridAreaRowsSchema", "GridAreasSchema", "GridLayoutPropertiesSchema", "GridBreakpointConfigSchema", "GridLayoutConfigSchema", "GridWidthNames", "GridOffsetNames", "ElementGridPropertiesSchema", "ItemGridBreakpointSchema", "ElementGridConfigSchema", "BREAKPOINT_ORDER", "CASCADE_SLOTS", "DEFAULT_BREAKPOINTS", "DEFAULT_GAP", "DEFAULT_MIN_COLUMN_WIDTH", "GAP_TOKEN_VARIABLES", "gapBaseVariable", "token", "gapTokenValue", "DEFAULT_GAP_CSS", "ITEM_DISPLAY_MODE", "ROOT_FONT_PX", "deepFreeze", "value", "child", "resolveResponsiveGap", "overrides", "resolved", "breakpoint", "BREAKPOINT_ORDER", "entry", "tokens", "GridGapTokens", "resolveGridTheme", "options", "breakpoints", "gap", "responsive", "minColumnWidth", "assertBreakpointOrder", "isCssLengthUnit", "unit", "thresholdToPx", "threshold", "match", "rawUnit", "previousPx", "previousToken", "px", "canonicalResponsiveGap", "canonicalGridTheme", "theme", "GRID_CLASS", "GRID_ITEM_CLASS", "GRID_PROPERTIES", "DEFAULT_COLUMN_VARIABLE", "ITEM_PROPERTIES", "GRID_ALIGNMENT_PROPERTIES", "tight", "fallback", "gateName", "themeId", "table", "row", "slot", "cascadingVar", "variable", "declarations", "properties", "property", "flatDeclarations", "gates", "inheritanceResets", "withSlots", "name", "getGridThemeCss", "scope", "gridScope", "itemScope", "lines", "ramped", "rampedTokens", "LAYOUT_THEME_BRAND", "isLayoutTheme", "value", "hashThemeId", "serialized", "hash", "index", "canonicalAppearance", "appearance", "axis", "createLayoutTheme", "options", "compiler", "grid", "resolveGridTheme", "compileAppearance", "id", "canonicalGridTheme", "css", "getGridThemeCss", "getAppearanceCss", "theme", "cachedDefaultLayoutTheme", "getDefaultLayoutTheme", "assertAxesNotReserved", "reservedNames", "reserved", "assertAxisNotReserved"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type * as z from 'zod/mini';
|
|
2
|
+
import type { ProtocolRecipeRegistration, ProtocolRecipeSlotSchemas, ProtocolRecipeSpec } from './types';
|
|
3
|
+
/**
|
|
4
|
+
* @remarks
|
|
5
|
+
* Typed by the spec, so the registration carries the protocol's slot and kind names. Domains wrap it
|
|
6
|
+
* to type `render` for their renderers.
|
|
7
|
+
*
|
|
8
|
+
* The two casts widen `slotDefaults` and `appearanceAxes`: the spec types them by the slot schemas it
|
|
9
|
+
* was defined with (`RecipeSlotDefaults<TSlots>`, `SlotAppearanceAxes<keyof TSlots>`), and the
|
|
10
|
+
* registration by the protocol's slot names, which cannot be derived from the schemas generically.
|
|
11
|
+
*/
|
|
12
|
+
export declare function bindRecipe<TSlot extends string, TKind extends string, const TType extends string, TSchema extends z.ZodMiniType, TSlots extends ProtocolRecipeSlotSchemas<TSlot>, TRender>(spec: ProtocolRecipeSpec<TSlot, TKind, TType, TSchema, TSlots>, render: TRender): ProtocolRecipeRegistration<TSlot, TKind, TType, TSchema, TRender>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function o(e,t){return{$type:e.$type,kind:e.kind,slots:e.slots,schema:e.schema,metadata:e.metadata,slotDefaults:e.slotDefaults,appearanceAxes:e.appearanceAxes,render:t}}export{o as bindRecipe};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/recipes/bind-recipe.ts"],
|
|
4
|
+
"sourcesContent": ["import type * as z from 'zod/mini';\nimport type { SlotAppearanceAxes } from '../lib/appearance';\nimport type { ProtocolRecipeRegistration, ProtocolRecipeSlotSchemas, ProtocolRecipeSpec } from './types';\n\n/**\n * @remarks\n * Typed by the spec, so the registration carries the protocol's slot and kind names. Domains wrap it\n * to type `render` for their renderers.\n *\n * The two casts widen `slotDefaults` and `appearanceAxes`: the spec types them by the slot schemas it\n * was defined with (`RecipeSlotDefaults<TSlots>`, `SlotAppearanceAxes<keyof TSlots>`), and the\n * registration by the protocol's slot names, which cannot be derived from the schemas generically.\n */\nexport function bindRecipe<\n\tTSlot extends string,\n\tTKind extends string,\n\tconst TType extends string,\n\tTSchema extends z.ZodMiniType,\n\tTSlots extends ProtocolRecipeSlotSchemas<TSlot>,\n\tTRender,\n>(\n\tspec: ProtocolRecipeSpec<TSlot, TKind, TType, TSchema, TSlots>,\n\trender: TRender,\n): ProtocolRecipeRegistration<TSlot, TKind, TType, TSchema, TRender> {\n\treturn {\n\t\t$type: spec.$type,\n\t\tkind: spec.kind,\n\t\tslots: spec.slots,\n\t\tschema: spec.schema,\n\t\tmetadata: spec.metadata,\n\t\tslotDefaults: spec.slotDefaults as Partial<Record<TSlot, Record<string, unknown>>> | undefined,\n\t\tappearanceAxes: spec.appearanceAxes as SlotAppearanceAxes<TSlot> | undefined,\n\t\trender,\n\t};\n}\n"],
|
|
5
|
+
"mappings": "AAaO,SAASA,EAQfC,EACAC,EACoE,CACpE,MAAO,CACN,MAAOD,EAAK,MACZ,KAAMA,EAAK,KACX,MAAOA,EAAK,MACZ,OAAQA,EAAK,OACb,SAAUA,EAAK,SACf,aAAcA,EAAK,aACnB,eAAgBA,EAAK,eACrB,OAAAC,CACD,CACD",
|
|
6
|
+
"names": ["bindRecipe", "spec", "render"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import * as z from 'zod/mini';
|
|
2
|
+
import type { SlotAppearanceAxes } from '../lib/appearance';
|
|
3
|
+
import { type RecipeProtocol } from './protocol';
|
|
4
|
+
import type { RecipeMetadata, RecipeSlotDefaults, ProtocolRecipeSlotSchemas, ProtocolRecipeSpec } from './types';
|
|
5
|
+
/**
|
|
6
|
+
* Strict view schema of a spec: the literal `$type` plus each declared slot, which defaults to `{}`.
|
|
7
|
+
*
|
|
8
|
+
* @remarks
|
|
9
|
+
* A slot is an optional key on input and always present on output, parsed from `{}` when the author
|
|
10
|
+
* omits it, so each slot schema's own defaults fill it. Keeping the concrete object type, rather than `z.ZodMiniType`, lets the engine infer the
|
|
11
|
+
* authoring type of `view` from a registration.
|
|
12
|
+
*/
|
|
13
|
+
export type RecipeViewSchema<TType extends string, TSlots extends ProtocolRecipeSlotSchemas> = z.ZodMiniObject<{
|
|
14
|
+
$type: z.ZodMiniLiteral<TType>;
|
|
15
|
+
} & {
|
|
16
|
+
[K in keyof TSlots]: TSlots[K] extends z.ZodMiniType ? z.ZodMiniPrefault<TSlots[K]> : never;
|
|
17
|
+
}, z.core.$strict>;
|
|
18
|
+
/**
|
|
19
|
+
* What a domain passes to `defineProtocolRecipeSpec`; the slot and kind names come from its protocol.
|
|
20
|
+
*
|
|
21
|
+
* @remarks
|
|
22
|
+
* The slots come from `slotSchemas` alone: `slotDefaults` and `appearanceAxes` are checked
|
|
23
|
+
* against them but take no part in inference, so a spec can add a slot to another spec's schemas
|
|
24
|
+
* while reusing that spec's defaults.
|
|
25
|
+
*
|
|
26
|
+
* `slotSchemas` also maps every key outside the protocol's slots to `never`. The `TSlots` constraint
|
|
27
|
+
* alone accepts extra properties, so without it a slot the protocol does not declare would compile.
|
|
28
|
+
*/
|
|
29
|
+
export interface ProtocolRecipeSpecDefinition<TSlot extends string, TKind extends string, TType extends string, TSlots extends ProtocolRecipeSlotSchemas<TSlot>> {
|
|
30
|
+
$type: TType;
|
|
31
|
+
kind: NoInfer<TKind>;
|
|
32
|
+
metadata: RecipeMetadata;
|
|
33
|
+
slotSchemas?: TSlots & {
|
|
34
|
+
[K in Exclude<keyof TSlots, TSlot>]: never;
|
|
35
|
+
};
|
|
36
|
+
slotDefaults?: RecipeSlotDefaults<NoInfer<TSlots>>;
|
|
37
|
+
appearanceAxes?: SlotAppearanceAxes<keyof NoInfer<TSlots>>;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Declares a recipe's `$type`, kind, slot schemas, and metadata against a domain's protocol.
|
|
41
|
+
*
|
|
42
|
+
* @remarks
|
|
43
|
+
* The protocol decides which slots and kinds exist, in the types and at runtime, and its rules run
|
|
44
|
+
* here for an early failure. The spec lists its declared slots in the protocol's order.
|
|
45
|
+
*
|
|
46
|
+
* The rules run before the slots are listed, because listing filters the protocol's slots and would
|
|
47
|
+
* otherwise drop a slot the protocol does not declare without a word.
|
|
48
|
+
*/
|
|
49
|
+
export declare function defineProtocolRecipeSpec<TSlot extends string, TKind extends string, const TType extends string, const TSlots extends ProtocolRecipeSlotSchemas<TSlot> = Record<never, never>>(protocol: RecipeProtocol<TSlot, TKind>, definition: ProtocolRecipeSpecDefinition<TSlot, TKind, TType, TSlots>): ProtocolRecipeSpec<TSlot, TKind, TType, RecipeViewSchema<TType, TSlots>, TSlots>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import*as c from"zod/mini";import{createRegistry as f}from"@schema-engine/registry";function p(t,e){let o=t.kinds,s=t.slots;if(!o.includes(e.kind))throw new Error(`Recipe '${e.$type}' has kind '${e.kind}', which the protocol does not declare (kinds: ${t.kinds.join(", ")}).`);for(let r of e.slots)if(!s.includes(r))throw new Error(`Recipe '${e.$type}' declares slot '${r}', which the protocol does not declare (slots: ${t.slots.join(", ")}).`);for(let r of t.rules){let n=r.check(e);if(n!==void 0)throw new Error(`Recipe '${e.$type}' breaks rule '${r.name}': ${n}.`)}}function d(t,e){let o={$type:c.literal(t)};for(let[s,r]of Object.entries(e))r&&(o[s]=c.prefault(r,{}));return c.strictObject(o)}function T(t,e,o){for(let[s,r]of Object.entries(o??{})){let n=e[s];if(!n)throw new Error(`Recipe '${t}' slotDefaults.${s}: the recipe does not declare a '${s}' slot.`);let i=c.safeParse(n,r);if(!i.success){let a=i.error.issues.map(l=>`${[...l.path,..."keys"in l&&Array.isArray(l.keys)?l.keys:[]].join(".")||"(value)"}: ${l.message}`);throw new Error(`Recipe '${t}' slotDefaults.${s} is invalid: ${a.join("; ")}`)}}}function S(t,e,o){for(let[s,r]of Object.entries(o??{})){if(!r)continue;let n=e[s];if(!n)throw new Error(`Recipe '${t}' appearanceAxes.${s}: the recipe does not declare a '${s}' slot.`);if(c.safeParse(n,{appearance:{}}).error?.issues.some(l=>l.code==="unrecognized_keys"&&l.keys.includes("appearance")))throw new Error(`Recipe '${t}' appearanceAxes.${s}: the '${s}' slot schema must accept an 'appearance' key (z.optional(AppearanceConfigSchema)).`)}}function h(t,e){let o=e.slotSchemas??{},s=Object.keys(o).filter(i=>o[i]);p(t,{$type:e.$type,kind:e.kind,slots:s});let r=t.slots.filter(i=>o[i]);T(e.$type,o,e.slotDefaults),S(e.$type,o,e.appearanceAxes);let n=d(e.$type,o);return{$type:e.$type,kind:e.kind,slots:r,slotSchemas:o,slotDefaults:e.slotDefaults,appearanceAxes:e.appearanceAxes,metadata:e.metadata,schema:n}}export{h as defineProtocolRecipeSpec};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/recipes/define-recipe-spec.ts", "../../src/recipes/protocol.ts"],
|
|
4
|
+
"sourcesContent": ["import * as z from 'zod/mini';\nimport type { SlotAppearanceAxes } from '../lib/appearance';\nimport { assertRecipeRules, type RecipeProtocol } from './protocol';\nimport type { RecipeMetadata, RecipeSlotDefaults, ProtocolRecipeSlotSchemas, ProtocolRecipeSpec } from './types';\n\n/**\n * Strict view schema of a spec: the literal `$type` plus each declared slot, which defaults to `{}`.\n *\n * @remarks\n * A slot is an optional key on input and always present on output, parsed from `{}` when the author\n * omits it, so each slot schema's own defaults fill it. Keeping the concrete object type, rather than `z.ZodMiniType`, lets the engine infer the\n * authoring type of `view` from a registration.\n */\nexport type RecipeViewSchema<TType extends string, TSlots extends ProtocolRecipeSlotSchemas> = z.ZodMiniObject<\n\t{ $type: z.ZodMiniLiteral<TType> } & {\n\t\t[K in keyof TSlots]: TSlots[K] extends z.ZodMiniType ? z.ZodMiniPrefault<TSlots[K]> : never;\n\t},\n\tz.core.$strict\n>;\n\n/**\n * What a domain passes to `defineProtocolRecipeSpec`; the slot and kind names come from its protocol.\n *\n * @remarks\n * The slots come from `slotSchemas` alone: `slotDefaults` and `appearanceAxes` are checked\n * against them but take no part in inference, so a spec can add a slot to another spec's schemas\n * while reusing that spec's defaults.\n *\n * `slotSchemas` also maps every key outside the protocol's slots to `never`. The `TSlots` constraint\n * alone accepts extra properties, so without it a slot the protocol does not declare would compile.\n */\nexport interface ProtocolRecipeSpecDefinition<\n\tTSlot extends string,\n\tTKind extends string,\n\tTType extends string,\n\tTSlots extends ProtocolRecipeSlotSchemas<TSlot>,\n> {\n\t$type: TType;\n\tkind: NoInfer<TKind>;\n\tmetadata: RecipeMetadata;\n\tslotSchemas?: TSlots & { [K in Exclude<keyof TSlots, TSlot>]: never };\n\tslotDefaults?: RecipeSlotDefaults<NoInfer<TSlots>>;\n\tappearanceAxes?: SlotAppearanceAxes<keyof NoInfer<TSlots>>;\n}\n\n/**\n * @remarks\n * The shape is assembled dynamically from the same slot schemas that `RecipeViewSchema` maps over,\n * so the cast only restores the static type TypeScript cannot derive from a loop.\n */\nfunction mergeRecipeSlotSchemas<const TType extends string, const TSlots extends ProtocolRecipeSlotSchemas>(\n\t$type: TType,\n\tslotSchemas: TSlots,\n): RecipeViewSchema<TType, TSlots> {\n\tconst shape: Record<string, z.ZodMiniType> = {\n\t\t$type: z.literal($type),\n\t};\n\n\tfor (const [slot, schema] of Object.entries(slotSchemas)) {\n\t\tif (schema) {\n\t\t\tshape[slot] = z.prefault(schema, {});\n\t\t}\n\t}\n\n\treturn z.strictObject(shape) as unknown as RecipeViewSchema<TType, TSlots>;\n}\n\n/**\n * @remarks\n * Validation only: the parsed output is discarded. The defaults are merged under the author's\n * slot config before the view schema parses, so schema defaults still fill what they leave unset.\n */\nfunction assertSlotDefaults(\n\t$type: string,\n\tslotSchemas: ProtocolRecipeSlotSchemas,\n\tslotDefaults: Record<string, unknown> | undefined,\n): void {\n\tfor (const [slot, value] of Object.entries(slotDefaults ?? {})) {\n\t\tconst schema = slotSchemas[slot];\n\t\tif (!schema) {\n\t\t\tthrow new Error(`Recipe '${$type}' slotDefaults.${slot}: the recipe does not declare a '${slot}' slot.`);\n\t\t}\n\t\tconst result = z.safeParse(schema, value);\n\t\tif (!result.success) {\n\t\t\tconst problems = result.error.issues.map((issue) => {\n\t\t\t\tconst keys = [...issue.path, ...('keys' in issue && Array.isArray(issue.keys) ? issue.keys : [])];\n\t\t\t\treturn `${keys.join('.') || '(value)'}: ${issue.message}`;\n\t\t\t});\n\t\t\tthrow new Error(`Recipe '${$type}' slotDefaults.${slot} is invalid: ${problems.join('; ')}`);\n\t\t}\n\t}\n}\n\n/**\n * Validation only: a slot that declares appearance axes must exist and must accept the `appearance` key.\n */\nfunction assertAppearanceAxes(\n\t$type: string,\n\tslotSchemas: ProtocolRecipeSlotSchemas,\n\tappearanceAxes: SlotAppearanceAxes | undefined,\n): void {\n\tfor (const [slot, axes] of Object.entries(appearanceAxes ?? {})) {\n\t\tif (!axes) continue;\n\t\tconst schema = slotSchemas[slot];\n\t\tif (!schema) {\n\t\t\tthrow new Error(`Recipe '${$type}' appearanceAxes.${slot}: the recipe does not declare a '${slot}' slot.`);\n\t\t}\n\t\tconst result = z.safeParse(schema, { appearance: {} });\n\t\tconst rejectsKey = result.error?.issues.some(\n\t\t\t(issue) => issue.code === 'unrecognized_keys' && issue.keys.includes('appearance'),\n\t\t);\n\t\tif (rejectsKey) {\n\t\t\tthrow new Error(\n\t\t\t\t`Recipe '${$type}' appearanceAxes.${slot}: the '${slot}' slot schema must accept an 'appearance' key (z.optional(AppearanceConfigSchema)).`,\n\t\t\t);\n\t\t}\n\t}\n}\n\n/**\n * Declares a recipe's `$type`, kind, slot schemas, and metadata against a domain's protocol.\n *\n * @remarks\n * The protocol decides which slots and kinds exist, in the types and at runtime, and its rules run\n * here for an early failure. The spec lists its declared slots in the protocol's order.\n *\n * The rules run before the slots are listed, because listing filters the protocol's slots and would\n * otherwise drop a slot the protocol does not declare without a word.\n */\nexport function defineProtocolRecipeSpec<\n\tTSlot extends string,\n\tTKind extends string,\n\tconst TType extends string,\n\tconst TSlots extends ProtocolRecipeSlotSchemas<TSlot> = Record<never, never>,\n>(\n\tprotocol: RecipeProtocol<TSlot, TKind>,\n\tdefinition: ProtocolRecipeSpecDefinition<TSlot, TKind, TType, TSlots>,\n): ProtocolRecipeSpec<TSlot, TKind, TType, RecipeViewSchema<TType, TSlots>, TSlots> {\n\tconst slotSchemas = (definition.slotSchemas ?? {}) as TSlots;\n\tconst declared = Object.keys(slotSchemas).filter((slot) => slotSchemas[slot as TSlot]);\n\tassertRecipeRules(protocol, { $type: definition.$type, kind: definition.kind, slots: declared });\n\tconst slots = protocol.slots.filter((slot) => slotSchemas[slot]);\n\tassertSlotDefaults(definition.$type, slotSchemas, definition.slotDefaults);\n\tassertAppearanceAxes(definition.$type, slotSchemas, definition.appearanceAxes as SlotAppearanceAxes | undefined);\n\tconst schema = mergeRecipeSlotSchemas(definition.$type, slotSchemas);\n\treturn {\n\t\t$type: definition.$type,\n\t\tkind: definition.kind,\n\t\tslots,\n\t\tslotSchemas,\n\t\tslotDefaults: definition.slotDefaults,\n\t\tappearanceAxes: definition.appearanceAxes,\n\t\tmetadata: definition.metadata,\n\t\tschema,\n\t};\n}\n", "import { createRegistry, type BaseRegistration, type ReadOnlyRegistry } from '@schema-engine/registry';\n\n/** The part of a recipe that a protocol reads: its `$type`, kind and the slots it declares. */\nexport interface RecipeShape<TSlot extends string = string, TKind extends string = string> {\n\treadonly $type: string;\n\treadonly kind: TKind;\n\treadonly slots: readonly TSlot[];\n}\n\n/**\n * A named check a domain runs on every recipe of its protocol.\n *\n * @remarks\n * `check` returns the problem as a phrase that continues \"Recipe 'x' breaks rule 'name': \", or\n * `undefined` when the recipe passes. Rules read the declared kind and slots only. The slot and\n * kind vocabulary is checked before rules run, so a rule never sees a name outside the protocol.\n */\nexport interface RecipeRule<TSlot extends string = string, TKind extends string = string> {\n\treadonly name: string;\n\tcheck(recipe: RecipeShape<TSlot, TKind>): string | undefined;\n}\n\n/**\n * The slots, kinds and rules one domain gives its recipes.\n *\n * @remarks\n * `slots` is ordered: it is the order a spec lists its declared slots in, and the order a renderer\n * can compose them in.\n */\nexport interface RecipeProtocol<TSlot extends string = string, TKind extends string = string> {\n\treadonly slots: readonly TSlot[];\n\treadonly kinds: readonly TKind[];\n\treadonly rules: readonly RecipeRule<TSlot, TKind>[];\n}\n\nexport type SlotOf<TProtocol extends RecipeProtocol> = TProtocol extends RecipeProtocol<infer TSlot> ? TSlot : never;\n\nexport type KindOf<TProtocol extends RecipeProtocol> =\n\tTProtocol extends RecipeProtocol<string, infer TKind> ? TKind : never;\n\nfunction assertUnique(values: readonly string[], noun: 'slot' | 'kind'): void {\n\tif (values.length === 0) {\n\t\tthrow new Error(`A recipe protocol must declare at least one ${noun}.`);\n\t}\n\tconst seen = new Set<string>();\n\tfor (const value of values) {\n\t\tif (seen.has(value)) {\n\t\t\tthrow new Error(`A recipe protocol's ${noun} '${value}' is declared twice.`);\n\t\t}\n\t\tseen.add(value);\n\t}\n}\n\n/**\n * Declares the slots, kinds and rules of one domain's recipes, once.\n *\n * @param definition.slots - Slot names in composition order\n * @param definition.kinds - Kind names a recipe can take\n * @param definition.rules - Checks run on each recipe when a spec is defined and when a registry is built\n * @throws {Error} When no slot or kind is declared, or a name repeats\n */\nexport function defineRecipeProtocol<const TSlot extends string, const TKind extends string>(definition: {\n\tslots: readonly TSlot[];\n\tkinds: readonly TKind[];\n\trules?: readonly RecipeRule<NoInfer<TSlot>, NoInfer<TKind>>[];\n}): RecipeProtocol<TSlot, TKind> {\n\tassertUnique(definition.slots, 'slot');\n\tassertUnique(definition.kinds, 'kind');\n\treturn Object.freeze({\n\t\tslots: Object.freeze([...definition.slots]),\n\t\tkinds: Object.freeze([...definition.kinds]),\n\t\trules: Object.freeze([...(definition.rules ?? [])]),\n\t});\n}\n\n/**\n * Checks a recipe against its protocol: the kind and every slot must be declared, then each rule runs.\n *\n * @throws {Error} Naming the recipe, and the rule when one fails\n *\n * @remarks\n * Runs in `defineProtocolRecipeSpec` for an early failure and in {@link createRecipeRegistry} for each winning\n * registration, which also covers hand-written recipes whose schema is not a Zod schema.\n *\n * The vocabulary is checked before any rule runs, so the narrowing of the recipe to the protocol's\n * own slot and kind names, which the rules receive, holds.\n */\nexport function assertRecipeRules<TSlot extends string, TKind extends string>(\n\tprotocol: RecipeProtocol<TSlot, TKind>,\n\trecipe: RecipeShape,\n): void {\n\tconst kinds: readonly string[] = protocol.kinds;\n\tconst slots: readonly string[] = protocol.slots;\n\tif (!kinds.includes(recipe.kind)) {\n\t\tthrow new Error(\n\t\t\t`Recipe '${recipe.$type}' has kind '${recipe.kind}', which the protocol does not declare (kinds: ${protocol.kinds.join(', ')}).`,\n\t\t);\n\t}\n\tfor (const slot of recipe.slots) {\n\t\tif (!slots.includes(slot)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Recipe '${recipe.$type}' declares slot '${slot}', which the protocol does not declare (slots: ${protocol.slots.join(', ')}).`,\n\t\t\t);\n\t\t}\n\t}\n\tfor (const rule of protocol.rules) {\n\t\tconst problem = rule.check(recipe as RecipeShape<TSlot, TKind>);\n\t\tif (problem !== undefined) {\n\t\t\tthrow new Error(`Recipe '${recipe.$type}' breaks rule '${rule.name}': ${problem}.`);\n\t\t}\n\t}\n}\n\n/**\n * Builds the read-only `Recipe` registry of a domain, with its protocol rules run at build.\n *\n * @throws {Error} Naming the recipe when a winning registration breaks the protocol or has no Standard Schema\n *\n * @remarks\n * Only the winning registration of each `$type` is checked, the same as the registry's schema check: a\n * recipe overridden later in the list is skipped.\n */\nexport function createRecipeRegistry<\n\tTSlot extends string,\n\tTKind extends string,\n\tTRecipe extends BaseRegistration & RecipeShape<TSlot, TKind>,\n>(protocol: RecipeProtocol<TSlot, TKind>, recipes: readonly TRecipe[]): ReadOnlyRegistry<TRecipe> {\n\tconst registry = createRegistry('Recipe', recipes);\n\tfor (const recipe of registry.all()) {\n\t\tassertRecipeRules(protocol, recipe);\n\t}\n\treturn registry;\n}\n"],
|
|
5
|
+
"mappings": "AAAA,UAAYA,MAAO,WCAnB,OAAS,kBAAAC,MAAoE,0BAuFtE,SAASC,EACfC,EACAC,EACO,CACP,IAAMC,EAA2BF,EAAS,MACpCG,EAA2BH,EAAS,MAC1C,GAAI,CAACE,EAAM,SAASD,EAAO,IAAI,EAC9B,MAAM,IAAI,MACT,WAAWA,EAAO,KAAK,eAAeA,EAAO,IAAI,kDAAkDD,EAAS,MAAM,KAAK,IAAI,CAAC,IAC7H,EAED,QAAWI,KAAQH,EAAO,MACzB,GAAI,CAACE,EAAM,SAASC,CAAI,EACvB,MAAM,IAAI,MACT,WAAWH,EAAO,KAAK,oBAAoBG,CAAI,kDAAkDJ,EAAS,MAAM,KAAK,IAAI,CAAC,IAC3H,EAGF,QAAWK,KAAQL,EAAS,MAAO,CAClC,IAAMM,EAAUD,EAAK,MAAMJ,CAAmC,EAC9D,GAAIK,IAAY,OACf,MAAM,IAAI,MAAM,WAAWL,EAAO,KAAK,kBAAkBI,EAAK,IAAI,MAAMC,CAAO,GAAG,CAEpF,CACD,CD7DA,SAASC,EACRC,EACAC,EACkC,CAClC,IAAMC,EAAuC,CAC5C,MAAS,UAAQF,CAAK,CACvB,EAEA,OAAW,CAACG,EAAMC,CAAM,IAAK,OAAO,QAAQH,CAAW,EAClDG,IACHF,EAAMC,CAAI,EAAM,WAASC,EAAQ,CAAC,CAAC,GAIrC,OAAS,eAAaF,CAAK,CAC5B,CAOA,SAASG,EACRL,EACAC,EACAK,EACO,CACP,OAAW,CAACH,EAAMI,CAAK,IAAK,OAAO,QAAQD,GAAgB,CAAC,CAAC,EAAG,CAC/D,IAAMF,EAASH,EA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,EAAS,MAAM,OAAQZ,GAASF,EAAYE,CAAI,CAAC,EAC/DE,EAAmBW,EAAW,MAAOf,EAAae,EAAW,YAAY,EACzEL,EAAqBK,EAAW,MAAOf,EAAae,EAAW,cAAgD,EAC/G,IAAMZ,EAASL,EAAuBiB,EAAW,MAAOf,CAAW,EACnE,MAAO,CACN,MAAOe,EAAW,MAClB,KAAMA,EAAW,KACjB,MAAAG,EACA,YAAAlB,EACA,aAAce,EAAW,aACzB,eAAgBA,EAAW,eAC3B,SAAUA,EAAW,SACrB,OAAAZ,CACD,CACD",
|
|
6
|
+
"names": ["z", "createRegistry", "assertRecipeRules", "protocol", "recipe", "kinds", "slots", "slot", "rule", "problem", "mergeRecipeSlotSchemas", "$type", "slotSchemas", "shape", "slot", "schema", "assertSlotDefaults", "slotDefaults", "value", "result", "problems", "issue", "assertAppearanceAxes", "appearanceAxes", "axes", "defineProtocolRecipeSpec", "protocol", "definition", "declared", "assertRecipeRules", "slots"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Lays a view's slot config over the recipe's `slotDefaults`, deep for plain objects.
|
|
3
|
+
*
|
|
4
|
+
* @remarks
|
|
5
|
+
* Runs before the view schema parses, so schema defaults fill only what neither the author
|
|
6
|
+
* 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.
|
|
7
|
+
*/
|
|
8
|
+
export declare function mergeSlotDefaults(view: Record<string, unknown>, slotDefaults: Record<string, unknown> | undefined): Record<string, unknown>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function u(n){if(typeof n!="object"||n===null)return!1;let t=Object.getPrototypeOf(n);return t===Object.prototype||t===null}function c(n,t){if(t===void 0)return n;if(!u(n)||!u(t))return t;let e={...n};for(let[o,r]of Object.entries(t))e[o]=c(n[o],r);return e}function f(n,t){if(!t)return n;let e={...n};for(let[o,r]of Object.entries(t))e[o]=c(r,n[o]);return e}export{f as mergeSlotDefaults};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/recipes/merge-slot-defaults.ts"],
|
|
4
|
+
"sourcesContent": ["/**\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"],
|
|
5
|
+
"mappings": "AAKA,SAASA,EAAcC,EAAkD,CACxE,GAAI,OAAOA,GAAU,UAAYA,IAAU,KAAM,MAAO,GACxD,IAAMC,EAAY,OAAO,eAAeD,CAAK,EAC7C,OAAOC,IAAc,OAAO,WAAaA,IAAc,IACxD,CAEA,SAASC,EAAUC,EAAeC,EAA4B,CAC7D,GAAIA,IAAa,OAAW,OAAOD,EACnC,GAAI,CAACJ,EAAcI,CAAI,GAAK,CAACJ,EAAcK,CAAQ,EAAG,OAAOA,EAC7D,IAAMC,EAAkC,CAAE,GAAGF,CAAK,EAClD,OAAW,CAACG,EAAKN,CAAK,IAAK,OAAO,QAAQI,CAAQ,EACjDC,EAAOC,CAAG,EAAIJ,EAAUC,EAAKG,CAAG,EAAGN,CAAK,EAEzC,OAAOK,CACR,CASO,SAASE,EACfC,EACAC,EAC0B,CAC1B,GAAI,CAACA,EAAc,OAAOD,EAC1B,IAAMH,EAAS,CAAE,GAAGG,CAAK,EACzB,OAAW,CAACE,EAAMC,CAAQ,IAAK,OAAO,QAAQF,CAAY,EACzDJ,EAAOK,CAAI,EAAIR,EAAUS,EAAUH,EAAKE,CAAI,CAAC,EAE9C,OAAOL,CACR",
|
|
6
|
+
"names": ["isPlainObject", "value", "prototype", "mergeDeep", "base", "override", "merged", "key", "mergeSlotDefaults", "view", "slotDefaults", "slot", "defaults"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { type BaseRegistration, type ReadOnlyRegistry } from '@schema-engine/registry';
|
|
2
|
+
/** The part of a recipe that a protocol reads: its `$type`, kind and the slots it declares. */
|
|
3
|
+
export interface RecipeShape<TSlot extends string = string, TKind extends string = string> {
|
|
4
|
+
readonly $type: string;
|
|
5
|
+
readonly kind: TKind;
|
|
6
|
+
readonly slots: readonly TSlot[];
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* A named check a domain runs on every recipe of its protocol.
|
|
10
|
+
*
|
|
11
|
+
* @remarks
|
|
12
|
+
* `check` returns the problem as a phrase that continues "Recipe 'x' breaks rule 'name': ", or
|
|
13
|
+
* `undefined` when the recipe passes. Rules read the declared kind and slots only. The slot and
|
|
14
|
+
* kind vocabulary is checked before rules run, so a rule never sees a name outside the protocol.
|
|
15
|
+
*/
|
|
16
|
+
export interface RecipeRule<TSlot extends string = string, TKind extends string = string> {
|
|
17
|
+
readonly name: string;
|
|
18
|
+
check(recipe: RecipeShape<TSlot, TKind>): string | undefined;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* The slots, kinds and rules one domain gives its recipes.
|
|
22
|
+
*
|
|
23
|
+
* @remarks
|
|
24
|
+
* `slots` is ordered: it is the order a spec lists its declared slots in, and the order a renderer
|
|
25
|
+
* can compose them in.
|
|
26
|
+
*/
|
|
27
|
+
export interface RecipeProtocol<TSlot extends string = string, TKind extends string = string> {
|
|
28
|
+
readonly slots: readonly TSlot[];
|
|
29
|
+
readonly kinds: readonly TKind[];
|
|
30
|
+
readonly rules: readonly RecipeRule<TSlot, TKind>[];
|
|
31
|
+
}
|
|
32
|
+
export type SlotOf<TProtocol extends RecipeProtocol> = TProtocol extends RecipeProtocol<infer TSlot> ? TSlot : never;
|
|
33
|
+
export type KindOf<TProtocol extends RecipeProtocol> = TProtocol extends RecipeProtocol<string, infer TKind> ? TKind : never;
|
|
34
|
+
/**
|
|
35
|
+
* Declares the slots, kinds and rules of one domain's recipes, once.
|
|
36
|
+
*
|
|
37
|
+
* @param definition.slots - Slot names in composition order
|
|
38
|
+
* @param definition.kinds - Kind names a recipe can take
|
|
39
|
+
* @param definition.rules - Checks run on each recipe when a spec is defined and when a registry is built
|
|
40
|
+
* @throws {Error} When no slot or kind is declared, or a name repeats
|
|
41
|
+
*/
|
|
42
|
+
export declare function defineRecipeProtocol<const TSlot extends string, const TKind extends string>(definition: {
|
|
43
|
+
slots: readonly TSlot[];
|
|
44
|
+
kinds: readonly TKind[];
|
|
45
|
+
rules?: readonly RecipeRule<NoInfer<TSlot>, NoInfer<TKind>>[];
|
|
46
|
+
}): RecipeProtocol<TSlot, TKind>;
|
|
47
|
+
/**
|
|
48
|
+
* Checks a recipe against its protocol: the kind and every slot must be declared, then each rule runs.
|
|
49
|
+
*
|
|
50
|
+
* @throws {Error} Naming the recipe, and the rule when one fails
|
|
51
|
+
*
|
|
52
|
+
* @remarks
|
|
53
|
+
* Runs in `defineProtocolRecipeSpec` for an early failure and in {@link createRecipeRegistry} for each winning
|
|
54
|
+
* registration, which also covers hand-written recipes whose schema is not a Zod schema.
|
|
55
|
+
*
|
|
56
|
+
* The vocabulary is checked before any rule runs, so the narrowing of the recipe to the protocol's
|
|
57
|
+
* own slot and kind names, which the rules receive, holds.
|
|
58
|
+
*/
|
|
59
|
+
export declare function assertRecipeRules<TSlot extends string, TKind extends string>(protocol: RecipeProtocol<TSlot, TKind>, recipe: RecipeShape): void;
|
|
60
|
+
/**
|
|
61
|
+
* Builds the read-only `Recipe` registry of a domain, with its protocol rules run at build.
|
|
62
|
+
*
|
|
63
|
+
* @throws {Error} Naming the recipe when a winning registration breaks the protocol or has no Standard Schema
|
|
64
|
+
*
|
|
65
|
+
* @remarks
|
|
66
|
+
* Only the winning registration of each `$type` is checked, the same as the registry's schema check: a
|
|
67
|
+
* recipe overridden later in the list is skipped.
|
|
68
|
+
*/
|
|
69
|
+
export declare function createRecipeRegistry<TSlot extends string, TKind extends string, TRecipe extends BaseRegistration & RecipeShape<TSlot, TKind>>(protocol: RecipeProtocol<TSlot, TKind>, recipes: readonly TRecipe[]): ReadOnlyRegistry<TRecipe>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createRegistry as l}from"@schema-engine/registry";function i(e,t){if(e.length===0)throw new Error(`A recipe protocol must declare at least one ${t}.`);let o=new Set;for(let n of e){if(o.has(n))throw new Error(`A recipe protocol's ${t} '${n}' is declared twice.`);o.add(n)}}function a(e){return i(e.slots,"slot"),i(e.kinds,"kind"),Object.freeze({slots:Object.freeze([...e.slots]),kinds:Object.freeze([...e.kinds]),rules:Object.freeze([...e.rules??[]])})}function d(e,t){let o=e.kinds,n=e.slots;if(!o.includes(t.kind))throw new Error(`Recipe '${t.$type}' has kind '${t.kind}', which the protocol does not declare (kinds: ${e.kinds.join(", ")}).`);for(let r of t.slots)if(!n.includes(r))throw new Error(`Recipe '${t.$type}' declares slot '${r}', which the protocol does not declare (slots: ${e.slots.join(", ")}).`);for(let r of e.rules){let s=r.check(t);if(s!==void 0)throw new Error(`Recipe '${t.$type}' breaks rule '${r.name}': ${s}.`)}}function p(e,t){let o=l("Recipe",t);for(let n of o.all())d(e,n);return o}export{d as assertRecipeRules,p as createRecipeRegistry,a as defineRecipeProtocol};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/recipes/protocol.ts"],
|
|
4
|
+
"sourcesContent": ["import { createRegistry, type BaseRegistration, type ReadOnlyRegistry } from '@schema-engine/registry';\n\n/** The part of a recipe that a protocol reads: its `$type`, kind and the slots it declares. */\nexport interface RecipeShape<TSlot extends string = string, TKind extends string = string> {\n\treadonly $type: string;\n\treadonly kind: TKind;\n\treadonly slots: readonly TSlot[];\n}\n\n/**\n * A named check a domain runs on every recipe of its protocol.\n *\n * @remarks\n * `check` returns the problem as a phrase that continues \"Recipe 'x' breaks rule 'name': \", or\n * `undefined` when the recipe passes. Rules read the declared kind and slots only. The slot and\n * kind vocabulary is checked before rules run, so a rule never sees a name outside the protocol.\n */\nexport interface RecipeRule<TSlot extends string = string, TKind extends string = string> {\n\treadonly name: string;\n\tcheck(recipe: RecipeShape<TSlot, TKind>): string | undefined;\n}\n\n/**\n * The slots, kinds and rules one domain gives its recipes.\n *\n * @remarks\n * `slots` is ordered: it is the order a spec lists its declared slots in, and the order a renderer\n * can compose them in.\n */\nexport interface RecipeProtocol<TSlot extends string = string, TKind extends string = string> {\n\treadonly slots: readonly TSlot[];\n\treadonly kinds: readonly TKind[];\n\treadonly rules: readonly RecipeRule<TSlot, TKind>[];\n}\n\nexport type SlotOf<TProtocol extends RecipeProtocol> = TProtocol extends RecipeProtocol<infer TSlot> ? TSlot : never;\n\nexport type KindOf<TProtocol extends RecipeProtocol> =\n\tTProtocol extends RecipeProtocol<string, infer TKind> ? TKind : never;\n\nfunction assertUnique(values: readonly string[], noun: 'slot' | 'kind'): void {\n\tif (values.length === 0) {\n\t\tthrow new Error(`A recipe protocol must declare at least one ${noun}.`);\n\t}\n\tconst seen = new Set<string>();\n\tfor (const value of values) {\n\t\tif (seen.has(value)) {\n\t\t\tthrow new Error(`A recipe protocol's ${noun} '${value}' is declared twice.`);\n\t\t}\n\t\tseen.add(value);\n\t}\n}\n\n/**\n * Declares the slots, kinds and rules of one domain's recipes, once.\n *\n * @param definition.slots - Slot names in composition order\n * @param definition.kinds - Kind names a recipe can take\n * @param definition.rules - Checks run on each recipe when a spec is defined and when a registry is built\n * @throws {Error} When no slot or kind is declared, or a name repeats\n */\nexport function defineRecipeProtocol<const TSlot extends string, const TKind extends string>(definition: {\n\tslots: readonly TSlot[];\n\tkinds: readonly TKind[];\n\trules?: readonly RecipeRule<NoInfer<TSlot>, NoInfer<TKind>>[];\n}): RecipeProtocol<TSlot, TKind> {\n\tassertUnique(definition.slots, 'slot');\n\tassertUnique(definition.kinds, 'kind');\n\treturn Object.freeze({\n\t\tslots: Object.freeze([...definition.slots]),\n\t\tkinds: Object.freeze([...definition.kinds]),\n\t\trules: Object.freeze([...(definition.rules ?? [])]),\n\t});\n}\n\n/**\n * Checks a recipe against its protocol: the kind and every slot must be declared, then each rule runs.\n *\n * @throws {Error} Naming the recipe, and the rule when one fails\n *\n * @remarks\n * Runs in `defineProtocolRecipeSpec` for an early failure and in {@link createRecipeRegistry} for each winning\n * registration, which also covers hand-written recipes whose schema is not a Zod schema.\n *\n * The vocabulary is checked before any rule runs, so the narrowing of the recipe to the protocol's\n * own slot and kind names, which the rules receive, holds.\n */\nexport function assertRecipeRules<TSlot extends string, TKind extends string>(\n\tprotocol: RecipeProtocol<TSlot, TKind>,\n\trecipe: RecipeShape,\n): void {\n\tconst kinds: readonly string[] = protocol.kinds;\n\tconst slots: readonly string[] = protocol.slots;\n\tif (!kinds.includes(recipe.kind)) {\n\t\tthrow new Error(\n\t\t\t`Recipe '${recipe.$type}' has kind '${recipe.kind}', which the protocol does not declare (kinds: ${protocol.kinds.join(', ')}).`,\n\t\t);\n\t}\n\tfor (const slot of recipe.slots) {\n\t\tif (!slots.includes(slot)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Recipe '${recipe.$type}' declares slot '${slot}', which the protocol does not declare (slots: ${protocol.slots.join(', ')}).`,\n\t\t\t);\n\t\t}\n\t}\n\tfor (const rule of protocol.rules) {\n\t\tconst problem = rule.check(recipe as RecipeShape<TSlot, TKind>);\n\t\tif (problem !== undefined) {\n\t\t\tthrow new Error(`Recipe '${recipe.$type}' breaks rule '${rule.name}': ${problem}.`);\n\t\t}\n\t}\n}\n\n/**\n * Builds the read-only `Recipe` registry of a domain, with its protocol rules run at build.\n *\n * @throws {Error} Naming the recipe when a winning registration breaks the protocol or has no Standard Schema\n *\n * @remarks\n * Only the winning registration of each `$type` is checked, the same as the registry's schema check: a\n * recipe overridden later in the list is skipped.\n */\nexport function createRecipeRegistry<\n\tTSlot extends string,\n\tTKind extends string,\n\tTRecipe extends BaseRegistration & RecipeShape<TSlot, TKind>,\n>(protocol: RecipeProtocol<TSlot, TKind>, recipes: readonly TRecipe[]): ReadOnlyRegistry<TRecipe> {\n\tconst registry = createRegistry('Recipe', recipes);\n\tfor (const recipe of registry.all()) {\n\t\tassertRecipeRules(protocol, recipe);\n\t}\n\treturn registry;\n}\n"],
|
|
5
|
+
"mappings": "AAAA,OAAS,kBAAAA,MAAoE,0BAwC7E,SAASC,EAAaC,EAA2BC,EAA6B,CAC7E,GAAID,EAAO,SAAW,EACrB,MAAM,IAAI,MAAM,+CAA+CC,CAAI,GAAG,EAEvE,IAAMC,EAAO,IAAI,IACjB,QAAWC,KAASH,EAAQ,CAC3B,GAAIE,EAAK,IAAIC,CAAK,EACjB,MAAM,IAAI,MAAM,uBAAuBF,CAAI,KAAKE,CAAK,sBAAsB,EAE5ED,EAAK,IAAIC,CAAK,CACf,CACD,CAUO,SAASC,EAA6EC,EAI5D,CAChC,OAAAN,EAAaM,EAAW,MAAO,MAAM,EACrCN,EAAaM,EAAW,MAAO,MAAM,EAC9B,OAAO,OAAO,CACpB,MAAO,OAAO,OAAO,CAAC,GAAGA,EAAW,KAAK,CAAC,EAC1C,MAAO,OAAO,OAAO,CAAC,GAAGA,EAAW,KAAK,CAAC,EAC1C,MAAO,OAAO,OAAO,CAAC,GAAIA,EAAW,OAAS,CAAC,CAAE,CAAC,CACnD,CAAC,CACF,CAcO,SAASC,EACfC,EACAC,EACO,CACP,IAAMC,EAA2BF,EAAS,MACpCG,EAA2BH,EAAS,MAC1C,GAAI,CAACE,EAAM,SAASD,EAAO,IAAI,EAC9B,MAAM,IAAI,MACT,WAAWA,EAAO,KAAK,eAAeA,EAAO,IAAI,kDAAkDD,EAAS,MAAM,KAAK,IAAI,CAAC,IAC7H,EAED,QAAWI,KAAQH,EAAO,MACzB,GAAI,CAACE,EAAM,SAASC,CAAI,EACvB,MAAM,IAAI,MACT,WAAWH,EAAO,KAAK,oBAAoBG,CAAI,kDAAkDJ,EAAS,MAAM,KAAK,IAAI,CAAC,IAC3H,EAGF,QAAWK,KAAQL,EAAS,MAAO,CAClC,IAAMM,EAAUD,EAAK,MAAMJ,CAAmC,EAC9D,GAAIK,IAAY,OACf,MAAM,IAAI,MAAM,WAAWL,EAAO,KAAK,kBAAkBI,EAAK,IAAI,MAAMC,CAAO,GAAG,CAEpF,CACD,CAWO,SAASC,EAIdP,EAAwCQ,EAAwD,CACjG,IAAMC,EAAWlB,EAAe,SAAUiB,CAAO,EACjD,QAAWP,KAAUQ,EAAS,IAAI,EACjCV,EAAkBC,EAAUC,CAAM,EAEnC,OAAOQ,CACR",
|
|
6
|
+
"names": ["createRegistry", "assertUnique", "values", "noun", "seen", "value", "defineRecipeProtocol", "definition", "assertRecipeRules", "protocol", "recipe", "kinds", "slots", "slot", "rule", "problem", "createRecipeRegistry", "recipes", "registry"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import type { StandardSchemaV1 } from '@standard-schema/spec';
|
|
2
|
+
import { type SlotAppearanceAxes } from '../lib/appearance';
|
|
3
|
+
import type { LayoutIssue } from '../lib/layout-issue';
|
|
4
|
+
import type { LayoutTheme } from '../lib/layout-theme';
|
|
5
|
+
/** Appearance picks a view inherits: the theme's vocabulary, and what the containing document picked. */
|
|
6
|
+
export interface RecipeViewScope {
|
|
7
|
+
readonly axes: LayoutTheme['axes'];
|
|
8
|
+
readonly inherited: Readonly<Record<string, string>>;
|
|
9
|
+
}
|
|
10
|
+
/** The part of a recipe registration that resolving a view reads. */
|
|
11
|
+
export interface RecipeViewSource {
|
|
12
|
+
readonly $type: string;
|
|
13
|
+
readonly slots: readonly string[];
|
|
14
|
+
readonly schema: StandardSchemaV1;
|
|
15
|
+
readonly slotDefaults?: Readonly<Record<string, unknown>>;
|
|
16
|
+
readonly appearanceAxes?: SlotAppearanceAxes;
|
|
17
|
+
}
|
|
18
|
+
/** An authored view: the recipe's `$type` and the config of its slots. */
|
|
19
|
+
export type RecipeViewInput = Readonly<Record<string, unknown>> & {
|
|
20
|
+
readonly $type: string;
|
|
21
|
+
};
|
|
22
|
+
/**
|
|
23
|
+
* What {@link resolveRecipeView} found.
|
|
24
|
+
*
|
|
25
|
+
* @remarks
|
|
26
|
+
* `view` is present when the schema parsed and kept its `$type`; it can still come with `issues`
|
|
27
|
+
* (an appearance pick that is not valid, or a key the recipe does not declare). `schemaIssues` is
|
|
28
|
+
* present, with no `view`, when the schema rejected the view: the caller formats them, since only
|
|
29
|
+
* the domain knows how it reports a schema's issues.
|
|
30
|
+
*/
|
|
31
|
+
export interface ResolvedRecipeView {
|
|
32
|
+
/** One issue per problem, with a path relative to the view (`[slot, 'appearance', axis]`, `[key]`). */
|
|
33
|
+
issues: LayoutIssue[];
|
|
34
|
+
view?: Record<string, unknown>;
|
|
35
|
+
schemaIssues?: StandardSchemaV1.Issue[];
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Resolves the view a document selects for a recipe: the recipe defaults laid under the author's
|
|
39
|
+
* slot config, each slot's appearance, the schema parse, and the keys the recipe does not declare.
|
|
40
|
+
*
|
|
41
|
+
* @param recipe - The winning registration the view's `$type` selects
|
|
42
|
+
* @param view - The authored view; not changed
|
|
43
|
+
* @param scope - The picks the view inherits from its document
|
|
44
|
+
*
|
|
45
|
+
* @remarks
|
|
46
|
+
* Slot appearance follows the recipe's inheritance rule: the document's picks reach a slot for the
|
|
47
|
+
* axes the recipe declares on it, and the slot's own pick wins. The authored `appearance` key is
|
|
48
|
+
* removed before the slot schema parses, so a schema only has to type it, and the resolved
|
|
49
|
+
* selection is written back on the slot when it is not empty. Domain rules that need the document
|
|
50
|
+
* (a kind that wants one step, a default recipe) stay with the domain's validator.
|
|
51
|
+
*/
|
|
52
|
+
export declare function resolveRecipeView(recipe: RecipeViewSource, view: RecipeViewInput, scope: RecipeViewScope): ResolvedRecipeView;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createRegistry as N}from"@schema-engine/registry";import*as l from"zod/mini";var T=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,j=/^[A-Za-z0-9][A-Za-z0-9_-]*$/,O=/[{};<]|\/\*/,A=2,h=5;function V(e){let t=e.$type;if(!T.test(t))throw new Error(`Invalid appearance axis name '${t}': use lowercase letters, digits and hyphens, starting with a letter.`);let n=Object.entries(e.values);if(n.length<A||n.length>h)throw new Error(`Invalid appearance axis '${t}': an axis has ${A} to ${h} values, found ${n.length}. A raw value is a token override, not an axis value.`);if(!Object.hasOwn(e.values,e.default))throw new Error(`Invalid appearance axis '${t}': default '${e.default}' is not one of its values (${n.map(([s])=>s).join(", ")}).`);for(let[s,o]of n){if(!j.test(s))throw new Error(`Invalid appearance value '${s}' on axis '${t}': use letters, digits, hyphens and underscores.`);for(let[r,c]of Object.entries(o)){if(!r.startsWith("--")||r.length<3)throw new Error(`Invalid appearance token '${r}' on '${t}.${s}': tokens are CSS custom properties and start with '--'.`);if(O.test(String(c)))throw new Error(`Invalid appearance token value for '${r}' on '${t}.${s}'.`)}}}function R(e){let t={$type:e.$type,values:e.values,default:e.default,metadata:e.metadata,schema:l.enum(Object.keys(e.values)).check(l.describe(e.metadata.description??e.metadata.name))};return V(t),Object.freeze(t)}var _=R({$type:"size",metadata:{name:"Size",description:"How much room components take: spacing, type size, control height and readable width."},default:"default",values:{compact:{"--se-space":"var(--se-space-compact, var(--se-renderer-space-compact, 1rem))","--se-font-size":"0.875rem","--se-measure":"24rem","--se-control-height":"var(--se-control-height-compact, var(--se-renderer-control-height-compact, 1.75rem))"},default:{"--se-space":"initial","--se-font-size":"initial","--se-measure":"initial","--se-control-height":"initial"},comfortable:{"--se-space":"var(--se-space-comfortable, var(--se-renderer-space-comfortable, 2rem))","--se-font-size":"1.0625rem","--se-measure":"32rem","--se-control-height":"var(--se-control-height-comfortable, var(--se-renderer-control-height-comfortable, 2.25rem))"}}}),C=R({$type:"surface",metadata:{name:"Surface",description:"How a container sets itself apart: border, shadow and background."},default:"elevated",values:{flat:{"--se-border-width":"0","--se-shadow":"none","--se-surface-background":"initial"},outlined:{"--se-border-width":"1px","--se-shadow":"none","--se-surface-background":"initial"},elevated:{"--se-border-width":"initial","--se-shadow":"initial","--se-surface-background":"initial"}}});function $(e,t){return{...e,...t}}function I(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function w(e,t){let n=[],s={};if(e===void 0)return{issues:n,appearance:s};if(!I(e))return{issues:[{path:["appearance"],message:"Expected an object of axis names to values."}],appearance:s};let o=Object.keys(t.axes).join(", ");for(let[r,c]of Object.entries(e)){let i=Object.hasOwn(t.axes,r)?t.axes[r]:void 0;if(!i){n.push({path:["appearance",r],message:`Unknown axis '${r}'. Declared axes: ${o}.`});continue}if(t.supported!==void 0&&!t.supported.includes(r)){let u=t.supported.length>0?t.supported.join(", "):"(none)";n.push({path:["appearance",r],message:`${t.subject} does not support the axis '${r}'. Supported axes: ${u}.`});continue}if(typeof c!="string"){n.push({path:["appearance",r],message:`Expected one of ${i.join(", ")}.`});continue}if(!i.includes(c)){n.push({path:["appearance",r],message:`'${c}' is not a value of '${r}'. Allowed: ${i.join(", ")}.`});continue}s[r]=c}return{issues:n,appearance:s}}function k(e,t){let n={};for(let s of t??[]){let o=e[s];o!==void 0&&(n[s]=o)}return n}function b(e){if(typeof e!="object"||e===null)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function v(e,t){if(t===void 0)return e;if(!b(e)||!b(t))return t;let n={...e};for(let[s,o]of Object.entries(t))n[s]=v(e[s],o);return n}function S(e,t){if(!t)return e;let n={...e};for(let[s,o]of Object.entries(t))n[s]=v(o,e[s]);return n}function f(e){if(typeof e!="object"||e===null)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function L(e){if(!("appearance"in e))return e;let{appearance:t,...n}=e;return n}function E(e,t){let n=e["~standard"].validate(t);if(n&&typeof n.then=="function")throw new Error("Async Standard Schema validation is not supported in this context");if(n===null||typeof n!="object")throw new Error("Standard Schema validation returned an invalid result");return n}function U(e,t,n){let s=[],o={...t},r={};for(let a of e.slots){let p=t[a],d=e.appearanceAxes?.[a]??[],g=w(f(p)?p.appearance:void 0,{axes:n.axes,subject:`Slot '${a}' of recipe '${e.$type}'`,supported:d});s.push(...g.issues.map(x=>({...x,path:[a,...x.path]})));let m=k($(n.inherited,g.appearance),d);Object.keys(m).length>0&&(r[a]=m),f(p)&&(o[a]=L(p))}let c=E(e.schema,S(o,e.slotDefaults));if(c.issues!==void 0)return{issues:s,schemaIssues:[...c.issues]};let i=c.value;if(typeof i!="object"||i===null||!("$type"in i)||typeof i.$type!="string")return s.push({path:["$type"],message:`Invalid view configuration for recipe '${e.$type}': parsed output is missing $type.`}),{issues:s};let u=new Set(e.slots);for(let a of Object.keys(t))a!=="$type"&&!u.has(a)&&s.push({path:[a],message:`Recipe '${e.$type}' does not accept view key '${a}'. Allowed: ${[...u].join(", ")||"(none)"}.`});let y={...i};for(let[a,p]of Object.entries(r)){let d=i[a];f(d)&&(y[a]={...d,appearance:p})}return{issues:s,view:y}}export{U as resolveRecipeView};
|