@schema-engine/layout 0.5.0 → 0.5.2

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/dist/index.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/schemas/appearance.ts", "../src/schemas/grid.ts", "../src/lib/appearance.ts", "../src/lib/grid-placement.ts", "../src/lib/grid-styles.ts", "../src/lib/layout-theme.ts", "../src/recipes/bind-recipe.ts", "../src/recipes/define-recipe-spec.ts", "../src/recipes/protocol.ts", "../src/recipes/merge-slot-defaults.ts", "../src/recipes/resolve-recipe-view.ts", "../src/recipes/view-model.ts"],
4
- "sourcesContent": ["import * as z from 'zod/mini';\nimport type { AxisRegistry } from '@/lib/appearance';\n\n/**\n * A pick of named appearance values, one per axis: `{ size: 'compact' }`.\n *\n * @remarks\n * The shape is open because the axes belong to the theme (`createLayoutTheme({ appearance })`). A\n * domain checks each axis and value against the theme's vocabulary and the owner's declared axes.\n */\nexport const AppearanceConfigSchema = z.record(z.string(), z.string());\n\nexport type AppearanceConfig = z.infer<typeof AppearanceConfigSchema>;\n\n/**\n * The pick schema of one theme: each axis is an optional enum of its values, and any other axis is\n * rejected.\n *\n * @param supported Restricts the schema to the axes one owner declares; omit it for an owner that\n * accepts every axis of the theme (the document and its steps). An empty list is a closed object\n * with no axes. A name the theme does not hold is skipped, since an engine rejects it when it builds.\n *\n * @remarks\n * Built for a JSON Schema export, so an editor autocompletes `appearance.size`. The enums are fresh\n * schemas rather than the axes' own, so the export inlines them instead of referencing a catalog\n * entry. It is built from the same registry and declarations `checkAppearance` validates against.\n */\nexport function createAppearanceSchema(axes: AxisRegistry, supported?: readonly string[]) {\n\tconst entries = axes\n\t\t.all()\n\t\t.filter((axis) => supported === undefined || supported.includes(axis.$type))\n\t\t.map((axis) => [axis.$type, z.optional(z.enum(Object.keys(axis.values) as [string, ...string[]]))] as const);\n\treturn z.strictObject(Object.fromEntries(entries));\n}\n\n/**\n * @remarks\n * Only narrows the members of a schema's definition, which Zod types as the core base. A classic\n * Zod schema passes too, since it has the same methods, and is rewritten the same way.\n */\nfunction isMiniSchema(schema: z.core.$ZodType): schema is z.ZodMiniType {\n\treturn 'check' in schema && typeof schema.check === 'function';\n}\n\nfunction isObjectSchema(schema: z.ZodMiniType): schema is z.ZodMiniObject {\n\treturn schema._zod.def.type === 'object';\n}\n\nfunction isPipeSchema(schema: z.ZodMiniType): schema is z.ZodMiniPipe {\n\treturn schema._zod.def.type === 'pipe';\n}\n\nfunction isPrefaultSchema(schema: z.ZodMiniType): schema is z.ZodMiniPrefault {\n\treturn schema._zod.def.type === 'prefault';\n}\n\n/**\n * Sets the `appearance` key on the object a schema parses, looking through a pipe (its input) and\n * a prefault (its inner schema). Any other schema comes back as it is.\n */\nfunction setAppearance(schema: z.ZodMiniType, appearance: z.ZodMiniType): z.ZodMiniType {\n\tif (isObjectSchema(schema)) return z.safeExtend(schema, { appearance });\n\tif (isPipeSchema(schema)) {\n\t\tconst { in: input, out } = schema._zod.def;\n\t\tif (!isMiniSchema(input)) return schema;\n\t\tconst next = setAppearance(input, appearance);\n\t\treturn next === input ? schema : z.pipe(next, out);\n\t}\n\tif (isPrefaultSchema(schema)) {\n\t\tconst { innerType, defaultValue } = schema._zod.def;\n\t\tif (!isMiniSchema(innerType)) return schema;\n\t\tconst next = setAppearance(innerType, appearance);\n\t\treturn next === innerType ? schema : z.prefault(next, defaultValue);\n\t}\n\treturn schema;\n}\n\nfunction declaredAppearance(axes: AxisRegistry, supported: readonly string[]) {\n\treturn z\n\t\t.optional(createAppearanceSchema(axes, supported))\n\t\t.check(z.describe('Named appearance values, one per declared axis'));\n}\n\n/**\n * Sets the `appearance` key of an object schema to the closed schema of the axes its owner\n * declares, for a JSON Schema export.\n *\n * @param supported The owner's declared axes (`appearanceAxes`); omit it for an owner that declares none,\n * which gets a closed object with no axes.\n *\n * @remarks\n * Validation strips an authored `appearance` before it parses the owner's own schema and checks the\n * pick against the declared axes (`checkAppearance`), on every owner whatever its schema says. So the\n * key is set whether or not the schema has one, and replaces an open one. This keeps the export from\n * drifting from validation. A pipe is rewritten on its input, so a transform after the object stays.\n * A schema that is not an object, a pipe of one or a prefault of one (a lazy schema, for example) is\n * returned unchanged. The result is for export only: parse with the original.\n */\nexport function withAppearanceAxes(\n\tschema: z.ZodMiniType,\n\taxes: AxisRegistry,\n\tsupported: readonly string[] = [],\n): z.ZodMiniType {\n\treturn setAppearance(schema, declaredAppearance(axes, supported));\n}\n\n/**\n * Applies {@link withAppearanceAxes} to each slot of a recipe's view schema, with the axes the\n * recipe declares for that slot.\n *\n * @param slotAxes The recipe's `appearanceAxes`; a slot it does not list declares none.\n *\n * @remarks\n * Expects the shape `defineProtocolRecipeSpec` builds: a strict object whose slots are objects\n * wrapped in `prefault`. Validation resolves the appearance of every slot, so every slot gets the\n * key. Any other shape is returned unchanged.\n */\nexport function withSlotAppearanceAxes(\n\tschema: z.ZodMiniType,\n\taxes: AxisRegistry,\n\tslotAxes: Readonly<Record<string, readonly string[] | undefined>> = {},\n): z.ZodMiniType {\n\tif (!isObjectSchema(schema)) return schema;\n\tconst replaced: Record<string, z.ZodMiniType> = {};\n\tfor (const [slot, slotSchema] of Object.entries(schema._zod.def.shape)) {\n\t\tif (!isMiniSchema(slotSchema)) continue;\n\t\tconst next = withAppearanceAxes(slotSchema, axes, slotAxes[slot]);\n\t\tif (next !== slotSchema) replaced[slot] = next;\n\t}\n\tif (Object.keys(replaced).length === 0) return schema;\n\treturn z.safeExtend(schema, replaced);\n}\n", "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 {\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 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", "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", "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", "/**\n * @remarks\n * Duplicates the helper the forms package keeps for its own deep operations on purpose: this\n * package cannot import forms.\n */\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n\tif (typeof value !== 'object' || value === null) return false;\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === Object.prototype || prototype === null;\n}\n\nfunction mergeDeep(base: unknown, override: unknown): unknown {\n\tif (override === undefined) return base;\n\tif (!isPlainObject(base) || !isPlainObject(override)) return override;\n\tconst merged: Record<string, unknown> = { ...base };\n\tfor (const [key, value] of Object.entries(override)) {\n\t\tmerged[key] = mergeDeep(base[key], value);\n\t}\n\treturn merged;\n}\n\n/**\n * Lays a view's slot config over the recipe's `slotDefaults`, deep for plain objects.\n *\n * @remarks\n * Runs before the view schema parses, so schema defaults fill only what neither the author\n * nor the recipe set. Arrays and other non-plain values replace the default whole. A key the author sets to `undefined` keeps the recipe default.\n */\nexport function mergeSlotDefaults(\n\tview: Record<string, unknown>,\n\tslotDefaults: Record<string, unknown> | undefined,\n): Record<string, unknown> {\n\tif (!slotDefaults) return view;\n\tconst merged = { ...view };\n\tfor (const [slot, defaults] of Object.entries(slotDefaults)) {\n\t\tmerged[slot] = mergeDeep(defaults, view[slot]);\n\t}\n\treturn merged;\n}\n", "import type { StandardSchemaV1 } from '@standard-schema/spec';\nimport { checkAppearance, mergeAppearance, pickSupportedAppearance, type SlotAppearanceAxes } from '../lib/appearance';\nimport type { LayoutIssue } from '../lib/layout-issue';\nimport type { LayoutTheme } from '../lib/layout-theme';\nimport { mergeSlotDefaults } from './merge-slot-defaults';\n\n/** Appearance picks a view inherits: the theme's vocabulary, and what the containing document picked. */\nexport interface RecipeViewScope {\n\treadonly axes: LayoutTheme['axes'];\n\treadonly inherited: Readonly<Record<string, string>>;\n}\n\n/** The part of a recipe registration that resolving a view reads. */\nexport interface RecipeViewSource {\n\treadonly $type: string;\n\treadonly slots: readonly string[];\n\treadonly schema: StandardSchemaV1;\n\treadonly slotDefaults?: Readonly<Record<string, unknown>>;\n\treadonly appearanceAxes?: SlotAppearanceAxes;\n}\n\n/** An authored view: the recipe's `$type` and the config of its slots. */\nexport type RecipeViewInput = Readonly<Record<string, unknown>> & { readonly $type: string };\n\n/**\n * What {@link resolveRecipeView} found.\n *\n * @remarks\n * `view` is present when the schema parsed and kept its `$type`; it can still come with `issues`\n * (an appearance pick that is not valid, or a key the recipe does not declare). `schemaIssues` is\n * present, with no `view`, when the schema rejected the view: the caller formats them, since only\n * the domain knows how it reports a schema's issues.\n */\nexport interface ResolvedRecipeView {\n\t/** One issue per problem, with a path relative to the view (`[slot, 'appearance', axis]`, `[key]`). */\n\tissues: LayoutIssue[];\n\tview?: Record<string, unknown>;\n\tschemaIssues?: StandardSchemaV1.Issue[];\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n\tif (typeof value !== 'object' || value === null) return false;\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === Object.prototype || prototype === null;\n}\n\nfunction withoutAppearance(config: Record<string, unknown>): Record<string, unknown> {\n\tif (!('appearance' in config)) return config;\n\tconst { appearance: _authored, ...rest } = config;\n\treturn rest;\n}\n\nfunction parseSync(schema: StandardSchemaV1, value: unknown): StandardSchemaV1.Result<unknown> {\n\tconst result = schema['~standard'].validate(value);\n\tif (result && typeof (result as Promise<unknown>).then === 'function') {\n\t\tthrow new Error('Async Standard Schema validation is not supported in this context');\n\t}\n\tif (result === null || typeof result !== 'object') {\n\t\tthrow new Error('Standard Schema validation returned an invalid result');\n\t}\n\treturn result as StandardSchemaV1.Result<unknown>;\n}\n\n/**\n * Resolves the view a document selects for a recipe: the recipe defaults laid under the author's\n * slot config, each slot's appearance, the schema parse, and the keys the recipe does not declare.\n *\n * @param recipe - The winning registration the view's `$type` selects\n * @param view - The authored view; not changed\n * @param scope - The picks the view inherits from its document\n *\n * @remarks\n * Slot appearance follows the recipe's inheritance rule: the document's picks reach a slot for the\n * axes the recipe declares on it, and the slot's own pick wins. The authored `appearance` key is\n * removed before the slot schema parses, so a schema only has to type it, and the resolved\n * selection is written back on the slot when it is not empty. Domain rules that need the document\n * (a kind that wants one step, a default recipe) stay with the domain's validator.\n */\nexport function resolveRecipeView(\n\trecipe: RecipeViewSource,\n\tview: RecipeViewInput,\n\tscope: RecipeViewScope,\n): ResolvedRecipeView {\n\tconst issues: LayoutIssue[] = [];\n\tconst stripped: Record<string, unknown> = { ...view };\n\tconst resolved: Record<string, Record<string, string>> = {};\n\tfor (const slot of recipe.slots) {\n\t\tconst authoredSlot = view[slot];\n\t\tconst supported = recipe.appearanceAxes?.[slot] ?? [];\n\t\tconst checked = checkAppearance(isPlainRecord(authoredSlot) ? authoredSlot.appearance : undefined, {\n\t\t\taxes: scope.axes,\n\t\t\tsubject: `Slot '${slot}' of recipe '${recipe.$type}'`,\n\t\t\tsupported,\n\t\t});\n\t\tissues.push(...checked.issues.map((issue) => ({ ...issue, path: [slot, ...issue.path] })));\n\t\tconst selection = pickSupportedAppearance(mergeAppearance(scope.inherited, checked.appearance), supported);\n\t\tif (Object.keys(selection).length > 0) resolved[slot] = selection;\n\t\tif (isPlainRecord(authoredSlot)) stripped[slot] = withoutAppearance(authoredSlot);\n\t}\n\n\tconst parsed = parseSync(recipe.schema, mergeSlotDefaults(stripped, recipe.slotDefaults));\n\tif (parsed.issues !== undefined) return { issues, schemaIssues: [...parsed.issues] };\n\tconst output = parsed.value;\n\tif (typeof output !== 'object' || output === null || !('$type' in output) || typeof output.$type !== 'string') {\n\t\tissues.push({\n\t\t\tpath: ['$type'],\n\t\t\tmessage: `Invalid view configuration for recipe '${recipe.$type}': parsed output is missing $type.`,\n\t\t});\n\t\treturn { issues };\n\t}\n\n\tconst allowedSlots = new Set<string>(recipe.slots);\n\tfor (const key of Object.keys(view)) {\n\t\tif (key !== '$type' && !allowedSlots.has(key)) {\n\t\t\tissues.push({\n\t\t\t\tpath: [key],\n\t\t\t\tmessage: `Recipe '${recipe.$type}' does not accept view key '${key}'. Allowed: ${[...allowedSlots].join(', ') || '(none)'}.`,\n\t\t\t});\n\t\t}\n\t}\n\n\tconst next: Record<string, unknown> = { ...output };\n\tfor (const [slot, selection] of Object.entries(resolved)) {\n\t\tconst slotConfig = (output as Record<string, unknown>)[slot];\n\t\tif (isPlainRecord(slotConfig)) next[slot] = { ...slotConfig, appearance: selection };\n\t}\n\treturn { issues, view: next };\n}\n", "import type * as z from 'zod/mini';\n\n/**\n * What every recipe renderer receives, whatever the domain: the recipe's kind and the resolved view.\n *\n * @remarks\n * A domain extends it with what its renderers also need, for example the steps of a form.\n */\nexport interface RecipeViewModel<TKind extends string = string> {\n\tkind: TKind;\n\tviewConfig: Record<string, unknown>;\n}\n\n/**\n * Reads one slot's complete config from a resolved view.\n *\n * @remarks\n * `schema` only types the result. The view is already complete, and parsing it again with the\n * block's own strict schema would reject a custom recipe whose slot schema extends the block's\n * with extra keys.\n */\nexport function readSlotConfig<TSchema extends z.ZodMiniType>(\n\tviewConfig: Record<string, unknown>,\n\tslot: string,\n\t_schema: TSchema,\n): z.output<TSchema> {\n\treturn viewConfig[slot] as z.output<TSchema>;\n}\n"],
5
- "mappings": "AAAA,UAAYA,MAAO,WAUZ,IAAMC,GAA2B,SAAS,SAAO,EAAK,SAAO,CAAC,EAiB9D,SAASC,EAAuBC,EAAoBC,EAA+B,CACzF,IAAMC,EAAUF,EAC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es", "supported", "entries", "axis", "isMiniSchema", "schema", "isObjectSchema", "isPipeSchema", "isPrefaultSchema", "setAppearance", "appearance", "input", "out", "next", "innerType", "defaultValue", "declaredAppearance", "withAppearanceAxes", "withSlotAppearanceAxes", "slotAxes", "replaced", "slot", "slotSchema", "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", "createRegistry", "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", "getAppearanceAttributes", "attributes", "mergeAppearance", "inherited", "own", "isRecord", "checkAppearance", "authored", "options", "issues", "declared", "values", "supported", "pickSupportedAppearance", "selection", "picked", "BREAKPOINT_ORDER", "CASCADE_SLOTS", "WIDTH_TRACKS", "WIDTH_SPANS", "GRID_TEMPLATE_KEYS", "isRecord", "value", "elementGridSlots", "element", "grid", "slots", "responsive", "slot", "entry", "elementGridKeys", "keys", "key", "elementUsesGridWidths", "usesGridWidths", "elements", "carryNamedPlacement", "carried", "namedPlacementOverflow", "tracks", "EMPTY_CELL", "splitRow", "row", "cell", "toRows", "rows", "gridAreaTemplates", "templates", "gridUsesAreas", "areaNames", "names", "areasTemplateValue", "elementAreaSlots", "areas", "elementHiddenSlots", "hidden", "cascadeValues", "authored", "cellCount", "count", "isRectangle", "name", "cells", "rowIndex", "columnIndex", "rowsUsed", "columnsUsed", "column", "height", "width", "areaTemplateIssues", "arrayForm", "issues", "path", "ragged", "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", "isGridGapToken", "resolveGridGap", "AXIS_QUALIFIERS", "splitPlaceShorthand", "alignLength", "align", "justify", "toGridTemplate", "columns", "customProperty", "emitGapEntry", "variables", "entryGap", "gapX", "gapY", "getGridVariables", "grid", "elements", "placeAlignItems", "placeJustifyItems", "placeAlignContent", "placeJustifyContent", "alignment", "emitTemplate", "usesGridWidths", "WIDTH_TRACKS", "templates", "gridAreaTemplates", "CASCADE_SLOTS", "rows", "areasTemplateValue", "namedColumn", "width", "offset", "start", "WIDTH_SPANS", "span", "formatGridLine", "emitItemEntry", "named", "carryNamedPlacement", "marginBlockStart", "marginBlockEnd", "getGridItemVariables", "alignSelf", "justifySelf", "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", "bindRecipe", "spec", "render", "z", "createRegistry", "assertUnique", "values", "noun", "seen", "value", "defineRecipeProtocol", "definition", "assertRecipeRules", "protocol", "recipe", "kinds", "slots", "slot", "rule", "problem", "createRecipeRegistry", "recipes", "registry", "mergeRecipeSlotSchemas", "$type", "slotSchemas", "shape", "slot", "schema", "assertSlotDefaults", "slotDefaults", "value", "result", "problems", "issue", "assertAppearanceAxes", "appearanceAxes", "axes", "defineProtocolRecipeSpec", "protocol", "definition", "declared", "assertRecipeRules", "slots", "isPlainObject", "value", "prototype", "mergeDeep", "base", "override", "merged", "key", "mergeSlotDefaults", "view", "slotDefaults", "slot", "defaults", "isPlainRecord", "value", "prototype", "withoutAppearance", "config", "_authored", "rest", "parseSync", "schema", "result", "resolveRecipeView", "recipe", "view", "scope", "issues", "stripped", "resolved", "slot", "authoredSlot", "supported", "checked", "checkAppearance", "issue", "selection", "pickSupportedAppearance", "mergeAppearance", "parsed", "mergeSlotDefaults", "output", "allowedSlots", "key", "next", "slotConfig", "readSlotConfig", "viewConfig", "slot", "_schema"]
3
+ "sources": ["../src/schemas/appearance.ts", "../src/schemas/grid.ts", "../src/lib/appearance.ts", "../src/lib/grid-placement.ts", "../src/lib/grid-styles.ts", "../src/lib/layout-theme.ts", "../src/recipes/bind-recipe.ts", "../src/recipes/define-recipe-spec.ts", "../src/recipes/protocol.ts", "../src/recipes/resolve-recipe-view.ts", "../src/recipes/merge-slot-defaults.ts", "../src/recipes/view-model.ts"],
4
+ "sourcesContent": ["import * as z from 'zod/mini';\nimport type { AxisRegistry } from '@/lib/appearance';\n\n/**\n * A pick of named appearance values, one per axis: `{ size: 'compact' }`.\n *\n * @remarks\n * The shape is open because the axes belong to the theme (`createLayoutTheme({ appearance })`). A\n * domain checks each axis and value against the theme's vocabulary and the owner's declared axes.\n */\nexport const AppearanceConfigSchema = z.record(z.string(), z.string());\n\nexport type AppearanceConfig = z.infer<typeof AppearanceConfigSchema>;\n\n/**\n * The pick schema of one theme: each axis is an optional enum of its values, and any other axis is\n * rejected.\n *\n * @param supported Restricts the schema to the axes one owner declares; omit it for an owner that\n * accepts every axis of the theme (the document and its steps). An empty list is a closed object\n * with no axes. A name the theme does not hold is skipped, since an engine rejects it when it builds.\n *\n * @remarks\n * Built for a JSON Schema export, so an editor autocompletes `appearance.size`. The enums are fresh\n * schemas rather than the axes' own, so the export inlines them instead of referencing a catalog\n * entry. It is built from the same registry and declarations `checkAppearance` validates against.\n */\nexport function createAppearanceSchema(axes: AxisRegistry, supported?: readonly string[]) {\n\tconst entries = axes\n\t\t.all()\n\t\t.filter((axis) => supported === undefined || supported.includes(axis.$type))\n\t\t.map((axis) => [axis.$type, z.optional(z.enum(Object.keys(axis.values) as [string, ...string[]]))] as const);\n\treturn z.strictObject(Object.fromEntries(entries));\n}\n\n/**\n * @remarks\n * Only narrows the members of a schema's definition, which Zod types as the core base. A classic\n * Zod schema passes too, since it has the same methods, and is rewritten the same way.\n */\nfunction isMiniSchema(schema: z.core.$ZodType): schema is z.ZodMiniType {\n\treturn 'check' in schema && typeof schema.check === 'function';\n}\n\nfunction isObjectSchema(schema: z.ZodMiniType): schema is z.ZodMiniObject {\n\treturn schema._zod.def.type === 'object';\n}\n\nfunction isPipeSchema(schema: z.ZodMiniType): schema is z.ZodMiniPipe {\n\treturn schema._zod.def.type === 'pipe';\n}\n\nfunction isPrefaultSchema(schema: z.ZodMiniType): schema is z.ZodMiniPrefault {\n\treturn schema._zod.def.type === 'prefault';\n}\n\n/**\n * Sets the `appearance` key on the object a schema parses, looking through a pipe (its input) and\n * a prefault (its inner schema). Any other schema comes back as it is.\n */\nfunction setAppearance(schema: z.ZodMiniType, appearance: z.ZodMiniType): z.ZodMiniType {\n\tif (isObjectSchema(schema)) return z.safeExtend(schema, { appearance });\n\tif (isPipeSchema(schema)) {\n\t\tconst { in: input, out } = schema._zod.def;\n\t\tif (!isMiniSchema(input)) return schema;\n\t\tconst next = setAppearance(input, appearance);\n\t\treturn next === input ? schema : z.pipe(next, out);\n\t}\n\tif (isPrefaultSchema(schema)) {\n\t\tconst { innerType, defaultValue } = schema._zod.def;\n\t\tif (!isMiniSchema(innerType)) return schema;\n\t\tconst next = setAppearance(innerType, appearance);\n\t\treturn next === innerType ? schema : z.prefault(next, defaultValue);\n\t}\n\treturn schema;\n}\n\nfunction declaredAppearance(axes: AxisRegistry, supported: readonly string[]) {\n\treturn z\n\t\t.optional(createAppearanceSchema(axes, supported))\n\t\t.check(z.describe('Named appearance values, one per declared axis'));\n}\n\n/**\n * Sets the `appearance` key of an object schema to the closed schema of the axes its owner\n * declares, for a JSON Schema export.\n *\n * @param supported The owner's declared axes (`appearanceAxes`); omit it for an owner that declares none,\n * which gets a closed object with no axes.\n *\n * @remarks\n * Validation strips an authored `appearance` before it parses the owner's own schema and checks the\n * pick against the declared axes (`checkAppearance`), on every owner whatever its schema says. So the\n * key is set whether or not the schema has one, and replaces an open one. This keeps the export from\n * drifting from validation. A pipe is rewritten on its input, so a transform after the object stays.\n * A schema that is not an object, a pipe of one or a prefault of one (a lazy schema, for example) is\n * returned unchanged. The result is for export only: parse with the original.\n */\nexport function withAppearanceAxes(\n\tschema: z.ZodMiniType,\n\taxes: AxisRegistry,\n\tsupported: readonly string[] = [],\n): z.ZodMiniType {\n\treturn setAppearance(schema, declaredAppearance(axes, supported));\n}\n\n/**\n * Applies {@link withAppearanceAxes} to each slot of a recipe's view schema, with the axes the\n * recipe declares for that slot.\n *\n * @param slotAxes The recipe's `appearanceAxes`; a slot it does not list declares none.\n *\n * @remarks\n * Expects the shape `defineProtocolRecipeSpec` builds: a strict object whose slots are objects\n * wrapped in `prefault`. Validation resolves the appearance of every slot, so every slot gets the\n * key. Any other shape is returned unchanged.\n */\nexport function withSlotAppearanceAxes(\n\tschema: z.ZodMiniType,\n\taxes: AxisRegistry,\n\tslotAxes: Readonly<Record<string, readonly string[] | undefined>> = {},\n): z.ZodMiniType {\n\tif (!isObjectSchema(schema)) return schema;\n\tconst replaced: Record<string, z.ZodMiniType> = {};\n\tfor (const [slot, slotSchema] of Object.entries(schema._zod.def.shape)) {\n\t\tif (!isMiniSchema(slotSchema)) continue;\n\t\tconst next = withAppearanceAxes(slotSchema, axes, slotAxes[slot]);\n\t\tif (next !== slotSchema) replaced[slot] = next;\n\t}\n\tif (Object.keys(replaced).length === 0) return schema;\n\treturn z.safeExtend(schema, replaced);\n}\n", "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.int().check(z.positive()), 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\tautoFlow: z\n\t\t.optional(z.enum(['row', 'dense']))\n\t\t.check(\n\t\t\tz.describe(\n\t\t\t\t\"How items without a position fill the tracks: 'row' in source order, 'dense' backfills earlier gaps with later, smaller items. Dense changes the visual order, not the DOM or focus order. Top level only.\",\n\t\t\t),\n\t\t),\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\tspan: z\n\t\t.optional(z.int().check(z.positive()))\n\t\t.check(\n\t\t\tz.describe(\n\t\t\t\t'Number of tracks to span, never more than the grid has. Needs a grid with a known track count, so not `columns: \"auto\"`.',\n\t\t\t),\n\t\t),\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\tsubgrid: z\n\t\t.optional(z.boolean())\n\t\t.check(\n\t\t\tz.describe(\n\t\t\t\t\"Spans the parent grid's full row and lays this element's children on the parent's column tracks and gap. Set on a container element, never per breakpoint.\",\n\t\t\t),\n\t\t),\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(\n\tz.omit(ElementGridPropertiesSchema, { placeSelf: true, subgrid: true }),\n\t{\n\t\thidden: z.optional(z.boolean()),\n\t},\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 {\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 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/** One authored entry of an element's grid: its cascade slot, its keys, and where it sits in the element. */\ninterface GridSlotEntry {\n\tslot: CascadeSlot;\n\tentry: Record<string, unknown>;\n\t/** `['grid']` for the top level, `['grid', 'responsive', slot]` for a responsive entry, `default` included. */\n\tpath: readonly string[];\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): GridSlotEntry[] {\n\tif (!isRecord(element) || !isRecord(element.grid)) return [];\n\tconst grid = element.grid;\n\tconst slots: GridSlotEntry[] = [{ slot: 'default', entry: grid, path: ['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, path: ['grid', 'responsive', slot] });\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/** Whether an element lays its children on its parent grid's tracks (`grid.subgrid`). */\nexport function elementIsSubgrid(element: unknown): boolean {\n\treturn isRecord(element) && isRecord(element.grid) && element.grid.subgrid === true;\n}\n\n/** Placement keys a subgrid cannot set: it always spans its parent's full row and is stretched on it. */\nconst SUBGRID_EXCLUSIVE_KEYS = ['width', 'offset', 'column', 'area', 'span', 'justifySelf', 'placeSelf'] as const;\n\n/**\n * Why a subgrid's placement is invalid, or `undefined` when it is fine.\n *\n * @remarks\n * A subgrid spans its parent's full row, so a `width`, `offset`, `span`, raw `column` or `area` would make it\n * span less, and CSS ignores `justify-self` on a subgrid. The path is relative to the element and names the first\n * conflicting key at the slot that sets it, as authored; the message is a clause the domain prefixes with\n * the element's name.\n */\nexport function subgridPlacementIssue(element: unknown): LayoutIssue | undefined {\n\tif (!elementIsSubgrid(element)) return undefined;\n\tfor (const { entry, path } of elementGridSlots(element)) {\n\t\tconst key = SUBGRID_EXCLUSIVE_KEYS.find((name) => entry[name] !== undefined);\n\t\tif (key === undefined) continue;\n\t\treturn {\n\t\t\tpath: [...path, key],\n\t\t\tmessage: `sets grid 'subgrid' and '${key}'; a subgrid spans its parent's full row, so it takes no 'width', 'offset', 'column', 'area', 'span', 'justifySelf' or 'placeSelf'.`,\n\t\t};\n\t}\n\treturn undefined;\n}\n\n/** Placement keys that `span` cannot share a slot with, because each sets the item's `grid-column` too. */\nconst SPAN_EXCLUSIVE_KEYS = ['width', 'offset', 'column', 'area'] as const;\n\n/**\n * Why an element's `span` cannot sit beside its other placement, or `undefined` when it is fine.\n *\n * @remarks\n * `span` sets the item's column like `width`, `offset`, a raw `column` and an `area` do, so a slot that\n * sets it and one of them would have two answers. Slots may differ: a narrower slot's `width` and a\n * wider slot's `span` is the usual way to change sizing mode. The path is relative to the element and\n * names the first conflicting key at the slot that sets it, as authored; the message is a clause the\n * domain prefixes with the element's name.\n */\nexport function spanPlacementIssue(element: unknown): LayoutIssue | undefined {\n\tfor (const { slot, entry, path } of elementGridSlots(element)) {\n\t\tif (entry.span === undefined) continue;\n\t\tconst key = SPAN_EXCLUSIVE_KEYS.find((name) => entry[name] !== undefined);\n\t\tif (key === undefined) continue;\n\t\treturn {\n\t\t\tpath: [...path, key],\n\t\t\tmessage: `sets grid 'span' and '${key}'${slot === 'default' ? '' : ` at '${slot}'`}; a span is a placement of its own, so use 'span' or one of 'width', 'offset', 'column' and 'area' in a breakpoint, not together.`,\n\t\t};\n\t}\n\treturn undefined;\n}\n\n/**\n * Where each element's `span` meets a grid whose track count CSS cannot know.\n *\n * @param grid The grid that places `elements`; one with no `columns: 'auto'` has no issue.\n * @param elements The elements the grid places: its items, and the children of every subgrid among them.\n *\n * @remarks\n * `columns: 'auto'` makes as many tracks as fit, a count that depends on the container's width and the\n * minimum column width and cannot be computed in CSS, so a span there falls back to one track. Rather than\n * render that silently, each element is checked against every slot where the grid's cascaded `columns` is\n * `'auto'`, with the placement in effect there (the last one a narrower or equal slot set): a span counts, and\n * a wider slot's raw `column` replaces it. The first such slot is reported per element. A grid that draws\n * `areas` or whose items use named widths has a known count and has no issue.\n *\n * The path starts with the element's index in `elements`, then names the `span` key the author wrote at\n * the slot that sets the span in effect: `[2, 'grid', 'span']` or `[2, 'grid', 'responsive', 'md', 'span']`.\n * The message is a clause the domain prefixes with the element's name.\n */\nexport function gridSpanIssues(grid: unknown, elements: readonly unknown[]): LayoutIssue[] {\n\tif (!isRecord(grid) || gridUsesAreas(grid) || usesGridWidths(elements)) return [];\n\tconst columns: Partial<Record<CascadeSlot, unknown>> = {};\n\tfor (const { slot, entry } of elementGridSlots({ grid })) columns[slot] = entry.columns ?? columns[slot];\n\tconst autoSlots = new Set(\n\t\tcascadeValues(columns)\n\t\t\t.filter(({ value }) => value === 'auto')\n\t\t\t.map(({ slot }) => slot),\n\t);\n\tif (autoSlots.size === 0) return [];\n\n\tconst issues: LayoutIssue[] = [];\n\telements.forEach((element, index) => {\n\t\tconst placements: Partial<Record<CascadeSlot, { spanPath?: readonly string[] }>> = {};\n\t\tfor (const { slot, entry, path } of elementGridSlots(element)) {\n\t\t\tif (entry.span !== undefined) placements[slot] = { spanPath: [...path, 'span'] };\n\t\t\telse if (SPAN_EXCLUSIVE_KEYS.some((key) => entry[key] !== undefined)) placements[slot] = {};\n\t\t}\n\t\tconst offending = cascadeValues(placements).find(({ slot, value }) => autoSlots.has(slot) && value?.spanPath);\n\t\tconst spanPath = offending?.value?.spanPath;\n\t\tif (!offending || !spanPath) return;\n\t\tissues.push({\n\t\t\tpath: [index, ...spanPath],\n\t\t\tmessage: `sets grid 'span' where the grid's columns are 'auto'${offending.slot === 'default' ? '' : ` at '${offending.slot}'`}; CSS cannot know how many tracks 'auto' makes, so the span falls back to one track. Set 'columns' to a number, per breakpoint if it changes, and use a theme with query 'container' so the breakpoints follow the grid's container.`,\n\t\t});\n\t});\n\treturn issues;\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 generated media or container 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\t/**\n\t * What the breakpoints measure: the viewport (`'media'`, the default) or the grid's own available width (`'container'`).\n\t *\n\t * @remarks\n\t * Container mode emits `@container se-grid (min-width: ...)` where media mode emits `@media`, with\n\t * the same breakpoint tokens, gap ramps and cascade, so a document reads the same in both. The\n\t * rules query the nearest ancestor that carries {@link GRID_CONTAINER_CLASS}, which an element\n\t * cannot be for its own children's placement: the renderer wraps each grid in one, and markup you\n\t * write wraps each grid itself. A grid with no such ancestor never matches a breakpoint and keeps\n\t * its base layout.\n\t *\n\t * The theme decides how breakpoints are queried and the document says what changes at each, so a\n\t * document is unchanged by where it is mounted. In a container query `em` resolves against the\n\t * container's font size.\n\t */\n\tquery?: GridQueryMode;\n}\n\n/** How a theme's breakpoints are queried; see {@link GridThemeOptions.query}. */\nexport type GridQueryMode = 'media' | 'container';\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\treadonly query: GridQueryMode;\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 * Variable a host sets on an item to choose the display the item rule applies.\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 this variable\n * rather than `display`. Responsive `hidden` then toggles between `none` and\n * that mode instead of forcing `block`. Custom properties inherit, so the grid\n * rule resets it: a fieldset that sets `grid` for itself must not turn the\n * fields of its own grid into grids.\n */\nconst ITEM_DISPLAY_MODE_VARIABLE = '--se-item-display-mode';\n\n/** Display a visible item falls back to. See {@link ITEM_DISPLAY_MODE_VARIABLE}. */\nconst ITEM_DISPLAY_MODE = `var(${ITEM_DISPLAY_MODE_VARIABLE}, 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 (the default `query`) follow viewport width \u2014 a grid inside a\n * narrow sidebar still receives the desktop rules of the wide screen it lives\n * on; `query: 'container'` follows the grid's wrapper instead.\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\tconst query = options?.query ?? 'media';\n\tassertBreakpointOrder(breakpoints);\n\tassertQueryMode(query);\n\treturn deepFreeze({\n\t\tbreakpoints,\n\t\tgap,\n\t\tresponsive,\n\t\tminColumnWidth,\n\t\tquery,\n\t});\n}\n\nfunction assertQueryMode(query: string): asserts query is GridQueryMode {\n\tif (query !== 'media' && query !== 'container') {\n\t\tthrow new Error(`Grid theme query must be 'media' or 'container'; received '${query}'.`);\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/**\n * The normalized grid theme in a stable shape, for hashing into a layout theme id.\n *\n * @remarks\n * The default query mode is left out, so a media theme keeps the id it had before the option existed.\n */\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\t...(theme.query === 'media' ? {} : { query: theme.query }),\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/**\n * Class an element placed in a grid carries, and the stylesheet's hook for it. See {@link GRID_CLASS}.\n *\n * @remarks\n * An item and the grid it contains must be different elements, as they are in both renderers. An item's\n * `span` reads the track count its parent grid computed, and an element that is both would read its own.\n */\nexport const GRID_ITEM_CLASS = 'se-grid-item';\n\n/**\n * Class of every box that passes its parent grid's column tracks down to a nested grid, and the stylesheet's hook for it.\n *\n * @remarks\n * `grid-template-columns: subgrid` only works on a grid item of the grid whose tracks it takes, so the\n * element with `grid.subgrid`, every box between it and the grid that lays out its children, and that\n * {@link GRID_CLASS} grid itself must all carry this class. A box in the chain that does not (a plain\n * `div`) computes its template to `none` and the children fall back to one column, with nothing reported.\n *\n * Keep a `<fieldset>` out of the chain: Chromium lays a fieldset's content out in an anonymous box that does\n * not take the subgrid, so its children fall back to one column there (Firefox and WebKit pass the tracks on).\n * Use a box with `role=\"group\"` and `aria-labelledby` its heading instead, which gives the same group and name\n * to assistive technology in every engine; `display: contents` on the fieldset is no answer, since engines expose\n * its semantics inconsistently. The grid of the children gets no tracks of its own, so it takes no\n * {@link GRID_CONTAINER_CLASS} wrapper either: layout containment would make it an independent formatting\n * context, and a subgrid inside one is `none`. Its breakpoints are queried against the container of the grid\n * the chain hangs from.\n */\nexport const GRID_SUBGRID_CLASS = 'se-subgrid';\n\n/**\n * Class of the element a grid in a `query: 'container'` theme is measured against, and the stylesheet's hook for it.\n *\n * @remarks\n * Put it, with `data-se-theme`, on an element that wraps one grid and fills its parent: the\n * breakpoints then follow that element's width. It must be an ancestor of the grid, because the\n * template of a grid and the placement of its items have to query one box, and an element cannot\n * query its own size. The stylesheet declares it only in container mode, as a block with\n * `container-type: inline-size`. Inline-size containment means it no longer sizes to its content, so\n * it collapses in a shrink-to-fit parent (an inline-block, a flex item without a basis, an `auto` grid\n * track). Wrap each grid, nested grids included, so an inner grid follows its own box.\n */\nexport const GRID_CONTAINER_CLASS = 'se-grid-container';\n\n/** Name of the container the container-mode rules query, so an unrelated container in between cannot capture them. */\nconst GRID_CONTAINER_NAME = 'se-grid';\n\n/**\n * Custom property a grid declares with the number of column tracks its template draws, which its items read to clamp a `span`.\n *\n * @remarks\n * It is a row of {@link GRID_PROPERTIES}, so it follows the template through the same gated cascade, per\n * slot and in both query modes, and a `span` clamps at the width the template switches at. The renderer\n * writes the count beside each template as `--se-grid-tracks[-slot]` ({@link getGridVariables}); an\n * unauthored grid draws one track. A subgrid inherits the resolved count of the grid it sits in, since\n * its children are placed on that grid's tracks.\n */\nconst TRACK_COUNT_VARIABLE = '--se-grid-track-count';\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\t[TRACK_COUNT_VARIABLE, 'se-grid-tracks', '1'],\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\t['grid-auto-flow', 'se-grid-auto-flow', 'row'],\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. In a media theme\n * every element of a theme shares the viewport, so one that is reached declares its own gates\n * wherever the query applies and needs no reset. A container theme measures each grid against its\n * own container, so a nested grid can sit below a breakpoint its ancestor is above and would read the\n * ancestor's gate: its rules reset every gate ({@link gateResets}).\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 * Resets every gate of a table, so an element reads only the gates its own container's query declares.\n *\n * @remarks\n * A gate is declared on the element a query matches and inherits from there. Under a container query a\n * nested grid or item sits in a narrower container than its ancestors, so the breakpoint they match\n * can be one it does not, and it would take their resolved values over its own cascade. `initial`\n * returns the gate to the guaranteed-invalid value, which the `var()` chain skips; the element's own\n * matching query block comes later in the sheet at the same specificity and declares it again.\n */\nfunction gateResets(themeId: string, table: string, properties: readonly ResponsiveProperty[]): string {\n\treturn properties\n\t\t.flatMap((_, row) => BREAKPOINT_ORDER.map((slot) => `${gateName(themeId, table, row, slot)}: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 * A `query: 'container'` theme changes the at-rule, to `@container se-grid`, adds the rule of\n * {@link GRID_CONTAINER_CLASS} and resets each grid's and item's gates in its base rule\n * ({@link gateResets}); a media theme emits neither.\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 subgridScope = `.${GRID_SUBGRID_CLASS}${scope}`;\n\tconst tokens = GridGapTokens.map((token) => `${gapBaseVariable(token)}:${theme.gap[token]};`).join('');\n\tconst container = theme.query === 'container';\n\tconst atRule = container ? `@container ${GRID_CONTAINER_NAME}` : '@media';\n\tconst lines: string[] = [\n\t\t`${scope}{${tokens}}`,\n\t\t...(container\n\t\t\t? [\n\t\t\t\t\t`.${GRID_CONTAINER_CLASS}${scope}{display:block;width:100%;min-width:0;container-type:inline-size;container-name:${GRID_CONTAINER_NAME};}`,\n\t\t\t\t]\n\t\t\t: []),\n\t\t`${subgridScope}{${ITEM_DISPLAY_MODE_VARIABLE}:grid;display:grid;grid-template-columns:subgrid;column-gap:normal;align-content:start;}`,\n\t\t`${subgridScope}>:not(.${GRID_ITEM_CLASS}){grid-column:1/-1;}`,\n\t\t`${gridScope}{${container ? gateResets(themeId, 'g', GRID_PROPERTIES) : ''}${inheritanceResets(GRID_PROPERTIES, true)}${inheritanceResets(GRID_ALIGNMENT_PROPERTIES, false)}${DEFAULT_COLUMN_VARIABLE}:initial;${ITEM_DISPLAY_MODE_VARIABLE}:initial;display:grid;${declarations(themeId, 'g', GRID_PROPERTIES)}${flatDeclarations(GRID_ALIGNMENT_PROPERTIES)}}`,\n\t\t`.${GRID_CLASS}${subgridScope}{--se-grid-template:subgrid;--se-grid-gap-x:normal;${DEFAULT_COLUMN_VARIABLE}:inherit;${TRACK_COUNT_VARIABLE}:inherit;}`,\n\t\t`${itemScope}{${container ? gateResets(themeId, 'i', ITEM_PROPERTIES) : ''}${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`${atRule} (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\tspan?: number;\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 * The items include the children of every subgrid element, however deep, because a subgrid places\n * them on this grid's tracks; a domain walks its children and passes them in. The grid of a subgrid\n * has no tracks of its own, so its renderer does not call this.\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\t'--se-grid-auto-flow': grid?.autoFlow,\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\tvariables[customProperty('se-grid-tracks', slot)] = String(columns === 'auto' ? 1 : columns);\n\t};\n\n\tif (usesGridWidths(elements)) {\n\t\tvariables['--se-grid-template'] = `repeat(${WIDTH_TRACKS}, minmax(0, 1fr))`;\n\t\tvariables['--se-grid-tracks'] = String(WIDTH_TRACKS);\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\tvariables[customProperty('se-grid-tracks', slot)] = String(rows[0]?.length ?? 1);\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\n/**\n * `grid-column` for a numeric span: `n` tracks, or the grid's own track count when that is fewer.\n *\n * @remarks\n * The count is {@link TRACK_COUNT_VARIABLE}, which the item inherits from the grid it sits in, so the clamp\n * changes at the width the grid's template does. `var()` inside `min()` inside a grid line is valid in Chromium,\n * Firefox and WebKit (the browser test of this package measures it); a grid that publishes no count gives\n * one track, never an implicit column.\n */\nfunction spanColumn(span: number): string {\n\treturn `span min(${span},var(${TRACK_COUNT_VARIABLE},1))`;\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.span !== undefined) {\n\t\tvariables[customProperty('se-item-grid-column', slot)] = spanColumn(entry.span);\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 * `subgrid` makes the element span `1 / -1`, its parent's whole row. It is the only placement a\n * subgrid takes, so validation rejects the other column keys beside it, and the stylesheet does the rest\n * under {@link GRID_SUBGRID_CLASS}.\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\tif (grid?.subgrid) variables['--se-item-grid-column'] = '1 / -1';\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", "import type { StandardSchemaV1 } from '@standard-schema/spec';\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 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 StandardSchemaV1,\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\tslotSchemas: spec.slotSchemas,\n\t\trender,\n\t};\n}\n", "import type { StandardSchemaV1 } from '@standard-schema/spec';\nimport { formatIssuePath, safeParseStandardSchema, standardSchema } from '@schema-engine/registry';\nimport type { AppearanceAxisList, SlotAppearanceAxes } from '../lib/appearance';\nimport { assertRecipeRules, type RecipeProtocol } from './protocol';\nimport { unknownViewKeyMessage } from './resolve-recipe-view';\nimport type { RecipeMetadata, RecipeSlotDefaults, ProtocolRecipeSlotSchemas, ProtocolRecipeSpec } from './types';\n\ntype Flat<T> = { [K in keyof T]: T[K] };\n\n/** What an author writes for a view: the literal `$type`, every declared slot optional. */\ntype RecipeViewSchemaInput<TType extends string, TSlots extends ProtocolRecipeSlotSchemas> = Flat<\n\t{ $type: TType } & { -readonly [K in keyof TSlots]?: StandardSchemaV1.InferInput<NonNullable<TSlots[K]>> }\n>;\n\n/** A parsed view: every declared slot present, as its schema outputs it. */\ntype RecipeViewSchemaOutput<TType extends string, TSlots extends ProtocolRecipeSlotSchemas> = Flat<\n\t{ $type: TType } & { -readonly [K in keyof TSlots]-?: StandardSchemaV1.InferOutput<NonNullable<TSlots[K]>> }\n>;\n\n/**\n * Strict view schema of a spec: the literal `$type` plus each declared slot, which parses from `{}` when omitted.\n *\n * @remarks\n * A Standard Schema, not a schema of any one library, so slot schemas can come from any library. It validates\n * synchronously and so needs synchronous slot schemas: a slot that validates asynchronously throws where the view is\n * parsed. A slot is an optional key on input and always present on output, so each slot schema's own defaults fill\n * it. A key outside `$type` and the declared slots is an issue at `[key]`. The input and output types let the engine\n * infer the authoring type of `view` from a registration.\n */\nexport type RecipeViewSchema<TType extends string, TSlots extends ProtocolRecipeSlotSchemas> = StandardSchemaV1<\n\tRecipeViewSchemaInput<TType, TSlots>,\n\tRecipeViewSchemaOutput<TType, TSlots>\n>;\n\n/** The axes a spec may declare per slot: a slot whose schema input has no `appearance` key takes none. */\ntype SlotAppearanceAxesOf<TSlots extends ProtocolRecipeSlotSchemas> = {\n\t[K in keyof TSlots]?: 'appearance' extends keyof StandardSchemaV1.InferInput<NonNullable<TSlots[K]>>\n\t\t? AppearanceAxisList\n\t\t: never;\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 *\n * `appearanceAxes` accepts only slots whose schema input has an `appearance` key, so a slot that cannot\n * be given a pick does not declare axes.\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?: SlotAppearanceAxesOf<NoInfer<TSlots>>;\n}\n\n/**\n * @remarks\n * The output 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. A slot an author omits\n * is validated as `{}`, as an object's own defaults would fill it.\n */\nfunction createRecipeViewSchema<const TType extends string, const TSlots extends ProtocolRecipeSlotSchemas>(\n\t$type: TType,\n\tslots: readonly string[],\n\tslotSchemas: TSlots,\n): RecipeViewSchema<TType, TSlots> {\n\treturn standardSchema<RecipeViewSchemaOutput<TType, TSlots>, RecipeViewSchemaInput<TType, TSlots>>((value) => {\n\t\tif (typeof value !== 'object' || value === null || Array.isArray(value)) {\n\t\t\treturn { issues: [{ message: 'Expected a view object.', path: [] }] };\n\t\t}\n\t\tconst view = value as Record<string, unknown>;\n\t\tconst issues: StandardSchemaV1.Issue[] = [];\n\t\tif (view.$type !== $type) {\n\t\t\tissues.push({ message: `Expected $type '${$type}'.`, path: ['$type'] });\n\t\t}\n\t\tfor (const key of Object.keys(view)) {\n\t\t\tif (key !== '$type' && !slots.includes(key)) {\n\t\t\t\tissues.push({ message: unknownViewKeyMessage($type, key, slots), path: [key] });\n\t\t\t}\n\t\t}\n\t\tconst output: Record<string, unknown> = { $type };\n\t\tfor (const slot of slots) {\n\t\t\tconst schema = slotSchemas[slot];\n\t\t\tif (!schema) continue;\n\t\t\tconst result = safeParseStandardSchema(schema, view[slot] === undefined ? {} : view[slot]);\n\t\t\tif (result.success) {\n\t\t\t\toutput[slot] = result.data;\n\t\t\t} else {\n\t\t\t\tissues.push(...result.error.issues.map((issue) => ({ ...issue, path: [slot, ...(issue.path ?? [])] })));\n\t\t\t}\n\t\t}\n\t\treturn issues.length > 0 ? { issues } : { value: output as RecipeViewSchemaOutput<TType, TSlots> };\n\t});\n}\n\n/**\n * One `<path>: <message>` line per location a slot schema issue points at, so a message names the offending key.\n *\n * @remarks\n * A Standard Schema issue carries a message and a path. A library may also report the offending `keys` of the object\n * at that path (Zod's unknown keys do, with the generic `Invalid input` when no locale is loaded), so each reported\n * key gets its own line at the key, the same place forms' validation points such an issue at. An empty path reads `(value)`.\n */\nfunction describeSlotIssue(issue: StandardSchemaV1.Issue): string[] {\n\tconst reported: unknown = (issue as StandardSchemaV1.Issue & { keys?: unknown }).keys;\n\tconst keys = Array.isArray(reported)\n\t\t? reported.filter((key): key is string | number => typeof key === 'string' || typeof key === 'number')\n\t\t: [];\n\tconst paths = keys.length > 0 ? keys.map((key) => [...(issue.path ?? []), key]) : [issue.path];\n\treturn paths.map((path) => `${formatIssuePath(path) || '(value)'}: ${issue.message}`);\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 = safeParseStandardSchema(schema, value);\n\t\tif (!result.success) {\n\t\t\tconst problems = result.error.issues.flatMap(describeSlotIssue);\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.\n *\n * @remarks\n * That the slot schema accepts an `appearance` key is a type constraint on\n * {@link ProtocolRecipeSpecDefinition.appearanceAxes}, not a runtime probe: Standard Schema reports no issue codes\n * to find a rejected key with, and validation removes `appearance` before the slot schema parses.\n */\nfunction assertAppearanceSlots(\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 && !slotSchemas[slot]) {\n\t\t\tthrow new Error(`Recipe '${$type}' appearanceAxes.${slot}: the recipe does not declare a '${slot}' slot.`);\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 *\n * A slot schema is any Standard Schema that validates synchronously. A spec that leaves out `slotSchemas` declares\n * no slots, so `TSlots` defaults to the empty object type.\n */\nexport function defineProtocolRecipeSpec<\n\tTSlot extends string,\n\tTKind extends string,\n\tconst TType extends string,\n\tconst TSlots extends ProtocolRecipeSlotSchemas<TSlot> = {},\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\tassertAppearanceSlots(definition.$type, slotSchemas, definition.appearanceAxes as SlotAppearanceAxes | undefined);\n\tconst schema = createRecipeViewSchema(definition.$type, slots, 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 {\n\tassertStandardSchema,\n\tcreateRegistry,\n\ttype BaseRegistration,\n\ttype ReadOnlyRegistry,\n} 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 * Checks that the slot schemas a registration carries are exactly its declared slots, each a Standard Schema.\n *\n * @throws {Error} Naming the recipe, its kind and `$type`\n *\n * @remarks\n * A registration without `slotSchemas` passes: a hand-written one need not state them.\n */\nfunction assertSlotSchemas(\n\tkind: string,\n\trecipe: RecipeShape & { readonly slotSchemas?: Readonly<Partial<Record<string, unknown>>> },\n): void {\n\tconst { slotSchemas } = recipe;\n\tif (slotSchemas === undefined) return;\n\tconst context = `${kind} '${recipe.$type}' slotSchemas`;\n\tconst listed = Object.keys(slotSchemas).filter((slot) => slotSchemas[slot] !== undefined);\n\tconst missing = recipe.slots.filter((slot) => !listed.includes(slot));\n\tconst extra = listed.filter((slot) => !recipe.slots.includes(slot));\n\tif (missing.length > 0 || extra.length > 0) {\n\t\tthrow new Error(\n\t\t\t`${context} must list exactly the recipe's slots (${recipe.slots.join(', ') || 'none'}): ${[\n\t\t\t\t...missing.map((slot) => `'${slot}' has no schema`),\n\t\t\t\t...extra.map((slot) => `'${slot}' is not a declared slot`),\n\t\t\t].join(', ')}.`,\n\t\t);\n\t}\n\tfor (const slot of listed) {\n\t\tassertStandardSchema(slotSchemas[slot], `${context}.${slot}`);\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, has no Standard Schema, or\n * carries `slotSchemas` that differ from its slots or are not Standard Schemas\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 &\n\t\tRecipeShape<TSlot, TKind> & { readonly slotSchemas?: Readonly<Partial<Record<string, unknown>>> },\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\tassertSlotSchemas(registry.kind, recipe);\n\t}\n\treturn registry;\n}\n", "import type { StandardSchemaV1 } from '@standard-schema/spec';\nimport { safeParseStandardSchema } from '@schema-engine/registry';\nimport { checkAppearance, mergeAppearance, pickSupportedAppearance, type SlotAppearanceAxes } from '../lib/appearance';\nimport type { LayoutIssue } from '../lib/layout-issue';\nimport type { LayoutTheme } from '../lib/layout-theme';\nimport { mergeSlotDefaults } from './merge-slot-defaults';\n\n/** Appearance picks a view inherits: the theme's vocabulary, and what the containing document picked. */\nexport interface RecipeViewScope {\n\treadonly axes: LayoutTheme['axes'];\n\treadonly inherited: Readonly<Record<string, string>>;\n}\n\n/** The part of a recipe registration that resolving a view reads. */\nexport interface RecipeViewSource {\n\treadonly $type: string;\n\treadonly slots: readonly string[];\n\treadonly schema: StandardSchemaV1;\n\treadonly slotDefaults?: Readonly<Record<string, unknown>>;\n\treadonly appearanceAxes?: SlotAppearanceAxes;\n}\n\n/** An authored view: the recipe's `$type` and the config of its slots. */\nexport type RecipeViewInput = Readonly<Record<string, unknown>> & { readonly $type: string };\n\n/**\n * What {@link resolveRecipeView} found.\n *\n * @remarks\n * `view` is present when the schema parsed and kept its `$type`; it can still come with `issues`\n * (an appearance pick that is not valid, or a key the recipe does not declare). `schemaIssues` is\n * present, with no `view`, when the schema rejected the view: the caller formats them, since only\n * the domain knows how it reports a schema's issues.\n */\nexport interface ResolvedRecipeView {\n\t/** One issue per problem, with a path relative to the view (`[slot, 'appearance', axis]`, `[key]`). */\n\tissues: LayoutIssue[];\n\tview?: Record<string, unknown>;\n\tschemaIssues?: StandardSchemaV1.Issue[];\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n\tif (typeof value !== 'object' || value === null) return false;\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === Object.prototype || prototype === null;\n}\n\nfunction withoutAppearance(config: Record<string, unknown>): Record<string, unknown> {\n\tif (!('appearance' in config)) return config;\n\tconst { appearance: _authored, ...rest } = config;\n\treturn rest;\n}\n\n/** The issue message for a view key that the recipe does not declare, shared by the view schema and {@link resolveRecipeView}. */\nexport function unknownViewKeyMessage($type: string, key: string, allowed: readonly string[]): string {\n\treturn `Recipe '${$type}' does not accept view key '${key}'. Allowed: ${allowed.join(', ') || '(none)'}.`;\n}\n\n/**\n * Resolves the view a document selects for a recipe: the recipe defaults laid under the author's\n * slot config, each slot's appearance, the schema parse, and the keys the recipe does not declare.\n *\n * @param recipe - The winning registration the view's `$type` selects\n * @param view - The authored view; not changed\n * @param scope - The picks the view inherits from its document\n *\n * @remarks\n * Slot appearance follows the recipe's inheritance rule: the document's picks reach a slot for the\n * axes the recipe declares on it, and the slot's own pick wins. The authored `appearance` key is\n * removed before the slot schema parses, so a schema only has to type it, and the resolved\n * selection is written back on the slot when it is not empty. Domain rules that need the document\n * (a kind that wants one step, a default recipe) stay with the domain's validator.\n */\nexport function resolveRecipeView(\n\trecipe: RecipeViewSource,\n\tview: RecipeViewInput,\n\tscope: RecipeViewScope,\n): ResolvedRecipeView {\n\tconst issues: LayoutIssue[] = [];\n\tconst stripped: Record<string, unknown> = { ...view };\n\tconst resolved: Record<string, Record<string, string>> = {};\n\tfor (const slot of recipe.slots) {\n\t\tconst authoredSlot = view[slot];\n\t\tconst supported = recipe.appearanceAxes?.[slot] ?? [];\n\t\tconst checked = checkAppearance(isPlainRecord(authoredSlot) ? authoredSlot.appearance : undefined, {\n\t\t\taxes: scope.axes,\n\t\t\tsubject: `Slot '${slot}' of recipe '${recipe.$type}'`,\n\t\t\tsupported,\n\t\t});\n\t\tissues.push(...checked.issues.map((issue) => ({ ...issue, path: [slot, ...issue.path] })));\n\t\tconst selection = pickSupportedAppearance(mergeAppearance(scope.inherited, checked.appearance), supported);\n\t\tif (Object.keys(selection).length > 0) resolved[slot] = selection;\n\t\tif (isPlainRecord(authoredSlot)) stripped[slot] = withoutAppearance(authoredSlot);\n\t}\n\n\tconst parsed = safeParseStandardSchema(recipe.schema, mergeSlotDefaults(stripped, recipe.slotDefaults));\n\tif (!parsed.success) return { issues, schemaIssues: parsed.error.issues };\n\tconst output = parsed.data;\n\tif (typeof output !== 'object' || output === null || !('$type' in output) || typeof output.$type !== 'string') {\n\t\tissues.push({\n\t\t\tpath: ['$type'],\n\t\t\tmessage: `Invalid view configuration for recipe '${recipe.$type}': parsed output is missing $type.`,\n\t\t});\n\t\treturn { issues };\n\t}\n\n\tconst allowedSlots = new Set<string>(recipe.slots);\n\tfor (const key of Object.keys(view)) {\n\t\tif (key !== '$type' && !allowedSlots.has(key)) {\n\t\t\tissues.push({ path: [key], message: unknownViewKeyMessage(recipe.$type, key, recipe.slots) });\n\t\t}\n\t}\n\n\tconst next: Record<string, unknown> = { ...output };\n\tfor (const [slot, selection] of Object.entries(resolved)) {\n\t\tconst slotConfig = (output as Record<string, unknown>)[slot];\n\t\tif (isPlainRecord(slotConfig)) next[slot] = { ...slotConfig, appearance: selection };\n\t}\n\treturn { issues, view: next };\n}\n", "/**\n * @remarks\n * Duplicates the helper the forms package keeps for its own deep operations on purpose: this\n * package cannot import forms.\n */\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n\tif (typeof value !== 'object' || value === null) return false;\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === Object.prototype || prototype === null;\n}\n\nfunction mergeDeep(base: unknown, override: unknown): unknown {\n\tif (override === undefined) return base;\n\tif (!isPlainObject(base) || !isPlainObject(override)) return override;\n\tconst merged: Record<string, unknown> = { ...base };\n\tfor (const [key, value] of Object.entries(override)) {\n\t\tmerged[key] = mergeDeep(base[key], value);\n\t}\n\treturn merged;\n}\n\n/**\n * Lays a view's slot config over the recipe's `slotDefaults`, deep for plain objects.\n *\n * @remarks\n * Runs before the view schema parses, so schema defaults fill only what neither the author\n * nor the recipe set. Arrays and other non-plain values replace the default whole. A key the author sets to `undefined` keeps the recipe default.\n */\nexport function mergeSlotDefaults(\n\tview: Record<string, unknown>,\n\tslotDefaults: Record<string, unknown> | undefined,\n): Record<string, unknown> {\n\tif (!slotDefaults) return view;\n\tconst merged = { ...view };\n\tfor (const [slot, defaults] of Object.entries(slotDefaults)) {\n\t\tmerged[slot] = mergeDeep(defaults, view[slot]);\n\t}\n\treturn merged;\n}\n", "import type { StandardSchemaV1 } from '@standard-schema/spec';\n\n/**\n * What every recipe renderer receives, whatever the domain: the recipe's kind and the resolved view.\n *\n * @remarks\n * A domain extends it with what its renderers also need, for example the steps of a form.\n */\nexport interface RecipeViewModel<TKind extends string = string> {\n\tkind: TKind;\n\tviewConfig: Record<string, unknown>;\n}\n\n/**\n * Reads one slot's complete config from a resolved view.\n *\n * @remarks\n * `schema` only types the result. The view is already complete, and parsing it again with the\n * block's own strict schema would reject a custom recipe whose slot schema extends the block's\n * with extra keys.\n */\nexport function readSlotConfig<TSchema extends StandardSchemaV1>(\n\tviewConfig: Record<string, unknown>,\n\tslot: string,\n\t_schema: TSchema,\n): StandardSchemaV1.InferOutput<TSchema> {\n\treturn viewConfig[slot] as StandardSchemaV1.InferOutput<TSchema>;\n}\n"],
5
+ "mappings": "AAAA,UAAYA,MAAO,WAUZ,IAAMC,GAA2B,SAAS,SAAO,EAAK,SAAO,CAAC,EAiB9D,SAASC,GAAuBC,EAAoBC,EAA+B,CACzF,IAAMC,EAAUF,EACd,IAAI,EACJ,OAAQG,GAASF,IAAc,QAAaA,EAAU,SAASE,EAAK,KAAK,CAAC,EAC1E,IAAKA,GAAS,CAACA,EAAK,MAAS,WAAW,OAAK,OAAO,KAAKA,EAAK,MAAM,CAA0B,CAAC,CAAC,CAAU,EAC5G,OAAS,eAAa,OAAO,YAAYD,CAAO,CAAC,CAClD,CAOA,SAASE,EAAaC,EAAkD,CACvE,MAAO,UAAWA,GAAU,OAAOA,EAAO,OAAU,UACrD,CAEA,SAASC,GAAeD,EAAkD,CACzE,OAAOA,EAAO,KAAK,IAAI,OAAS,QACjC,CAEA,SAASE,GAAaF,EAAgD,CACrE,OAAOA,EAAO,KAAK,IAAI,OAAS,MACjC,CAEA,SAASG,GAAiBH,EAAoD,CAC7E,OAAOA,EAAO,KAAK,IAAI,OAAS,UACjC,CAMA,SAASI,EAAcJ,EAAuBK,EAA0C,CACvF,GAAIJ,GAAeD,CAAM,EAAG,OAAS,aAAWA,EAAQ,CAAE,WAAAK,CAAW,CAAC,EACtE,GAAIH,GAAaF,CAA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AwBF,EAAQP,CAAK,EACpD,GAAI,CAACQ,EAAO,QAAS,CACpB,IAAMU,EAAWV,EAAO,MAAM,OAAO,QAAQG,EAAiB,EAC9D,MAAM,IAAI,MAAM,WAAWf,CAAK,kBAAkBU,CAAI,gBAAgBY,EAAS,KAAK,IAAI,CAAC,EAAE,CAC5F,CACD,CACD,CAUA,SAASC,GACRvB,EACAE,EACAsB,EACO,CACP,OAAW,CAACd,EAAMe,CAAI,IAAK,OAAO,QAAQD,GAAkB,CAAC,CAAC,EAC7D,GAAIC,GAAQ,CAACvB,EAAYQ,CAAI,EAC5B,MAAM,IAAI,MAAM,WAAWV,CAAK,oBAAoBU,CAAI,oCAAoCA,CAAI,SAAS,CAG5G,CAeO,SAASgB,GAMfC,EACAC,EACmF,CACnF,IAAM1B,EAAe0B,EAAW,aAAe,CAAC,EAC1CC,EAAW,OAAO,KAAK3B,CAAW,EAAE,OAAQQ,GAASR,EAAYQ,CAAa,CAAC,EACrFoB,EAAkBH,EAAU,CAAE,MAAOC,EAAW,MAAO,KAAMA,EAAW,KAAM,MAAOC,CAAS,CAAC,EAC/F,IAAM5B,EAAQ0B,EAAS,MAAM,OAAQjB,GAASR,EAAYQ,CAAI,CAAC,EAC/DU,GAAmBQ,EAAW,MAAO1B,EAAa0B,EAAW,YAAY,EACzEL,GAAsBK,EAAW,MAAO1B,EAAa0B,EAAW,cAAgD,EAChH,IAAMjB,EAASZ,GAAuB6B,EAAW,MAAO3B,EAAOC,CAAW,EAC1E,MAAO,CACN,MAAO0B,EAAW,MAClB,KAAMA,EAAW,KACjB,MAAA3B,EACA,YAAAC,EACA,aAAc0B,EAAW,aACzB,eAAgBA,EAAW,eAC3B,SAAUA,EAAW,SACrB,OAAAjB,CACD,CACD,CI3LO,SAASoB,GACfC,EACAC,EACAC,EACwC,CACxC,OAAOF,EAAWC,CAAI,CACvB",
6
+ "names": ["z", "AppearanceConfigSchema", "createAppearanceSchema", "axes", "supported", "entries", "axis", "isMiniSchema", "schema", "isObjectSchema", "isPipeSchema", "isPrefaultSchema", "setAppearance", "appearance", "input", "out", "next", "innerType", "defaultValue", "declaredAppearance", "withAppearanceAxes", "withSlotAppearanceAxes", "slotAxes", "replaced", "slot", "slotSchema", "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", "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", "getAppearanceAttributes", "attributes", "mergeAppearance", "inherited", "own", "isRecord", "checkAppearance", "authored", "options", "issues", "declared", "values", "supported", "pickSupportedAppearance", "selection", "picked", "BREAKPOINT_ORDER", "CASCADE_SLOTS", "WIDTH_TRACKS", "WIDTH_SPANS", "GRID_TEMPLATE_KEYS", "isRecord", "value", "elementGridSlots", "element", "grid", "slots", "responsive", "slot", "entry", "elementGridKeys", "keys", "key", "elementUsesGridWidths", "usesGridWidths", "elements", "elementIsSubgrid", "SUBGRID_EXCLUSIVE_KEYS", "subgridPlacementIssue", "path", "name", "SPAN_EXCLUSIVE_KEYS", "spanPlacementIssue", "gridSpanIssues", "gridUsesAreas", "columns", "autoSlots", "cascadeValues", "issues", "index", "placements", "offending", "spanPath", "carryNamedPlacement", "carried", "namedPlacementOverflow", "tracks", "EMPTY_CELL", "splitRow", "row", "cell", "toRows", "rows", "gridAreaTemplates", "templates", "areaNames", "names", "areasTemplateValue", "elementAreaSlots", "areas", "elementHiddenSlots", "hidden", "authored", "cellCount", "count", "isRectangle", "cells", "rowIndex", "columnIndex", "rowsUsed", "columnsUsed", "column", "height", "width", "areaTemplateIssues", "arrayForm", "ragged", "DEFAULT_BREAKPOINTS", "DEFAULT_GAP", "DEFAULT_MIN_COLUMN_WIDTH", "GAP_TOKEN_VARIABLES", "gapBaseVariable", "token", "gapTokenValue", "DEFAULT_GAP_CSS", "ITEM_DISPLAY_MODE_VARIABLE", "ITEM_DISPLAY_MODE", "ROOT_FONT_PX", "deepFreeze", "value", "child", "resolveResponsiveGap", "overrides", "resolved", "breakpoint", "BREAKPOINT_ORDER", "entry", "tokens", "GridGapTokens", "resolveGridTheme", "options", "breakpoints", "gap", "responsive", "minColumnWidth", "query", "assertBreakpointOrder", "assertQueryMode", "isCssLengthUnit", "unit", "thresholdToPx", "threshold", "match", "rawUnit", "previousPx", "previousToken", "px", "canonicalResponsiveGap", "canonicalGridTheme", "theme", "GRID_CLASS", "GRID_ITEM_CLASS", "GRID_SUBGRID_CLASS", "GRID_CONTAINER_CLASS", "GRID_CONTAINER_NAME", "TRACK_COUNT_VARIABLE", "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", "gateResets", "_", "getGridThemeCss", "scope", "gridScope", "itemScope", "subgridScope", "container", "atRule", "lines", "ramped", "rampedTokens", "isGridGapToken", "resolveGridGap", "AXIS_QUALIFIERS", "splitPlaceShorthand", "alignLength", "align", "justify", "toGridTemplate", "columns", "customProperty", "emitGapEntry", "variables", "entryGap", "gapX", "gapY", "getGridVariables", "grid", "elements", "placeAlignItems", "placeJustifyItems", "placeAlignContent", "placeJustifyContent", "alignment", "emitTemplate", "usesGridWidths", "WIDTH_TRACKS", "templates", "gridAreaTemplates", "CASCADE_SLOTS", "rows", "areasTemplateValue", "namedColumn", "width", "offset", "start", "WIDTH_SPANS", "span", "spanColumn", "formatGridLine", "emitItemEntry", "named", "carryNamedPlacement", "marginBlockStart", "marginBlockEnd", "getGridItemVariables", "alignSelf", "justifySelf", "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", "bindRecipe", "spec", "render", "formatIssuePath", "safeParseStandardSchema", "standardSchema", "assertStandardSchema", "createRegistry", "assertUnique", "values", "noun", "seen", "value", "defineRecipeProtocol", "definition", "assertRecipeRules", "protocol", "recipe", "kinds", "slots", "slot", "rule", "problem", "assertSlotSchemas", "kind", "slotSchemas", "context", "listed", "missing", "extra", "createRecipeRegistry", "recipes", "registry", "safeParseStandardSchema", "isPlainObject", "value", "prototype", "mergeDeep", "base", "override", "merged", "key", "mergeSlotDefaults", "view", "slotDefaults", "slot", "defaults", "isPlainRecord", "value", "prototype", "withoutAppearance", "config", "_authored", "rest", "unknownViewKeyMessage", "$type", "key", "allowed", "resolveRecipeView", "recipe", "view", "scope", "issues", "stripped", "resolved", "slot", "authoredSlot", "supported", "checked", "checkAppearance", "issue", "selection", "pickSupportedAppearance", "mergeAppearance", "parsed", "safeParseStandardSchema", "mergeSlotDefaults", "output", "allowedSlots", "next", "slotConfig", "createRecipeViewSchema", "$type", "slots", "slotSchemas", "standardSchema", "value", "view", "issues", "key", "unknownViewKeyMessage", "output", "slot", "schema", "result", "safeParseStandardSchema", "issue", "describeSlotIssue", "reported", "keys", "path", "formatIssuePath", "assertSlotDefaults", "slotDefaults", "problems", "assertAppearanceSlots", "appearanceAxes", "axes", "defineProtocolRecipeSpec", "protocol", "definition", "declared", "assertRecipeRules", "readSlotConfig", "viewConfig", "slot", "_schema"]
7
7
  }