@tenphi/eslint-plugin-tasty 1.8.2 → 1.8.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/context.js +17 -0
- package/dist/context.js.map +1 -1
- package/dist/parsers/state-key-parser.js +27 -1
- package/dist/parsers/state-key-parser.js.map +1 -1
- package/dist/parsers/utils.js +26 -1
- package/dist/parsers/utils.js.map +1 -1
- package/dist/rules/no-own-at-root.js +6 -6
- package/dist/rules/no-own-at-root.js.map +1 -1
- package/dist/rules/require-default-state.js +1 -0
- package/dist/rules/require-default-state.js.map +1 -1
- package/dist/rules/valid-transition.js +2 -1
- package/dist/rules/valid-transition.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -189,8 +189,8 @@ for typing shared signatures.
|
|
|
189
189
|
| `tasty/prefer-element-selector` | warn | Prefer element names such as `Primary > Search` over exact `data-element` attributes in sub-element `$` selectors (safely autofixable; [details](docs/rules/prefer-element-selector.md)) |
|
|
190
190
|
| `tasty/static-no-dynamic-values` | error | Dynamic values in `tastyStatic()` |
|
|
191
191
|
| `tasty/static-valid-selector` | error | Invalid selector in `tastyStatic(selector, ...)` |
|
|
192
|
-
| `tasty/require-default-state` | error | Missing default (`''`) or fallback floor (`_`) key in state mappings (skipped for extending calls) |
|
|
193
|
-
| `tasty/no-own-at-root` | warn | `@own()` used at root level where it is redundant |
|
|
192
|
+
| `tasty/require-default-state` | error | Missing default (`''`) or fallback floor (`_`) key in state mappings (skipped for extending calls and maps that spread another) |
|
|
193
|
+
| `tasty/no-own-at-root` | warn | `@own()` used at root level where it is redundant (not in shared style constants, which may be spread into a sub-element) |
|
|
194
194
|
| `tasty/no-ignored-pseudo-element-state` | error | States Tasty ignores on a pseudo-element, such as `@own([open])` on `$: 'a::before'`: attributes, modifiers, classes, and tree-structural pseudo-classes ([details](docs/rules/no-ignored-pseudo-element-state.md)) |
|
|
195
195
|
| `tasty/valid-default-state-order` | warn | Misplaced default (`''`) or redundant `''` when only `_` is present |
|
|
196
196
|
| `tasty/prefer-shorthand-property` | warn | Use Tasty shorthand instead of native CSS properties (`backgroundColor` → `fill`, `paddingBlock` → `blockPadding`, etc.). Report-only warnings explain how to override one part through a token, with concrete min/max dimension examples. Extension warnings point at the base component and are skipped over bases you cannot edit (see `ownedSources`; [details](docs/rules/prefer-shorthand-property.md)) |
|
package/dist/context.js
CHANGED
|
@@ -307,6 +307,23 @@ var TastyContext = class {
|
|
|
307
307
|
current = parent;
|
|
308
308
|
}
|
|
309
309
|
}
|
|
310
|
+
/**
|
|
311
|
+
* Whether the style object this node belongs to is declared on its own — a
|
|
312
|
+
* `const CELL_STYLES: Styles` or a value of a `Record<K, Styles>` — rather
|
|
313
|
+
* than handed to a call or prop. Such styles can be spread anywhere,
|
|
314
|
+
* including into a sub-element, so their root is not necessarily the
|
|
315
|
+
* component's root.
|
|
316
|
+
*/
|
|
317
|
+
isSharedStyleObject(node) {
|
|
318
|
+
const outermost = (inner) => {
|
|
319
|
+
let wrapped = inner;
|
|
320
|
+
while (wrapped.parent && unwrapExpression(wrapped.parent) === inner) wrapped = wrapped.parent;
|
|
321
|
+
return wrapped;
|
|
322
|
+
};
|
|
323
|
+
let parent = outermost(this.getRootStyleObject(node)).parent;
|
|
324
|
+
if (parent?.type === "Property" && parent.parent.type === "ObjectExpression") parent = outermost(parent.parent).parent;
|
|
325
|
+
return parent?.type === "VariableDeclarator";
|
|
326
|
+
}
|
|
310
327
|
/** Include helper calls nested inside a real sub-element, but not variant names. */
|
|
311
328
|
isInsideSubElement(node) {
|
|
312
329
|
let current = node.parent;
|
package/dist/context.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context.js","names":[],"sources":["../src/context.ts"],"sourcesContent":["import type { TSESTree } from '@typescript-eslint/utils';\nimport type { RuleContext } from '@typescript-eslint/utils/ts-eslint';\nimport type { ResolvedConfig, StyleFunctionConfig } from './types.js';\nimport { loadConfig } from './config.js';\nimport {\n DEFAULT_IMPORT_SOURCES,\n KNOWN_CSS_PROPERTIES,\n KNOWN_TASTY_PROPERTIES,\n SPECIAL_STYLE_KEYS,\n} from './constants.js';\nimport { getKeyName, unwrapExpression } from './utils.js';\nimport { finishJSXAnalysis, jsxPropKind } from './type-aware-jsx.js';\nimport { isModuleTastyComponent } from './module-components.js';\n\n/**\n * Every object is considered, then TastyContext gates it by its actual context.\n * Narrow ancestry selectors miss nested shared styles and wrapped JSX values.\n */\nexport const STYLE_OBJECT_SELECTORS = ['ObjectExpression'] as const;\n\n/** One listener per object; context recognition remains the caller's gate. */\nexport function styleObjectListeners(\n handler: (node: TSESTree.ObjectExpression) => void,\n): Record<string, (node: TSESTree.ObjectExpression) => void> {\n return { ObjectExpression: handler };\n}\n\nexport interface StyleContext {\n type: 'tasty' | 'tastyStatic' | 'useStyles' | 'useGlobalStyles';\n isStaticCall: boolean;\n isSelectorMode: boolean;\n isExtending: boolean;\n /**\n * Local name of the component this layer extends, when there is one and it is\n * an identifier. `null` covers every other case — a base definition, a\n * selector, or a layer whose base cannot be read off the AST — so a rule that\n * cares must treat `null` as \"unknown\", not as \"not extending\".\n */\n baseComponent: string | null;\n}\n\nexport interface TastyImport {\n localName: string;\n importedName: string;\n source: string;\n}\n\n/**\n * Whether a type annotation names tasty's `Styles` anywhere inside it.\n *\n * Walks the annotation rather than matching only the outermost reference, so a\n * wrapped tasty type (`Styles | undefined`, `Array<Styles>`) is recognised while\n * `CSSProperties` in the same positions is not. Maps of styles are told apart\n * first by `stylesAnnotationShape`. Deliberately name-based: the plugin has no type checker, and requiring one\n * would make every rule type-aware.\n */\nfunction referencesStylesType(node: TSESTree.TypeNode): boolean {\n const stack: TSESTree.Node[] = [node];\n\n while (stack.length) {\n const current = stack.pop()!;\n\n if (\n current.type === 'TSTypeReference' &&\n current.typeName.type === 'Identifier' &&\n /^Styles$/i.test(current.typeName.name)\n ) {\n return true;\n }\n\n for (const value of Object.values(\n current as unknown as Record<string, unknown>,\n )) {\n if (Array.isArray(value)) {\n for (const item of value) {\n if (item && typeof item === 'object' && 'type' in item) {\n stack.push(item as TSESTree.Node);\n }\n }\n } else if (value && typeof value === 'object' && 'type' in value) {\n // Skip `parent` — it points back up the tree and would loop forever.\n if (value !== (current as TSESTree.Node).parent) {\n stack.push(value as TSESTree.Node);\n }\n }\n }\n }\n\n return false;\n}\n\n/** Utility types whose result has the same shape as their argument. */\nconst SHAPE_PRESERVING_TYPES = new Set([\n 'Readonly',\n 'Partial',\n 'Required',\n 'NonNullable',\n]);\n\n/**\n * What a `Styles`-bearing annotation declares: `'styles'` for a style object,\n * `'map'` for an object whose *values* are style objects (`Record<K, Styles>`,\n * `{ [k: string]: Styles }`, `{ root: Styles }`), `null` when `Styles` does not\n * appear at all.\n *\n * The distinction matters for a map: its keys are variant or block names, so\n * checking the map itself as a style object reports every one of them as an\n * unknown property, while the style objects it holds go unchecked.\n */\nfunction stylesAnnotationShape(\n node: TSESTree.TypeNode,\n): 'styles' | 'map' | null {\n if (node.type === 'TSUnionType' || node.type === 'TSIntersectionType') {\n const shapes = node.types.map(stylesAnnotationShape);\n if (shapes.includes('styles')) return 'styles';\n return shapes.includes('map') ? 'map' : null;\n }\n\n if (node.type === 'TSTypeReference' && node.typeName.type === 'Identifier') {\n const name = node.typeName.name;\n const args = node.typeArguments?.params ?? [];\n\n if (/^Styles$/i.test(name)) return 'styles';\n if (name === 'Record' && args.length === 2) {\n if (stylesAnnotationShape(args[1]) === 'styles') return 'map';\n }\n if (SHAPE_PRESERVING_TYPES.has(name) && args.length === 1) {\n return stylesAnnotationShape(args[0]);\n }\n }\n\n if (node.type === 'TSTypeLiteral') {\n const holdsStyles = node.members.some(\n (member) =>\n (member.type === 'TSIndexSignature' ||\n member.type === 'TSPropertySignature') &&\n member.typeAnnotation !== undefined &&\n stylesAnnotationShape(member.typeAnnotation.typeAnnotation) ===\n 'styles',\n );\n if (holdsStyles) return 'map';\n }\n\n return referencesStylesType(node) ? 'styles' : null;\n}\n\n/**\n * Whether a key could plausibly be a tasty style key.\n *\n * Covers every top-level shape tasty accepts: a style property, a sub-element\n * (capitalised), an at-rule or state/custom-property/colour key (`@`, `&`, `$`,\n * `#`), and the default-state key.\n */\nfunction isPlausibleStyleKey(key: string): boolean {\n if (key === '' || key === '_') return true;\n if (/^[A-Z]/.test(key)) return true;\n if (/^[@&$#]/.test(key)) return true;\n if (SPECIAL_STYLE_KEYS.has(key)) return true;\n\n return KNOWN_TASTY_PROPERTIES.has(key) || KNOWN_CSS_PROPERTIES.has(key);\n}\n\n/**\n * Whether an object is a map of named CSS blocks rather than a tasty styles object.\n *\n * The shape is unmistakable — `{ table: {…}, th: {…}, td: {…} }`, `{ root: {…},\n * toolbar: {…} }` — and it is what a React inline-style map looks like when it\n * carries no type annotation to opt it out. Every key is a block name that is not a\n * style key, and every value is an object.\n *\n * Requiring *every* value to be an object literal is what keeps this from swallowing\n * the case it would hurt most: `const styles = { colour: 'red' }` has a string value,\n * so it is not treated as a block map and `known-property` still reports the typo.\n * Otherwise the rule that catches a misspelled property would be silenced by the\n * misspelling.\n */\nfunction isNamedCssBlockMap(node: TSESTree.ObjectExpression): boolean {\n if (node.properties.length === 0) return false;\n\n for (const prop of node.properties) {\n if (prop.type !== 'Property' || prop.computed) return false;\n\n const key = getKeyName(prop.key);\n\n if (key === null || isPlausibleStyleKey(key)) return false;\n if (prop.value.type !== 'ObjectExpression') return false;\n }\n\n return true;\n}\n\n/**\n * The component a `styles` JSX prop overrides — `<Card styles={…} />` -> `Card`.\n * A namespaced tag (`<UI.Card />`) resolves to its root object, since that is the\n * name an import can be matched against.\n */\nfunction jsxStylesPropTarget(node: TSESTree.ObjectExpression): string | null {\n let wrapped: TSESTree.Node = node;\n while (wrapped.parent && unwrapExpression(wrapped.parent) === node) {\n wrapped = wrapped.parent;\n }\n const container = wrapped.parent;\n if (container?.type !== 'JSXExpressionContainer') return null;\n\n const attribute = container.parent;\n if (attribute?.type !== 'JSXAttribute') return null;\n\n const element = attribute.parent;\n if (element?.type !== 'JSXOpeningElement') return null;\n\n let name: TSESTree.JSXTagNameExpression = element.name;\n while (name.type === 'JSXMemberExpression') name = name.object;\n\n return name.type === 'JSXIdentifier' ? name.name : null;\n}\n\n/**\n * The identifier a base-component argument resolves to — `tasty(UI.Card, {…})`\n * -> `UI`, which is what the import map is keyed by.\n *\n * Type assertions are stripped on the way down. Reading `Button as any` as an\n * unknown base would quietly promote an imported component to \"owned\", which is\n * the reading that produces a warning the author cannot act on.\n */\nfunction baseComponentName(node: TSESTree.Node): string | null {\n let current = unwrapExpression(node);\n\n while (current.type === 'MemberExpression') {\n current = unwrapExpression(current.object);\n }\n\n return current.type === 'Identifier' ? current.name : null;\n}\n\n/**\n * Whether `source` is inside this project. Relative and absolute specifiers are,\n * as are the conventional in-repo aliases (`~/`, `#internal`, `@/`) — `@` alone\n * is not, since `@scope/pkg` is a published package.\n */\nfunction isInRepoSource(source: string): boolean {\n return (\n source.startsWith('.') ||\n source.startsWith('/') ||\n source.startsWith('~') ||\n source.startsWith('#') ||\n source.startsWith('@/')\n );\n}\n\n/** Matches a source against an `ownedSources` pattern, where `*` is any run of characters. */\nfunction matchesSourcePattern(pattern: string, source: string): boolean {\n const escaped = pattern.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n\n return new RegExp(`^${escaped.replace(/\\\\\\*/g, '.*')}$`).test(source);\n}\n\nconst TASTY_FUNCTION_NAMES = new Set([\n 'tasty',\n 'tastyStatic',\n 'useStyles',\n 'useGlobalStyles',\n 'configure',\n]);\n\n/**\n * Context tracker for a single file's lint pass.\n * Tracks which imports come from tasty and provides\n * helpers to determine if a node is in a tasty style context.\n */\nexport class TastyContext {\n readonly config: ResolvedConfig;\n private imports = new Map<string, TastyImport>();\n private moduleSources = new Map<string, string>();\n private importSources: Set<string>;\n private relativeComponents = new Map<string, boolean>();\n\n constructor(\n private context: RuleContext<string, unknown[]>,\n config?: ResolvedConfig,\n ) {\n this.config = config ?? loadConfig(context.filename);\n this.importSources = new Set([\n ...DEFAULT_IMPORT_SOURCES,\n ...this.config.importSources,\n ]);\n }\n\n trackImport(node: TSESTree.ImportDeclaration): void {\n const source = node.source.value;\n\n // Every import is recorded, tasty or not. Where a *base component* comes\n // from is what tells a rule whether the file it would send the author to\n // edit is even theirs — see `isOwnedComponent`.\n for (const specifier of node.specifiers) {\n this.moduleSources.set(specifier.local.name, source);\n }\n\n if (!this.importSources.has(source) || node.importKind === 'type') return;\n\n for (const specifier of node.specifiers) {\n if (\n specifier.type === 'ImportSpecifier' &&\n specifier.importKind !== 'type'\n ) {\n const importedName =\n specifier.imported.type === 'Identifier'\n ? specifier.imported.name\n : specifier.imported.value;\n if (\n TASTY_FUNCTION_NAMES.has(importedName) ||\n Object.hasOwn(this.config.styleFunctions ?? {}, importedName)\n ) {\n this.imports.set(specifier.local.name, {\n localName: specifier.local.name,\n importedName,\n source,\n });\n }\n }\n }\n }\n\n isComponentJSXProp(node: TSESTree.JSXAttribute): boolean {\n return jsxPropKind(this.context, node) === 'component';\n }\n\n finishJSXAnalysis(): void {\n finishJSXAnalysis(this.context);\n }\n\n getImport(localName: string): TastyImport | undefined {\n return this.imports.get(localName);\n }\n\n /**\n * Whether the base component an extension layer sits on top of lives in a file\n * this project can edit — so a rule can decide whether pointing the author at\n * the base's own definition is advice they can act on.\n *\n * A name that was never imported is declared in this very file, and an unknown\n * base (`null`) counts as owned as well: staying quiet is for a base that is\n * demonstrably someone else's, never for one the plugin merely failed to read.\n */\n isOwnedComponent(localName: string | null): boolean {\n if (localName === null) return true;\n\n const source = this.moduleSources.get(localName);\n if (source === undefined) return true;\n if (isInRepoSource(source)) return true;\n\n // `ownedSources` is optional on the public `ResolvedConfig`, so a config\n // built by a consumer rather than by `loadConfig` may not carry it.\n return (this.config.ownedSources ?? []).some((pattern) =>\n matchesSourcePattern(pattern, source),\n );\n }\n\n isTastyCall(node: TSESTree.CallExpression): TastyImport | undefined {\n const callee = unwrapExpression(node.callee);\n if (callee.type !== 'Identifier') return undefined;\n const imp = this.imports.get(callee.name);\n if (!imp) return undefined;\n\n // A parameter or local declaration can shadow the imported helper. Only\n // the import binding carries evidence that the call accepts Tasty styles.\n let scope = this.context.sourceCode.getScope(callee);\n while (scope) {\n const variable = scope.set.get(callee.name);\n if (variable) {\n return variable.defs.some((def) => def.type === 'ImportBinding')\n ? imp\n : undefined;\n }\n if (!scope.upper) break;\n scope = scope.upper;\n }\n return undefined;\n }\n\n /** Local factory results, const aliases, and configured component imports. */\n isTastyJSXComponent(node: TSESTree.Node, name: string): boolean {\n const visited = new Set<TSESTree.VariableDeclarator>();\n const resolve = (reference: TSESTree.Node, localName: string): boolean => {\n let scope = this.context.sourceCode.getScope(reference);\n while (scope) {\n const variable = scope.set.get(localName);\n if (variable) {\n return variable.defs.some((def) => {\n if (def.type === 'ImportBinding') {\n if (\n def.parent.type !== 'ImportDeclaration' ||\n def.parent.importKind === 'type' ||\n (def.node.type === 'ImportSpecifier' &&\n def.node.importKind === 'type')\n ) {\n return false;\n }\n const source = def.parent.source.value;\n if (this.importSources.has(source)) return true;\n return this.isRelativeTastyImport(source, def.node);\n }\n if (def.type !== 'Variable') return false;\n const declaration = def.node;\n if (\n declaration.id.type !== 'Identifier' ||\n declaration.parent.kind !== 'const' ||\n !declaration.init ||\n visited.has(declaration)\n )\n return false;\n visited.add(declaration);\n const init = unwrapExpression(declaration.init);\n if (init.type === 'Identifier') return resolve(init, init.name);\n if (init.type === 'MemberExpression' && !init.computed) {\n let member: TSESTree.Node = init;\n while (member.type === 'MemberExpression') {\n if (member.computed) return false;\n member = unwrapExpression(member.object);\n }\n const root = baseComponentName(init);\n return root !== null && resolve(init, root);\n }\n if (init.type !== 'CallExpression') return false;\n const imp = this.isTastyCall(init);\n return (\n imp?.importedName === 'tasty' ||\n (imp !== undefined &&\n this.config.styleFunctions?.[imp.importedName]?.kind ===\n 'options')\n );\n });\n }\n if (!scope.upper) break;\n scope = scope.upper;\n }\n return false;\n };\n return resolve(node, name);\n }\n\n /**\n * Whether a binding imported from a relative module names a Tasty component\n * declared there — `import { Panel } from './styled'`. A namespace import has\n * no single export to follow.\n */\n private isRelativeTastyImport(\n source: string,\n specifier: TSESTree.Node,\n ): boolean {\n if (\n specifier.type !== 'ImportSpecifier' &&\n specifier.type !== 'ImportDefaultSpecifier'\n ) {\n return false;\n }\n const exportName =\n specifier.type === 'ImportDefaultSpecifier'\n ? 'default'\n : specifier.imported.type === 'Identifier'\n ? specifier.imported.name\n : specifier.imported.value;\n const key = `${source}\\0${exportName}`;\n let result = this.relativeComponents.get(key);\n if (result === undefined) {\n result = isModuleTastyComponent(\n this.context.filename,\n source,\n exportName,\n {\n importSources: this.importSources,\n isComponentFactory: (name) =>\n name === 'tasty' ||\n this.config.styleFunctions?.[name]?.kind === 'options',\n },\n );\n this.relativeComponents.set(key, result);\n }\n return result;\n }\n\n /**\n * Determines whether an object expression is a tasty style object\n * by walking up the AST to find a recognized call expression.\n */\n isStyleObject(node: TSESTree.ObjectExpression): boolean {\n return this.getStyleContext(node) !== null;\n }\n\n private getSubElementParent(\n node: TSESTree.ObjectExpression,\n ): TSESTree.ObjectExpression | null {\n let wrapped: TSESTree.Node = node;\n while (wrapped.parent && unwrapExpression(wrapped.parent) === node) {\n wrapped = wrapped.parent;\n }\n const parent = wrapped.parent;\n if (parent?.type !== 'Property' || parent.computed) return null;\n const key = getKeyName(parent.key);\n return key &&\n /^[A-Z]/.test(key) &&\n parent.parent.type === 'ObjectExpression'\n ? parent.parent\n : null;\n }\n\n /** Follow only sub-elements of recognized styles, never a variants container. */\n getRootStyleObject(\n node: TSESTree.ObjectExpression,\n ): TSESTree.ObjectExpression {\n let current = node;\n while (true) {\n const parent = this.getSubElementParent(current);\n if (!parent || !this.isStyleObject(parent)) return current;\n current = parent;\n }\n }\n\n /** Include helper calls nested inside a real sub-element, but not variant names. */\n isInsideSubElement(node: TSESTree.Node): boolean {\n let current = node.parent;\n while (current) {\n if (current.type === 'Property' && !current.computed) {\n const key = getKeyName(current.key);\n if (\n key &&\n /^[A-Z]/.test(key) &&\n current.parent.type === 'ObjectExpression' &&\n this.isStyleObject(current.parent)\n ) {\n return true;\n }\n }\n current = current.parent;\n }\n return false;\n }\n\n getStyleContext(node: TSESTree.Node): StyleContext | null {\n // Sub-element objects inherit their parent style object's context\n if (node.type === 'ObjectExpression') {\n const parent = this.getSubElementParent(node);\n if (parent) {\n const inherited = this.getStyleContext(parent);\n if (inherited) return inherited;\n }\n }\n\n // An object assigned to a `styles` key (or a `styles` JSX prop) is a style\n // object on its own terms — no enclosing tasty call or `styles`-ish variable\n // name required. Checked before the walk, which would otherwise climb past it\n // to an unrelated call or declaration and reject the whole thing.\n if (node.type === 'ObjectExpression' && this.isStylesPropertyValue(node)) {\n // A `styles` prop is an override layer by construction: the component it\n // is handed to already carries its own styles and this object lands on\n // top of them. A Storybook `args.styles` is the same prop by another name,\n // but the component behind `args` is not on the AST path, so its base\n // stays unknown.\n return {\n type: 'tasty',\n isStaticCall: false,\n isSelectorMode: false,\n isExtending: true,\n baseComponent: jsxStylesPropTarget(node),\n };\n }\n\n let current: TSESTree.Node | undefined = node;\n\n while (current) {\n if (current.type === 'CallExpression') {\n const imp = this.isTastyCall(current);\n if (!imp) return null;\n\n const name = imp.importedName;\n const isStaticCall = name === 'tastyStatic';\n\n if (name === 'tasty') {\n return this.getTastyCallContext(current, node);\n }\n\n if (name === 'tastyStatic') {\n return this.getTastyStaticCallContext(current, node);\n }\n\n if (name === 'useStyles') {\n if (current.arguments[0] === node) {\n return {\n type: 'useStyles',\n isStaticCall: false,\n isSelectorMode: false,\n isExtending: false,\n baseComponent: null,\n };\n }\n }\n\n if (name === 'useGlobalStyles') {\n if (current.arguments[1] === node) {\n return {\n type: 'useGlobalStyles',\n isStaticCall,\n isSelectorMode: true,\n isExtending: false,\n baseComponent: null,\n };\n }\n }\n\n // Built-in signatures always take precedence over configured ones.\n const custom = this.config.styleFunctions?.[name];\n if (!TASTY_FUNCTION_NAMES.has(name) && custom) {\n return this.getCustomCallContext(current, node, custom);\n }\n\n return null;\n }\n\n if (this.isStyleVariableDeclaration(current, node)) {\n return {\n type: 'tasty',\n isStaticCall: false,\n isSelectorMode: false,\n isExtending: false,\n baseComponent: null,\n };\n }\n\n current = current.parent;\n }\n\n return null;\n }\n\n private isStyleVariableDeclaration(\n current: TSESTree.Node,\n targetNode: TSESTree.Node,\n ): boolean {\n if (\n current.type !== 'VariableDeclarator' ||\n current.id.type !== 'Identifier'\n ) {\n return false;\n }\n\n let init: TSESTree.Node | null | undefined = current.init;\n while (\n init?.type === 'TSAsExpression' ||\n init?.type === 'TSSatisfiesExpression' ||\n init?.type === 'TSTypeAssertion' ||\n init?.type === 'TSNonNullExpression'\n ) {\n init = (init as TSESTree.TSAsExpression).expression;\n }\n\n // An explicit type annotation is authoritative, in both directions, and is\n // read before anything about the name. The name heuristics below are a\n // guess; a declared type is the author stating what the object is, so it\n // wins — `const CARD_STYLES: Styles` is as much a style object as\n // `const cardStyles: Styles`.\n //\n // This matters because the rewrites these rules offer are only valid *inside*\n // tasty: `#purple.05` and `$font-sans` are correct tasty declarations and\n // meaningless as raw CSS. A `const styles: Record<string, CSSProperties>`\n // handed to React's `style={…}` was matched on name alone, so its plain CSS\n // longhands were reported as tasty violations — and `--fix` rewrote real\n // `var(--shadow-sm-color)` to `#shadow-sm`, which nothing resolves there, so\n // the browser dropped the declaration.\n const annotated = this.stylesTypeAnnotation(current);\n\n // A map of style objects: its values are checked, never the map itself.\n if (annotated === 'map') {\n return (\n init?.type === 'ObjectExpression' &&\n init.properties.some(\n (prop) =>\n prop.type === 'Property' &&\n unwrapExpression(prop.value) === targetNode,\n )\n );\n }\n\n if (init !== targetNode) return false;\n if (annotated !== null) return annotated === 'styles';\n\n const name = current.id.name;\n\n // Unannotated constants are shared values, not style objects by name alone.\n if (/^[A-Z][A-Z0-9_]*$/.test(name)) return false;\n\n // Only `styles` and `*Styles` count. The singular `style` is conventionally\n // a DOM inline-style object (`el.style`, `CSSProperties`, `setStyle(el, …)`)\n // holding raw CSS longhands, not tasty syntax — matching it reported those\n // longhands as tasty violations.\n if (name === 'styles' || name.endsWith('Styles')) {\n // The name is the weakest evidence there is, so let an unmistakable shape\n // overrule it. Without an annotation to go on, a map of named CSS blocks was\n // reported as tasty — `known-property` on every HTML tag name, each block read\n // as a state map — and `--fix` offered rewrites that are only valid inside\n // tasty.\n return !(\n targetNode.type === 'ObjectExpression' && isNamedCssBlockMap(targetNode)\n );\n }\n\n return false;\n }\n\n private getCustomCallContext(\n call: TSESTree.CallExpression,\n targetNode: TSESTree.Node,\n config: StyleFunctionConfig,\n ): StyleContext | null {\n const { argument, kind } = config;\n if (argument !== 'all' && (!Number.isInteger(argument) || argument < 0)) {\n return null;\n }\n // A preceding spread makes the runtime argument index unknown. Never apply\n // style rewrites to an object that might occupy a different parameter.\n if (\n argument !== 'all' &&\n call.arguments\n .slice(0, argument)\n .some((arg) => arg.type === 'SpreadElement')\n ) {\n return null;\n }\n\n const args =\n argument === 'all' ? call.arguments : [call.arguments[argument]];\n for (const arg of args) {\n if (!arg) continue;\n const value = unwrapExpression(arg);\n if (value.type !== 'ObjectExpression') continue;\n\n const isVariant =\n kind === 'options' && this.isInsideVariantsProperty(value, targetNode);\n const matches =\n kind === 'styles'\n ? value === targetNode\n : kind === 'options' &&\n (this.isInsideStylesProperty(value, targetNode) || isVariant);\n\n if (matches) {\n return {\n type: 'tasty',\n isStaticCall: false,\n isSelectorMode: false,\n isExtending: !isVariant && (config.partial ?? false),\n baseComponent: null,\n };\n }\n }\n\n return null;\n }\n\n /**\n * Verdict from the declared type: `'styles'` the object is tasty, `'map'` its\n * values are, `false` explicitly neither, `null` when there is no annotation to\n * go on and the caller should fall back to the name.\n *\n * A `Styles` reference anywhere in the annotation counts, so wrappers like\n * `Styles | undefined` and `Record<string, Styles>` opt in — while\n * `CSSProperties`, `Record<string, CSSProperties>` and an inline literal of\n * them opt out.\n */\n private stylesTypeAnnotation(\n node: TSESTree.VariableDeclarator,\n ): 'styles' | 'map' | false | null {\n const annotation = node.id.typeAnnotation?.typeAnnotation;\n\n if (!annotation) return null;\n\n return stylesAnnotationShape(annotation) ?? false;\n }\n\n private getTastyCallContext(\n call: TSESTree.CallExpression,\n targetNode: TSESTree.Node,\n ) {\n const args = call.arguments;\n\n // tasty({ styles: { ... } }) or tasty(Component, { styles: { ... } })\n const isExtending =\n args.length >= 2 && unwrapExpression(args[0]).type !== 'ObjectExpression';\n const optionsArg = isExtending ? args[1] : args[0];\n\n if (\n optionsArg?.type === 'ObjectExpression' &&\n this.isInsideStylesProperty(optionsArg, targetNode)\n ) {\n return {\n type: 'tasty' as const,\n isStaticCall: false,\n isSelectorMode: false,\n isExtending,\n baseComponent: isExtending ? baseComponentName(args[0]) : null,\n };\n }\n\n // Check if inside variants\n if (\n optionsArg?.type === 'ObjectExpression' &&\n this.isInsideVariantsProperty(optionsArg, targetNode)\n ) {\n return {\n type: 'tasty' as const,\n isStaticCall: false,\n isSelectorMode: false,\n isExtending: false,\n baseComponent: null,\n };\n }\n\n return null;\n }\n\n private getTastyStaticCallContext(\n call: TSESTree.CallExpression,\n targetNode: TSESTree.Node,\n ) {\n const args = call.arguments;\n\n // tastyStatic({ ... })\n if (args.length === 1 && args[0] === targetNode) {\n return {\n type: 'tastyStatic' as const,\n isStaticCall: true,\n isSelectorMode: false,\n isExtending: false,\n baseComponent: null,\n };\n }\n\n // tastyStatic(base, { ... }) or tastyStatic('selector', { ... })\n if (args.length === 2 && args[1] === targetNode) {\n const isSelectorMode = unwrapExpression(args[0]).type === 'Literal';\n return {\n type: 'tastyStatic' as const,\n isStaticCall: true,\n isSelectorMode,\n isExtending: !isSelectorMode,\n baseComponent: isSelectorMode ? null : baseComponentName(args[0]),\n };\n }\n\n return null;\n }\n\n private isInsideStylesProperty(\n optionsObj: TSESTree.ObjectExpression,\n targetNode: TSESTree.Node,\n ): boolean {\n for (const prop of optionsObj.properties) {\n if (\n prop.type === 'Property' &&\n !prop.computed &&\n getKeyName(prop.key) === 'styles' &&\n unwrapExpression(prop.value) === targetNode\n ) {\n return true;\n }\n }\n return false;\n }\n\n private isInsideVariantsProperty(\n optionsObj: TSESTree.ObjectExpression,\n targetNode: TSESTree.Node,\n ): boolean {\n for (const prop of optionsObj.properties) {\n if (\n prop.type === 'Property' &&\n !prop.computed &&\n getKeyName(prop.key) === 'variants'\n ) {\n const variants = unwrapExpression(prop.value);\n if (variants.type !== 'ObjectExpression') continue;\n for (const variantProp of variants.properties) {\n if (\n variantProp.type === 'Property' &&\n unwrapExpression(variantProp.value) === targetNode\n ) {\n return true;\n }\n }\n }\n }\n return false;\n }\n\n /**\n * Whether this object is a `styles` JSX prop value or a Storybook `args.styles`.\n *\n * Both are unambiguous enough to stand on their own without an import-tracked\n * call or a `styles`-ish variable name. A bare `styles` key elsewhere is not —\n * see the selector list for why.\n */\n isStylesPropertyValue(node: TSESTree.ObjectExpression): boolean {\n let wrapped: TSESTree.Node = node;\n while (wrapped.parent && unwrapExpression(wrapped.parent) === node) {\n wrapped = wrapped.parent;\n }\n const parent = wrapped.parent;\n\n if (parent?.type === 'Property' && !parent.computed) {\n if (getKeyName(parent.key) !== 'styles') return false;\n\n // Only inside `args: { … }`.\n const argsObject = parent.parent;\n const argsProperty =\n argsObject?.type === 'ObjectExpression' ? argsObject.parent : undefined;\n\n return (\n argsProperty?.type === 'Property' &&\n !argsProperty.computed &&\n getKeyName(argsProperty.key) === 'args'\n );\n }\n\n if (parent?.type === 'JSXExpressionContainer') {\n const attribute = parent.parent;\n\n return (\n attribute?.type === 'JSXAttribute' &&\n attribute.name.type === 'JSXIdentifier' &&\n (attribute.name.name === 'styles' ||\n attribute.name.name.endsWith('Styles'))\n );\n }\n\n return false;\n }\n\n /**\n * Checks if a property value node is a state mapping object\n * (i.e., an object where keys are state expressions and values are style values).\n */\n isStateMap(\n node: TSESTree.ObjectExpression,\n parentProperty: TSESTree.Property,\n ): boolean {\n const keyName = getKeyName(parentProperty.key);\n if (keyName === null) return false;\n\n // If the key starts with uppercase, it's a sub-element, not a state map\n if (/^[A-Z]/.test(keyName)) return false;\n\n // Special keys are not state maps\n // At-rule blocks are not state maps — their object values are descriptor maps.\n if (SPECIAL_STYLE_KEYS.has(keyName)) return false;\n\n // If the object has keys that look like state expressions, it's a state map.\n // A lone `_` (the fallback floor) or `''` (the default) is enough — both are\n // already covered by the string-literal / identifier branches below.\n return node.properties.some((prop) => {\n if (prop.type !== 'Property') return false;\n if (prop.key.type === 'Literal' && prop.key.value === '') return true;\n if (prop.key.type === 'Identifier') return true;\n if (prop.key.type === 'Literal' && typeof prop.key.value === 'string') {\n return true;\n }\n return false;\n });\n }\n\n /**\n * Checks if a key represents a sub-element (starts with uppercase).\n */\n isSubElementKey(key: string): boolean {\n return /^[A-Z]/.test(key);\n }\n\n /**\n * Checks if a key represents a nested selector (starts with &).\n */\n isNestedSelectorKey(key: string): boolean {\n return key.startsWith('&');\n }\n\n /**\n * Checks if a key is a custom CSS property definition ($name or $$name).\n */\n isCustomPropertyKey(key: string): boolean {\n return key.startsWith('$');\n }\n\n /**\n * Checks if a key is a color token definition (#name or ##name).\n */\n isColorTokenKey(key: string): boolean {\n return key.startsWith('#');\n }\n\n /**\n * Checks if a key is a special @ property (@keyframes, @property, ...).\n */\n isSpecialKey(key: string): boolean {\n return key.startsWith('@');\n }\n}\n"],"mappings":";;;;;;;;AAqBA,SAAgB,qBACd,SAC2D;AAC3D,QAAO,EAAE,kBAAkB,SAAS;;;;;;;;;;;AAgCtC,SAAS,qBAAqB,MAAkC;CAC9D,MAAM,QAAyB,CAAC,KAAK;AAErC,QAAO,MAAM,QAAQ;EACnB,MAAM,UAAU,MAAM,KAAK;AAE3B,MACE,QAAQ,SAAS,qBACjB,QAAQ,SAAS,SAAS,gBAC1B,YAAY,KAAK,QAAQ,SAAS,KAAK,CAEvC,QAAO;AAGT,OAAK,MAAM,SAAS,OAAO,OACzB,QACD,CACC,KAAI,MAAM,QAAQ,MAAM,EACtB;QAAK,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,KAAsB;AACjC,SAAO,IAAI,WAAW,IAAI"}
|
|
1
|
+
{"version":3,"file":"context.js","names":[],"sources":["../src/context.ts"],"sourcesContent":["import type { TSESTree } from '@typescript-eslint/utils';\nimport type { RuleContext } from '@typescript-eslint/utils/ts-eslint';\nimport type { ResolvedConfig, StyleFunctionConfig } from './types.js';\nimport { loadConfig } from './config.js';\nimport {\n DEFAULT_IMPORT_SOURCES,\n KNOWN_CSS_PROPERTIES,\n KNOWN_TASTY_PROPERTIES,\n SPECIAL_STYLE_KEYS,\n} from './constants.js';\nimport { getKeyName, unwrapExpression } from './utils.js';\nimport { finishJSXAnalysis, jsxPropKind } from './type-aware-jsx.js';\nimport { isModuleTastyComponent } from './module-components.js';\n\n/**\n * Every object is considered, then TastyContext gates it by its actual context.\n * Narrow ancestry selectors miss nested shared styles and wrapped JSX values.\n */\nexport const STYLE_OBJECT_SELECTORS = ['ObjectExpression'] as const;\n\n/** One listener per object; context recognition remains the caller's gate. */\nexport function styleObjectListeners(\n handler: (node: TSESTree.ObjectExpression) => void,\n): Record<string, (node: TSESTree.ObjectExpression) => void> {\n return { ObjectExpression: handler };\n}\n\nexport interface StyleContext {\n type: 'tasty' | 'tastyStatic' | 'useStyles' | 'useGlobalStyles';\n isStaticCall: boolean;\n isSelectorMode: boolean;\n isExtending: boolean;\n /**\n * Local name of the component this layer extends, when there is one and it is\n * an identifier. `null` covers every other case — a base definition, a\n * selector, or a layer whose base cannot be read off the AST — so a rule that\n * cares must treat `null` as \"unknown\", not as \"not extending\".\n */\n baseComponent: string | null;\n}\n\nexport interface TastyImport {\n localName: string;\n importedName: string;\n source: string;\n}\n\n/**\n * Whether a type annotation names tasty's `Styles` anywhere inside it.\n *\n * Walks the annotation rather than matching only the outermost reference, so a\n * wrapped tasty type (`Styles | undefined`, `Array<Styles>`) is recognised while\n * `CSSProperties` in the same positions is not. Maps of styles are told apart\n * first by `stylesAnnotationShape`. Deliberately name-based: the plugin has no type checker, and requiring one\n * would make every rule type-aware.\n */\nfunction referencesStylesType(node: TSESTree.TypeNode): boolean {\n const stack: TSESTree.Node[] = [node];\n\n while (stack.length) {\n const current = stack.pop()!;\n\n if (\n current.type === 'TSTypeReference' &&\n current.typeName.type === 'Identifier' &&\n /^Styles$/i.test(current.typeName.name)\n ) {\n return true;\n }\n\n for (const value of Object.values(\n current as unknown as Record<string, unknown>,\n )) {\n if (Array.isArray(value)) {\n for (const item of value) {\n if (item && typeof item === 'object' && 'type' in item) {\n stack.push(item as TSESTree.Node);\n }\n }\n } else if (value && typeof value === 'object' && 'type' in value) {\n // Skip `parent` — it points back up the tree and would loop forever.\n if (value !== (current as TSESTree.Node).parent) {\n stack.push(value as TSESTree.Node);\n }\n }\n }\n }\n\n return false;\n}\n\n/** Utility types whose result has the same shape as their argument. */\nconst SHAPE_PRESERVING_TYPES = new Set([\n 'Readonly',\n 'Partial',\n 'Required',\n 'NonNullable',\n]);\n\n/**\n * What a `Styles`-bearing annotation declares: `'styles'` for a style object,\n * `'map'` for an object whose *values* are style objects (`Record<K, Styles>`,\n * `{ [k: string]: Styles }`, `{ root: Styles }`), `null` when `Styles` does not\n * appear at all.\n *\n * The distinction matters for a map: its keys are variant or block names, so\n * checking the map itself as a style object reports every one of them as an\n * unknown property, while the style objects it holds go unchecked.\n */\nfunction stylesAnnotationShape(\n node: TSESTree.TypeNode,\n): 'styles' | 'map' | null {\n if (node.type === 'TSUnionType' || node.type === 'TSIntersectionType') {\n const shapes = node.types.map(stylesAnnotationShape);\n if (shapes.includes('styles')) return 'styles';\n return shapes.includes('map') ? 'map' : null;\n }\n\n if (node.type === 'TSTypeReference' && node.typeName.type === 'Identifier') {\n const name = node.typeName.name;\n const args = node.typeArguments?.params ?? [];\n\n if (/^Styles$/i.test(name)) return 'styles';\n if (name === 'Record' && args.length === 2) {\n if (stylesAnnotationShape(args[1]) === 'styles') return 'map';\n }\n if (SHAPE_PRESERVING_TYPES.has(name) && args.length === 1) {\n return stylesAnnotationShape(args[0]);\n }\n }\n\n if (node.type === 'TSTypeLiteral') {\n const holdsStyles = node.members.some(\n (member) =>\n (member.type === 'TSIndexSignature' ||\n member.type === 'TSPropertySignature') &&\n member.typeAnnotation !== undefined &&\n stylesAnnotationShape(member.typeAnnotation.typeAnnotation) ===\n 'styles',\n );\n if (holdsStyles) return 'map';\n }\n\n return referencesStylesType(node) ? 'styles' : null;\n}\n\n/**\n * Whether a key could plausibly be a tasty style key.\n *\n * Covers every top-level shape tasty accepts: a style property, a sub-element\n * (capitalised), an at-rule or state/custom-property/colour key (`@`, `&`, `$`,\n * `#`), and the default-state key.\n */\nfunction isPlausibleStyleKey(key: string): boolean {\n if (key === '' || key === '_') return true;\n if (/^[A-Z]/.test(key)) return true;\n if (/^[@&$#]/.test(key)) return true;\n if (SPECIAL_STYLE_KEYS.has(key)) return true;\n\n return KNOWN_TASTY_PROPERTIES.has(key) || KNOWN_CSS_PROPERTIES.has(key);\n}\n\n/**\n * Whether an object is a map of named CSS blocks rather than a tasty styles object.\n *\n * The shape is unmistakable — `{ table: {…}, th: {…}, td: {…} }`, `{ root: {…},\n * toolbar: {…} }` — and it is what a React inline-style map looks like when it\n * carries no type annotation to opt it out. Every key is a block name that is not a\n * style key, and every value is an object.\n *\n * Requiring *every* value to be an object literal is what keeps this from swallowing\n * the case it would hurt most: `const styles = { colour: 'red' }` has a string value,\n * so it is not treated as a block map and `known-property` still reports the typo.\n * Otherwise the rule that catches a misspelled property would be silenced by the\n * misspelling.\n */\nfunction isNamedCssBlockMap(node: TSESTree.ObjectExpression): boolean {\n if (node.properties.length === 0) return false;\n\n for (const prop of node.properties) {\n if (prop.type !== 'Property' || prop.computed) return false;\n\n const key = getKeyName(prop.key);\n\n if (key === null || isPlausibleStyleKey(key)) return false;\n if (prop.value.type !== 'ObjectExpression') return false;\n }\n\n return true;\n}\n\n/**\n * The component a `styles` JSX prop overrides — `<Card styles={…} />` -> `Card`.\n * A namespaced tag (`<UI.Card />`) resolves to its root object, since that is the\n * name an import can be matched against.\n */\nfunction jsxStylesPropTarget(node: TSESTree.ObjectExpression): string | null {\n let wrapped: TSESTree.Node = node;\n while (wrapped.parent && unwrapExpression(wrapped.parent) === node) {\n wrapped = wrapped.parent;\n }\n const container = wrapped.parent;\n if (container?.type !== 'JSXExpressionContainer') return null;\n\n const attribute = container.parent;\n if (attribute?.type !== 'JSXAttribute') return null;\n\n const element = attribute.parent;\n if (element?.type !== 'JSXOpeningElement') return null;\n\n let name: TSESTree.JSXTagNameExpression = element.name;\n while (name.type === 'JSXMemberExpression') name = name.object;\n\n return name.type === 'JSXIdentifier' ? name.name : null;\n}\n\n/**\n * The identifier a base-component argument resolves to — `tasty(UI.Card, {…})`\n * -> `UI`, which is what the import map is keyed by.\n *\n * Type assertions are stripped on the way down. Reading `Button as any` as an\n * unknown base would quietly promote an imported component to \"owned\", which is\n * the reading that produces a warning the author cannot act on.\n */\nfunction baseComponentName(node: TSESTree.Node): string | null {\n let current = unwrapExpression(node);\n\n while (current.type === 'MemberExpression') {\n current = unwrapExpression(current.object);\n }\n\n return current.type === 'Identifier' ? current.name : null;\n}\n\n/**\n * Whether `source` is inside this project. Relative and absolute specifiers are,\n * as are the conventional in-repo aliases (`~/`, `#internal`, `@/`) — `@` alone\n * is not, since `@scope/pkg` is a published package.\n */\nfunction isInRepoSource(source: string): boolean {\n return (\n source.startsWith('.') ||\n source.startsWith('/') ||\n source.startsWith('~') ||\n source.startsWith('#') ||\n source.startsWith('@/')\n );\n}\n\n/** Matches a source against an `ownedSources` pattern, where `*` is any run of characters. */\nfunction matchesSourcePattern(pattern: string, source: string): boolean {\n const escaped = pattern.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n\n return new RegExp(`^${escaped.replace(/\\\\\\*/g, '.*')}$`).test(source);\n}\n\nconst TASTY_FUNCTION_NAMES = new Set([\n 'tasty',\n 'tastyStatic',\n 'useStyles',\n 'useGlobalStyles',\n 'configure',\n]);\n\n/**\n * Context tracker for a single file's lint pass.\n * Tracks which imports come from tasty and provides\n * helpers to determine if a node is in a tasty style context.\n */\nexport class TastyContext {\n readonly config: ResolvedConfig;\n private imports = new Map<string, TastyImport>();\n private moduleSources = new Map<string, string>();\n private importSources: Set<string>;\n private relativeComponents = new Map<string, boolean>();\n\n constructor(\n private context: RuleContext<string, unknown[]>,\n config?: ResolvedConfig,\n ) {\n this.config = config ?? loadConfig(context.filename);\n this.importSources = new Set([\n ...DEFAULT_IMPORT_SOURCES,\n ...this.config.importSources,\n ]);\n }\n\n trackImport(node: TSESTree.ImportDeclaration): void {\n const source = node.source.value;\n\n // Every import is recorded, tasty or not. Where a *base component* comes\n // from is what tells a rule whether the file it would send the author to\n // edit is even theirs — see `isOwnedComponent`.\n for (const specifier of node.specifiers) {\n this.moduleSources.set(specifier.local.name, source);\n }\n\n if (!this.importSources.has(source) || node.importKind === 'type') return;\n\n for (const specifier of node.specifiers) {\n if (\n specifier.type === 'ImportSpecifier' &&\n specifier.importKind !== 'type'\n ) {\n const importedName =\n specifier.imported.type === 'Identifier'\n ? specifier.imported.name\n : specifier.imported.value;\n if (\n TASTY_FUNCTION_NAMES.has(importedName) ||\n Object.hasOwn(this.config.styleFunctions ?? {}, importedName)\n ) {\n this.imports.set(specifier.local.name, {\n localName: specifier.local.name,\n importedName,\n source,\n });\n }\n }\n }\n }\n\n isComponentJSXProp(node: TSESTree.JSXAttribute): boolean {\n return jsxPropKind(this.context, node) === 'component';\n }\n\n finishJSXAnalysis(): void {\n finishJSXAnalysis(this.context);\n }\n\n getImport(localName: string): TastyImport | undefined {\n return this.imports.get(localName);\n }\n\n /**\n * Whether the base component an extension layer sits on top of lives in a file\n * this project can edit — so a rule can decide whether pointing the author at\n * the base's own definition is advice they can act on.\n *\n * A name that was never imported is declared in this very file, and an unknown\n * base (`null`) counts as owned as well: staying quiet is for a base that is\n * demonstrably someone else's, never for one the plugin merely failed to read.\n */\n isOwnedComponent(localName: string | null): boolean {\n if (localName === null) return true;\n\n const source = this.moduleSources.get(localName);\n if (source === undefined) return true;\n if (isInRepoSource(source)) return true;\n\n // `ownedSources` is optional on the public `ResolvedConfig`, so a config\n // built by a consumer rather than by `loadConfig` may not carry it.\n return (this.config.ownedSources ?? []).some((pattern) =>\n matchesSourcePattern(pattern, source),\n );\n }\n\n isTastyCall(node: TSESTree.CallExpression): TastyImport | undefined {\n const callee = unwrapExpression(node.callee);\n if (callee.type !== 'Identifier') return undefined;\n const imp = this.imports.get(callee.name);\n if (!imp) return undefined;\n\n // A parameter or local declaration can shadow the imported helper. Only\n // the import binding carries evidence that the call accepts Tasty styles.\n let scope = this.context.sourceCode.getScope(callee);\n while (scope) {\n const variable = scope.set.get(callee.name);\n if (variable) {\n return variable.defs.some((def) => def.type === 'ImportBinding')\n ? imp\n : undefined;\n }\n if (!scope.upper) break;\n scope = scope.upper;\n }\n return undefined;\n }\n\n /** Local factory results, const aliases, and configured component imports. */\n isTastyJSXComponent(node: TSESTree.Node, name: string): boolean {\n const visited = new Set<TSESTree.VariableDeclarator>();\n const resolve = (reference: TSESTree.Node, localName: string): boolean => {\n let scope = this.context.sourceCode.getScope(reference);\n while (scope) {\n const variable = scope.set.get(localName);\n if (variable) {\n return variable.defs.some((def) => {\n if (def.type === 'ImportBinding') {\n if (\n def.parent.type !== 'ImportDeclaration' ||\n def.parent.importKind === 'type' ||\n (def.node.type === 'ImportSpecifier' &&\n def.node.importKind === 'type')\n ) {\n return false;\n }\n const source = def.parent.source.value;\n if (this.importSources.has(source)) return true;\n return this.isRelativeTastyImport(source, def.node);\n }\n if (def.type !== 'Variable') return false;\n const declaration = def.node;\n if (\n declaration.id.type !== 'Identifier' ||\n declaration.parent.kind !== 'const' ||\n !declaration.init ||\n visited.has(declaration)\n )\n return false;\n visited.add(declaration);\n const init = unwrapExpression(declaration.init);\n if (init.type === 'Identifier') return resolve(init, init.name);\n if (init.type === 'MemberExpression' && !init.computed) {\n let member: TSESTree.Node = init;\n while (member.type === 'MemberExpression') {\n if (member.computed) return false;\n member = unwrapExpression(member.object);\n }\n const root = baseComponentName(init);\n return root !== null && resolve(init, root);\n }\n if (init.type !== 'CallExpression') return false;\n const imp = this.isTastyCall(init);\n return (\n imp?.importedName === 'tasty' ||\n (imp !== undefined &&\n this.config.styleFunctions?.[imp.importedName]?.kind ===\n 'options')\n );\n });\n }\n if (!scope.upper) break;\n scope = scope.upper;\n }\n return false;\n };\n return resolve(node, name);\n }\n\n /**\n * Whether a binding imported from a relative module names a Tasty component\n * declared there — `import { Panel } from './styled'`. A namespace import has\n * no single export to follow.\n */\n private isRelativeTastyImport(\n source: string,\n specifier: TSESTree.Node,\n ): boolean {\n if (\n specifier.type !== 'ImportSpecifier' &&\n specifier.type !== 'ImportDefaultSpecifier'\n ) {\n return false;\n }\n const exportName =\n specifier.type === 'ImportDefaultSpecifier'\n ? 'default'\n : specifier.imported.type === 'Identifier'\n ? specifier.imported.name\n : specifier.imported.value;\n const key = `${source}\\0${exportName}`;\n let result = this.relativeComponents.get(key);\n if (result === undefined) {\n result = isModuleTastyComponent(\n this.context.filename,\n source,\n exportName,\n {\n importSources: this.importSources,\n isComponentFactory: (name) =>\n name === 'tasty' ||\n this.config.styleFunctions?.[name]?.kind === 'options',\n },\n );\n this.relativeComponents.set(key, result);\n }\n return result;\n }\n\n /**\n * Determines whether an object expression is a tasty style object\n * by walking up the AST to find a recognized call expression.\n */\n isStyleObject(node: TSESTree.ObjectExpression): boolean {\n return this.getStyleContext(node) !== null;\n }\n\n private getSubElementParent(\n node: TSESTree.ObjectExpression,\n ): TSESTree.ObjectExpression | null {\n let wrapped: TSESTree.Node = node;\n while (wrapped.parent && unwrapExpression(wrapped.parent) === node) {\n wrapped = wrapped.parent;\n }\n const parent = wrapped.parent;\n if (parent?.type !== 'Property' || parent.computed) return null;\n const key = getKeyName(parent.key);\n return key &&\n /^[A-Z]/.test(key) &&\n parent.parent.type === 'ObjectExpression'\n ? parent.parent\n : null;\n }\n\n /** Follow only sub-elements of recognized styles, never a variants container. */\n getRootStyleObject(\n node: TSESTree.ObjectExpression,\n ): TSESTree.ObjectExpression {\n let current = node;\n while (true) {\n const parent = this.getSubElementParent(current);\n if (!parent || !this.isStyleObject(parent)) return current;\n current = parent;\n }\n }\n\n /**\n * Whether the style object this node belongs to is declared on its own — a\n * `const CELL_STYLES: Styles` or a value of a `Record<K, Styles>` — rather\n * than handed to a call or prop. Such styles can be spread anywhere,\n * including into a sub-element, so their root is not necessarily the\n * component's root.\n */\n isSharedStyleObject(node: TSESTree.ObjectExpression): boolean {\n const outermost = (inner: TSESTree.Node): TSESTree.Node => {\n let wrapped = inner;\n while (wrapped.parent && unwrapExpression(wrapped.parent) === inner) {\n wrapped = wrapped.parent;\n }\n return wrapped;\n };\n\n let parent = outermost(this.getRootStyleObject(node)).parent;\n if (\n parent?.type === 'Property' &&\n parent.parent.type === 'ObjectExpression'\n ) {\n parent = outermost(parent.parent).parent;\n }\n return parent?.type === 'VariableDeclarator';\n }\n\n /** Include helper calls nested inside a real sub-element, but not variant names. */\n isInsideSubElement(node: TSESTree.Node): boolean {\n let current = node.parent;\n while (current) {\n if (current.type === 'Property' && !current.computed) {\n const key = getKeyName(current.key);\n if (\n key &&\n /^[A-Z]/.test(key) &&\n current.parent.type === 'ObjectExpression' &&\n this.isStyleObject(current.parent)\n ) {\n return true;\n }\n }\n current = current.parent;\n }\n return false;\n }\n\n getStyleContext(node: TSESTree.Node): StyleContext | null {\n // Sub-element objects inherit their parent style object's context\n if (node.type === 'ObjectExpression') {\n const parent = this.getSubElementParent(node);\n if (parent) {\n const inherited = this.getStyleContext(parent);\n if (inherited) return inherited;\n }\n }\n\n // An object assigned to a `styles` key (or a `styles` JSX prop) is a style\n // object on its own terms — no enclosing tasty call or `styles`-ish variable\n // name required. Checked before the walk, which would otherwise climb past it\n // to an unrelated call or declaration and reject the whole thing.\n if (node.type === 'ObjectExpression' && this.isStylesPropertyValue(node)) {\n // A `styles` prop is an override layer by construction: the component it\n // is handed to already carries its own styles and this object lands on\n // top of them. A Storybook `args.styles` is the same prop by another name,\n // but the component behind `args` is not on the AST path, so its base\n // stays unknown.\n return {\n type: 'tasty',\n isStaticCall: false,\n isSelectorMode: false,\n isExtending: true,\n baseComponent: jsxStylesPropTarget(node),\n };\n }\n\n let current: TSESTree.Node | undefined = node;\n\n while (current) {\n if (current.type === 'CallExpression') {\n const imp = this.isTastyCall(current);\n if (!imp) return null;\n\n const name = imp.importedName;\n const isStaticCall = name === 'tastyStatic';\n\n if (name === 'tasty') {\n return this.getTastyCallContext(current, node);\n }\n\n if (name === 'tastyStatic') {\n return this.getTastyStaticCallContext(current, node);\n }\n\n if (name === 'useStyles') {\n if (current.arguments[0] === node) {\n return {\n type: 'useStyles',\n isStaticCall: false,\n isSelectorMode: false,\n isExtending: false,\n baseComponent: null,\n };\n }\n }\n\n if (name === 'useGlobalStyles') {\n if (current.arguments[1] === node) {\n return {\n type: 'useGlobalStyles',\n isStaticCall,\n isSelectorMode: true,\n isExtending: false,\n baseComponent: null,\n };\n }\n }\n\n // Built-in signatures always take precedence over configured ones.\n const custom = this.config.styleFunctions?.[name];\n if (!TASTY_FUNCTION_NAMES.has(name) && custom) {\n return this.getCustomCallContext(current, node, custom);\n }\n\n return null;\n }\n\n if (this.isStyleVariableDeclaration(current, node)) {\n return {\n type: 'tasty',\n isStaticCall: false,\n isSelectorMode: false,\n isExtending: false,\n baseComponent: null,\n };\n }\n\n current = current.parent;\n }\n\n return null;\n }\n\n private isStyleVariableDeclaration(\n current: TSESTree.Node,\n targetNode: TSESTree.Node,\n ): boolean {\n if (\n current.type !== 'VariableDeclarator' ||\n current.id.type !== 'Identifier'\n ) {\n return false;\n }\n\n let init: TSESTree.Node | null | undefined = current.init;\n while (\n init?.type === 'TSAsExpression' ||\n init?.type === 'TSSatisfiesExpression' ||\n init?.type === 'TSTypeAssertion' ||\n init?.type === 'TSNonNullExpression'\n ) {\n init = (init as TSESTree.TSAsExpression).expression;\n }\n\n // An explicit type annotation is authoritative, in both directions, and is\n // read before anything about the name. The name heuristics below are a\n // guess; a declared type is the author stating what the object is, so it\n // wins — `const CARD_STYLES: Styles` is as much a style object as\n // `const cardStyles: Styles`.\n //\n // This matters because the rewrites these rules offer are only valid *inside*\n // tasty: `#purple.05` and `$font-sans` are correct tasty declarations and\n // meaningless as raw CSS. A `const styles: Record<string, CSSProperties>`\n // handed to React's `style={…}` was matched on name alone, so its plain CSS\n // longhands were reported as tasty violations — and `--fix` rewrote real\n // `var(--shadow-sm-color)` to `#shadow-sm`, which nothing resolves there, so\n // the browser dropped the declaration.\n const annotated = this.stylesTypeAnnotation(current);\n\n // A map of style objects: its values are checked, never the map itself.\n if (annotated === 'map') {\n return (\n init?.type === 'ObjectExpression' &&\n init.properties.some(\n (prop) =>\n prop.type === 'Property' &&\n unwrapExpression(prop.value) === targetNode,\n )\n );\n }\n\n if (init !== targetNode) return false;\n if (annotated !== null) return annotated === 'styles';\n\n const name = current.id.name;\n\n // Unannotated constants are shared values, not style objects by name alone.\n if (/^[A-Z][A-Z0-9_]*$/.test(name)) return false;\n\n // Only `styles` and `*Styles` count. The singular `style` is conventionally\n // a DOM inline-style object (`el.style`, `CSSProperties`, `setStyle(el, …)`)\n // holding raw CSS longhands, not tasty syntax — matching it reported those\n // longhands as tasty violations.\n if (name === 'styles' || name.endsWith('Styles')) {\n // The name is the weakest evidence there is, so let an unmistakable shape\n // overrule it. Without an annotation to go on, a map of named CSS blocks was\n // reported as tasty — `known-property` on every HTML tag name, each block read\n // as a state map — and `--fix` offered rewrites that are only valid inside\n // tasty.\n return !(\n targetNode.type === 'ObjectExpression' && isNamedCssBlockMap(targetNode)\n );\n }\n\n return false;\n }\n\n private getCustomCallContext(\n call: TSESTree.CallExpression,\n targetNode: TSESTree.Node,\n config: StyleFunctionConfig,\n ): StyleContext | null {\n const { argument, kind } = config;\n if (argument !== 'all' && (!Number.isInteger(argument) || argument < 0)) {\n return null;\n }\n // A preceding spread makes the runtime argument index unknown. Never apply\n // style rewrites to an object that might occupy a different parameter.\n if (\n argument !== 'all' &&\n call.arguments\n .slice(0, argument)\n .some((arg) => arg.type === 'SpreadElement')\n ) {\n return null;\n }\n\n const args =\n argument === 'all' ? call.arguments : [call.arguments[argument]];\n for (const arg of args) {\n if (!arg) continue;\n const value = unwrapExpression(arg);\n if (value.type !== 'ObjectExpression') continue;\n\n const isVariant =\n kind === 'options' && this.isInsideVariantsProperty(value, targetNode);\n const matches =\n kind === 'styles'\n ? value === targetNode\n : kind === 'options' &&\n (this.isInsideStylesProperty(value, targetNode) || isVariant);\n\n if (matches) {\n return {\n type: 'tasty',\n isStaticCall: false,\n isSelectorMode: false,\n isExtending: !isVariant && (config.partial ?? false),\n baseComponent: null,\n };\n }\n }\n\n return null;\n }\n\n /**\n * Verdict from the declared type: `'styles'` the object is tasty, `'map'` its\n * values are, `false` explicitly neither, `null` when there is no annotation to\n * go on and the caller should fall back to the name.\n *\n * A `Styles` reference anywhere in the annotation counts, so wrappers like\n * `Styles | undefined` and `Record<string, Styles>` opt in — while\n * `CSSProperties`, `Record<string, CSSProperties>` and an inline literal of\n * them opt out.\n */\n private stylesTypeAnnotation(\n node: TSESTree.VariableDeclarator,\n ): 'styles' | 'map' | false | null {\n const annotation = node.id.typeAnnotation?.typeAnnotation;\n\n if (!annotation) return null;\n\n return stylesAnnotationShape(annotation) ?? false;\n }\n\n private getTastyCallContext(\n call: TSESTree.CallExpression,\n targetNode: TSESTree.Node,\n ) {\n const args = call.arguments;\n\n // tasty({ styles: { ... } }) or tasty(Component, { styles: { ... } })\n const isExtending =\n args.length >= 2 && unwrapExpression(args[0]).type !== 'ObjectExpression';\n const optionsArg = isExtending ? args[1] : args[0];\n\n if (\n optionsArg?.type === 'ObjectExpression' &&\n this.isInsideStylesProperty(optionsArg, targetNode)\n ) {\n return {\n type: 'tasty' as const,\n isStaticCall: false,\n isSelectorMode: false,\n isExtending,\n baseComponent: isExtending ? baseComponentName(args[0]) : null,\n };\n }\n\n // Check if inside variants\n if (\n optionsArg?.type === 'ObjectExpression' &&\n this.isInsideVariantsProperty(optionsArg, targetNode)\n ) {\n return {\n type: 'tasty' as const,\n isStaticCall: false,\n isSelectorMode: false,\n isExtending: false,\n baseComponent: null,\n };\n }\n\n return null;\n }\n\n private getTastyStaticCallContext(\n call: TSESTree.CallExpression,\n targetNode: TSESTree.Node,\n ) {\n const args = call.arguments;\n\n // tastyStatic({ ... })\n if (args.length === 1 && args[0] === targetNode) {\n return {\n type: 'tastyStatic' as const,\n isStaticCall: true,\n isSelectorMode: false,\n isExtending: false,\n baseComponent: null,\n };\n }\n\n // tastyStatic(base, { ... }) or tastyStatic('selector', { ... })\n if (args.length === 2 && args[1] === targetNode) {\n const isSelectorMode = unwrapExpression(args[0]).type === 'Literal';\n return {\n type: 'tastyStatic' as const,\n isStaticCall: true,\n isSelectorMode,\n isExtending: !isSelectorMode,\n baseComponent: isSelectorMode ? null : baseComponentName(args[0]),\n };\n }\n\n return null;\n }\n\n private isInsideStylesProperty(\n optionsObj: TSESTree.ObjectExpression,\n targetNode: TSESTree.Node,\n ): boolean {\n for (const prop of optionsObj.properties) {\n if (\n prop.type === 'Property' &&\n !prop.computed &&\n getKeyName(prop.key) === 'styles' &&\n unwrapExpression(prop.value) === targetNode\n ) {\n return true;\n }\n }\n return false;\n }\n\n private isInsideVariantsProperty(\n optionsObj: TSESTree.ObjectExpression,\n targetNode: TSESTree.Node,\n ): boolean {\n for (const prop of optionsObj.properties) {\n if (\n prop.type === 'Property' &&\n !prop.computed &&\n getKeyName(prop.key) === 'variants'\n ) {\n const variants = unwrapExpression(prop.value);\n if (variants.type !== 'ObjectExpression') continue;\n for (const variantProp of variants.properties) {\n if (\n variantProp.type === 'Property' &&\n unwrapExpression(variantProp.value) === targetNode\n ) {\n return true;\n }\n }\n }\n }\n return false;\n }\n\n /**\n * Whether this object is a `styles` JSX prop value or a Storybook `args.styles`.\n *\n * Both are unambiguous enough to stand on their own without an import-tracked\n * call or a `styles`-ish variable name. A bare `styles` key elsewhere is not —\n * see the selector list for why.\n */\n isStylesPropertyValue(node: TSESTree.ObjectExpression): boolean {\n let wrapped: TSESTree.Node = node;\n while (wrapped.parent && unwrapExpression(wrapped.parent) === node) {\n wrapped = wrapped.parent;\n }\n const parent = wrapped.parent;\n\n if (parent?.type === 'Property' && !parent.computed) {\n if (getKeyName(parent.key) !== 'styles') return false;\n\n // Only inside `args: { … }`.\n const argsObject = parent.parent;\n const argsProperty =\n argsObject?.type === 'ObjectExpression' ? argsObject.parent : undefined;\n\n return (\n argsProperty?.type === 'Property' &&\n !argsProperty.computed &&\n getKeyName(argsProperty.key) === 'args'\n );\n }\n\n if (parent?.type === 'JSXExpressionContainer') {\n const attribute = parent.parent;\n\n return (\n attribute?.type === 'JSXAttribute' &&\n attribute.name.type === 'JSXIdentifier' &&\n (attribute.name.name === 'styles' ||\n attribute.name.name.endsWith('Styles'))\n );\n }\n\n return false;\n }\n\n /**\n * Checks if a property value node is a state mapping object\n * (i.e., an object where keys are state expressions and values are style values).\n */\n isStateMap(\n node: TSESTree.ObjectExpression,\n parentProperty: TSESTree.Property,\n ): boolean {\n const keyName = getKeyName(parentProperty.key);\n if (keyName === null) return false;\n\n // If the key starts with uppercase, it's a sub-element, not a state map\n if (/^[A-Z]/.test(keyName)) return false;\n\n // Special keys are not state maps\n // At-rule blocks are not state maps — their object values are descriptor maps.\n if (SPECIAL_STYLE_KEYS.has(keyName)) return false;\n\n // If the object has keys that look like state expressions, it's a state map.\n // A lone `_` (the fallback floor) or `''` (the default) is enough — both are\n // already covered by the string-literal / identifier branches below.\n return node.properties.some((prop) => {\n if (prop.type !== 'Property') return false;\n if (prop.key.type === 'Literal' && prop.key.value === '') return true;\n if (prop.key.type === 'Identifier') return true;\n if (prop.key.type === 'Literal' && typeof prop.key.value === 'string') {\n return true;\n }\n return false;\n });\n }\n\n /**\n * Checks if a key represents a sub-element (starts with uppercase).\n */\n isSubElementKey(key: string): boolean {\n return /^[A-Z]/.test(key);\n }\n\n /**\n * Checks if a key represents a nested selector (starts with &).\n */\n isNestedSelectorKey(key: string): boolean {\n return key.startsWith('&');\n }\n\n /**\n * Checks if a key is a custom CSS property definition ($name or $$name).\n */\n isCustomPropertyKey(key: string): boolean {\n return key.startsWith('$');\n }\n\n /**\n * Checks if a key is a color token definition (#name or ##name).\n */\n isColorTokenKey(key: string): boolean {\n return key.startsWith('#');\n }\n\n /**\n * Checks if a key is a special @ property (@keyframes, @property, ...).\n */\n isSpecialKey(key: string): boolean {\n return key.startsWith('@');\n }\n}\n"],"mappings":";;;;;;;;AAqBA,SAAgB,qBACd,SAC2D;AAC3D,QAAO,EAAE,kBAAkB,SAAS;;;;;;;;;;;AAgCtC,SAAS,qBAAqB,MAAkC;CAC9D,MAAM,QAAyB,CAAC,KAAK;AAErC,QAAO,MAAM,QAAQ;EACnB,MAAM,UAAU,MAAM,KAAK;AAE3B,MACE,QAAQ,SAAS,qBACjB,QAAQ,SAAS,SAAS,gBAC1B,YAAY,KAAK,QAAQ,SAAS,KAAK,CAEvC,QAAO;AAGT,OAAK,MAAM,SAAS,OAAO,OACzB,QACD,CACC,KAAI,MAAM,QAAQ,MAAM,EACtB;QAAK,MAAM,QAAQ,MACjB,KAAI,QAAQ,OAAO,SAAS,YAAY,UAAU,KAChD,OAAM,KAAK,KAAsB;aAG5B,SAAS,OAAO,UAAU,YAAY,UAAU,OAEzD;OAAI,UAAW,QAA0B,OACvC,OAAM,KAAK,MAAuB;;;AAM1C,QAAO;;;AAIT,MAAM,yBAAyB,IAAI,IAAI;CACrC;CACA;CACA;CACA;CACD,CAAC;;;;;;;;;;;AAYF,SAAS,sBACP,MACyB;AACzB,KAAI,KAAK,SAAS,iBAAiB,KAAK,SAAS,sBAAsB;EACrE,MAAM,SAAS,KAAK,MAAM,IAAI,sBAAsB;AACpD,MAAI,OAAO,SAAS,SAAS,CAAE,QAAO;AACtC,SAAO,OAAO,SAAS,MAAM,GAAG,QAAQ;;AAG1C,KAAI,KAAK,SAAS,qBAAqB,KAAK,SAAS,SAAS,cAAc;EAC1E,MAAM,OAAO,KAAK,SAAS;EA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,eACJ,YAAY,SAAS,qBAAqB,WAAW,SAAS;AAEhE,UACE,cAAc,SAAS,cACvB,CAAC,aAAa,YACd,WAAW,aAAa,IAAI,KAAK;;AAIrC,MAAI,QAAQ,SAAS,0BAA0B;GAC7C,MAAM,YAAY,OAAO;AAEzB,UACE,WAAW,SAAS,kBACpB,UAAU,KAAK,SAAS,oBACvB,UAAU,KAAK,SAAS,YACvB,UAAU,KAAK,KAAK,SAAS,SAAS;;AAI5C,SAAO;;;;;;CAOT,WACE,MACA,gBACS;EACT,MAAM,UAAU,WAAW,eAAe,IAAI;AAC9C,MAAI,YAAY,KAAM,QAAO;AAG7B,MAAI,SAAS,KAAK,QAAQ,CAAE,QAAO;AAInC,MAAI,mBAAmB,IAAI,QAAQ,CAAE,QAAO;AAK5C,SAAO,KAAK,WAAW,MAAM,SAAS;AACpC,OAAI,KAAK,SAAS,WAAY,QAAO;AACrC,OAAI,KAAK,IAAI,SAAS,aAAa,KAAK,IAAI,UAAU,GAAI,QAAO;AACjE,OAAI,KAAK,IAAI,SAAS,aAAc,QAAO;AAC3C,OAAI,KAAK,IAAI,SAAS,aAAa,OAAO,KAAK,IAAI,UAAU,SAC3D,QAAO;AAET,UAAO;IACP;;;;;CAMJ,gBAAgB,KAAsB;AACpC,SAAO,SAAS,KAAK,IAAI;;;;;CAM3B,oBAAoB,KAAsB;AACxC,SAAO,IAAI,WAAW,IAAI;;;;;CAM5B,oBAAoB,KAAsB;AACxC,SAAO,IAAI,WAAW,IAAI;;;;;CAM5B,gBAAgB,KAAsB;AACpC,SAAO,IAAI,WAAW,IAAI;;;;;CAM5B,aAAa,KAAsB;AACjC,SAAO,IAAI,WAAW,IAAI"}
|
|
@@ -485,6 +485,32 @@ function getStateNegationEdits(stateKey) {
|
|
|
485
485
|
});
|
|
486
486
|
}
|
|
487
487
|
/**
|
|
488
|
+
* Unwrap every `@own(...)` term of a key, for a scope where `@own` is the
|
|
489
|
+
* element itself. A term with operators inside keeps them grouped, so
|
|
490
|
+
* `@own(a | b) & c` becomes `(a | b) & c`, not `a | b & c`. Returns no edits
|
|
491
|
+
* when any term cannot be unwrapped safely, so a key is never half-rewritten.
|
|
492
|
+
*/
|
|
493
|
+
function getOwnUnwrapEdits(stateKey) {
|
|
494
|
+
if (!stateKey.includes("@own(")) return [];
|
|
495
|
+
if (checkBracketBalance(stateKey)) return [];
|
|
496
|
+
if (parseStateKey(stateKey).errors.length > 0) return [];
|
|
497
|
+
const { tokens } = tokenize(stateKey);
|
|
498
|
+
const edits = [];
|
|
499
|
+
for (const token of tokens) {
|
|
500
|
+
if (token.type !== "STATE" || !token.value.startsWith("@own(")) continue;
|
|
501
|
+
const inner = token.value.slice(5, -1).trim();
|
|
502
|
+
if (!inner || findTopLevelComma(inner) !== -1) return [];
|
|
503
|
+
const innerTokens = tokenize(inner).tokens;
|
|
504
|
+
const single = tokens.length === 1 || innerTokens.length === 1 && innerTokens[0].value === inner;
|
|
505
|
+
edits.push({
|
|
506
|
+
start: token.offset,
|
|
507
|
+
end: token.offset + token.length,
|
|
508
|
+
replacement: single ? inner : `(${inner})`
|
|
509
|
+
});
|
|
510
|
+
}
|
|
511
|
+
return edits;
|
|
512
|
+
}
|
|
513
|
+
/**
|
|
488
514
|
* The state atoms of a key, without its operators and grouping. The contents
|
|
489
515
|
* of `@own(...)` are listed atom by atom; `@root()`, `@parent()`, and at-rule
|
|
490
516
|
* conditions stay single atoms, since they describe other things.
|
|
@@ -554,5 +580,5 @@ function validateStateDefinition(value, opts = {}) {
|
|
|
554
580
|
}
|
|
555
581
|
|
|
556
582
|
//#endregion
|
|
557
|
-
export { getStateAtoms, getStateNegationEdits, parseStateKey, validateStateDefinition };
|
|
583
|
+
export { getOwnUnwrapEdits, getStateAtoms, getStateNegationEdits, parseStateKey, validateStateDefinition };
|
|
558
584
|
//# sourceMappingURL=state-key-parser.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"state-key-parser.js","names":[],"sources":["../../src/parsers/state-key-parser.ts"],"sourcesContent":["import { KNOWN_PSEUDO_CLASSES } from '../constants.js';\nimport type { StringEdit } from '../fix-utils.js';\nimport { checkBracketBalance } from './utils.js';\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface StateKeyError {\n message: string;\n offset: number;\n length: number;\n}\n\nexport interface StateKeyResult {\n errors: StateKeyError[];\n hasOwn: boolean;\n referencedAliases: string[];\n}\n\nexport interface StateKeyParserOptions {\n knownAliases?: string[];\n}\n\n// ============================================================================\n// Tokenizer\n// ============================================================================\n\ntype TokenType = 'AND' | 'OR' | 'NOT' | 'XOR' | 'LPAREN' | 'RPAREN' | 'STATE';\n\ninterface Token {\n type: TokenType;\n value: string;\n offset: number;\n length: number;\n}\n\n/**\n * Pattern for tokenizing state notation.\n * Matches operators, parentheses, @-prefixed states, value mods, boolean mods,\n * pseudo-classes with functions (including :is/:has/:not/:where with nesting),\n * class selectors, and attribute selectors.\n */\nconst STATE_TOKEN_PATTERN =\n /([&|!^])|([()])|(@media:[a-z]+)|(@media\\([^)]*\\))|(@supports\\([^()]*(?:\\([^)]*\\))?[^)]*\\))|(@root\\([^()]*(?:\\([^()]*(?:\\([^)]*\\))?[^)]*\\))*[^)]*\\))|(@parent\\([^()]*(?:\\([^()]*(?:\\([^)]*\\))?[^)]*\\))*[^)]*\\))|(@own\\([^()]*(?:\\([^()]*(?:\\([^)]*\\))?[^)]*\\))*[^)]*\\))|(@\\([^()]*(?:\\([^)]*\\))?[^)]*\\))|(@starting)|(@[A-Za-z][A-Za-z0-9-]*)|([a-z][a-z0-9-]*(?:\\^=|\\$=|\\*=|=)(?:\"[^\"]*\"|'[^']*'|[^\\s&|!^()]+))|([a-z][a-z0-9-]+)|(:(?:is|has|not|where)\\([^()]*(?:\\([^()]*(?:\\([^)]*\\))?[^)]*\\))*[^)]*\\))|(:[-a-z][a-z0-9-]*(?:\\([^)]+\\))?)|(\\.[a-z][a-z0-9-]+)|(\\[[^\\]]+\\])/gi;\n\nfunction tokenize(stateKey: string): {\n tokens: Token[];\n errors: StateKeyError[];\n} {\n const tokens: Token[] = [];\n const errors: StateKeyError[] = [];\n\n // Replace commas with | outside of parentheses\n const normalized = replaceCommasOutsideParens(stateKey);\n\n const covered = new Set<number>();\n\n STATE_TOKEN_PATTERN.lastIndex = 0;\n let match: RegExpExecArray | null;\n while ((match = STATE_TOKEN_PATTERN.exec(normalized)) !== null) {\n const fullMatch = match[0];\n const offset = match.index;\n\n for (let i = offset; i < offset + fullMatch.length; i++) {\n covered.add(i);\n }\n\n if (match[1]) {\n switch (fullMatch) {\n case '&':\n tokens.push({ type: 'AND', value: '&', offset, length: 1 });\n break;\n case '|':\n tokens.push({ type: 'OR', value: '|', offset, length: 1 });\n break;\n case '!':\n tokens.push({ type: 'NOT', value: '!', offset, length: 1 });\n break;\n case '^':\n tokens.push({ type: 'XOR', value: '^', offset, length: 1 });\n break;\n }\n } else if (match[2]) {\n if (fullMatch === '(') {\n tokens.push({ type: 'LPAREN', value: '(', offset, length: 1 });\n } else {\n tokens.push({ type: 'RPAREN', value: ')', offset, length: 1 });\n }\n } else {\n tokens.push({\n type: 'STATE',\n value: fullMatch,\n offset,\n length: fullMatch.length,\n });\n }\n }\n\n // Check for uncovered characters (unrecognized tokens)\n const uncovered: { ch: string; pos: number }[] = [];\n for (let i = 0; i < stateKey.length; i++) {\n const ch = stateKey[i];\n if (ch === ' ' || ch === '\\t' || ch === ',') continue;\n if (!covered.has(i)) {\n uncovered.push({ ch, pos: i });\n }\n }\n\n if (uncovered.length > 0) {\n const chars = [...new Set(uncovered.map((u) => u.ch))].join('');\n errors.push({\n message: `Unrecognized characters '${chars}' in state key '${stateKey}'.`,\n offset: uncovered[0].pos,\n length: 1,\n });\n }\n\n return { tokens, errors };\n}\n\nfunction replaceCommasOutsideParens(str: string): string {\n let result = '';\n let depth = 0;\n\n for (const char of str) {\n if (char === '(') {\n depth++;\n result += char;\n } else if (char === ')') {\n depth--;\n result += char;\n } else if (char === ',' && depth === 0) {\n result += '|';\n } else {\n result += char;\n }\n }\n\n return result;\n}\n\n// ============================================================================\n// Validator\n// ============================================================================\n\nconst MAX_XOR_CHAIN_LENGTH = 4;\n\nconst DIMENSION_SHORTHANDS = new Set(['w', 'h', 'is', 'bs']);\nconst DIMENSION_FULL = new Set([\n 'width',\n 'height',\n 'inline-size',\n 'block-size',\n]);\n\nclass StateKeyValidator {\n private errors: StateKeyError[] = [];\n private hasOwn = false;\n private referencedAliases: string[] = [];\n private tokens: Token[];\n private pos = 0;\n private opts: StateKeyParserOptions;\n private insideOwn = false;\n\n constructor(\n tokens: Token[],\n tokenErrors: StateKeyError[],\n opts: StateKeyParserOptions,\n ) {\n this.tokens = tokens;\n this.errors = [...tokenErrors];\n this.opts = opts;\n }\n\n validate(): StateKeyResult {\n if (this.tokens.length > 0) {\n this.parseExpression();\n }\n\n return {\n errors: this.errors,\n hasOwn: this.hasOwn,\n referencedAliases: this.referencedAliases,\n };\n }\n\n private current(): Token | undefined {\n return this.tokens[this.pos];\n }\n\n private advance(): Token | undefined {\n return this.tokens[this.pos++];\n }\n\n private match(type: TokenType): boolean {\n if (this.current()?.type === type) {\n this.advance();\n return true;\n }\n return false;\n }\n\n private parseExpression(): void {\n this.parseAnd();\n }\n\n private parseAnd(): void {\n this.parseOr();\n while (this.current()?.type === 'AND') {\n this.advance();\n if (!this.current() || this.current()?.type === 'AND') {\n const prev = this.tokens[this.pos - 1];\n this.errors.push({\n message: \"Expected expression after '&' operator.\",\n offset: prev.offset,\n length: prev.length,\n });\n return;\n }\n this.parseOr();\n }\n }\n\n private parseOr(): void {\n this.parseXor();\n while (this.current()?.type === 'OR') {\n this.advance();\n if (!this.current() || this.current()?.type === 'OR') {\n const prev = this.tokens[this.pos - 1];\n this.errors.push({\n message: \"Expected expression after '|' operator.\",\n offset: prev.offset,\n length: prev.length,\n });\n return;\n }\n this.parseXor();\n }\n }\n\n private parseXor(): void {\n this.parseUnary();\n let operandCount = 1;\n\n while (this.current()?.type === 'XOR') {\n this.advance();\n operandCount++;\n if (operandCount > MAX_XOR_CHAIN_LENGTH) {\n const prev = this.tokens[this.pos - 1];\n this.errors.push({\n message: `XOR chain with ${operandCount} operands produces ${Math.pow(2, operandCount - 1)} OR branches. Consider breaking into smaller expressions.`,\n offset: prev.offset,\n length: prev.length,\n });\n }\n this.parseUnary();\n }\n }\n\n private parseUnary(): void {\n if (this.match('NOT')) {\n if (\n !this.current() ||\n this.current()?.type === 'AND' ||\n this.current()?.type === 'OR' ||\n this.current()?.type === 'XOR'\n ) {\n const prev = this.tokens[this.pos - 1];\n this.errors.push({\n message: \"Expected expression after '!' operator.\",\n offset: prev.offset,\n length: prev.length,\n });\n return;\n }\n this.parseUnary();\n return;\n }\n this.parsePrimary();\n }\n\n private parsePrimary(): void {\n if (this.match('LPAREN')) {\n this.parseExpression();\n if (!this.match('RPAREN')) {\n this.errors.push({\n message: \"Missing closing ')' in state expression.\",\n offset: this.tokens[this.pos - 1]?.offset ?? 0,\n length: 1,\n });\n }\n return;\n }\n\n const token = this.current();\n if (token?.type === 'STATE') {\n this.advance();\n this.validateStateToken(token);\n return;\n }\n\n // Unexpected token or end\n if (token) {\n this.errors.push({\n message: `Unexpected token '${token.value}'.`,\n offset: token.offset,\n length: token.length,\n });\n this.advance();\n }\n }\n\n private validateStateToken(token: Token): void {\n const value = token.value;\n\n // @starting\n if (value === '@starting') return;\n\n // @media:type\n if (value.startsWith('@media:')) {\n const mediaType = value.slice(7);\n const validTypes = new Set(['print', 'screen', 'all', 'speech']);\n if (!validTypes.has(mediaType)) {\n this.errors.push({\n message: `Unknown media type '${mediaType}'. Valid: print, screen, all, speech.`,\n offset: token.offset,\n length: token.length,\n });\n }\n return;\n }\n\n // @media(...)\n if (value.startsWith('@media(')) {\n this.validateMediaQuery(value, token);\n return;\n }\n\n // @supports(...)\n if (value.startsWith('@supports(')) {\n this.validateSupportsQuery(value, token);\n return;\n }\n\n // @root(...)\n if (value.startsWith('@root(')) {\n this.validateInnerStateExpression(value, 6, token);\n return;\n }\n\n // @parent(...)\n if (value.startsWith('@parent(')) {\n this.validateParentState(value, token);\n return;\n }\n\n // @own(...)\n if (value.startsWith('@own(')) {\n this.hasOwn = true;\n if (this.insideOwn) {\n this.errors.push({\n message: 'Nested @own() is not allowed.',\n offset: token.offset,\n length: token.length,\n });\n return;\n }\n const prevInsideOwn = this.insideOwn;\n this.insideOwn = true;\n this.validateInnerStateExpression(value, 5, token);\n this.insideOwn = prevInsideOwn;\n return;\n }\n\n // @(...) container query\n if (value.startsWith('@(')) {\n this.validateContainerQuery(value, token);\n return;\n }\n\n // @alias predefined state\n if (value.startsWith('@') && /^@[A-Za-z][A-Za-z0-9-]*$/.test(value)) {\n this.referencedAliases.push(value);\n return;\n }\n\n // Pseudo-class/pseudo-element\n if (value.startsWith(':')) {\n this.validatePseudoClass(value, token);\n return;\n }\n\n // Class selector\n if (value.startsWith('.')) return;\n\n // Attribute selector\n if (value.startsWith('[')) {\n this.validateAttributeSelector(value, token);\n return;\n }\n\n // Value modifier (e.g., theme=danger)\n if (value.includes('=')) {\n this.validateValueModifier(value, token);\n return;\n }\n\n // Boolean modifier (e.g., hovered, disabled)\n if (/^[a-z][a-z0-9-]+$/i.test(value)) return;\n\n this.errors.push({\n message: `Unrecognized state token '${value}'.`,\n offset: token.offset,\n length: token.length,\n });\n }\n\n private validateMediaQuery(raw: string, token: Token): void {\n const content = raw.slice(7, -1);\n if (!content.trim()) {\n this.errors.push({\n message: 'Empty @media() query.',\n offset: token.offset,\n length: token.length,\n });\n return;\n }\n\n // Expand dimension shorthands for validation\n const expanded = expandDimensionShorthands(content.trim());\n\n // Feature query (contains ':' but no comparison operators)\n if (\n expanded.includes(':') &&\n !expanded.includes('<') &&\n !expanded.includes('>') &&\n !expanded.includes('=')\n ) {\n return;\n }\n\n // Boolean feature query (no comparison operators)\n if (\n !expanded.includes('<') &&\n !expanded.includes('>') &&\n !expanded.includes('=')\n ) {\n return;\n }\n\n // Dimension query — validate dimension names\n this.validateDimensionCondition(expanded, token);\n }\n\n private validateDimensionCondition(condition: string, token: Token): void {\n // Range syntax: 600px <= width < 1200px\n const rangeMatch = condition.match(\n /^(.+?)\\s*(<=|<)\\s*(\\S+)\\s*(<=|<)\\s*(.+)$/,\n );\n if (rangeMatch) {\n const dim = rangeMatch[3];\n if (!DIMENSION_FULL.has(dim) && !DIMENSION_SHORTHANDS.has(dim)) {\n this.errors.push({\n message: `Unknown dimension '${dim}' in media/container query. Valid: width, height, inline-size, block-size (or w, h, is, bs).`,\n offset: token.offset,\n length: token.length,\n });\n }\n return;\n }\n\n // Simple comparison: width < 768px\n const simpleMatch = condition.match(/^(\\S+)\\s*(<=|>=|<|>|=)\\s*(.+)$/);\n if (simpleMatch) {\n const dim = simpleMatch[1];\n if (DIMENSION_FULL.has(dim) || DIMENSION_SHORTHANDS.has(dim)) {\n return;\n }\n }\n\n // Reversed: 768px > width\n const reversedMatch = condition.match(/^(.+?)\\s*(<=|>=|<|>|=)\\s*(\\S+)$/);\n if (reversedMatch) {\n const dim = reversedMatch[3];\n if (DIMENSION_FULL.has(dim) || DIMENSION_SHORTHANDS.has(dim)) {\n return;\n }\n }\n }\n\n private validateSupportsQuery(raw: string, token: Token): void {\n const content = raw.slice(10, -1);\n if (!content.trim()) {\n this.errors.push({\n message: 'Empty @supports() query.',\n offset: token.offset,\n length: token.length,\n });\n }\n }\n\n private validateInnerStateExpression(\n raw: string,\n prefixLen: number,\n _token: Token,\n ): void {\n const content = raw.slice(prefixLen, -1);\n if (!content.trim()) return;\n\n const innerResult = parseStateKey(content, this.opts);\n this.errors.push(...innerResult.errors);\n if (innerResult.hasOwn) this.hasOwn = true;\n this.referencedAliases.push(...innerResult.referencedAliases);\n }\n\n private validateParentState(raw: string, token: Token): void {\n const content = raw.slice(8, -1);\n if (!content.trim()) {\n this.errors.push({\n message: 'Empty @parent() state.',\n offset: token.offset,\n length: token.length,\n });\n return;\n }\n\n let condition = content.trim();\n\n // Check for direct parent combinator: @parent(hovered, >)\n const lastCommaIdx = condition.lastIndexOf(',');\n if (lastCommaIdx !== -1) {\n const afterComma = condition.slice(lastCommaIdx + 1).trim();\n if (afterComma === '>') {\n condition = condition.slice(0, lastCommaIdx).trim();\n }\n }\n\n const innerResult = parseStateKey(condition, this.opts);\n this.errors.push(...innerResult.errors);\n this.referencedAliases.push(...innerResult.referencedAliases);\n }\n\n private validateContainerQuery(raw: string, token: Token): void {\n const content = raw.slice(2, -1);\n if (!content.trim()) {\n this.errors.push({\n message: 'Empty container query.',\n offset: token.offset,\n length: token.length,\n });\n return;\n }\n\n // Named container: @(layout, w < 600px)\n const commaIdx = findTopLevelComma(content);\n let condition: string;\n\n if (commaIdx !== -1) {\n condition = content.slice(commaIdx + 1).trim();\n } else {\n condition = content.trim();\n }\n\n // Style query: @($variant=primary) — skip\n if (condition.startsWith('$')) return;\n\n // Function-like: scroll-state(...) — skip\n if (/^[a-zA-Z][\\w-]*\\s*\\(/.test(condition)) return;\n\n // Dimension query\n const expanded = expandDimensionShorthands(condition);\n if (\n expanded.includes('<') ||\n expanded.includes('>') ||\n expanded.includes('=')\n ) {\n this.validateDimensionCondition(expanded, token);\n }\n }\n\n private validatePseudoClass(value: string, token: Token): void {\n // :is(), :has(), :not(), :where() — structural pseudo-classes\n const enhancedMatch = /^:(is|has|not|where)\\(/.exec(value);\n if (enhancedMatch) return;\n\n // Functional pseudo-classes like :nth-child(2n+1)\n const funcMatch = /^(:[a-z-]+)\\(/.exec(value);\n if (funcMatch) {\n const baseName = funcMatch[1];\n if (!KNOWN_PSEUDO_CLASSES.has(baseName)) {\n this.errors.push({\n message: `Unknown pseudo-class '${baseName}'.`,\n offset: token.offset,\n length: token.length,\n });\n }\n return;\n }\n\n // Simple pseudo-class: :hover, :focus, etc.\n if (!KNOWN_PSEUDO_CLASSES.has(value)) {\n this.errors.push({\n message: `Unknown pseudo-class '${value}'.`,\n offset: token.offset,\n length: token.length,\n });\n }\n }\n\n private validateAttributeSelector(value: string, token: Token): void {\n if (!value.startsWith('[') || !value.endsWith(']')) {\n this.errors.push({\n message: `Malformed attribute selector '${value}'.`,\n offset: token.offset,\n length: token.length,\n });\n }\n }\n\n private validateValueModifier(value: string, token: Token): void {\n const opMatch = value.match(/^([a-z][a-z0-9-]*)(\\^=|\\$=|\\*=|=)(.+)$/i);\n if (!opMatch) {\n this.errors.push({\n message: `Invalid value modifier syntax '${value}'.`,\n offset: token.offset,\n length: token.length,\n });\n }\n }\n}\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\nfunction expandDimensionShorthands(condition: string): string {\n return condition\n .replace(/\\bw\\b/g, 'width')\n .replace(/\\bh\\b/g, 'height')\n .replace(/\\bis\\b/g, 'inline-size')\n .replace(/\\bbs\\b/g, 'block-size');\n}\n\nfunction findTopLevelComma(str: string): number {\n let depth = 0;\n for (let i = 0; i < str.length; i++) {\n const ch = str[i];\n if (ch === '(') depth++;\n else if (ch === ')') depth = Math.max(0, depth - 1);\n else if (ch === ',' && depth === 0) return i;\n }\n return -1;\n}\n\n// ============================================================================\n// Public API\n// ============================================================================\n\n/**\n * Rewrite :not() state atoms, leaving raw CSS inside other functions alone.\n * A selector list/compound must stay inside :is(): negating individual parts\n * would change which elements match. Only a single pseudo can be unwrapped.\n */\nexport function getStateNegationEdits(stateKey: string): StringEdit[] {\n if (!stateKey.includes(':not(')) return [];\n if (checkBracketBalance(stateKey)) return [];\n if (parseStateKey(stateKey).errors.length > 0) return [];\n\n const { tokens } = tokenize(stateKey);\n return tokens\n .filter(\n (token) => token.type === 'STATE' && token.value.startsWith(':not('),\n )\n .flatMap((token) => {\n if (checkBracketBalance(token.value)) return [];\n const inner = token.value.slice(5, -1).trim();\n if (!inner) return [];\n\n const { tokens: innerTokens, errors } = tokenize(inner);\n const singlePseudo =\n errors.length === 0 &&\n innerTokens.length === 1 &&\n innerTokens[0].type === 'STATE' &&\n innerTokens[0].value === inner &&\n inner.startsWith(':') &&\n parseStateKey(inner).errors.length === 0 &&\n !inner.startsWith(':not(') &&\n // Keep forgiving selector-list wrappers, even for invalid branches.\n !inner.startsWith(':is(') &&\n !inner.startsWith(':where(') &&\n // Promoting :has() to a state atom enables Tasty's trailing-combinator\n // completion. Preserve the original raw CSS instead in that case.\n !(inner.startsWith(':has(') && /[>+~]\\s*\\)$/.test(inner));\n\n return [\n {\n start: token.offset,\n end: token.offset + token.length,\n replacement: singlePseudo ? `!${inner}` : `!:is(${inner})`,\n },\n ];\n });\n}\n\nexport interface StateAtom {\n /** The atom as written: `hovered`, `:hover`, `[open]`, `@root(...)`. */\n value: string;\n /** Whether the atom sits inside `@own(...)`. */\n own: boolean;\n}\n\n/**\n * The state atoms of a key, without its operators and grouping. The contents\n * of `@own(...)` are listed atom by atom; `@root()`, `@parent()`, and at-rule\n * conditions stay single atoms, since they describe other things.\n */\nexport function getStateAtoms(stateKey: string): StateAtom[] {\n const atoms: StateAtom[] = [];\n for (const token of tokenize(stateKey.trim()).tokens) {\n if (token.type !== 'STATE') continue;\n if (!token.value.startsWith('@own(')) {\n atoms.push({ value: token.value, own: false });\n continue;\n }\n for (const inner of tokenize(token.value.slice(5, -1)).tokens) {\n if (inner.type === 'STATE') atoms.push({ value: inner.value, own: true });\n }\n }\n return atoms;\n}\n\n/**\n * Validate a state key string and return detailed errors.\n */\nexport function parseStateKey(\n stateKey: string,\n opts: StateKeyParserOptions = {},\n): StateKeyResult {\n if (!stateKey || !stateKey.trim()) {\n return { errors: [], hasOwn: false, referencedAliases: [] };\n }\n\n const trimmed = stateKey.trim();\n\n // The standalone `_` key is the map-wide fallback floor. It always applies\n // and must be used on its own — it carries no state logic to validate.\n if (trimmed === '_') {\n return { errors: [], hasOwn: false, referencedAliases: [] };\n }\n\n // A `_` combined with state logic (`_ & hovered`, `_ | x`) is a misuse: the\n // fallback floor can only be used on its own. Tasty ignores such keys at\n // runtime and warns; flag them here so the mistake surfaces in the editor.\n if (isMisusedFallbackKey(trimmed)) {\n return {\n errors: [\n {\n message:\n 'The fallback floor \"_\" cannot be combined with other state ' +\n 'logic. Use \"_\" on its own as a map-wide fallback floor.',\n offset: 0,\n length: stateKey.length,\n },\n ],\n hasOwn: false,\n referencedAliases: [],\n };\n }\n\n const { tokens, errors: tokenErrors } = tokenize(trimmed);\n const validator = new StateKeyValidator(tokens, tokenErrors, opts);\n return validator.validate();\n}\n\n/**\n * Detect a misused standalone `_` fallback key: a key that is not exactly\n * `_` but contains `_` as a standalone atom among state-logic operators\n * (`&`, `|`, `^`, `,`) or grouping parens. A `_` embedded in a longer token\n * (e.g. a modifier named `_private`) is not a misuse.\n */\nfunction isMisusedFallbackKey(stateKey: string): boolean {\n if (stateKey === '_' || !stateKey.includes('_')) return false;\n return /(?:^|[\\s&|^,(])_(?:[\\s&|^,)]|$)/.test(stateKey);\n}\n\n/**\n * Validate a state definition value (the RHS of a state alias).\n * State definitions should be valid state expressions like\n * '@media(w < 768px)', '@root(theme=dark)', etc.\n */\nexport function validateStateDefinition(\n value: string,\n opts: StateKeyParserOptions = {},\n): StateKeyResult {\n return parseStateKey(value, opts);\n}\n"],"mappings":";;;;;;;;;;AA2CA,MAAM,sBACJ;AAEF,SAAS,SAAS,UAGhB;CACA,MAAM,SAAkB,EAAE;CAC1B,MAAM,SAA0B,EAAE;CAGlC,MAAM,aAAa,2BAA2B,SAAS;CAEvD,MAAM,0BAAU,IAAI,KAAa;AAEjC,qBAAoB,YAAY;CAChC,IAAI;AACJ,SAAQ,QAAQ,oBAAoB,KAAK,WAAW,MAAM,MAAM;EAC9D,MAAM,YAAY,MAAM;EACxB,MAAM,SAAS,MAAM;AAErB,OAAK,IAAI,IAAI,QAAQ,IAAI,SAAS,UAAU,QAAQ,IAClD,SAAQ,IAAI,EAAE;AAGhB,MAAI,MAAM,GACR,SAAQ,WAAR;GACE,KAAK;AACH,WAAO,KAAK;KAAE,MAAM;KAAO,OAAO;KAAK;KAAQ,QAAQ;KAAG,CAAC;AAC3D;GACF,KAAK;AACH,WAAO,KAAK;KAAE,MAAM;KAAM,OAAO;KAAK;KAAQ,QAAQ;KAAG,CA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Q,QAAQ,gBAAgB,SAAS,QAAQ;AAEzD,QADkB,IAAI,kBAAkB,QAAQ,aAAa,KAAK,CACjD,UAAU;;;;;;;;AAS7B,SAAS,qBAAqB,UAA2B;AACvD,KAAI,aAAa,OAAO,CAAC,SAAS,SAAS,IAAI,CAAE,QAAO;AACxD,QAAO,kCAAkC,KAAK,SAAS;;;;;;;AAQzD,SAAgB,wBACd,OACA,OAA8B,EAAE,EAChB;AAChB,QAAO,cAAc,OAAO,KAAK"}
|
|
1
|
+
{"version":3,"file":"state-key-parser.js","names":[],"sources":["../../src/parsers/state-key-parser.ts"],"sourcesContent":["import { KNOWN_PSEUDO_CLASSES } from '../constants.js';\nimport type { StringEdit } from '../fix-utils.js';\nimport { checkBracketBalance } from './utils.js';\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface StateKeyError {\n message: string;\n offset: number;\n length: number;\n}\n\nexport interface StateKeyResult {\n errors: StateKeyError[];\n hasOwn: boolean;\n referencedAliases: string[];\n}\n\nexport interface StateKeyParserOptions {\n knownAliases?: string[];\n}\n\n// ============================================================================\n// Tokenizer\n// ============================================================================\n\ntype TokenType = 'AND' | 'OR' | 'NOT' | 'XOR' | 'LPAREN' | 'RPAREN' | 'STATE';\n\ninterface Token {\n type: TokenType;\n value: string;\n offset: number;\n length: number;\n}\n\n/**\n * Pattern for tokenizing state notation.\n * Matches operators, parentheses, @-prefixed states, value mods, boolean mods,\n * pseudo-classes with functions (including :is/:has/:not/:where with nesting),\n * class selectors, and attribute selectors.\n */\nconst STATE_TOKEN_PATTERN =\n /([&|!^])|([()])|(@media:[a-z]+)|(@media\\([^)]*\\))|(@supports\\([^()]*(?:\\([^)]*\\))?[^)]*\\))|(@root\\([^()]*(?:\\([^()]*(?:\\([^)]*\\))?[^)]*\\))*[^)]*\\))|(@parent\\([^()]*(?:\\([^()]*(?:\\([^)]*\\))?[^)]*\\))*[^)]*\\))|(@own\\([^()]*(?:\\([^()]*(?:\\([^)]*\\))?[^)]*\\))*[^)]*\\))|(@\\([^()]*(?:\\([^)]*\\))?[^)]*\\))|(@starting)|(@[A-Za-z][A-Za-z0-9-]*)|([a-z][a-z0-9-]*(?:\\^=|\\$=|\\*=|=)(?:\"[^\"]*\"|'[^']*'|[^\\s&|!^()]+))|([a-z][a-z0-9-]+)|(:(?:is|has|not|where)\\([^()]*(?:\\([^()]*(?:\\([^)]*\\))?[^)]*\\))*[^)]*\\))|(:[-a-z][a-z0-9-]*(?:\\([^)]+\\))?)|(\\.[a-z][a-z0-9-]+)|(\\[[^\\]]+\\])/gi;\n\nfunction tokenize(stateKey: string): {\n tokens: Token[];\n errors: StateKeyError[];\n} {\n const tokens: Token[] = [];\n const errors: StateKeyError[] = [];\n\n // Replace commas with | outside of parentheses\n const normalized = replaceCommasOutsideParens(stateKey);\n\n const covered = new Set<number>();\n\n STATE_TOKEN_PATTERN.lastIndex = 0;\n let match: RegExpExecArray | null;\n while ((match = STATE_TOKEN_PATTERN.exec(normalized)) !== null) {\n const fullMatch = match[0];\n const offset = match.index;\n\n for (let i = offset; i < offset + fullMatch.length; i++) {\n covered.add(i);\n }\n\n if (match[1]) {\n switch (fullMatch) {\n case '&':\n tokens.push({ type: 'AND', value: '&', offset, length: 1 });\n break;\n case '|':\n tokens.push({ type: 'OR', value: '|', offset, length: 1 });\n break;\n case '!':\n tokens.push({ type: 'NOT', value: '!', offset, length: 1 });\n break;\n case '^':\n tokens.push({ type: 'XOR', value: '^', offset, length: 1 });\n break;\n }\n } else if (match[2]) {\n if (fullMatch === '(') {\n tokens.push({ type: 'LPAREN', value: '(', offset, length: 1 });\n } else {\n tokens.push({ type: 'RPAREN', value: ')', offset, length: 1 });\n }\n } else {\n tokens.push({\n type: 'STATE',\n value: fullMatch,\n offset,\n length: fullMatch.length,\n });\n }\n }\n\n // Check for uncovered characters (unrecognized tokens)\n const uncovered: { ch: string; pos: number }[] = [];\n for (let i = 0; i < stateKey.length; i++) {\n const ch = stateKey[i];\n if (ch === ' ' || ch === '\\t' || ch === ',') continue;\n if (!covered.has(i)) {\n uncovered.push({ ch, pos: i });\n }\n }\n\n if (uncovered.length > 0) {\n const chars = [...new Set(uncovered.map((u) => u.ch))].join('');\n errors.push({\n message: `Unrecognized characters '${chars}' in state key '${stateKey}'.`,\n offset: uncovered[0].pos,\n length: 1,\n });\n }\n\n return { tokens, errors };\n}\n\nfunction replaceCommasOutsideParens(str: string): string {\n let result = '';\n let depth = 0;\n\n for (const char of str) {\n if (char === '(') {\n depth++;\n result += char;\n } else if (char === ')') {\n depth--;\n result += char;\n } else if (char === ',' && depth === 0) {\n result += '|';\n } else {\n result += char;\n }\n }\n\n return result;\n}\n\n// ============================================================================\n// Validator\n// ============================================================================\n\nconst MAX_XOR_CHAIN_LENGTH = 4;\n\nconst DIMENSION_SHORTHANDS = new Set(['w', 'h', 'is', 'bs']);\nconst DIMENSION_FULL = new Set([\n 'width',\n 'height',\n 'inline-size',\n 'block-size',\n]);\n\nclass StateKeyValidator {\n private errors: StateKeyError[] = [];\n private hasOwn = false;\n private referencedAliases: string[] = [];\n private tokens: Token[];\n private pos = 0;\n private opts: StateKeyParserOptions;\n private insideOwn = false;\n\n constructor(\n tokens: Token[],\n tokenErrors: StateKeyError[],\n opts: StateKeyParserOptions,\n ) {\n this.tokens = tokens;\n this.errors = [...tokenErrors];\n this.opts = opts;\n }\n\n validate(): StateKeyResult {\n if (this.tokens.length > 0) {\n this.parseExpression();\n }\n\n return {\n errors: this.errors,\n hasOwn: this.hasOwn,\n referencedAliases: this.referencedAliases,\n };\n }\n\n private current(): Token | undefined {\n return this.tokens[this.pos];\n }\n\n private advance(): Token | undefined {\n return this.tokens[this.pos++];\n }\n\n private match(type: TokenType): boolean {\n if (this.current()?.type === type) {\n this.advance();\n return true;\n }\n return false;\n }\n\n private parseExpression(): void {\n this.parseAnd();\n }\n\n private parseAnd(): void {\n this.parseOr();\n while (this.current()?.type === 'AND') {\n this.advance();\n if (!this.current() || this.current()?.type === 'AND') {\n const prev = this.tokens[this.pos - 1];\n this.errors.push({\n message: \"Expected expression after '&' operator.\",\n offset: prev.offset,\n length: prev.length,\n });\n return;\n }\n this.parseOr();\n }\n }\n\n private parseOr(): void {\n this.parseXor();\n while (this.current()?.type === 'OR') {\n this.advance();\n if (!this.current() || this.current()?.type === 'OR') {\n const prev = this.tokens[this.pos - 1];\n this.errors.push({\n message: \"Expected expression after '|' operator.\",\n offset: prev.offset,\n length: prev.length,\n });\n return;\n }\n this.parseXor();\n }\n }\n\n private parseXor(): void {\n this.parseUnary();\n let operandCount = 1;\n\n while (this.current()?.type === 'XOR') {\n this.advance();\n operandCount++;\n if (operandCount > MAX_XOR_CHAIN_LENGTH) {\n const prev = this.tokens[this.pos - 1];\n this.errors.push({\n message: `XOR chain with ${operandCount} operands produces ${Math.pow(2, operandCount - 1)} OR branches. Consider breaking into smaller expressions.`,\n offset: prev.offset,\n length: prev.length,\n });\n }\n this.parseUnary();\n }\n }\n\n private parseUnary(): void {\n if (this.match('NOT')) {\n if (\n !this.current() ||\n this.current()?.type === 'AND' ||\n this.current()?.type === 'OR' ||\n this.current()?.type === 'XOR'\n ) {\n const prev = this.tokens[this.pos - 1];\n this.errors.push({\n message: \"Expected expression after '!' operator.\",\n offset: prev.offset,\n length: prev.length,\n });\n return;\n }\n this.parseUnary();\n return;\n }\n this.parsePrimary();\n }\n\n private parsePrimary(): void {\n if (this.match('LPAREN')) {\n this.parseExpression();\n if (!this.match('RPAREN')) {\n this.errors.push({\n message: \"Missing closing ')' in state expression.\",\n offset: this.tokens[this.pos - 1]?.offset ?? 0,\n length: 1,\n });\n }\n return;\n }\n\n const token = this.current();\n if (token?.type === 'STATE') {\n this.advance();\n this.validateStateToken(token);\n return;\n }\n\n // Unexpected token or end\n if (token) {\n this.errors.push({\n message: `Unexpected token '${token.value}'.`,\n offset: token.offset,\n length: token.length,\n });\n this.advance();\n }\n }\n\n private validateStateToken(token: Token): void {\n const value = token.value;\n\n // @starting\n if (value === '@starting') return;\n\n // @media:type\n if (value.startsWith('@media:')) {\n const mediaType = value.slice(7);\n const validTypes = new Set(['print', 'screen', 'all', 'speech']);\n if (!validTypes.has(mediaType)) {\n this.errors.push({\n message: `Unknown media type '${mediaType}'. Valid: print, screen, all, speech.`,\n offset: token.offset,\n length: token.length,\n });\n }\n return;\n }\n\n // @media(...)\n if (value.startsWith('@media(')) {\n this.validateMediaQuery(value, token);\n return;\n }\n\n // @supports(...)\n if (value.startsWith('@supports(')) {\n this.validateSupportsQuery(value, token);\n return;\n }\n\n // @root(...)\n if (value.startsWith('@root(')) {\n this.validateInnerStateExpression(value, 6, token);\n return;\n }\n\n // @parent(...)\n if (value.startsWith('@parent(')) {\n this.validateParentState(value, token);\n return;\n }\n\n // @own(...)\n if (value.startsWith('@own(')) {\n this.hasOwn = true;\n if (this.insideOwn) {\n this.errors.push({\n message: 'Nested @own() is not allowed.',\n offset: token.offset,\n length: token.length,\n });\n return;\n }\n const prevInsideOwn = this.insideOwn;\n this.insideOwn = true;\n this.validateInnerStateExpression(value, 5, token);\n this.insideOwn = prevInsideOwn;\n return;\n }\n\n // @(...) container query\n if (value.startsWith('@(')) {\n this.validateContainerQuery(value, token);\n return;\n }\n\n // @alias predefined state\n if (value.startsWith('@') && /^@[A-Za-z][A-Za-z0-9-]*$/.test(value)) {\n this.referencedAliases.push(value);\n return;\n }\n\n // Pseudo-class/pseudo-element\n if (value.startsWith(':')) {\n this.validatePseudoClass(value, token);\n return;\n }\n\n // Class selector\n if (value.startsWith('.')) return;\n\n // Attribute selector\n if (value.startsWith('[')) {\n this.validateAttributeSelector(value, token);\n return;\n }\n\n // Value modifier (e.g., theme=danger)\n if (value.includes('=')) {\n this.validateValueModifier(value, token);\n return;\n }\n\n // Boolean modifier (e.g., hovered, disabled)\n if (/^[a-z][a-z0-9-]+$/i.test(value)) return;\n\n this.errors.push({\n message: `Unrecognized state token '${value}'.`,\n offset: token.offset,\n length: token.length,\n });\n }\n\n private validateMediaQuery(raw: string, token: Token): void {\n const content = raw.slice(7, -1);\n if (!content.trim()) {\n this.errors.push({\n message: 'Empty @media() query.',\n offset: token.offset,\n length: token.length,\n });\n return;\n }\n\n // Expand dimension shorthands for validation\n const expanded = expandDimensionShorthands(content.trim());\n\n // Feature query (contains ':' but no comparison operators)\n if (\n expanded.includes(':') &&\n !expanded.includes('<') &&\n !expanded.includes('>') &&\n !expanded.includes('=')\n ) {\n return;\n }\n\n // Boolean feature query (no comparison operators)\n if (\n !expanded.includes('<') &&\n !expanded.includes('>') &&\n !expanded.includes('=')\n ) {\n return;\n }\n\n // Dimension query — validate dimension names\n this.validateDimensionCondition(expanded, token);\n }\n\n private validateDimensionCondition(condition: string, token: Token): void {\n // Range syntax: 600px <= width < 1200px\n const rangeMatch = condition.match(\n /^(.+?)\\s*(<=|<)\\s*(\\S+)\\s*(<=|<)\\s*(.+)$/,\n );\n if (rangeMatch) {\n const dim = rangeMatch[3];\n if (!DIMENSION_FULL.has(dim) && !DIMENSION_SHORTHANDS.has(dim)) {\n this.errors.push({\n message: `Unknown dimension '${dim}' in media/container query. Valid: width, height, inline-size, block-size (or w, h, is, bs).`,\n offset: token.offset,\n length: token.length,\n });\n }\n return;\n }\n\n // Simple comparison: width < 768px\n const simpleMatch = condition.match(/^(\\S+)\\s*(<=|>=|<|>|=)\\s*(.+)$/);\n if (simpleMatch) {\n const dim = simpleMatch[1];\n if (DIMENSION_FULL.has(dim) || DIMENSION_SHORTHANDS.has(dim)) {\n return;\n }\n }\n\n // Reversed: 768px > width\n const reversedMatch = condition.match(/^(.+?)\\s*(<=|>=|<|>|=)\\s*(\\S+)$/);\n if (reversedMatch) {\n const dim = reversedMatch[3];\n if (DIMENSION_FULL.has(dim) || DIMENSION_SHORTHANDS.has(dim)) {\n return;\n }\n }\n }\n\n private validateSupportsQuery(raw: string, token: Token): void {\n const content = raw.slice(10, -1);\n if (!content.trim()) {\n this.errors.push({\n message: 'Empty @supports() query.',\n offset: token.offset,\n length: token.length,\n });\n }\n }\n\n private validateInnerStateExpression(\n raw: string,\n prefixLen: number,\n _token: Token,\n ): void {\n const content = raw.slice(prefixLen, -1);\n if (!content.trim()) return;\n\n const innerResult = parseStateKey(content, this.opts);\n this.errors.push(...innerResult.errors);\n if (innerResult.hasOwn) this.hasOwn = true;\n this.referencedAliases.push(...innerResult.referencedAliases);\n }\n\n private validateParentState(raw: string, token: Token): void {\n const content = raw.slice(8, -1);\n if (!content.trim()) {\n this.errors.push({\n message: 'Empty @parent() state.',\n offset: token.offset,\n length: token.length,\n });\n return;\n }\n\n let condition = content.trim();\n\n // Check for direct parent combinator: @parent(hovered, >)\n const lastCommaIdx = condition.lastIndexOf(',');\n if (lastCommaIdx !== -1) {\n const afterComma = condition.slice(lastCommaIdx + 1).trim();\n if (afterComma === '>') {\n condition = condition.slice(0, lastCommaIdx).trim();\n }\n }\n\n const innerResult = parseStateKey(condition, this.opts);\n this.errors.push(...innerResult.errors);\n this.referencedAliases.push(...innerResult.referencedAliases);\n }\n\n private validateContainerQuery(raw: string, token: Token): void {\n const content = raw.slice(2, -1);\n if (!content.trim()) {\n this.errors.push({\n message: 'Empty container query.',\n offset: token.offset,\n length: token.length,\n });\n return;\n }\n\n // Named container: @(layout, w < 600px)\n const commaIdx = findTopLevelComma(content);\n let condition: string;\n\n if (commaIdx !== -1) {\n condition = content.slice(commaIdx + 1).trim();\n } else {\n condition = content.trim();\n }\n\n // Style query: @($variant=primary) — skip\n if (condition.startsWith('$')) return;\n\n // Function-like: scroll-state(...) — skip\n if (/^[a-zA-Z][\\w-]*\\s*\\(/.test(condition)) return;\n\n // Dimension query\n const expanded = expandDimensionShorthands(condition);\n if (\n expanded.includes('<') ||\n expanded.includes('>') ||\n expanded.includes('=')\n ) {\n this.validateDimensionCondition(expanded, token);\n }\n }\n\n private validatePseudoClass(value: string, token: Token): void {\n // :is(), :has(), :not(), :where() — structural pseudo-classes\n const enhancedMatch = /^:(is|has|not|where)\\(/.exec(value);\n if (enhancedMatch) return;\n\n // Functional pseudo-classes like :nth-child(2n+1)\n const funcMatch = /^(:[a-z-]+)\\(/.exec(value);\n if (funcMatch) {\n const baseName = funcMatch[1];\n if (!KNOWN_PSEUDO_CLASSES.has(baseName)) {\n this.errors.push({\n message: `Unknown pseudo-class '${baseName}'.`,\n offset: token.offset,\n length: token.length,\n });\n }\n return;\n }\n\n // Simple pseudo-class: :hover, :focus, etc.\n if (!KNOWN_PSEUDO_CLASSES.has(value)) {\n this.errors.push({\n message: `Unknown pseudo-class '${value}'.`,\n offset: token.offset,\n length: token.length,\n });\n }\n }\n\n private validateAttributeSelector(value: string, token: Token): void {\n if (!value.startsWith('[') || !value.endsWith(']')) {\n this.errors.push({\n message: `Malformed attribute selector '${value}'.`,\n offset: token.offset,\n length: token.length,\n });\n }\n }\n\n private validateValueModifier(value: string, token: Token): void {\n const opMatch = value.match(/^([a-z][a-z0-9-]*)(\\^=|\\$=|\\*=|=)(.+)$/i);\n if (!opMatch) {\n this.errors.push({\n message: `Invalid value modifier syntax '${value}'.`,\n offset: token.offset,\n length: token.length,\n });\n }\n }\n}\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\nfunction expandDimensionShorthands(condition: string): string {\n return condition\n .replace(/\\bw\\b/g, 'width')\n .replace(/\\bh\\b/g, 'height')\n .replace(/\\bis\\b/g, 'inline-size')\n .replace(/\\bbs\\b/g, 'block-size');\n}\n\nfunction findTopLevelComma(str: string): number {\n let depth = 0;\n for (let i = 0; i < str.length; i++) {\n const ch = str[i];\n if (ch === '(') depth++;\n else if (ch === ')') depth = Math.max(0, depth - 1);\n else if (ch === ',' && depth === 0) return i;\n }\n return -1;\n}\n\n// ============================================================================\n// Public API\n// ============================================================================\n\n/**\n * Rewrite :not() state atoms, leaving raw CSS inside other functions alone.\n * A selector list/compound must stay inside :is(): negating individual parts\n * would change which elements match. Only a single pseudo can be unwrapped.\n */\nexport function getStateNegationEdits(stateKey: string): StringEdit[] {\n if (!stateKey.includes(':not(')) return [];\n if (checkBracketBalance(stateKey)) return [];\n if (parseStateKey(stateKey).errors.length > 0) return [];\n\n const { tokens } = tokenize(stateKey);\n return tokens\n .filter(\n (token) => token.type === 'STATE' && token.value.startsWith(':not('),\n )\n .flatMap((token) => {\n if (checkBracketBalance(token.value)) return [];\n const inner = token.value.slice(5, -1).trim();\n if (!inner) return [];\n\n const { tokens: innerTokens, errors } = tokenize(inner);\n const singlePseudo =\n errors.length === 0 &&\n innerTokens.length === 1 &&\n innerTokens[0].type === 'STATE' &&\n innerTokens[0].value === inner &&\n inner.startsWith(':') &&\n parseStateKey(inner).errors.length === 0 &&\n !inner.startsWith(':not(') &&\n // Keep forgiving selector-list wrappers, even for invalid branches.\n !inner.startsWith(':is(') &&\n !inner.startsWith(':where(') &&\n // Promoting :has() to a state atom enables Tasty's trailing-combinator\n // completion. Preserve the original raw CSS instead in that case.\n !(inner.startsWith(':has(') && /[>+~]\\s*\\)$/.test(inner));\n\n return [\n {\n start: token.offset,\n end: token.offset + token.length,\n replacement: singlePseudo ? `!${inner}` : `!:is(${inner})`,\n },\n ];\n });\n}\n\n/**\n * Unwrap every `@own(...)` term of a key, for a scope where `@own` is the\n * element itself. A term with operators inside keeps them grouped, so\n * `@own(a | b) & c` becomes `(a | b) & c`, not `a | b & c`. Returns no edits\n * when any term cannot be unwrapped safely, so a key is never half-rewritten.\n */\nexport function getOwnUnwrapEdits(stateKey: string): StringEdit[] {\n if (!stateKey.includes('@own(')) return [];\n if (checkBracketBalance(stateKey)) return [];\n if (parseStateKey(stateKey).errors.length > 0) return [];\n\n const { tokens } = tokenize(stateKey);\n const edits: StringEdit[] = [];\n for (const token of tokens) {\n if (token.type !== 'STATE' || !token.value.startsWith('@own(')) continue;\n const inner = token.value.slice(5, -1).trim();\n // A comma is an OR only outside parentheses; it would not survive grouping.\n if (!inner || findTopLevelComma(inner) !== -1) return [];\n\n const innerTokens = tokenize(inner).tokens;\n const single =\n tokens.length === 1 ||\n (innerTokens.length === 1 && innerTokens[0].value === inner);\n edits.push({\n start: token.offset,\n end: token.offset + token.length,\n replacement: single ? inner : `(${inner})`,\n });\n }\n return edits;\n}\n\nexport interface StateAtom {\n /** The atom as written: `hovered`, `:hover`, `[open]`, `@root(...)`. */\n value: string;\n /** Whether the atom sits inside `@own(...)`. */\n own: boolean;\n}\n\n/**\n * The state atoms of a key, without its operators and grouping. The contents\n * of `@own(...)` are listed atom by atom; `@root()`, `@parent()`, and at-rule\n * conditions stay single atoms, since they describe other things.\n */\nexport function getStateAtoms(stateKey: string): StateAtom[] {\n const atoms: StateAtom[] = [];\n for (const token of tokenize(stateKey.trim()).tokens) {\n if (token.type !== 'STATE') continue;\n if (!token.value.startsWith('@own(')) {\n atoms.push({ value: token.value, own: false });\n continue;\n }\n for (const inner of tokenize(token.value.slice(5, -1)).tokens) {\n if (inner.type === 'STATE') atoms.push({ value: inner.value, own: true });\n }\n }\n return atoms;\n}\n\n/**\n * Validate a state key string and return detailed errors.\n */\nexport function parseStateKey(\n stateKey: string,\n opts: StateKeyParserOptions = {},\n): StateKeyResult {\n if (!stateKey || !stateKey.trim()) {\n return { errors: [], hasOwn: false, referencedAliases: [] };\n }\n\n const trimmed = stateKey.trim();\n\n // The standalone `_` key is the map-wide fallback floor. It always applies\n // and must be used on its own — it carries no state logic to validate.\n if (trimmed === '_') {\n return { errors: [], hasOwn: false, referencedAliases: [] };\n }\n\n // A `_` combined with state logic (`_ & hovered`, `_ | x`) is a misuse: the\n // fallback floor can only be used on its own. Tasty ignores such keys at\n // runtime and warns; flag them here so the mistake surfaces in the editor.\n if (isMisusedFallbackKey(trimmed)) {\n return {\n errors: [\n {\n message:\n 'The fallback floor \"_\" cannot be combined with other state ' +\n 'logic. Use \"_\" on its own as a map-wide fallback floor.',\n offset: 0,\n length: stateKey.length,\n },\n ],\n hasOwn: false,\n referencedAliases: [],\n };\n }\n\n const { tokens, errors: tokenErrors } = tokenize(trimmed);\n const validator = new StateKeyValidator(tokens, tokenErrors, opts);\n return validator.validate();\n}\n\n/**\n * Detect a misused standalone `_` fallback key: a key that is not exactly\n * `_` but contains `_` as a standalone atom among state-logic operators\n * (`&`, `|`, `^`, `,`) or grouping parens. A `_` embedded in a longer token\n * (e.g. a modifier named `_private`) is not a misuse.\n */\nfunction isMisusedFallbackKey(stateKey: string): boolean {\n if (stateKey === '_' || !stateKey.includes('_')) return false;\n return /(?:^|[\\s&|^,(])_(?:[\\s&|^,)]|$)/.test(stateKey);\n}\n\n/**\n * Validate a state definition value (the RHS of a state alias).\n * State definitions should be valid state expressions like\n * '@media(w < 768px)', '@root(theme=dark)', etc.\n */\nexport function validateStateDefinition(\n value: string,\n opts: StateKeyParserOptions = {},\n): StateKeyResult {\n return parseStateKey(value, opts);\n}\n"],"mappings":";;;;;;;;;;AA2CA,MAAM,sBACJ;AAEF,SAAS,SAAS,UAGhB;CACA,MAAM,SAAkB,EAAE;CAC1B,MAAM,SAA0B,EAAE;CAGlC,MAAM,aAAa,2BAA2B,SAAS;CAEvD,MAAM,0BAAU,IAAI,KAAa;AAEjC,qBAAoB,YAAY;CAChC,IAAI;AACJ,SAAQ,QAAQ,oBAAoB,KAAK,WAAW,MAAM,MAAM;EAC9D,MAAM,YAAY,MAAM;EACxB,MAAM,SAAS,MAAM;AAErB,OAAK,IAAI,IAAI,QAAQ,IAAI,SAAS,UAAU,QAAQ,IAClD,SAAQ,IAAI,EAAE;AAGhB,MAAI,MAAM,GACR,SAAQ,WAAR;GACE,KAAK;AACH,WAAO,KAAK;KAAE,MAAM;KAAO,OAAO;KAAK;KAAQ,QAAQ;KAAG,CAAC;AAC3D;GACF,KAAK;AACH,WAAO,KAAK;KAAE,MAAM;KAAM,OAAO;KAAK;KAAQ,QAAQ;KAAG,CAAC;AAC1D;GACF,KAAK;AACH,WAAO,KAAK;KAAE,MAAM;KAAO,OAAO;KAAK;KAAQ,QAAQ;KAAG,CAAC;AAC3D;GACF,KAAK;AACH,WAAO,KAAK;KAAE,MAAM;KAAO,OAAO;KAAK;KAAQ,QAAQ;KAAG,CAAC;AAC3D;;WAEK,MAAM,GACf,KAAI,cAAc,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AO,MAAM;GAAO,KAAK;GAAM,CAAC;;AAG7E,QAAO;;;;;AAMT,SAAgB,cACd,UACA,OAA8B,EAAE,EAChB;AAChB,KAAI,CAAC,YAAY,CAAC,SAAS,MAAM,CAC/B,QAAO;EAAE,QAAQ,EAAE;EAAE,QAAQ;EAAO,mBAAmB,EAAE;EAAE;CAG7D,MAAM,UAAU,SAAS,MAAM;AAI/B,KAAI,YAAY,IACd,QAAO;EAAE,QAAQ,EAAE;EAAE,QAAQ;EAAO,mBAAmB,EAAE;EAAE;AAM7D,KAAI,qBAAqB,QAAQ,CAC/B,QAAO;EACL,QAAQ,CACN;GACE,SACE;GAEF,QAAQ;GACR,QAAQ,SAAS;GAClB,CACF;EACD,QAAQ;EACR,mBAAmB,EAAE;EACtB;CAGH,MAAM,EAAE,QAAQ,QAAQ,gBAAgB,SAAS,QAAQ;AAEzD,QADkB,IAAI,kBAAkB,QAAQ,aAAa,KAAK,CACjD,UAAU;;;;;;;;AAS7B,SAAS,qBAAqB,UAA2B;AACvD,KAAI,aAAa,OAAO,CAAC,SAAS,SAAS,IAAI,CAAE,QAAO;AACxD,QAAO,kCAAkC,KAAK,SAAS;;;;;;;AAQzD,SAAgB,wBACd,OACA,OAA8B,EAAE,EAChB;AAChB,QAAO,cAAc,OAAO,KAAK"}
|
package/dist/parsers/utils.js
CHANGED
|
@@ -3,6 +3,31 @@ function isWhitespace(ch) {
|
|
|
3
3
|
return ch === " " || ch === "\n" || ch === " " || ch === "\r" || ch === "\f";
|
|
4
4
|
}
|
|
5
5
|
/**
|
|
6
|
+
* Split on commas outside parentheses and quotes, so a comma inside a function
|
|
7
|
+
* (`steps(2, start)`, `cubic-bezier(0.5, 0, 0.3, 1)`) stays in its part. Like
|
|
8
|
+
* `split(',')`, the parts joined with `,` give back the input.
|
|
9
|
+
*/
|
|
10
|
+
function splitTopLevelCommas(src) {
|
|
11
|
+
const parts = [];
|
|
12
|
+
let depth = 0;
|
|
13
|
+
let inQuote = 0;
|
|
14
|
+
let start = 0;
|
|
15
|
+
for (let i = 0; i < src.length; i++) {
|
|
16
|
+
const ch = src[i];
|
|
17
|
+
if (inQuote) {
|
|
18
|
+
if (ch === inQuote) inQuote = 0;
|
|
19
|
+
} else if (ch === "\"" || ch === "'") inQuote = ch;
|
|
20
|
+
else if (ch === "(") depth++;
|
|
21
|
+
else if (ch === ")") depth = Math.max(0, depth - 1);
|
|
22
|
+
else if (ch === "," && depth === 0) {
|
|
23
|
+
parts.push(src.slice(start, i));
|
|
24
|
+
start = i + 1;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
parts.push(src.slice(start));
|
|
28
|
+
return parts;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
6
31
|
* Check that all brackets/parentheses are balanced in a source string.
|
|
7
32
|
* Returns null if balanced, or an error with position if not.
|
|
8
33
|
*/
|
|
@@ -124,5 +149,5 @@ function scanTokens(src) {
|
|
|
124
149
|
}
|
|
125
150
|
|
|
126
151
|
//#endregion
|
|
127
|
-
export { checkBracketBalance, scanTokens };
|
|
152
|
+
export { checkBracketBalance, scanTokens, splitTopLevelCommas };
|
|
128
153
|
//# sourceMappingURL=utils.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","names":[],"sources":["../../src/parsers/utils.ts"],"sourcesContent":["export function isWhitespace(ch: string | undefined): boolean {\n return ch === ' ' || ch === '\\n' || ch === '\\t' || ch === '\\r' || ch === '\\f';\n}\n\nexport function isDigit(ch: string): boolean {\n return ch >= '0' && ch <= '9';\n}\n\nexport function isAlpha(ch: string): boolean {\n return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');\n}\n\nexport interface BracketError {\n position: number;\n message: string;\n}\n\n/**\n * Check that all brackets/parentheses are balanced in a source string.\n * Returns null if balanced, or an error with position if not.\n */\nexport function checkBracketBalance(src: string): BracketError | null {\n let depth = 0;\n let inQuote: string | 0 = 0;\n\n for (let i = 0; i < src.length; i++) {\n const ch = src[i];\n\n if (inQuote) {\n if (ch === inQuote && src[i - 1] !== '\\\\') inQuote = 0;\n continue;\n }\n if (ch === '\"' || ch === \"'\") {\n inQuote = ch;\n continue;\n }\n\n if (ch === '(') depth++;\n if (ch === ')') {\n depth--;\n if (depth < 0) {\n return { position: i, message: 'Unexpected closing parenthesis' };\n }\n }\n }\n\n if (depth !== 0) {\n return {\n position: src.length - 1,\n message: 'Unbalanced parentheses: missing closing parenthesis',\n };\n }\n\n return null;\n}\n\nexport interface ScannedToken {\n value: string;\n isComma: boolean;\n isSlash: boolean;\n offset: number;\n}\n\n/**\n * Tokenize a style value string following tasty's scan() semantics:\n * - Whitespace splits tokens\n * - Commas separate groups\n * - Spaced slashes (`a / b`) separate parts\n * - Non-spaced slashes (`center/cover`) stay inside the token\n * - Parenthesized content stays as a single token\n * - Quoted strings stay as a single token\n * - `url(...)` content is never split\n */\nexport function scanTokens(src: string): ScannedToken[] {\n const result: ScannedToken[] = [];\n let depth = 0;\n let inUrl = false;\n let inQuote: string | 0 = 0;\n let start = 0;\n let i = 0;\n let pendingSlash = false;\n\n const flush = (isComma: boolean, isSlash: boolean) => {\n const actualSlash = isSlash || pendingSlash;\n pendingSlash = false;\n\n if (start < i) {\n result.push({\n value: src.slice(start, i),\n isComma,\n isSlash: actualSlash,\n offset: start,\n });\n } else if (isComma) {\n result.push({ value: '', isComma: true, isSlash: false, offset: i });\n } else if (actualSlash) {\n result.push({ value: '', isComma: false, isSlash: true, offset: i });\n }\n start = i + 1;\n };\n\n for (; i < src.length; i++) {\n const ch = src[i];\n\n if (inQuote) {\n if (ch === inQuote && src[i - 1] !== '\\\\') inQuote = 0;\n continue;\n }\n if (ch === '\"' || ch === \"'\") {\n inQuote = ch;\n continue;\n }\n\n if (ch === '(') {\n if (!depth) {\n const maybe = src.slice(Math.max(0, i - 3), i + 1);\n if (maybe === 'url(') inUrl = true;\n }\n depth++;\n continue;\n }\n if (ch === ')') {\n depth = Math.max(0, depth - 1);\n if (inUrl && depth === 0) inUrl = false;\n continue;\n }\n\n if (inUrl) continue;\n\n if (!depth) {\n if (ch === ',') {\n flush(true, false);\n continue;\n }\n if (ch === '/') {\n const prevIsWs = isWhitespace(src[i - 1]);\n const nextIsWs = isWhitespace(src[i + 1]);\n if (prevIsWs && nextIsWs) {\n pendingSlash = true;\n start = i + 1;\n continue;\n }\n continue;\n }\n if (isWhitespace(ch)) {\n flush(false, false);\n continue;\n }\n }\n }\n flush(false, false);\n\n return result;\n}\n"],"mappings":";AAAA,SAAgB,aAAa,IAAiC;AAC5D,QAAO,OAAO,OAAO,OAAO,QAAQ,OAAO,OAAQ,OAAO,QAAQ,OAAO;;;;;;
|
|
1
|
+
{"version":3,"file":"utils.js","names":[],"sources":["../../src/parsers/utils.ts"],"sourcesContent":["export function isWhitespace(ch: string | undefined): boolean {\n return ch === ' ' || ch === '\\n' || ch === '\\t' || ch === '\\r' || ch === '\\f';\n}\n\nexport function isDigit(ch: string): boolean {\n return ch >= '0' && ch <= '9';\n}\n\nexport function isAlpha(ch: string): boolean {\n return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');\n}\n\n/**\n * Split on commas outside parentheses and quotes, so a comma inside a function\n * (`steps(2, start)`, `cubic-bezier(0.5, 0, 0.3, 1)`) stays in its part. Like\n * `split(',')`, the parts joined with `,` give back the input.\n */\nexport function splitTopLevelCommas(src: string): string[] {\n const parts: string[] = [];\n let depth = 0;\n let inQuote: string | 0 = 0;\n let start = 0;\n for (let i = 0; i < src.length; i++) {\n const ch = src[i];\n if (inQuote) {\n if (ch === inQuote) inQuote = 0;\n } else if (ch === '\"' || ch === \"'\") inQuote = ch;\n else if (ch === '(') depth++;\n else if (ch === ')') depth = Math.max(0, depth - 1);\n else if (ch === ',' && depth === 0) {\n parts.push(src.slice(start, i));\n start = i + 1;\n }\n }\n parts.push(src.slice(start));\n return parts;\n}\n\nexport interface BracketError {\n position: number;\n message: string;\n}\n\n/**\n * Check that all brackets/parentheses are balanced in a source string.\n * Returns null if balanced, or an error with position if not.\n */\nexport function checkBracketBalance(src: string): BracketError | null {\n let depth = 0;\n let inQuote: string | 0 = 0;\n\n for (let i = 0; i < src.length; i++) {\n const ch = src[i];\n\n if (inQuote) {\n if (ch === inQuote && src[i - 1] !== '\\\\') inQuote = 0;\n continue;\n }\n if (ch === '\"' || ch === \"'\") {\n inQuote = ch;\n continue;\n }\n\n if (ch === '(') depth++;\n if (ch === ')') {\n depth--;\n if (depth < 0) {\n return { position: i, message: 'Unexpected closing parenthesis' };\n }\n }\n }\n\n if (depth !== 0) {\n return {\n position: src.length - 1,\n message: 'Unbalanced parentheses: missing closing parenthesis',\n };\n }\n\n return null;\n}\n\nexport interface ScannedToken {\n value: string;\n isComma: boolean;\n isSlash: boolean;\n offset: number;\n}\n\n/**\n * Tokenize a style value string following tasty's scan() semantics:\n * - Whitespace splits tokens\n * - Commas separate groups\n * - Spaced slashes (`a / b`) separate parts\n * - Non-spaced slashes (`center/cover`) stay inside the token\n * - Parenthesized content stays as a single token\n * - Quoted strings stay as a single token\n * - `url(...)` content is never split\n */\nexport function scanTokens(src: string): ScannedToken[] {\n const result: ScannedToken[] = [];\n let depth = 0;\n let inUrl = false;\n let inQuote: string | 0 = 0;\n let start = 0;\n let i = 0;\n let pendingSlash = false;\n\n const flush = (isComma: boolean, isSlash: boolean) => {\n const actualSlash = isSlash || pendingSlash;\n pendingSlash = false;\n\n if (start < i) {\n result.push({\n value: src.slice(start, i),\n isComma,\n isSlash: actualSlash,\n offset: start,\n });\n } else if (isComma) {\n result.push({ value: '', isComma: true, isSlash: false, offset: i });\n } else if (actualSlash) {\n result.push({ value: '', isComma: false, isSlash: true, offset: i });\n }\n start = i + 1;\n };\n\n for (; i < src.length; i++) {\n const ch = src[i];\n\n if (inQuote) {\n if (ch === inQuote && src[i - 1] !== '\\\\') inQuote = 0;\n continue;\n }\n if (ch === '\"' || ch === \"'\") {\n inQuote = ch;\n continue;\n }\n\n if (ch === '(') {\n if (!depth) {\n const maybe = src.slice(Math.max(0, i - 3), i + 1);\n if (maybe === 'url(') inUrl = true;\n }\n depth++;\n continue;\n }\n if (ch === ')') {\n depth = Math.max(0, depth - 1);\n if (inUrl && depth === 0) inUrl = false;\n continue;\n }\n\n if (inUrl) continue;\n\n if (!depth) {\n if (ch === ',') {\n flush(true, false);\n continue;\n }\n if (ch === '/') {\n const prevIsWs = isWhitespace(src[i - 1]);\n const nextIsWs = isWhitespace(src[i + 1]);\n if (prevIsWs && nextIsWs) {\n pendingSlash = true;\n start = i + 1;\n continue;\n }\n continue;\n }\n if (isWhitespace(ch)) {\n flush(false, false);\n continue;\n }\n }\n }\n flush(false, false);\n\n return result;\n}\n"],"mappings":";AAAA,SAAgB,aAAa,IAAiC;AAC5D,QAAO,OAAO,OAAO,OAAO,QAAQ,OAAO,OAAQ,OAAO,QAAQ,OAAO;;;;;;;AAgB3E,SAAgB,oBAAoB,KAAuB;CACzD,MAAM,QAAkB,EAAE;CAC1B,IAAI,QAAQ;CACZ,IAAI,UAAsB;CAC1B,IAAI,QAAQ;AACZ,MAAK,IAAI,IAAI,GAAG,IAAI,IAAI,QAAQ,KAAK;EACnC,MAAM,KAAK,IAAI;AACf,MAAI,SACF;OAAI,OAAO,QAAS,WAAU;aACrB,OAAO,QAAO,OAAO,IAAK,WAAU;WACtC,OAAO,IAAK;WACZ,OAAO,IAAK,SAAQ,KAAK,IAAI,GAAG,QAAQ,EAAE;WAC1C,OAAO,OAAO,UAAU,GAAG;AAClC,SAAM,KAAK,IAAI,MAAM,OAAO,EAAE,CAAC;AAC/B,WAAQ,IAAI;;;AAGhB,OAAM,KAAK,IAAI,MAAM,MAAM,CAAC;AAC5B,QAAO;;;;;;AAYT,SAAgB,oBAAoB,KAAkC;CACpE,IAAI,QAAQ;CACZ,IAAI,UAAsB;AAE1B,MAAK,IAAI,IAAI,GAAG,IAAI,IAAI,QAAQ,KAAK;EACnC,MAAM,KAAK,IAAI;AAEf,MAAI,SAAS;AACX,OAAI,OAAO,WAAW,IAAI,IAAI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AAQ,EAAE;AAC9B,OAAI,SAAS,UAAU,EAAG,SAAQ;AAClC;;AAGF,MAAI,MAAO;AAEX,MAAI,CAAC,OAAO;AACV,OAAI,OAAO,KAAK;AACd,UAAM,MAAM,MAAM;AAClB;;AAEF,OAAI,OAAO,KAAK;IACd,MAAM,WAAW,aAAa,IAAI,IAAI,GAAG;IACzC,MAAM,WAAW,aAAa,IAAI,IAAI,GAAG;AACzC,QAAI,YAAY,UAAU;AACxB,oBAAe;AACf,aAAQ,IAAI;AACZ;;AAEF;;AAEF,OAAI,aAAa,GAAG,EAAE;AACpB,UAAM,OAAO,MAAM;AACnB;;;;AAIN,OAAM,OAAO,MAAM;AAEnB,QAAO"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { createRule } from "../create-rule.js";
|
|
2
2
|
import { getKeyName, getStringValue } from "../utils.js";
|
|
3
3
|
import { TastyContext, styleObjectListeners } from "../context.js";
|
|
4
|
-
import { parseStateKey } from "../parsers/state-key-parser.js";
|
|
5
|
-
import {
|
|
4
|
+
import { getOwnUnwrapEdits, parseStateKey } from "../parsers/state-key-parser.js";
|
|
5
|
+
import { replaceInStringValue } from "../fix-utils.js";
|
|
6
6
|
|
|
7
7
|
//#region src/rules/no-own-at-root.ts
|
|
8
8
|
var no_own_at_root_default = createRule({
|
|
@@ -20,6 +20,7 @@ var no_own_at_root_default = createRule({
|
|
|
20
20
|
function handleStyleObject(node) {
|
|
21
21
|
if (!ctx.isStyleObject(node)) return;
|
|
22
22
|
if (ctx.isInsideSubElement(node)) return;
|
|
23
|
+
if (ctx.isSharedStyleObject(node)) return;
|
|
23
24
|
for (const prop of node.properties) {
|
|
24
25
|
if (prop.type !== "Property" || prop.computed) continue;
|
|
25
26
|
const key = getKeyName(prop.key);
|
|
@@ -34,10 +35,9 @@ var no_own_at_root_default = createRule({
|
|
|
34
35
|
node: stateProp.key,
|
|
35
36
|
messageId: "ownAtRoot",
|
|
36
37
|
fix(fixer) {
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
return replaceStringValue(fixer, stateProp.key, inner);
|
|
38
|
+
const edits = getOwnUnwrapEdits(stateKey);
|
|
39
|
+
if (edits.length === 0) return null;
|
|
40
|
+
return replaceInStringValue(fixer, stateProp.key, edits, context.sourceCode);
|
|
41
41
|
}
|
|
42
42
|
});
|
|
43
43
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"no-own-at-root.js","names":[],"sources":["../../src/rules/no-own-at-root.ts"],"sourcesContent":["import type { TSESTree } from '@typescript-eslint/utils';\nimport { createRule } from '../create-rule.js';\nimport { TastyContext, styleObjectListeners } from '../context.js';\nimport { getKeyName, getStringValue } from '../utils.js';\nimport {
|
|
1
|
+
{"version":3,"file":"no-own-at-root.js","names":[],"sources":["../../src/rules/no-own-at-root.ts"],"sourcesContent":["import type { TSESTree } from '@typescript-eslint/utils';\nimport { createRule } from '../create-rule.js';\nimport { TastyContext, styleObjectListeners } from '../context.js';\nimport { getKeyName, getStringValue } from '../utils.js';\nimport {\n getOwnUnwrapEdits,\n parseStateKey,\n} from '../parsers/state-key-parser.js';\nimport { replaceInStringValue } from '../fix-utils.js';\n\ntype MessageIds = 'ownAtRoot';\n\nexport default createRule<[], MessageIds>({\n name: 'no-own-at-root',\n meta: {\n type: 'suggestion',\n fixable: 'code',\n docs: {\n description:\n 'Warn when @own() is used outside sub-element styles where it is redundant',\n },\n messages: {\n ownAtRoot:\n '@own() is redundant outside sub-element styles. Use the inner selector directly instead (e.g. :hover instead of @own(:hover)).',\n },\n schema: [],\n },\n defaultOptions: [],\n create(context) {\n const ctx = new TastyContext(context);\n\n function handleStyleObject(node: TSESTree.ObjectExpression) {\n if (!ctx.isStyleObject(node)) return;\n\n if (ctx.isInsideSubElement(node)) return;\n // Shared styles may be spread into a sub-element, where `@own` matters.\n if (ctx.isSharedStyleObject(node)) return;\n\n for (const prop of node.properties) {\n if (prop.type !== 'Property' || prop.computed) continue;\n\n const key = getKeyName(prop.key);\n if (key === null) continue;\n\n if (/^[A-Z]/.test(key) || key.startsWith('@') || key.startsWith('&'))\n continue;\n\n if (prop.value.type !== 'ObjectExpression') continue;\n\n for (const stateProp of prop.value.properties) {\n if (stateProp.type !== 'Property') continue;\n\n const stateKey = !stateProp.computed\n ? getKeyName(stateProp.key)\n : getStringValue(stateProp.key);\n if (stateKey === null || stateKey === '' || stateKey === '_')\n continue;\n\n const result = parseStateKey(stateKey);\n\n if (result.hasOwn) {\n context.report({\n node: stateProp.key,\n messageId: 'ownAtRoot',\n fix(fixer) {\n const edits = getOwnUnwrapEdits(stateKey);\n if (edits.length === 0) return null;\n return replaceInStringValue(\n fixer,\n stateProp.key,\n edits,\n context.sourceCode,\n );\n },\n });\n }\n }\n }\n }\n\n return {\n ImportDeclaration(node) {\n ctx.trackImport(node);\n },\n\n ...styleObjectListeners(handleStyleObject),\n };\n },\n});\n"],"mappings":";;;;;;;AAYA,6BAAe,WAA2B;CACxC,MAAM;CACN,MAAM;EACJ,MAAM;EACN,SAAS;EACT,MAAM,EACJ,aACE,6EACH;EACD,UAAU,EACR,WACE,kIACH;EACD,QAAQ,EAAE;EACX;CACD,gBAAgB,EAAE;CAClB,OAAO,SAAS;EACd,MAAM,MAAM,IAAI,aAAa,QAAQ;EAErC,SAAS,kBAAkB,MAAiC;AAC1D,OAAI,CAAC,IAAI,cAAc,KAAK,CAAE;AAE9B,OAAI,IAAI,mBAAmB,KAAK,CAAE;AAElC,OAAI,IAAI,oBAAoB,KAAK,CAAE;AAEnC,QAAK,MAAM,QAAQ,KAAK,YAAY;AAClC,QAAI,KAAK,SAAS,cAAc,KAAK,SAAU;IAE/C,MAAM,MAAM,WAAW,KAAK,IAAI;AAChC,QAAI,QAAQ,KAAM;AAElB,QAAI,SAAS,KAAK,IAAI,IAAI,IAAI,WAAW,IAAI,IAAI,IAAI,WAAW,IAAI,CAClE;AAEF,QAAI,KAAK,MAAM,SAAS,mBAAoB;AAE5C,SAAK,MAAM,aAAa,KAAK,MAAM,YAAY;AAC7C,SAAI,UAAU,SAAS,WAAY;KAEnC,MAAM,WAAW,CAAC,UAAU,WACxB,WAAW,UAAU,IAAI,GACzB,eAAe,UAAU,IAAI;AACjC,SAAI,aAAa,QAAQ,aAAa,MAAM,aAAa,IACvD;AAIF,SAFe,cAAc,SAAS,CAE3B,OACT,SAAQ,OAAO;MACb,MAAM,UAAU;MAChB,WAAW;MACX,IAAI,OAAO;OACT,MAAM,QAAQ,kBAAkB,SAAS;AACzC,WAAI,MAAM,WAAW,EAAG,QAAO;AAC/B,cAAO,qBACL,OACA,UAAU,KACV,OACA,QAAQ,WACT;;MAEJ,CAAC;;;;AAMV,SAAO;GACL,kBAAkB,MAAM;AACtB,QAAI,YAAY,KAAK;;GAGvB,GAAG,qBAAqB,kBAAkB;GAC3C;;CAEJ,CAAC"}
|
|
@@ -24,6 +24,7 @@ var require_default_state_default = createRule({
|
|
|
24
24
|
if (key === null) continue;
|
|
25
25
|
if (/^[A-Z@&$#]/.test(key)) continue;
|
|
26
26
|
if (prop.value.type !== "ObjectExpression") continue;
|
|
27
|
+
if (prop.value.properties.some((p) => p.type === "SpreadElement")) continue;
|
|
27
28
|
if (!prop.value.properties.some((p) => {
|
|
28
29
|
if (p.type !== "Property" || p.computed) return false;
|
|
29
30
|
const stateKey = getKeyName(p.key);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"require-default-state.js","names":[],"sources":["../../src/rules/require-default-state.ts"],"sourcesContent":["import type { TSESTree } from '@typescript-eslint/utils';\nimport { createRule } from '../create-rule.js';\nimport { TastyContext, styleObjectListeners } from '../context.js';\nimport { getKeyName } from '../utils.js';\n\ntype MessageIds = 'missingDefaultState';\n\nexport default createRule<[], MessageIds>({\n name: 'require-default-state',\n meta: {\n type: 'suggestion',\n docs: {\n description:\n \"Warn when a state mapping object doesn't have a default ('') key\",\n },\n messages: {\n missingDefaultState:\n \"State mapping for '{{property}}' has no default ('') or fallback floor ('_') value.\",\n },\n schema: [],\n },\n defaultOptions: [],\n create(context) {\n const ctx = new TastyContext(context);\n\n function handleStyleObject(node: TSESTree.ObjectExpression) {\n const styleCtx = ctx.getStyleContext(node);\n if (!styleCtx) return;\n\n // Skip if extending (omitting '' is intentional)\n if (styleCtx.isExtending) return;\n\n for (const prop of node.properties) {\n if (prop.type !== 'Property' || prop.computed) continue;\n\n const key = getKeyName(prop.key);\n if (key === null) continue;\n\n // Skip sub-elements and special keys\n if (/^[A-Z@&$#]/.test(key)) continue;\n\n if (prop.value.type !== 'ObjectExpression') continue;\n\n // A '' default or a '_' fallback floor both provide a value in the\n // normal state, so either one satisfies the requirement.\n const hasDefault = prop.value.properties.some((p) => {\n if (p.type !== 'Property' || p.computed) return false;\n const stateKey = getKeyName(p.key);\n return stateKey === '' || stateKey === '_';\n });\n\n if (!hasDefault) {\n context.report({\n node: prop.value,\n messageId: 'missingDefaultState',\n data: { property: key },\n });\n }\n }\n }\n\n return {\n ImportDeclaration(node) {\n ctx.trackImport(node);\n },\n ...styleObjectListeners(handleStyleObject),\n };\n },\n});\n"],"mappings":";;;;;AAOA,oCAAe,WAA2B;CACxC,MAAM;CACN,MAAM;EACJ,MAAM;EACN,MAAM,EACJ,aACE,oEACH;EACD,UAAU,EACR,qBACE,uFACH;EACD,QAAQ,EAAE;EACX;CACD,gBAAgB,EAAE;CAClB,OAAO,SAAS;EACd,MAAM,MAAM,IAAI,aAAa,QAAQ;EAErC,SAAS,kBAAkB,MAAiC;GAC1D,MAAM,WAAW,IAAI,gBAAgB,KAAK;AAC1C,OAAI,CAAC,SAAU;AAGf,OAAI,SAAS,YAAa;AAE1B,QAAK,MAAM,QAAQ,KAAK,YAAY;AAClC,QAAI,KAAK,SAAS,cAAc,KAAK,SAAU;IAE/C,MAAM,MAAM,WAAW,KAAK,IAAI;AAChC,QAAI,QAAQ,KAAM;AAGlB,QAAI,aAAa,KAAK,IAAI,CAAE;AAE5B,QAAI,KAAK,MAAM,SAAS,mBAAoB;
|
|
1
|
+
{"version":3,"file":"require-default-state.js","names":[],"sources":["../../src/rules/require-default-state.ts"],"sourcesContent":["import type { TSESTree } from '@typescript-eslint/utils';\nimport { createRule } from '../create-rule.js';\nimport { TastyContext, styleObjectListeners } from '../context.js';\nimport { getKeyName } from '../utils.js';\n\ntype MessageIds = 'missingDefaultState';\n\nexport default createRule<[], MessageIds>({\n name: 'require-default-state',\n meta: {\n type: 'suggestion',\n docs: {\n description:\n \"Warn when a state mapping object doesn't have a default ('') key\",\n },\n messages: {\n missingDefaultState:\n \"State mapping for '{{property}}' has no default ('') or fallback floor ('_') value.\",\n },\n schema: [],\n },\n defaultOptions: [],\n create(context) {\n const ctx = new TastyContext(context);\n\n function handleStyleObject(node: TSESTree.ObjectExpression) {\n const styleCtx = ctx.getStyleContext(node);\n if (!styleCtx) return;\n\n // Skip if extending (omitting '' is intentional)\n if (styleCtx.isExtending) return;\n\n for (const prop of node.properties) {\n if (prop.type !== 'Property' || prop.computed) continue;\n\n const key = getKeyName(prop.key);\n if (key === null) continue;\n\n // Skip sub-elements and special keys\n if (/^[A-Z@&$#]/.test(key)) continue;\n\n if (prop.value.type !== 'ObjectExpression') continue;\n\n // A spread may bring the default with it (`...BASE_STYLES.fill`), and\n // its source is often a cast member expression that cannot be read.\n if (prop.value.properties.some((p) => p.type === 'SpreadElement'))\n continue;\n\n // A '' default or a '_' fallback floor both provide a value in the\n // normal state, so either one satisfies the requirement.\n const hasDefault = prop.value.properties.some((p) => {\n if (p.type !== 'Property' || p.computed) return false;\n const stateKey = getKeyName(p.key);\n return stateKey === '' || stateKey === '_';\n });\n\n if (!hasDefault) {\n context.report({\n node: prop.value,\n messageId: 'missingDefaultState',\n data: { property: key },\n });\n }\n }\n }\n\n return {\n ImportDeclaration(node) {\n ctx.trackImport(node);\n },\n ...styleObjectListeners(handleStyleObject),\n };\n },\n});\n"],"mappings":";;;;;AAOA,oCAAe,WAA2B;CACxC,MAAM;CACN,MAAM;EACJ,MAAM;EACN,MAAM,EACJ,aACE,oEACH;EACD,UAAU,EACR,qBACE,uFACH;EACD,QAAQ,EAAE;EACX;CACD,gBAAgB,EAAE;CAClB,OAAO,SAAS;EACd,MAAM,MAAM,IAAI,aAAa,QAAQ;EAErC,SAAS,kBAAkB,MAAiC;GAC1D,MAAM,WAAW,IAAI,gBAAgB,KAAK;AAC1C,OAAI,CAAC,SAAU;AAGf,OAAI,SAAS,YAAa;AAE1B,QAAK,MAAM,QAAQ,KAAK,YAAY;AAClC,QAAI,KAAK,SAAS,cAAc,KAAK,SAAU;IAE/C,MAAM,MAAM,WAAW,KAAK,IAAI;AAChC,QAAI,QAAQ,KAAM;AAGlB,QAAI,aAAa,KAAK,IAAI,CAAE;AAE5B,QAAI,KAAK,MAAM,SAAS,mBAAoB;AAI5C,QAAI,KAAK,MAAM,WAAW,MAAM,MAAM,EAAE,SAAS,gBAAgB,CAC/D;AAUF,QAAI,CANe,KAAK,MAAM,WAAW,MAAM,MAAM;AACnD,SAAI,EAAE,SAAS,cAAc,EAAE,SAAU,QAAO;KAChD,MAAM,WAAW,WAAW,EAAE,IAAI;AAClC,YAAO,aAAa,MAAM,aAAa;MACvC,CAGA,SAAQ,OAAO;KACb,MAAM,KAAK;KACX,WAAW;KACX,MAAM,EAAE,UAAU,KAAK;KACxB,CAAC;;;AAKR,SAAO;GACL,kBAAkB,MAAM;AACtB,QAAI,YAAY,KAAK;;GAEvB,GAAG,qBAAqB,kBAAkB;GAC3C;;CAEJ,CAAC"}
|
|
@@ -2,6 +2,7 @@ import { createRule } from "../create-rule.js";
|
|
|
2
2
|
import { KNOWN_CSS_PROPERTIES, SEMANTIC_TRANSITIONS, TRANSITION_SEMANTIC_MAPPING } from "../constants.js";
|
|
3
3
|
import { TastyContext } from "../context.js";
|
|
4
4
|
import { stringStyleValueListeners } from "../style-values.js";
|
|
5
|
+
import { splitTopLevelCommas } from "../parsers/utils.js";
|
|
5
6
|
import { replaceInStringValue } from "../fix-utils.js";
|
|
6
7
|
|
|
7
8
|
//#region src/rules/valid-transition.ts
|
|
@@ -44,7 +45,7 @@ var valid_transition_default = createRule({
|
|
|
44
45
|
create(context) {
|
|
45
46
|
const ctx = new TastyContext(context);
|
|
46
47
|
function checkTransitionValue(value, node) {
|
|
47
|
-
const groups = value
|
|
48
|
+
const groups = splitTopLevelCommas(value);
|
|
48
49
|
let offset = 0;
|
|
49
50
|
for (const group of groups) {
|
|
50
51
|
const parts = group.trim().split(/\s+/);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"valid-transition.js","names":[],"sources":["../../src/rules/valid-transition.ts"],"sourcesContent":["import type { TSESTree } from '@typescript-eslint/utils';\nimport { createRule } from '../create-rule.js';\nimport { TastyContext } from '../context.js';\nimport { stringStyleValueListeners } from '../style-values.js';\nimport {\n SEMANTIC_TRANSITIONS,\n KNOWN_CSS_PROPERTIES,\n TRANSITION_SEMANTIC_MAPPING,\n} from '../constants.js';\nimport { replaceInStringValue } from '../fix-utils.js';\n\ntype MessageIds =\n | 'unknownTransition'\n | 'preferSemanticTransition'\n | 'useSemantic'\n | 'camelCaseTransition'\n | 'useKebabCase';\n\n/**\n * `KNOWN_CSS_PROPERTIES` is keyed by camelCase style keys, but a `transition`\n * value names *CSS* properties, which are kebab-case (`text-decoration-color`).\n * Tasty emits an unmapped name verbatim into the CSS `transition`, so the\n * kebab form is the correct spelling — normalize before the lookup.\n */\nfunction kebabToCamel(name: string): string {\n return name.replace(/-([a-z])/g, (_, char: string) => char.toUpperCase());\n}\n\n/** `gridTemplateColumns` -> `grid-template-columns`. */\nfunction camelToKebab(name: string): string {\n return name.replace(/[A-Z]/g, (char) => `-${char.toLowerCase()}`);\n}\n\n/**\n * Tasty style names that `KNOWN_CSS_PROPERTIES` also lists, but that name no\n * property a browser implements. The `flow` style sets `flex-direction` /\n * `grid-auto-flow`, yet Tasty has no `flow` transition: it emits the name\n * verbatim (`transition: flow …`), which animates nothing.\n */\nconst NON_TRANSITION_STYLE_NAMES = new Set(['flow']);\n\nexport default createRule<[], MessageIds>({\n name: 'valid-transition',\n meta: {\n type: 'suggestion',\n hasSuggestions: true,\n docs: {\n description:\n 'Validate transition property values use valid semantic transition names',\n },\n messages: {\n unknownTransition:\n \"Unknown transition name '{{name}}'. Use a semantic name ({{known}}) or a CSS property name.\",\n preferSemanticTransition:\n \"Transition '{{native}}' has a Tasty semantic equivalent — use '{{semantic}}' instead.\",\n useSemantic: \"Use '{{semantic}}' instead of '{{native}}'\",\n camelCaseTransition:\n \"Transition '{{name}}' compiles to '{{lowered}}', which is not a CSS property. Use the CSS name '{{kebab}}'.\",\n useKebabCase: \"Use '{{kebab}}' instead of '{{name}}'\",\n },\n schema: [],\n },\n defaultOptions: [],\n create(context) {\n const ctx = new TastyContext(context);\n\n function checkTransitionValue(value: string, node: TSESTree.Node): void {\n const groups = value
|
|
1
|
+
{"version":3,"file":"valid-transition.js","names":[],"sources":["../../src/rules/valid-transition.ts"],"sourcesContent":["import type { TSESTree } from '@typescript-eslint/utils';\nimport { createRule } from '../create-rule.js';\nimport { TastyContext } from '../context.js';\nimport { stringStyleValueListeners } from '../style-values.js';\nimport {\n SEMANTIC_TRANSITIONS,\n KNOWN_CSS_PROPERTIES,\n TRANSITION_SEMANTIC_MAPPING,\n} from '../constants.js';\nimport { replaceInStringValue } from '../fix-utils.js';\nimport { splitTopLevelCommas } from '../parsers/utils.js';\n\ntype MessageIds =\n | 'unknownTransition'\n | 'preferSemanticTransition'\n | 'useSemantic'\n | 'camelCaseTransition'\n | 'useKebabCase';\n\n/**\n * `KNOWN_CSS_PROPERTIES` is keyed by camelCase style keys, but a `transition`\n * value names *CSS* properties, which are kebab-case (`text-decoration-color`).\n * Tasty emits an unmapped name verbatim into the CSS `transition`, so the\n * kebab form is the correct spelling — normalize before the lookup.\n */\nfunction kebabToCamel(name: string): string {\n return name.replace(/-([a-z])/g, (_, char: string) => char.toUpperCase());\n}\n\n/** `gridTemplateColumns` -> `grid-template-columns`. */\nfunction camelToKebab(name: string): string {\n return name.replace(/[A-Z]/g, (char) => `-${char.toLowerCase()}`);\n}\n\n/**\n * Tasty style names that `KNOWN_CSS_PROPERTIES` also lists, but that name no\n * property a browser implements. The `flow` style sets `flex-direction` /\n * `grid-auto-flow`, yet Tasty has no `flow` transition: it emits the name\n * verbatim (`transition: flow …`), which animates nothing.\n */\nconst NON_TRANSITION_STYLE_NAMES = new Set(['flow']);\n\nexport default createRule<[], MessageIds>({\n name: 'valid-transition',\n meta: {\n type: 'suggestion',\n hasSuggestions: true,\n docs: {\n description:\n 'Validate transition property values use valid semantic transition names',\n },\n messages: {\n unknownTransition:\n \"Unknown transition name '{{name}}'. Use a semantic name ({{known}}) or a CSS property name.\",\n preferSemanticTransition:\n \"Transition '{{native}}' has a Tasty semantic equivalent — use '{{semantic}}' instead.\",\n useSemantic: \"Use '{{semantic}}' instead of '{{native}}'\",\n camelCaseTransition:\n \"Transition '{{name}}' compiles to '{{lowered}}', which is not a CSS property. Use the CSS name '{{kebab}}'.\",\n useKebabCase: \"Use '{{kebab}}' instead of '{{name}}'\",\n },\n schema: [],\n },\n defaultOptions: [],\n create(context) {\n const ctx = new TastyContext(context);\n\n function checkTransitionValue(value: string, node: TSESTree.Node): void {\n const groups = splitTopLevelCommas(value);\n let offset = 0;\n\n for (const group of groups) {\n const parts = group.trim().split(/\\s+/);\n if (parts.length === 0 || parts[0] === '') {\n offset += group.length + 1;\n continue;\n }\n\n const name = parts[0];\n\n // $$ prefix is always valid (custom property reference: $$name -> --name)\n if (name.startsWith('$$')) {\n offset += group.length + 1;\n continue;\n }\n\n // ## prefix is always valid (color property reference: ##name -> --name-color)\n if (name.startsWith('##')) {\n offset += group.length + 1;\n continue;\n }\n\n const start = offset + group.indexOf(name);\n const end = start + name.length;\n\n const semantic = TRANSITION_SEMANTIC_MAPPING[name];\n if (semantic) {\n context.report({\n node,\n messageId: 'preferSemanticTransition',\n data: { native: name, semantic },\n suggest: [\n {\n messageId: 'useSemantic',\n data: { native: name, semantic },\n fix(fixer) {\n return replaceInStringValue(\n fixer,\n node,\n [{ start, end, replacement: semantic }],\n context.sourceCode,\n );\n },\n },\n ],\n });\n offset += group.length + 1;\n continue;\n }\n\n // Tasty lowercases the name and emits it verbatim, so a camelCase CSS\n // property comes out as `gridtemplatecolumns`, which is no property.\n // Only the semantic names (`zIndex` -> `z-index`) are translated.\n if (\n /[A-Z]/.test(name) &&\n !SEMANTIC_TRANSITIONS.has(name) &&\n KNOWN_CSS_PROPERTIES.has(name)\n ) {\n const kebab = camelToKebab(name);\n const data = { name, lowered: name.toLowerCase(), kebab };\n context.report({\n node,\n messageId: 'camelCaseTransition',\n data,\n suggest: [\n {\n messageId: 'useKebabCase',\n data,\n fix(fixer) {\n return replaceInStringValue(\n fixer,\n node,\n [{ start, end, replacement: kebab }],\n context.sourceCode,\n );\n },\n },\n ],\n });\n offset += group.length + 1;\n continue;\n }\n\n if (\n NON_TRANSITION_STYLE_NAMES.has(name) ||\n (!SEMANTIC_TRANSITIONS.has(name) &&\n !KNOWN_CSS_PROPERTIES.has(name) &&\n !KNOWN_CSS_PROPERTIES.has(kebabToCamel(name)) &&\n !name.startsWith('--') &&\n name !== 'all' &&\n name !== 'none')\n ) {\n context.report({\n node,\n messageId: 'unknownTransition',\n data: {\n name,\n known: [...SEMANTIC_TRANSITIONS].join(', '),\n },\n });\n }\n\n offset += group.length + 1;\n }\n }\n\n return stringStyleValueListeners(\n ctx,\n (value, node, property) => {\n if (property === 'transition') checkTransitionValue(value, node);\n },\n { requireTastyJSX: true },\n );\n },\n});\n"],"mappings":";;;;;;;;;;;;;;AAyBA,SAAS,aAAa,MAAsB;AAC1C,QAAO,KAAK,QAAQ,cAAc,GAAG,SAAiB,KAAK,aAAa,CAAC;;;AAI3E,SAAS,aAAa,MAAsB;AAC1C,QAAO,KAAK,QAAQ,WAAW,SAAS,IAAI,KAAK,aAAa,GAAG;;;;;;;;AASnE,MAAM,6BAA6B,IAAI,IAAI,CAAC,OAAO,CAAC;AAEpD,+BAAe,WAA2B;CACxC,MAAM;CACN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