domflax 0.1.2 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +66 -31
  2. package/dist/chunk-EYQXQQQH.js +336 -0
  3. package/dist/chunk-EYQXQQQH.js.map +1 -0
  4. package/dist/{chunk-DNHOGPYV.js → chunk-FPT4EJ6Q.js} +1100 -1551
  5. package/dist/chunk-FPT4EJ6Q.js.map +1 -0
  6. package/dist/chunk-JBM3MJRM.js +382 -0
  7. package/dist/chunk-JBM3MJRM.js.map +1 -0
  8. package/dist/{chunk-DWLB7FRR.js → chunk-TTJEXWAC.js} +322 -9
  9. package/dist/chunk-TTJEXWAC.js.map +1 -0
  10. package/dist/{chunk-6WVVF6AD.js → chunk-U5GOONKV.js} +5 -2
  11. package/dist/{chunk-6WVVF6AD.js.map → chunk-U5GOONKV.js.map} +1 -1
  12. package/dist/cli.cjs +3010 -2789
  13. package/dist/cli.cjs.map +1 -1
  14. package/dist/cli.js +268 -232
  15. package/dist/cli.js.map +1 -1
  16. package/dist/index.cjs +1684 -1649
  17. package/dist/index.cjs.map +1 -1
  18. package/dist/index.d.cts +255 -498
  19. package/dist/index.d.ts +255 -498
  20. package/dist/index.js +17 -37
  21. package/dist/{pattern-F5xBtIE-.d.cts → pattern-DotR_dHs.d.cts} +1 -1
  22. package/dist/pattern-kit.cjs +60 -1
  23. package/dist/pattern-kit.cjs.map +1 -1
  24. package/dist/pattern-kit.d.cts +2 -2
  25. package/dist/pattern-kit.d.ts +2 -2
  26. package/dist/pattern-kit.js +2 -2
  27. package/dist/{pattern-CV607P87.d.ts → pattern-urm5uuwj.d.ts} +1 -1
  28. package/dist/{resolve-ops-DIwEelH-.d.ts → resolve-ops-D8aQina5.d.cts} +20 -0
  29. package/dist/{resolve-ops-DIwEelH-.d.cts → resolve-ops-D8aQina5.d.ts} +20 -0
  30. package/dist/verify.d.cts +1 -1
  31. package/dist/verify.d.ts +1 -1
  32. package/dist/verify.js +1 -1
  33. package/dist/webpack-loader.cjs +1615 -1633
  34. package/dist/webpack-loader.cjs.map +1 -1
  35. package/dist/webpack-loader.d.cts +8 -2
  36. package/dist/webpack-loader.d.ts +8 -2
  37. package/dist/webpack-loader.js +8 -5
  38. package/dist/webpack-loader.js.map +1 -1
  39. package/dist/worker.cjs +5337 -0
  40. package/dist/worker.cjs.map +1 -0
  41. package/dist/worker.d.cts +2 -0
  42. package/dist/worker.d.ts +2 -0
  43. package/dist/worker.js +72 -0
  44. package/dist/worker.js.map +1 -0
  45. package/package.json +4 -2
  46. package/dist/chunk-DNHOGPYV.js.map +0 -1
  47. package/dist/chunk-DOQEBGWB.js +0 -188
  48. package/dist/chunk-DOQEBGWB.js.map +0 -1
  49. package/dist/chunk-DWLB7FRR.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/webpack-loader.ts","../../../node_modules/tsup/assets/cjs_shims.js","../../core/src/builders.ts","../../core/src/ops/runtime.ts","../../core/src/ops/apply.ts","../../core/src/pass-context.ts","../../core/src/flatten-safety.ts","../../core/src/pass-manager.ts","../../core/src/pipeline.ts","../../core/src/reverse-emit.ts","../../pattern-kit/src/normalize.ts","../../pattern-kit/src/combinators.ts","../../pattern-kit/src/define.ts","../../pattern-kit/src/pattern.ts","../../patterns/src/library/flatten/display-contents-wrapper.pattern.ts","../../patterns/src/library/flatten/empty-style-div.pattern.ts","../../patterns/src/library/flatten/flex-center-wrapper.pattern.ts","../../patterns/src/library/flatten/inline-flex-center-wrapper.pattern.ts","../../patterns/src/library/flatten/nested-flex-merge.pattern.ts","../../patterns/src/library/flatten/nested-grid-merge.pattern.ts","../../patterns/src/library/flatten/passthrough-wrapper.pattern.ts","../../patterns/src/library/flatten/redundant-fragment.pattern.ts","../../patterns/src/library/flatten/redundant-inline-wrapper.pattern.ts","../../patterns/src/library/compress/border-radius-shorthand.pattern.ts","../../patterns/src/library/compress/border-shorthand.pattern.ts","../../patterns/src/library/compress/dedupe-classes.pattern.ts","../../patterns/src/library/compress/gap-shorthand.pattern.ts","../../patterns/src/library/compress/inset-shorthand.pattern.ts","../../patterns/src/library/compress/margin-shorthand.pattern.ts","../../patterns/src/library/compress/overflow-shorthand.pattern.ts","../../patterns/src/library/compress/overscroll-behavior-shorthand.pattern.ts","../../patterns/src/library/compress/padding-shorthand.pattern.ts","../../patterns/src/library/compress/place-shorthand.pattern.ts","../../patterns/src/library/compress/scroll-margin-shorthand.pattern.ts","../../patterns/src/library/compress/scroll-padding-shorthand.pattern.ts","../../patterns/src/library/compress/size-shorthand.pattern.ts","../../patterns/src/_registry.generated.ts","../../resolver-tailwind/src/tailwind/fingerprint.ts","../../resolver-tailwind/src/tailwind/emit.ts","../../resolver-tailwind/src/tailwind/engine.ts","../../resolver-tailwind/src/tailwind/selector.ts","../../resolver-tailwind/src/tailwind/extract.ts","../../resolver-tailwind/src/tailwind/serialize.ts","../../resolver-tailwind/src/tailwind/stylemap.ts","../../resolver-tailwind/src/tailwind/usage.ts","../../resolver-tailwind/src/tailwind/resolver.ts","../../resolver-css/src/constants.ts","../../resolver-css/src/engine.ts","../../resolver-css/src/postcss-helpers.ts","../../resolver-css/src/misc-helpers.ts","../../resolver-css/src/selector-helpers.ts","../../resolver-css/src/resolver.ts","../src/index.ts","../../frontend-jsx/src/frontend-ast.ts","../../frontend-jsx/src/frontend-parse.ts","../../frontend-jsx/src/frontend.ts","../../frontend-jsx/src/backend.ts","../src/pipeline-run.ts"],"sourcesContent":["/**\n * domflax webpack loader.\n *\n * A genuine webpack loader module: webpack requires this file by absolute path (wired by the\n * `domflax.webpack()` plugin, see {@link ./index.webpack}) and invokes the default export once per\n * matched `.jsx`/`.tsx` module. It runs the SAME single-file engine as {@link createDomflax} — so the\n * heavy Tailwind/postcss engines stay LAZY (constructed on first transform, only for the selected\n * provider), exactly as in the Vite adapter and the programmatic API.\n *\n * The loader is intentionally synchronous (the transform is a pure CPU function with no source map\n * yet) and structurally typed against webpack: it depends only on a minimal local `LoaderContext`\n * shape, never on the `webpack` package itself.\n */\nimport { createDomflax } from './index';\nimport type { Domflax, DomflaxOptions } from './index';\n\n/**\n * The slice of webpack's `LoaderContext` the domflax loader touches. Declared locally so this module\n * does not hard-depend on `webpack` types.\n */\nexport interface DomflaxLoaderContext {\n /** Absolute path of the module being transformed (no query suffix). */\n readonly resourcePath: string;\n /** Loader options passed via the `module.rule` `use[].options` entry. */\n getOptions?(): DomflaxOptions | undefined;\n}\n\n/**\n * Engine cache keyed by the serialized options, so a build reuses one configured engine (and its\n * one lazily-loaded resolver) across every transformed file instead of rebuilding per module.\n */\nconst engines = new Map<string, Domflax>();\n\nfunction engineFor(options: DomflaxOptions): Domflax {\n const key = JSON.stringify(options ?? {});\n let engine = engines.get(key);\n if (!engine) {\n engine = createDomflax(options);\n engines.set(key, engine);\n }\n return engine;\n}\n\n/**\n * webpack loader entry point. Returns the (possibly rewritten) source; non-jsx/tsx or unchanged\n * modules round-trip through {@link Domflax.transform} unchanged.\n */\nexport default function domflaxLoader(this: DomflaxLoaderContext, source: string): string {\n const options = this.getOptions?.() ?? {};\n const engine = engineFor(options);\n return engine.transform(source, this.resourcePath).code;\n}\n","// Shim globals in cjs bundle\n// There's a weird bug that esbuild will always inject importMetaUrl\n// if we export it as `const importMetaUrl = ... __filename ...`\n// But using a function will not cause this issue\n\nconst getImportMetaUrl = () => \n typeof document === \"undefined\" \n ? new URL(`file:${__filename}`).href \n : (document.currentScript && document.currentScript.tagName.toUpperCase() === 'SCRIPT') \n ? document.currentScript.src \n : new URL(\"main.js\", document.baseURI).href;\n\nexport const importMetaUrl = /* @__PURE__ */ getImportMetaUrl()\n","/**\n * @domflax/core — runtime builders + traversal.\n *\n * Pure, dependency-free helpers to construct IR nodes, assemble an {@link IRDocument},\n * and walk the tree honouring {@link VisitSignal}. No heavy third-party deps: only the\n * type contract in `./types`.\n */\n\nimport type {\n AttrMap,\n Backref,\n BackrefTable,\n ClassList,\n ConditionKey,\n CssProperty,\n ExprRecord,\n ExprRef,\n ExprRegistry,\n FrontendKind,\n IdAllocator,\n IRComment,\n IRDocument,\n IRElement,\n IRExpr,\n IRFragment,\n IRNamespace,\n IRNode,\n IRNodeId,\n IRText,\n InlineStyle,\n NodeMeta,\n SafetyLevel,\n SourceSpan,\n StyleBlock,\n StyleCondition,\n StyleMap,\n Visitor,\n VisitContext,\n VisitSignal,\n} from './types';\n\n/* ───────────────────────── id / registry primitives ───────────────────────── */\n\n/** Monotonic IRNodeId allocator. `peek` reports the id `next()` would return. */\nexport function createIdAllocator(start = 1): IdAllocator {\n let n = start;\n return {\n next(): IRNodeId {\n const id = n;\n n += 1;\n return id as IRNodeId;\n },\n get peek(): IRNodeId {\n return n as IRNodeId;\n },\n };\n}\n\n/** Minimal in-memory ExprRegistry. */\nexport function createExprRegistry(start = 1): ExprRegistry {\n const map = new Map<ExprRef, ExprRecord>();\n let n = start;\n return {\n get(r: ExprRef): ExprRecord | undefined {\n return map.get(r);\n },\n intern(rec: Omit<ExprRecord, 'ref'>): ExprRef {\n const ref = n as ExprRef;\n n += 1;\n map.set(ref, { ...rec, ref });\n return ref;\n },\n releasePayloads(): void {\n for (const [k, v] of map) map.set(k, { ...v, payload: undefined });\n },\n };\n}\n\n/** Mutable BackrefTable: frontends register backrefs as they parse. */\nexport interface MutableBackrefTable extends BackrefTable {\n set(id: IRNodeId, backref: Backref): void;\n}\n\nexport function createBackrefTable(): MutableBackrefTable {\n const map = new Map<IRNodeId, Backref>();\n return {\n get(id: IRNodeId): Backref | undefined {\n return map.get(id);\n },\n span(id: IRNodeId): SourceSpan | null {\n return map.get(id)?.span ?? null;\n },\n childrenSpan(id: IRNodeId): SourceSpan | null {\n return map.get(id)?.innerSpan ?? null;\n },\n set(id: IRNodeId, backref: Backref): void {\n map.set(id, backref);\n },\n };\n}\n\n/* ───────────────────────── default sub-structures ───────────────────────── */\n\n/** A NodeMeta with every barrier/flag cleared. */\nexport function defaultMeta(safetyFloor: SafetyLevel = 0): NodeMeta {\n return {\n hasRef: false,\n hasEventHandlers: false,\n hasKey: false,\n hasSpreadAttrs: false,\n hasDynamicChildren: false,\n isComponent: false,\n hasDangerousHtml: false,\n targetedByCombinator: false,\n targetedByStructuralPseudo: false,\n selectorDependents: 0,\n hasOwnVisualStyle: false,\n establishesBox: false,\n establishesStackingContext: false,\n isContainingBlock: false,\n establishesFormattingContext: false,\n declaresCustomProperties: false,\n whitespaceSensitive: false,\n touched: false,\n synthetic: false,\n safetyFloor,\n };\n}\n\n/** Canonical base style condition (`media:'' states:[] pseudoElement:''`). */\nexport const BASE_CONDITION: StyleCondition = { media: '', states: [], pseudoElement: '' };\n\n/** Stable serialization of a StyleCondition into a ConditionKey. */\nexport function conditionKey(c: StyleCondition): ConditionKey {\n const states = [...c.states].sort().join(',');\n return `${c.media}|${states}|${c.pseudoElement}` as ConditionKey;\n}\n\nexport const BASE_CONDITION_KEY: ConditionKey = conditionKey(BASE_CONDITION);\n\n/** An empty StyleMap (no blocks). */\nexport function emptyStyleMap(): StyleMap {\n return { blocks: new Map<ConditionKey, StyleBlock>() };\n}\n\n/** An empty (absent) ClassList. */\nexport function emptyClassList(): ClassList {\n return {\n form: 'absent',\n segments: [],\n valueSpan: null,\n hasDynamic: false,\n opaque: false,\n rewritable: false,\n };\n}\n\n/** An empty AttrMap. */\nexport function emptyAttrMap(): AttrMap {\n return { entries: new Map(), spreads: [], order: [] };\n}\n\n/** An empty InlineStyle. */\nexport function emptyInlineStyle(): InlineStyle {\n return { decls: new Map<CssProperty, never>() as InlineStyle['decls'], dynamic: null };\n}\n\n/* ───────────────────────── node factories ───────────────────────── */\n\nexport interface ElementInit {\n readonly tag: string;\n readonly namespace?: IRNamespace;\n readonly isComponent?: boolean;\n readonly selfClosing?: boolean;\n readonly classes?: ClassList;\n readonly inlineStyle?: InlineStyle;\n readonly computed?: StyleMap;\n readonly attrs?: AttrMap;\n readonly children?: IRNodeId[];\n readonly parent?: IRNodeId | null;\n readonly span?: SourceSpan | null;\n readonly meta?: NodeMeta;\n}\n\nexport function createElement(id: IRNodeId, init: ElementInit): IRElement {\n return {\n id,\n kind: 'element',\n parent: init.parent ?? null,\n span: init.span ?? null,\n meta: init.meta ?? defaultMeta(),\n tag: init.tag,\n namespace: init.namespace ?? 'html',\n isComponent: init.isComponent ?? false,\n selfClosing: init.selfClosing ?? false,\n classes: init.classes ?? emptyClassList(),\n inlineStyle: init.inlineStyle ?? emptyInlineStyle(),\n computed: init.computed ?? emptyStyleMap(),\n attrs: init.attrs ?? emptyAttrMap(),\n children: init.children ?? [],\n };\n}\n\nexport function createText(\n id: IRNodeId,\n value: string,\n opts?: { collapsible?: boolean; parent?: IRNodeId | null; span?: SourceSpan | null },\n): IRText {\n return {\n id,\n kind: 'text',\n parent: opts?.parent ?? null,\n span: opts?.span ?? null,\n meta: defaultMeta(),\n value,\n collapsible: opts?.collapsible ?? true,\n };\n}\n\nexport function createExpr(\n id: IRNodeId,\n expr: ExprRef,\n opts?: { parent?: IRNodeId | null; span?: SourceSpan | null },\n): IRExpr {\n return {\n id,\n kind: 'expr',\n parent: opts?.parent ?? null,\n span: opts?.span ?? null,\n meta: defaultMeta(),\n expr,\n };\n}\n\nexport function createFragment(\n id: IRNodeId,\n opts?: { children?: IRNodeId[]; parent?: IRNodeId | null; span?: SourceSpan | null },\n): IRFragment {\n return {\n id,\n kind: 'fragment',\n parent: opts?.parent ?? null,\n span: opts?.span ?? null,\n meta: defaultMeta(),\n children: opts?.children ?? [],\n };\n}\n\nexport function createComment(\n id: IRNodeId,\n value: string,\n opts?: { parent?: IRNodeId | null; span?: SourceSpan | null },\n): IRComment {\n return {\n id,\n kind: 'comment',\n parent: opts?.parent ?? null,\n span: opts?.span ?? null,\n meta: defaultMeta(),\n value,\n };\n}\n\n/** Build an empty document whose root is a fresh fragment. */\nexport function createDocument(frontend: FrontendKind): IRDocument {\n const alloc = createIdAllocator();\n const rootId = alloc.next();\n const root = createFragment(rootId);\n const nodes = new Map<IRNodeId, IRNode>([[rootId, root]]);\n return {\n root: rootId,\n nodes,\n exprs: createExprRegistry(),\n sources: new Map(),\n backref: createBackrefTable(),\n frontend,\n alloc,\n };\n}\n\n/* ───────────────────────── tree accessors ───────────────────────── */\n\n/** Returns the child id list for container nodes, or an empty array. */\nexport function childIds(node: IRNode): readonly IRNodeId[] {\n return node.kind === 'element' || node.kind === 'fragment' ? node.children : [];\n}\n\n/** Returns the node, or undefined. */\nexport function getNode(doc: IRDocument, id: IRNodeId): IRNode | undefined {\n return doc.nodes.get(id);\n}\n\n/** Returns the node iff it is an element. */\nexport function getElement(doc: IRDocument, id: IRNodeId): IRElement | undefined {\n const n = doc.nodes.get(id);\n return n && n.kind === 'element' ? n : undefined;\n}\n\n/** Pre-order list of every element id reachable from the root. */\nexport function elementIds(doc: IRDocument): IRNodeId[] {\n const out: IRNodeId[] = [];\n const visit = (id: IRNodeId): void => {\n const n = doc.nodes.get(id);\n if (!n) return;\n if (n.kind === 'element') out.push(id);\n for (const c of childIds(n)) visit(c);\n };\n visit(doc.root);\n return out;\n}\n\n/* ───────────────────────── traversal ───────────────────────── */\n\n/**\n * Depth-first pre/post-order walk. `enter` may return `'skip'` (don't descend) or `'stop'`\n * (abort the whole walk); `exit` may return `'stop'`. The visitor receives a live {@link IRNode}\n * plus a {@link VisitContext} exposing depth and the parent node.\n */\nexport function walk(doc: IRDocument, visitor: Visitor): void {\n const roDoc = doc as unknown as VisitContext['doc'];\n let stopped = false;\n\n const visit = (id: IRNodeId, depth: number): void => {\n if (stopped) return;\n const node = doc.nodes.get(id);\n if (!node) return;\n\n const ctx: VisitContext = {\n doc: roDoc,\n depth,\n parent(): IRNode | null {\n return node.parent == null ? null : doc.nodes.get(node.parent) ?? null;\n },\n };\n\n const entered: VisitSignal = visitor.enter ? visitor.enter(node, ctx) : undefined;\n if (entered === 'stop') {\n stopped = true;\n return;\n }\n if (entered !== 'skip') {\n for (const child of childIds(node)) {\n visit(child, depth + 1);\n if (stopped) return;\n }\n }\n\n const exited: VisitSignal = visitor.exit ? visitor.exit(node, ctx) : undefined;\n if (exited === 'stop') stopped = true;\n };\n\n visit(doc.root, 0);\n}\n","/**\n * @domflax/core — applier runtime helpers (shared by the per-op handlers in `./apply`).\n *\n * Pure, dependency-free building blocks for the trusted mutator: input-preserving cloning, the\n * mutable apply state, small tree helpers, detached-spec materialization, and style merging.\n * Only depends on the `../types` contract and `../builders` runtime helpers.\n */\n\nimport type {\n ApplyContext,\n ApplyResult,\n AttrMap,\n AttrValue,\n ConditionKey,\n CssProperty,\n Diagnostic,\n DiagnosticCode,\n ElementSpec,\n IRDocument,\n IRNode,\n IRNodeId,\n NodeSpec,\n RewriteOp,\n SkippedOpGroup,\n StyleBlock,\n StyleConflictPolicy,\n StyleDecl,\n StyleMap,\n} from '../types';\n\nimport {\n createComment,\n createElement,\n createExpr,\n createFragment,\n createText,\n defaultMeta,\n} from '../builders';\n\n/* ───────────────────────── result of an apply run ───────────────────────── */\n\nexport interface ApplyOutcome {\n /** The new document (the input doc is never mutated). */\n readonly doc: IRDocument;\n readonly result: ApplyResult;\n}\n\nexport interface MutState {\n readonly doc: IRDocument;\n readonly touched: Set<IRNodeId>;\n readonly removed: Set<IRNodeId>;\n readonly created: Set<IRNodeId>;\n readonly diagnostics: Diagnostic[];\n readonly skipped: SkippedOpGroup[];\n appliedGroups: number;\n readonly ceiling: number;\n readonly ctx: ApplyContext;\n}\n\n/* ───────────────────────── cloning (keep input pure) ───────────────────────── */\n\nexport function cloneStyleMap(sm: StyleMap): StyleMap {\n const blocks = new Map<ConditionKey, StyleBlock>();\n for (const [key, block] of sm.blocks) {\n blocks.set(key, {\n condition: block.condition,\n decls: new Map<CssProperty, StyleDecl>(block.decls),\n });\n }\n return { blocks };\n}\n\nfunction cloneNode(node: IRNode): IRNode {\n const meta = { ...node.meta };\n switch (node.kind) {\n case 'element':\n return {\n ...node,\n meta,\n children: [...node.children],\n computed: cloneStyleMap(node.computed),\n };\n case 'fragment':\n return { ...node, meta, children: [...node.children] };\n default:\n return { ...node, meta };\n }\n}\n\n/** Shallow-immutable clone: input doc and its node objects are never mutated. */\nexport function cloneDocument(doc: IRDocument): IRDocument {\n const nodes = new Map<IRNodeId, IRNode>();\n for (const [id, n] of doc.nodes) nodes.set(id, cloneNode(n));\n return {\n root: doc.root,\n nodes,\n exprs: doc.exprs,\n sources: doc.sources,\n backref: doc.backref,\n frontend: doc.frontend,\n alloc: doc.alloc,\n };\n}\n\n/* ───────────────────────── small helpers ───────────────────────── */\n\nexport function diag(\n code: DiagnosticCode,\n message: string,\n extra?: Partial<Diagnostic>,\n): Diagnostic {\n return { code, severity: 'warn', message, ...extra };\n}\n\nexport function getParentChildren(doc: IRDocument, id: IRNodeId): IRNodeId[] | null {\n const node = doc.nodes.get(id);\n if (!node || node.parent == null) return null;\n const parent = doc.nodes.get(node.parent);\n if (!parent) return null;\n if (parent.kind === 'element' || parent.kind === 'fragment') return parent.children;\n return null;\n}\n\nexport function indexInParent(doc: IRDocument, id: IRNodeId): number {\n const siblings = getParentChildren(doc, id);\n return siblings ? siblings.indexOf(id) : -1;\n}\n\nexport function markTouched(state: MutState, id: IRNodeId): void {\n const n = state.doc.nodes.get(id);\n if (n) {\n n.meta.touched = true;\n state.touched.add(id);\n }\n}\n\nexport function removeSubtree(state: MutState, id: IRNodeId): void {\n const node = state.doc.nodes.get(id);\n if (!node) return;\n if (node.kind === 'element' || node.kind === 'fragment') {\n for (const child of [...node.children]) removeSubtree(state, child);\n }\n state.doc.nodes.delete(id);\n state.removed.add(id);\n}\n\nexport function precond(op: RewriteOp, nodeId: IRNodeId, message: string): Diagnostic {\n return diag('DF_OP_PRECONDITION_FAILED', message, {\n nodeId,\n pattern: op.origin.pattern,\n severity: 'error',\n });\n}\n\nexport function primaryTarget(op: RewriteOp): IRNodeId | null {\n switch (op.op) {\n case 'removeNode':\n case 'unwrap':\n case 'replaceWith':\n case 'wrap':\n case 'moveNode':\n case 'setClassList':\n case 'mergeStyle':\n return op.target;\n case 'insertBefore':\n case 'insertAfter':\n return op.anchor;\n case 'mergeSiblings':\n return op.first;\n case 'foldInheritedStyles':\n return op.from;\n }\n}\n\n/* ───────────────────────── spec materialization ───────────────────────── */\n\nfunction specToAttrs(map: ReadonlyMap<string, string | boolean> | undefined): AttrMap {\n if (!map || map.size === 0) return { entries: new Map(), spreads: [], order: [] };\n const entries = new Map<string, AttrValue>();\n const order: string[] = [];\n for (const [k, v] of map) {\n entries.set(k, { kind: 'static', value: v });\n order.push(k);\n }\n return { entries, spreads: [], order };\n}\n\n/** Materialize a detached {@link NodeSpec} into live nodes; returns the new (or reused) id. */\nexport function materialize(state: MutState, spec: NodeSpec, parent: IRNodeId | null): IRNodeId {\n const { doc } = state;\n if (spec.kind === 'ref') {\n const existing = doc.nodes.get(spec.ref);\n if (existing) existing.parent = parent;\n return spec.ref;\n }\n\n const id = doc.alloc.next();\n state.created.add(id);\n switch (spec.kind) {\n case 'element': {\n const childIds: IRNodeId[] = [];\n const el = createElement(id, {\n tag: spec.tag,\n namespace: spec.namespace,\n selfClosing: spec.selfClosing,\n attrs: specToAttrs(spec.attrs),\n parent,\n meta: { ...defaultMeta(), synthetic: true },\n });\n if (spec.classes) el.computed = cloneStyleMap(spec.classes);\n doc.nodes.set(id, el);\n for (const child of spec.children ?? []) {\n childIds.push(materialize(state, child, id));\n }\n el.children = childIds;\n return id;\n }\n case 'text': {\n const t = createText(id, spec.value, { parent });\n t.meta.synthetic = true;\n doc.nodes.set(id, t);\n return id;\n }\n case 'expr': {\n const e = createExpr(id, spec.expr, { parent });\n e.meta.synthetic = true;\n doc.nodes.set(id, e);\n return id;\n }\n case 'comment': {\n const c = createComment(id, spec.value, { parent });\n c.meta.synthetic = true;\n doc.nodes.set(id, c);\n return id;\n }\n case 'fragment': {\n const frag = createFragment(id, { parent });\n frag.meta.synthetic = true;\n doc.nodes.set(id, frag);\n const childIds: IRNodeId[] = [];\n for (const child of spec.children) childIds.push(materialize(state, child, id));\n frag.children = childIds;\n return id;\n }\n }\n}\n\nexport function elementSpecToNode(\n state: MutState,\n spec: ElementSpec,\n parent: IRNodeId | null,\n): IRNodeId {\n return materialize(state, spec, parent);\n}\n\n/* ───────────────────────── style merging ───────────────────────── */\n\nexport function isInherited(state: MutState, decl: StyleDecl): boolean {\n if (decl.inherited) return true;\n const table = state.ctx.normalizer?.inherited;\n if (table) {\n try {\n return table.isInherited(decl.property);\n } catch {\n return decl.inherited;\n }\n }\n return decl.inherited;\n}\n\nexport interface MergeReport {\n readonly map: StyleMap;\n readonly conflict: boolean;\n}\n\n/** Merge `source` decls into `target`, condition-by-condition, per the conflict policy. */\nexport function mergeStyleMaps(\n target: StyleMap,\n source: StyleMap,\n policy: StyleConflictPolicy,\n): MergeReport {\n // Mutable working copy; returned (widened) as an immutable StyleMap.\n const blocks = new Map<ConditionKey, StyleBlock>(cloneStyleMap(target).blocks);\n let conflict = false;\n\n for (const [key, srcBlock] of source.blocks) {\n const existing = blocks.get(key);\n if (!existing) {\n blocks.set(key, {\n condition: srcBlock.condition,\n decls: new Map<CssProperty, StyleDecl>(srcBlock.decls),\n });\n continue;\n }\n const decls = new Map<CssProperty, StyleDecl>(existing.decls);\n for (const [prop, srcDecl] of srcBlock.decls) {\n const had = decls.get(prop);\n if (had && had.value !== srcDecl.value) {\n conflict = true;\n if (policy === 'target-wins') continue;\n // 'abort' is handled by the caller before commit; 'source-wins' falls through.\n }\n if (policy === 'target-wins' && had) continue;\n decls.set(prop, srcDecl);\n }\n blocks.set(key, { condition: existing.condition, decls });\n }\n return { map: { blocks }, conflict };\n}\n","/**\n * @domflax/core — the per-op handlers + public apply entry points.\n *\n * {@link applyOps} validates each {@link RewriteOp} against the safety ceiling / node-local floor\n * and commits it to a clone of the document; {@link applyGroups} commits whole {@link RewriteGroup}s\n * atomically. Rejected ops are collected into {@link ApplyResult.skipped} rather than throwing.\n */\n\nimport type {\n ApplyContext,\n ApplyResult,\n ConditionKey,\n CssProperty,\n Diagnostic,\n IRDocument,\n IRNodeId,\n RewriteGroup,\n RewriteOp,\n SkippedOpGroup,\n StyleBlock,\n StyleDecl,\n} from '../types';\n\nimport { BASE_CONDITION_KEY } from '../builders';\n\nimport {\n cloneDocument,\n cloneStyleMap,\n diag,\n elementSpecToNode,\n getParentChildren,\n isInherited,\n markTouched,\n materialize,\n mergeStyleMaps,\n precond,\n primaryTarget,\n removeSubtree,\n type ApplyOutcome,\n type MutState,\n} from './runtime';\n\nexport type { ApplyOutcome } from './runtime';\nexport { cloneDocument } from './runtime';\n\n/* ───────────────────────── per-op handlers ───────────────────────── */\n\nfunction safetyOk(state: MutState, op: RewriteOp, targetId: IRNodeId): Diagnostic | null {\n const opSafety = op.origin.safety;\n if (opSafety > state.ceiling) {\n return diag(\n 'DF_SAFETY_CEILING_EXCEEDED',\n `op '${op.op}' safety ${opSafety} exceeds ceiling ${state.ceiling}`,\n { nodeId: targetId, pattern: op.origin.pattern, severity: 'error' },\n );\n }\n const node = state.doc.nodes.get(targetId);\n if (node && opSafety > node.meta.safetyFloor) {\n return diag(\n 'DF_SAFETY_CEILING_EXCEEDED',\n `op '${op.op}' safety ${opSafety} exceeds node ${targetId} floor ${node.meta.safetyFloor}`,\n { nodeId: targetId, pattern: op.origin.pattern, severity: 'error' },\n );\n }\n return null;\n}\n\n/** Returns a list of validation issues; empty ⇒ the op was applied. */\nfunction applyOne(state: MutState, op: RewriteOp): Diagnostic[] {\n const { doc } = state;\n\n const primary = primaryTarget(op);\n if (primary != null) {\n if (!doc.nodes.get(primary)) {\n return [\n diag('DF_OP_PRECONDITION_FAILED', `target node ${primary} not found`, {\n nodeId: primary,\n pattern: op.origin.pattern,\n severity: 'error',\n }),\n ];\n }\n const safety = safetyOk(state, op, primary);\n if (safety) return [safety];\n }\n\n switch (op.op) {\n case 'removeNode': {\n const siblings = getParentChildren(doc, op.target);\n if (siblings) {\n const i = siblings.indexOf(op.target);\n if (i >= 0) siblings.splice(i, 1);\n }\n removeSubtree(state, op.target);\n return [];\n }\n\n case 'unwrap': {\n const node = doc.nodes.get(op.target);\n if (!node || (node.kind !== 'element' && node.kind !== 'fragment')) {\n return [precond(op, op.target, 'unwrap target is not a container')];\n }\n const siblings = getParentChildren(doc, op.target);\n if (!siblings) return [precond(op, op.target, 'unwrap target has no parent')];\n const at = siblings.indexOf(op.target);\n const kids = node.children;\n for (const k of kids) {\n const kn = doc.nodes.get(k);\n if (kn) kn.parent = node.parent;\n }\n siblings.splice(at, 1, ...kids);\n doc.nodes.delete(op.target);\n state.removed.add(op.target);\n if (node.parent != null) markTouched(state, node.parent);\n return [];\n }\n\n case 'replaceWith': {\n const siblings = getParentChildren(doc, op.target);\n if (!siblings) return [precond(op, op.target, 'replaceWith target has no parent')];\n const at = siblings.indexOf(op.target);\n const parentId = doc.nodes.get(op.target)?.parent ?? null;\n const newId = materialize(state, op.replacement, parentId);\n siblings.splice(at, 1, newId);\n removeSubtree(state, op.target);\n if (parentId != null) markTouched(state, parentId);\n return [];\n }\n\n case 'wrap': {\n const siblings = getParentChildren(doc, op.target);\n if (!siblings) return [precond(op, op.target, 'wrap target has no parent')];\n const at = siblings.indexOf(op.target);\n const parentId = doc.nodes.get(op.target)?.parent ?? null;\n const wrapperId = elementSpecToNode(state, op.wrapper, parentId);\n const wrapper = doc.nodes.get(wrapperId);\n const targetNode = doc.nodes.get(op.target);\n if (wrapper && (wrapper.kind === 'element' || wrapper.kind === 'fragment')) {\n wrapper.children.push(op.target);\n }\n if (targetNode) targetNode.parent = wrapperId;\n siblings.splice(at, 1, wrapperId);\n return [];\n }\n\n case 'insertBefore':\n case 'insertAfter': {\n const siblings = getParentChildren(doc, op.anchor);\n if (!siblings) return [precond(op, op.anchor, 'insert anchor has no parent')];\n const at = siblings.indexOf(op.anchor);\n const parentId = doc.nodes.get(op.anchor)?.parent ?? null;\n const newId = materialize(state, op.node, parentId);\n siblings.splice(op.op === 'insertBefore' ? at : at + 1, 0, newId);\n if (parentId != null) markTouched(state, parentId);\n return [];\n }\n\n case 'moveNode': {\n const newParent = doc.nodes.get(op.newParent);\n if (!newParent || (newParent.kind !== 'element' && newParent.kind !== 'fragment')) {\n return [precond(op, op.newParent, 'moveNode newParent is not a container')];\n }\n const siblings = getParentChildren(doc, op.target);\n if (siblings) {\n const i = siblings.indexOf(op.target);\n if (i >= 0) siblings.splice(i, 1);\n }\n const target = doc.nodes.get(op.target);\n if (target) target.parent = op.newParent;\n const idx = Math.max(0, Math.min(op.index, newParent.children.length));\n newParent.children.splice(idx, 0, op.target);\n markTouched(state, op.newParent);\n return [];\n }\n\n case 'mergeSiblings': {\n const first = doc.nodes.get(op.first);\n const second = doc.nodes.get(op.second);\n if (!first || !second) return [precond(op, op.first, 'mergeSiblings node missing')];\n if (\n (first.kind === 'element' || first.kind === 'fragment') &&\n (second.kind === 'element' || second.kind === 'fragment')\n ) {\n for (const c of second.children) {\n const cn = doc.nodes.get(c);\n if (cn) cn.parent = op.first;\n first.children.push(c);\n }\n second.children = [];\n }\n const siblings = getParentChildren(doc, op.second);\n if (siblings) {\n const i = siblings.indexOf(op.second);\n if (i >= 0) siblings.splice(i, 1);\n }\n doc.nodes.delete(op.second);\n state.removed.add(op.second);\n markTouched(state, op.first);\n return [];\n }\n\n case 'setClassList': {\n const el = doc.nodes.get(op.target);\n if (!el || el.kind !== 'element') {\n return [precond(op, op.target, 'setClassList target is not an element')];\n }\n el.computed = cloneStyleMap(op.style);\n markTouched(state, op.target);\n return [];\n }\n\n case 'mergeStyle': {\n const el = doc.nodes.get(op.target);\n if (!el || el.kind !== 'element') {\n return [precond(op, op.target, 'mergeStyle target is not an element')];\n }\n const report = mergeStyleMaps(el.computed, op.style, op.onConflict);\n if (report.conflict && op.onConflict === 'abort') {\n return [\n diag('DF_STYLE_CONFLICT_UNRESOLVED', `mergeStyle aborted on conflict at ${op.target}`, {\n nodeId: op.target,\n pattern: op.origin.pattern,\n severity: 'error',\n }),\n ];\n }\n el.computed = report.map;\n if (op.source != null) {\n const src = doc.nodes.get(op.source);\n if (src) markTouched(state, op.source);\n }\n markTouched(state, op.target);\n return [];\n }\n\n case 'foldInheritedStyles':\n return applyFold(state, op);\n }\n}\n\nfunction applyFold(\n state: MutState,\n op: Extract<RewriteOp, { op: 'foldInheritedStyles' }>,\n): Diagnostic[] {\n const { doc } = state;\n const from = doc.nodes.get(op.from);\n if (!from || from.kind !== 'element') {\n return [precond(op, op.from, 'fold source is not an element')];\n }\n const issues: Diagnostic[] = [];\n const onlyProps: ReadonlySet<CssProperty> | null =\n op.properties === 'all-inherited' ? null : new Set(op.properties);\n\n const conditionKeys =\n op.conditions === 'all'\n ? [...from.computed.blocks.keys()]\n : [BASE_CONDITION_KEY];\n\n for (const intoId of op.into) {\n const into = doc.nodes.get(intoId);\n if (!into || into.kind !== 'element') {\n issues.push(precond(op, intoId, 'fold target is not an element'));\n continue;\n }\n // Mutable working copy; assigned back (widened) as an immutable StyleMap.\n const nextBlocks = new Map<ConditionKey, StyleBlock>(cloneStyleMap(into.computed).blocks);\n let folded = false;\n\n for (const key of conditionKeys) {\n const srcBlock = from.computed.blocks.get(key);\n if (!srcBlock) continue;\n const dstBlock = nextBlocks.get(key);\n const decls = dstBlock\n ? new Map<CssProperty, StyleDecl>(dstBlock.decls)\n : new Map<CssProperty, StyleDecl>();\n\n for (const [prop, decl] of srcBlock.decls) {\n if (onlyProps && !onlyProps.has(prop)) continue;\n if (!isInherited(state, decl)) continue;\n if (decl.relativeToParent) {\n issues.push(\n diag(\n 'DF_RELATIVE_UNIT_FOLD',\n `refused to fold relative-unit declaration '${decl.property}' onto ${intoId}`,\n { nodeId: intoId, pattern: op.origin.pattern, severity: 'warn' },\n ),\n );\n continue;\n }\n if (!decls.has(prop)) {\n decls.set(prop, decl);\n folded = true;\n }\n }\n nextBlocks.set(key, { condition: srcBlock.condition, decls });\n }\n\n if (folded) {\n into.computed = { blocks: nextBlocks };\n markTouched(state, intoId);\n }\n }\n // Non-blocking (DF_RELATIVE_UNIT_FOLD) diagnostics are recorded but do not skip the op.\n for (const d of issues) state.diagnostics.push(d);\n return [];\n}\n\n/* ───────────────────────── public entry points ───────────────────────── */\n\n/**\n * Apply a flat list of ops to a copy of `doc`. The input document is never mutated.\n * Each op is independently validated; failing ops are skipped (collected in\n * {@link ApplyResult.skipped}) instead of throwing.\n */\nexport function applyOps(\n doc: IRDocument,\n ops: readonly RewriteOp[],\n ctx?: Partial<ApplyContext>,\n): ApplyOutcome {\n const cloned = cloneDocument(doc);\n const state: MutState = {\n doc: cloned,\n touched: new Set(),\n removed: new Set(),\n created: new Set(),\n diagnostics: [],\n skipped: [],\n appliedGroups: 0,\n ceiling: ctx?.safetyCeiling ?? 3,\n ctx: { doc: cloned, safetyCeiling: ctx?.safetyCeiling ?? 3, ...ctx } as ApplyContext,\n };\n\n for (const op of ops) {\n const issues = applyOne(state, op);\n if (issues.length > 0) {\n state.skipped.push({\n group: { pattern: op.origin.pattern, anchor: primaryTarget(op) ?? doc.root, ops: [op] },\n issues: issues.map((d) => ({ op, code: d.code, message: d.message })),\n });\n for (const d of issues) state.diagnostics.push(d);\n } else {\n state.appliedGroups += 1;\n }\n }\n\n return { doc: cloned, result: finalize(state) };\n}\n\n/**\n * Apply pre-grouped ops (each {@link RewriteGroup} is committed atomically: if ANY op in the group\n * fails validation, the whole group is skipped and none of its ops mutate the tree).\n */\nexport function applyGroups(\n doc: IRDocument,\n groups: readonly RewriteGroup[],\n ctx?: Partial<ApplyContext>,\n): ApplyOutcome {\n // Group-atomicity is realized by working on a throwaway clone per group, then committing.\n let current = cloneDocument(doc);\n const touched = new Set<IRNodeId>();\n const removed = new Set<IRNodeId>();\n const created = new Set<IRNodeId>();\n const diagnostics: Diagnostic[] = [];\n const skipped: SkippedOpGroup[] = [];\n let appliedGroups = 0;\n\n for (const group of groups) {\n const attempt = applyOps(current, group.ops, ctx);\n if (attempt.result.skipped.length > 0) {\n skipped.push({\n group,\n issues: attempt.result.skipped.flatMap((s) => s.issues),\n });\n for (const s of attempt.result.skipped) for (const i of s.issues) {\n diagnostics.push(diag(i.code, i.message, { pattern: group.pattern }));\n }\n continue; // discard the attempt — group is atomic\n }\n current = attempt.doc;\n appliedGroups += 1;\n for (const id of attempt.result.touched) touched.add(id);\n for (const id of attempt.result.removed) removed.add(id);\n for (const id of attempt.result.created) created.add(id);\n for (const d of attempt.result.diagnostics) diagnostics.push(d);\n }\n\n const result: ApplyResult = {\n touched,\n removed,\n created,\n appliedGroups,\n skipped,\n journal: [],\n diagnostics,\n };\n return { doc: current, result };\n}\n\nfunction finalize(state: MutState): ApplyResult {\n return {\n touched: state.touched,\n removed: state.removed,\n created: state.created,\n appliedGroups: state.appliedGroups,\n skipped: state.skipped,\n journal: [],\n diagnostics: state.diagnostics,\n };\n}\n","/**\n * @domflax/core — pass-manager supporting contexts (resolvers, selector index, rewrite factory,\n * match context).\n *\n * Split out of `pass-manager.ts` so the sync engine, the async verifier-gated engine, and the\n * classification module can all share the same context construction without any of those files\n * exceeding the module-size budget. Dependency-free: only the `./types` contract + `./builders`.\n */\n\nimport type {\n DeepReadonly,\n ElementLike,\n ElementSpec,\n EmitContext,\n EmitResult,\n IRDocument,\n IRElement,\n IRNode,\n IRNodeId,\n MatchContext,\n NodeLike,\n NodeSpec,\n PassPhase,\n ResolveInput,\n ResolveResult,\n RewriteFactory,\n RewriteOpDraft,\n SelectorIndex,\n SelectorUsage,\n StyleConflictPolicy,\n StyleMap,\n StyleResolver,\n} from './types';\n\nimport { elementIds, emptyStyleMap, getElement } from './builders';\n\n/* ───────────────────────── default resolvers / selector index ───────────────────────── */\n\n/** A no-op resolver: owns nothing, resolves to empty styles. Useful as an injection default. */\nexport function createNullResolver(): StyleResolver {\n const empty: ResolveResult = {\n styles: emptyStyleMap(),\n resolved: [],\n unknown: [],\n opaque: [],\n warnings: [],\n };\n const usage: SelectorUsage = {\n asSubject: false,\n asAncestor: false,\n asCompound: false,\n asSibling: false,\n asHasArgument: false,\n asStructural: false,\n droppable: true,\n };\n return {\n id: 'null',\n provider: 'null@0.0.0',\n fingerprint: 'null',\n owns(): boolean {\n return false;\n },\n resolve(_input: ResolveInput): ResolveResult {\n return empty;\n },\n emit(_styles: StyleMap, _ctx: EmitContext): EmitResult {\n return { classes: [], exact: true, warnings: [] };\n },\n selectorUsage(): SelectorUsage {\n return usage;\n },\n };\n}\n\n/** A SelectorIndex that reports zero CSS-targeting (no combinator/structural coupling). */\nexport function createNullSelectorIndex(): SelectorIndex {\n const none: ReadonlySet<IRNodeId> = new Set();\n return {\n targetedByCombinator(): boolean {\n return false;\n },\n targetedByStructuralPseudo(): boolean {\n return false;\n },\n reparentImpact(): ReadonlySet<IRNodeId> {\n return none;\n },\n };\n}\n\n/** Resolvers that can enumerate the project's COMPLEX selectors (the custom-CSS resolver) expose this. */\ninterface ComplexSelectorCapable {\n complexSelectors(): readonly string[];\n}\n\nfunction hasComplexSelectors(r: StyleResolver): r is StyleResolver & ComplexSelectorCapable {\n return typeof (r as Partial<ComplexSelectorCapable>).complexSelectors === 'function';\n}\n\n/**\n * Build a real {@link SelectorIndex} from the active resolver.\n *\n * For a resolver that reports project COMPLEX selectors — anything with a combinator (`>`/`+`/`~`/\n * descendant) or a structural pseudo, i.e. the custom-CSS resolver — every element whose static class\n * participates in such a selector is flagged so the flatten/compress guards (`targetedByCombinator` /\n * `affectsSelectorMatching`) fire and a wrapper a selector depends on is NOT flattened. An element is\n * combinator-coupled when one of its classes is used as a descendant/child ancestor, as a sibling\n * subject, or as a `:has()` argument; structural-coupled when used in `:nth-child(...)` etc.\n *\n * For a combinator-free resolver (Tailwind utilities — no `complexSelectors()`), this degrades to the\n * null index so behaviour is unchanged.\n */\nexport function buildSelectorIndex(doc: IRDocument, resolver: StyleResolver): SelectorIndex {\n if (!hasComplexSelectors(resolver) || resolver.complexSelectors().length === 0) {\n return createNullSelectorIndex();\n }\n\n const combinator = new Set<IRNodeId>();\n const structural = new Set<IRNodeId>();\n\n for (const id of elementIds(doc)) {\n const el = getElement(doc, id);\n if (!el) continue;\n for (const seg of el.classes.segments) {\n if (seg.kind !== 'static') continue;\n for (const t of seg.tokens) {\n const u = resolver.selectorUsage(t.value);\n // Combinator coupling: descendant/child ancestor, sibling subject, or `:has()` argument —\n // reparenting/removing the element would change a combinator match-set.\n if (u.asAncestor || u.asSibling || u.asHasArgument) combinator.add(id);\n if (u.asStructural) structural.add(id);\n }\n }\n }\n\n // reparentImpact(id): non-empty when removing/unwrapping `id` would change a combinator/structural\n // match-set — `id` itself is coupled (its own match), or it is the matched ancestor of a child\n // (removing it reparents that child out of the relation). Self + element children is conservative\n // and sufficient for the flatten guard.\n const impact = new Map<IRNodeId, Set<IRNodeId>>();\n for (const id of elementIds(doc)) {\n const el = getElement(doc, id);\n if (!el) continue;\n if (!combinator.has(id) && !structural.has(id)) continue;\n const set = new Set<IRNodeId>([id]);\n for (const c of el.children) {\n const cn = doc.nodes.get(c);\n if (cn && cn.kind === 'element') set.add(c);\n }\n impact.set(id, set);\n }\n\n const empty: ReadonlySet<IRNodeId> = new Set();\n return {\n targetedByCombinator: (id: IRNodeId): boolean => combinator.has(id),\n targetedByStructuralPseudo: (id: IRNodeId): boolean => structural.has(id),\n reparentImpact: (id: IRNodeId): ReadonlySet<IRNodeId> => impact.get(id) ?? empty,\n };\n}\n\n/* ───────────────────────── rewrite factory (emits origin-free drafts) ───────────────────────── */\n\n/** Every {@link NodeLike}/{@link ElementLike} carries a readonly `id`. */\nfunction idOf(n: ElementLike | NodeLike): IRNodeId {\n return (n as IRElement).id;\n}\n\n/** The pattern-kit factory: produces op DRAFTS and detached NodeSpecs without any allocation. */\nexport function createRewriteFactory(): RewriteFactory {\n return {\n unwrap(target: ElementLike): RewriteOpDraft {\n return { op: 'unwrap', target: idOf(target) };\n },\n removeNode(target: NodeLike): RewriteOpDraft {\n return { op: 'removeNode', target: idOf(target) };\n },\n replaceWith(target: NodeLike, replacement: NodeSpec): RewriteOpDraft {\n return { op: 'replaceWith', target: idOf(target), replacement };\n },\n wrap(target: NodeLike, wrapper: ElementSpec): RewriteOpDraft {\n return { op: 'wrap', target: idOf(target), wrapper };\n },\n insertBefore(anchor: NodeLike, node: NodeSpec): RewriteOpDraft {\n return { op: 'insertBefore', anchor: idOf(anchor), node };\n },\n insertAfter(anchor: NodeLike, node: NodeSpec): RewriteOpDraft {\n return { op: 'insertAfter', anchor: idOf(anchor), node };\n },\n moveNode(target: NodeLike, newParent: ElementLike, index: number): RewriteOpDraft {\n return { op: 'moveNode', target: idOf(target), newParent: idOf(newParent), index };\n },\n mergeSiblings(first: NodeLike, second: NodeLike): RewriteOpDraft {\n return { op: 'mergeSiblings', first: idOf(first), second: idOf(second) };\n },\n setClassList(target: ElementLike, style: StyleMap, preserveOpaque = true): RewriteOpDraft {\n return { op: 'setClassList', target: idOf(target), style, preserveOpaque };\n },\n mergeStyle(\n target: ElementLike,\n source: ElementLike | null,\n style: StyleMap,\n onConflict: StyleConflictPolicy = 'abort',\n ): RewriteOpDraft {\n return {\n op: 'mergeStyle',\n target: idOf(target),\n source: source ? idOf(source) : null,\n style,\n onConflict,\n };\n },\n foldInheritedStyles(\n from: ElementLike,\n into: ElementLike | readonly ElementLike[],\n opts?: { only?: readonly import('./types').CssProperty[]; conditions?: 'base' | 'all' },\n ): RewriteOpDraft {\n const list: readonly ElementLike[] = Array.isArray(into)\n ? (into as readonly ElementLike[])\n : [into as ElementLike];\n return {\n op: 'foldInheritedStyles',\n from: idOf(from),\n into: list.map((t) => idOf(t)),\n properties: opts?.only ?? 'all-inherited',\n conditions: opts?.conditions ?? 'base',\n };\n },\n element(spec: ElementSpec): NodeSpec {\n return spec;\n },\n text(value: string): NodeSpec {\n return { kind: 'text', value };\n },\n keep(node: NodeLike): NodeSpec {\n return { kind: 'ref', ref: idOf(node) };\n },\n };\n}\n\n/* ───────────────────────── match context ───────────────────────── */\n\nfunction ro<T>(v: T): DeepReadonly<T> {\n return v as DeepReadonly<T>;\n}\n\n/** Build the read-only {@link MatchContext} a pattern's `evaluate` receives for one element. */\nexport function buildMatchContext(\n doc: IRDocument,\n elementId: IRNodeId,\n resolver: StyleResolver,\n selectors: SelectorIndex,\n safety: import('./types').SafetyLevel,\n phase: PassPhase,\n iteration: number,\n): MatchContext {\n const self = getElement(doc, elementId)!;\n\n const parentEl = (): DeepReadonly<IRElement> | null => {\n if (self.parent == null) return null;\n const p = doc.nodes.get(self.parent);\n return p && p.kind === 'element' ? ro(p) : null;\n };\n\n const elementChildren = (): readonly DeepReadonly<IRElement>[] => {\n const out: DeepReadonly<IRElement>[] = [];\n for (const c of self.children) {\n const cn = doc.nodes.get(c);\n if (cn && cn.kind === 'element') out.push(ro(cn));\n }\n return out;\n };\n\n const ancestors = (): readonly DeepReadonly<IRElement>[] => {\n const out: DeepReadonly<IRElement>[] = [];\n let cur: IRNodeId | null = self.parent;\n while (cur != null) {\n const n: IRNode | undefined = doc.nodes.get(cur);\n if (!n) break;\n if (n.kind === 'element') out.push(ro(n));\n cur = n.parent;\n }\n return out;\n };\n\n const siblingAt = (delta: number): DeepReadonly<IRNode> | null => {\n if (self.parent == null) return null;\n const p = doc.nodes.get(self.parent);\n if (!p || (p.kind !== 'element' && p.kind !== 'fragment')) return null;\n const i = p.children.indexOf(elementId);\n const sib = p.children[i + delta];\n if (sib == null) return null;\n const sn = doc.nodes.get(sib);\n return sn ? ro(sn) : null;\n };\n\n const computedOf = (n: NodeLike): StyleMap => {\n const node = doc.nodes.get((n as IRNode).id);\n return node && node.kind === 'element' ? node.computed : emptyStyleMap();\n };\n\n return {\n node: ro(self),\n doc: ro(doc),\n resolver,\n selectors,\n safety,\n phase,\n iteration,\n parent: parentEl,\n elementChildren,\n onlyElementChild(): DeepReadonly<IRElement> | null {\n const els = elementChildren();\n return els.length === 1 ? els[0]! : null;\n },\n computed(): StyleMap {\n return self.computed;\n },\n computedOf,\n isOpaque(n?: ElementLike): boolean {\n const target = n ? doc.nodes.get((n as IRElement).id) : self;\n if (!target || target.kind !== 'element') return true;\n return target.classes.opaque || target.meta.hasSpreadAttrs;\n },\n ancestors,\n closest(pred): DeepReadonly<IRElement> | null {\n for (const a of ancestors()) if (pred(a)) return a;\n return null;\n },\n prevSibling(): DeepReadonly<IRNode> | null {\n return siblingAt(-1);\n },\n nextSibling(): DeepReadonly<IRNode> | null {\n return siblingAt(1);\n },\n nthChildIndex(): number {\n if (self.parent == null) return 1;\n const p = doc.nodes.get(self.parent);\n if (!p || (p.kind !== 'element' && p.kind !== 'fragment')) return 1;\n let idx = 0;\n for (const c of p.children) {\n const cn = doc.nodes.get(c);\n if (cn && cn.kind === 'element') {\n idx += 1;\n if (c === elementId) return idx;\n }\n }\n return idx;\n },\n };\n}\n","/**\n * @domflax/core — static classification of a flatten (the VERIFIER-GATED safety core).\n *\n * A flatten pattern matches on `paintsNothing` + a structural/style signature, but unwrapping a\n * wrapper can still change rendering: a wrapper with non-paint layout styles (e.g. `px-4 py-4`) drops\n * that padding when removed (it is NOT reproduced on the surviving child), and a centering wrapper\n * collapsed to `place-self:center` only stays centered when the child's NEW parent is flex/grid. The\n * existing emittability revert only checks the ADDED style is re-emittable — not that the wrapper's\n * own styles survive, nor that the parent context holds.\n *\n * {@link classifyFlattenOps} answers, for one applied flatten op-group, whether it is:\n *\n * • `'provably-safe'` — removing the wrapper changes NOTHING renderable: the wrapper\n * establishes no box/formatting/stacking context, has no non-inherited\n * own declaration that the rewrite does not reproduce on the surviving\n * child, AND the rewrite adds no parent-context-dependent self-alignment\n * (unless the new parent is statically flex/grid). Examples: passthrough\n * / empty-style / display-contents / redundant-fragment wrappers.\n * • `'needs-verification'` — anything else (drops/relies on a style, or centering→place-self).\n *\n * Pure + dependency-free: only the `./types` contract + `./builders` accessors.\n */\n\nimport { conditionKey, getElement } from './builders';\nimport type {\n CssProperty,\n IRDocument,\n IRElement,\n IRNodeId,\n RewriteOp,\n StyleDecl,\n StyleMap,\n StyleNormalizer,\n} from './types';\n\n/** The static verdict for one flatten op-group. */\nexport type FlattenClass = 'provably-safe' | 'needs-verification';\n\n/** A classified flatten plus the structural anchors a verifier needs to render before/after. */\nexport interface FlattenClassification {\n readonly kind: FlattenClass;\n /** The unwrapped wrapper (in the BEFORE doc), or null when the group removes no element box. */\n readonly wrapperId: IRNodeId | null;\n /** The surviving child styles fold onto (the AFTER subtree root), or null. */\n readonly childId: IRNodeId | null;\n}\n\n/* ───────────────────────── display / context reasoning ───────────────────────── */\n\nconst DISPLAY = 'display' as CssProperty;\nconst POSITION = 'position' as CssProperty;\nconst TRANSFORM = 'transform' as CssProperty;\n\n/** Displays that generate no independent formatting context for the wrapper's children. */\nconst CONTEXT_SAFE_DISPLAYS: ReadonlySet<string> = new Set(['block', 'contents', '']);\n/** `position` values that neither establish a containing block nor offset the element. */\nconst STATIC_POSITIONS: ReadonlySet<string> = new Set(['static', '']);\n\n/** Self-alignment properties whose effect depends on the parent being a flex/grid container. */\nconst SELF_ALIGN_PROPS: readonly CssProperty[] = [\n 'place-self' as CssProperty,\n 'align-self' as CssProperty,\n 'justify-self' as CssProperty,\n];\n/** Self-alignment values that are no-ops (so adding them assumes nothing about the parent). */\nconst NEUTRAL_ALIGN: ReadonlySet<string> = new Set(['auto', 'normal', 'auto auto', '']);\n/** Parent displays under which `place-self`/`*-self` centering actually takes effect. */\nconst FLEX_GRID_DISPLAYS: ReadonlySet<string> = new Set(['flex', 'inline-flex', 'grid', 'inline-grid']);\n\n/**\n * True when the wrapper establishes a box/formatting/stacking context that positions or sizes its\n * children — so removing its box could move/resize the surviving child. Derived from the COMPUTED\n * style (the frontend leaves the `meta.establishes*` flags unset for class-resolved styles), exactly\n * how `hasOwnVisualStyle` reasons over the computed map.\n */\nfunction establishesChildContext(sm: StyleMap): boolean {\n for (const block of sm.blocks.values()) {\n const display = block.decls.get(DISPLAY);\n if (display && !CONTEXT_SAFE_DISPLAYS.has(String(display.value))) return true;\n const position = block.decls.get(POSITION);\n if (position && !STATIC_POSITIONS.has(String(position.value))) return true;\n const transform = block.decls.get(TRANSFORM);\n if (transform && String(transform.value) !== 'none') return true;\n }\n return false;\n}\n\n/* ───────────────────────── declaration reasoning ───────────────────────── */\n\nfunction isInherited(decl: StyleDecl, norm: StyleNormalizer): boolean {\n if (decl.inherited) return true;\n try {\n return norm.inherited.isInherited(decl.property);\n } catch {\n return false;\n }\n}\n\n/** True when the child reproduces this exact declaration (same property + value) in the same condition. */\nfunction childReproduces(\n childComputed: StyleMap | null,\n conditionK: string,\n prop: CssProperty,\n value: string,\n): boolean {\n if (!childComputed) return false;\n const block = childComputed.blocks.get(conditionK as never);\n if (!block) return false;\n const d = block.decls.get(prop);\n return d != null && String(d.value) === value;\n}\n\n/**\n * True when the wrapper carries a non-inherited declaration that is NOT reproduced on the surviving\n * child — i.e. flattening would DROP a renderable style. `display`/`position`/`transform` are skipped\n * because {@link establishesChildContext} already governs them (and when it passed they are no-ops).\n */\nfunction dropsOwnStyle(\n wrapperComputed: StyleMap,\n childComputed: StyleMap | null,\n norm: StyleNormalizer,\n): boolean {\n for (const block of wrapperComputed.blocks.values()) {\n const ck = conditionKey(block.condition);\n for (const [prop, decl] of block.decls) {\n if (prop === DISPLAY || prop === POSITION || prop === TRANSFORM) continue;\n if (isInherited(decl, norm)) continue; // folded onto the child by foldInheritedStyles\n if (!childReproduces(childComputed, ck, prop, String(decl.value))) return true;\n }\n }\n return false;\n}\n\n/* ───────────────────────── parent-context reasoning ───────────────────────── */\n\n/** The element's base-condition `display` value (normalized), or '' when unset/not an element. */\nfunction displayOf(el: IRElement | undefined, norm: StyleNormalizer): string {\n if (!el) return '';\n for (const block of norm.normalizeStyleMap(el.computed).blocks.values()) {\n if (block.condition.media === '' && block.condition.states.length === 0 && block.condition.pseudoElement === '') {\n const d = block.decls.get(DISPLAY);\n if (d) return String(d.value);\n }\n }\n return '';\n}\n\n/** True when unwrapping `wrapper` reparents the child UNDER a flex/grid container in the before-tree. */\nfunction newParentIsFlexOrGrid(before: IRDocument, wrapper: IRElement, norm: StyleNormalizer): boolean {\n if (wrapper.parent == null) return false;\n const p = before.nodes.get(wrapper.parent);\n if (!p || p.kind !== 'element') return false;\n return FLEX_GRID_DISPLAYS.has(displayOf(p, norm));\n}\n\n/**\n * True when the rewrite GRANTS the child a parent-context-dependent self-alignment (place-self /\n * align-self / justify-self with a non-neutral value) that was not already on it — centering that only\n * holds if the new parent is flex/grid.\n */\nfunction addsParentContextStyle(\n childBefore: StyleMap | null,\n childAfter: StyleMap | null,\n norm: StyleNormalizer,\n): boolean {\n if (!childAfter) return false;\n const before = childBefore ? norm.normalizeStyleMap(childBefore) : null;\n const after = norm.normalizeStyleMap(childAfter);\n for (const block of after.blocks.values()) {\n const ck = conditionKey(block.condition);\n for (const prop of SELF_ALIGN_PROPS) {\n const d = block.decls.get(prop);\n if (!d || NEUTRAL_ALIGN.has(String(d.value))) continue;\n const prev = before?.blocks.get(ck as never)?.decls.get(prop);\n if (!prev || String(prev.value) !== String(d.value)) return true;\n }\n }\n return false;\n}\n\n/* ───────────────────────── op-group anchors ───────────────────────── */\n\n/** The wrapper the group unwraps (the structural removal), or null when the group removes no box. */\nfunction unwrapTargetOf(ops: readonly RewriteOp[]): IRNodeId | null {\n for (const op of ops) if (op.op === 'unwrap') return op.target;\n return null;\n}\n\n/** The surviving child styles fold onto: the mergeStyle/fold target, else the wrapper's sole element child. */\nfunction survivingChildOf(ops: readonly RewriteOp[], wrapper: IRElement, before: IRDocument): IRNodeId | null {\n for (const op of ops) if (op.op === 'mergeStyle') return op.target;\n for (const op of ops) if (op.op === 'foldInheritedStyles' && op.into.length > 0) return op.into[0]!;\n for (const c of wrapper.children) {\n const n = before.nodes.get(c);\n if (n && n.kind === 'element') return c;\n }\n return null;\n}\n\n/* ───────────────────────── the classifier ───────────────────────── */\n\n/**\n * Statically classify one applied flatten op-group. `before` is the doc as it was BEFORE the group's\n * ops; `after` is the result of applying them.\n *\n * A group that unwraps no element box (e.g. {@link redundant-fragment}, or a style-only flatten) is\n * `provably-safe` — there is no box whose removal could move/resize anything. Otherwise the three\n * criteria above decide.\n */\nexport function classifyFlattenOps(\n before: IRDocument,\n after: IRDocument,\n ops: readonly RewriteOp[],\n norm: StyleNormalizer,\n): FlattenClassification {\n const wrapperId = unwrapTargetOf(ops);\n if (wrapperId == null) return { kind: 'provably-safe', wrapperId: null, childId: null };\n\n const wrapper = before.nodes.get(wrapperId);\n // A fragment carries no box and no computed style — unwrapping it is always layout-identical.\n if (!wrapper || wrapper.kind !== 'element') {\n return { kind: 'provably-safe', wrapperId: null, childId: null };\n }\n\n const childId = survivingChildOf(ops, wrapper, before);\n const wrapperComputed = norm.normalizeStyleMap(wrapper.computed);\n const childAfter = childId != null ? getElement(after, childId)?.computed ?? null : null;\n const childBefore = childId != null ? getElement(before, childId)?.computed ?? null : null;\n\n // (A) wrapper positions/sizes its children → removing its box can move/resize them.\n if (establishesChildContext(wrapperComputed)) {\n return { kind: 'needs-verification', wrapperId, childId };\n }\n // (B) wrapper drops a non-inherited own style the child does not reproduce.\n if (dropsOwnStyle(wrapperComputed, childAfter ? norm.normalizeStyleMap(childAfter) : null, norm)) {\n return { kind: 'needs-verification', wrapperId, childId };\n }\n // (C) rewrite adds parent-context-dependent centering, but the new parent is not statically flex/grid.\n if (addsParentContextStyle(childBefore, childAfter, norm) && !newParentIsFlexOrGrid(before, wrapper, norm)) {\n return { kind: 'needs-verification', wrapperId, childId };\n }\n\n return { kind: 'provably-safe', wrapperId, childId };\n}\n","/**\n * @domflax/core — pass manager (the sync, static flatten driver).\n *\n * Runs {@link Pattern}s grouped by {@link PassPhase} in declared order, driving the `flatten` phase to\n * a fixpoint under a max-iteration budget, isolating per-node pattern errors into {@link Diagnostic}s\n * (a thrown pattern never aborts the run — it becomes `DF_PATTERN_THREW`), and applying the static\n * flatten policy ({@link ApplyContext.gate}) — under `'provably-safe'` only provably layout-neutral\n * flattens commit, so the transform never changes rendering and never launches a browser.\n *\n * The supporting contexts (resolvers, selector index, rewrite factory, match context) live in\n * `./pass-context`; the static flatten classifier in `./flatten-safety`. Dependency-free: only the\n * `./types` contract + sibling runtime helpers.\n */\n\nimport type {\n ApplyContext,\n Diagnostic,\n FixpointConfig,\n HaltReason,\n IRDocument,\n IRNodeId,\n Pass,\n PassManager,\n PassPhase,\n Pattern,\n PhaseRunResult,\n RewriteFactory,\n RewriteOp,\n RewriteOpDraft,\n StyleMap,\n StyleNormalizer,\n StyleResolver,\n SyntheticSink,\n EmitContext,\n} from './types';\n\nimport { childIds, elementIds, getElement } from './builders';\nimport { applyOps } from './ops';\nimport { buildMatchContext, createRewriteFactory } from './pass-context';\nimport { classifyFlattenOps } from './flatten-safety';\n\n// Re-export the supporting contexts so `@domflax/core` consumers keep importing them from here / the\n// barrel exactly as before this module was split.\nexport {\n buildMatchContext,\n buildSelectorIndex,\n createNullResolver,\n createNullSelectorIndex,\n createRewriteFactory,\n} from './pass-context';\n\n/* ───────────────────────── defaults ───────────────────────── */\n\nexport const DEFAULT_FIXPOINT: FixpointConfig = {\n maxIterations: 16,\n phases: { flatten: 16, compress: 8, extract: 4 },\n onBudgetExhausted: 'warn',\n detectOscillation: true,\n};\n\nexport const PHASE_ORDER: readonly PassPhase[] = ['flatten', 'compress', 'extract'];\n\n/* ───────────────────────── op stamping + phase grouping ───────────────────────── */\n\nexport function stampOrigin(draft: RewriteOpDraft, pattern: Pattern): RewriteOp {\n return {\n ...draft,\n origin: { pattern: pattern.name, category: pattern.category, safety: pattern.safety },\n } as RewriteOp;\n}\n\nexport function patternsForPhase(passes: readonly Pass[], phase: PassPhase): Pattern[] {\n const out: Pattern[] = [];\n for (const pass of passes) {\n if (pass.phase !== phase) continue;\n for (const p of pass.patterns) out.push(p);\n }\n out.sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0));\n return out;\n}\n\nexport interface RunState {\n doc: IRDocument;\n}\n\n/* ───────────────────────── flatten residual-skip (never drop an unreproducible style) ───────────────────────── */\n\n/** A throwaway {@link SyntheticSink} for the emit exactness probe (registrations are discarded). */\nfunction probeSink(): SyntheticSink {\n return {\n register(s): string {\n return s.className;\n },\n drain(): readonly never[] {\n return [];\n },\n };\n}\n\n/** Nodes a group writes STYLE onto (the survivors a flatten transfers declarations to). */\nfunction styleWriteTargets(ops: readonly RewriteOp[]): IRNodeId[] {\n const ids: IRNodeId[] = [];\n for (const op of ops) {\n if (op.op === 'mergeStyle' || op.op === 'setClassList') ids.push(op.target);\n else if (op.op === 'foldInheritedStyles') ids.push(...op.into);\n }\n return ids;\n}\n\n/** True iff the resolver can EXACTLY reverse-emit `sm` (no residual). An empty map is trivially exact. */\nfunction emitIsExact(resolver: StyleResolver, normalizer: StyleNormalizer, sm: StyleMap): boolean {\n if (sm.blocks.size === 0) return true;\n try {\n const ctx: EmitContext = { normalizer, sink: probeSink() };\n const r = resolver.emit(sm, ctx);\n return r.exact && r.residual == null;\n } catch {\n return true; // a throwing resolver must never block a flatten\n }\n}\n\n/**\n * T5 — flatten must never DROP a style it can't reproduce. After a flatten transfers declarations onto\n * a surviving (rewritable) element, if the resolver can no longer EXACTLY reverse-emit that element's\n * computed style — and it could before — the flatten would silently lose the residual declarations\n * during reverse-emit, so the whole flatten is reverted (the wrapper is kept). Pre-existing residue\n * (already non-exact before the flatten) is not blamed on the flatten and does not trigger a revert.\n */\nexport function flattenWouldDropStyle(\n before: IRDocument,\n after: IRDocument,\n ops: readonly RewriteOp[],\n resolver: StyleResolver,\n normalizer: StyleNormalizer,\n): boolean {\n for (const id of styleWriteTargets(ops)) {\n const newEl = getElement(after, id);\n if (!newEl) continue; // target was itself removed — its style lives on the survivor we also check\n // Opaque / dynamic class lists are kept verbatim by reverse-emit, so no style is dropped there.\n if (newEl.classes.opaque || newEl.classes.hasDynamic) continue;\n if (emitIsExact(resolver, normalizer, newEl.computed)) continue;\n const oldEl = getElement(before, id);\n const wasExact = !oldEl || emitIsExact(resolver, normalizer, oldEl.computed);\n if (wasExact) return true; // the flatten introduced an unreproducible style → revert\n }\n return false;\n}\n\n/* ───────────────────────── flatten gate decision (shared sync core) ───────────────────────── */\n\nexport type FlattenVerdict = 'commit' | 'revert';\n\n/**\n * Decide what to do with a freshly-applied flatten op-group, given the gate. Returns:\n * • `'commit'` — keep the outcome (the historical path for `'all'`, and provably-safe flattens).\n * • `'revert'` — discard + bar the node (residual-drop, or a needs-verification flatten under the\n * `'provably-safe'` gate).\n *\n * `before`/`after` are the docs immediately around the group's application.\n */\nexport function flattenVerdict(\n before: IRDocument,\n after: IRDocument,\n ops: readonly RewriteOp[],\n ctx: ApplyContext,\n): FlattenVerdict {\n // T5 (independent of the gate): a flatten must never drop a style the resolver can't re-emit.\n if (flattenWouldDropStyle(before, after, ops, ctx.resolver, ctx.normalizer)) return 'revert';\n\n const gate = ctx.gate ?? 'all';\n if (gate === 'all') return 'commit';\n\n const cls = classifyFlattenOps(before, after, ops, ctx.normalizer);\n return cls.kind === 'provably-safe' ? 'commit' : 'revert';\n}\n\n/* ───────────────────────── per-element pattern evaluation (shared) ───────────────────────── */\n\n/**\n * Evaluate every pattern against `elId` until one produces ops; returns the stamped op list (and its\n * pattern), or null when no pattern matched. Pattern throws become `DF_PATTERN_THREW` diagnostics.\n */\nexport function evaluateElement(\n doc: IRDocument,\n elId: IRNodeId,\n patterns: readonly Pattern[],\n ctx: ApplyContext,\n factory: RewriteFactory,\n phase: PassPhase,\n iteration: number,\n diagnostics: Diagnostic[],\n): { ops: RewriteOp[]; pattern: Pattern } | null {\n for (const pattern of patterns) {\n if (pattern.safety > ctx.safetyCeiling) continue;\n let drafts: readonly RewriteOpDraft[] = [];\n try {\n const mctx = buildMatchContext(doc, elId, ctx.resolver, ctx.selectors, ctx.safetyCeiling, phase, iteration);\n const result = pattern.evaluate(mctx, factory);\n if (!result) continue;\n drafts = result.ops;\n if (result.diagnostics) for (const d of result.diagnostics) diagnostics.push(d);\n } catch (err) {\n diagnostics.push({\n code: 'DF_PATTERN_THREW',\n severity: 'error',\n message: `pattern '${pattern.name}' threw: ${String((err as Error)?.message ?? err)}`,\n nodeId: elId,\n pattern: pattern.name,\n phase,\n iteration,\n cause: err,\n });\n continue;\n }\n if (drafts.length === 0) continue;\n return { ops: drafts.map((d) => stampOrigin(d, pattern)), pattern };\n }\n return null;\n}\n\n/** Emit the diagnostic recorded when a flatten is reverted by the gate / residual guard. */\nexport function revertDiagnostic(\n pattern: Pattern,\n elId: IRNodeId,\n phase: PassPhase,\n iteration: number,\n resolverId: string,\n): Diagnostic {\n return {\n code: 'DF_VERIFY_REVERTED',\n severity: 'warn',\n message:\n `flatten '${pattern.name}' reverted on node ${elId}: it would change rendering (drops a style, ` +\n `establishes layout context, or assumes a parent context) and was not proven safe by resolver ` +\n `'${resolverId}'`,\n nodeId: elId,\n pattern: pattern.name,\n phase,\n iteration,\n };\n}\n\n/* ───────────────────────── one sweep (sync) ───────────────────────── */\n\n/**\n * One sweep of a phase: evaluate every pattern against every live element, collect op drafts, stamp\n * origin, apply, then commit/revert per {@link flattenVerdict}. Returns the number of ops applied\n * (0 ⇒ fixpoint for this phase). Under the `'provably-safe'` gate, any flatten that is not provably\n * safe is reverted — the transform is fully static and never changes rendering.\n */\nfunction runSweep(\n state: RunState,\n patterns: readonly Pattern[],\n ctx: ApplyContext,\n factory: RewriteFactory,\n phase: PassPhase,\n iteration: number,\n touched: Set<IRNodeId>,\n diagnostics: Diagnostic[],\n flattenBarred: Set<IRNodeId>,\n): number {\n let appliedOps = 0;\n\n for (const elId of elementIds(state.doc)) {\n const el = getElement(state.doc, elId);\n if (!el) continue; // removed earlier in this sweep\n if (phase === 'flatten' && flattenBarred.has(elId)) continue;\n\n const evaluated = evaluateElement(state.doc, elId, patterns, ctx, factory, phase, iteration, diagnostics);\n if (!evaluated) continue;\n const { ops, pattern } = evaluated;\n\n const outcome = applyOps(state.doc, ops, ctx);\n for (const d of outcome.result.diagnostics) diagnostics.push(d);\n if (outcome.result.appliedGroups === 0) continue;\n\n if (phase === 'flatten') {\n const verdict = flattenVerdict(state.doc, outcome.doc, ops, ctx);\n if (verdict !== 'commit') {\n // Discard the outcome (keep the wrapper) AND bar this node from any further flatten this run.\n diagnostics.push(revertDiagnostic(pattern, elId, phase, iteration, ctx.resolver.id));\n flattenBarred.add(elId);\n continue;\n }\n }\n\n state.doc = outcome.doc;\n appliedOps += outcome.result.appliedGroups;\n for (const id of outcome.result.touched) touched.add(id);\n for (const id of outcome.result.created) touched.add(id);\n }\n return appliedOps;\n}\n\n/* ───────────────────────── oscillation fingerprint ───────────────────────── */\n\n/** Cheap structural fingerprint of the document for oscillation detection. */\nexport function docFingerprint(doc: IRDocument): string {\n const parts: string[] = [];\n const visit = (id: IRNodeId): void => {\n const n = doc.nodes.get(id);\n if (!n) return;\n parts.push(`${id}:${n.kind}`);\n for (const c of childIds(n)) visit(c);\n };\n visit(doc.root);\n return parts.join('|');\n}\n\n/* ───────────────────────── the fixpoint driver (sync) ───────────────────────── */\n\n/** A single phase's terminal result, built from the loop's accounting. */\nexport interface PhaseLoopState {\n iterations: number;\n converged: boolean;\n haltReason: HaltReason;\n readonly touched: Set<IRNodeId>;\n readonly diagnostics: Diagnostic[];\n readonly seen: Set<string>;\n}\n\n/** Record the budget-exhausted diagnostic + finalize a phase result. Shared by sync + async drivers. */\nexport function finalizePhase(\n phase: PassPhase,\n s: PhaseLoopState,\n budget: number,\n onBudgetExhausted: 'warn' | 'error',\n): PhaseRunResult {\n if (!s.converged && s.haltReason !== 'oscillation') {\n s.haltReason = 'budget';\n s.diagnostics.push({\n code: 'DF_FIXPOINT_BUDGET',\n severity: onBudgetExhausted === 'error' ? 'error' : 'warn',\n message: `phase '${phase}' exhausted ${budget}-iteration budget`,\n phase,\n iteration: s.iterations,\n });\n }\n return {\n phase,\n iterations: s.iterations,\n converged: s.converged,\n haltReason: s.haltReason,\n touched: s.touched,\n diagnostics: s.diagnostics,\n };\n}\n\n/**\n * Runs `passes` over `doc` to a per-phase fixpoint (synchronous). This is the concrete entry the\n * pipeline calls. Under the `'provably-safe'` gate, flattens that are not provably layout-neutral are\n * reverted — the transform is fully static and never changes rendering.\n */\nexport function runPasses(\n doc: IRDocument,\n passes: readonly Pass[],\n ctx: ApplyContext,\n config?: FixpointConfig,\n): { readonly doc: IRDocument; readonly results: readonly PhaseRunResult[] } {\n const cfg: FixpointConfig = { ...DEFAULT_FIXPOINT, ...config };\n const factory = createRewriteFactory();\n const state: RunState = { doc };\n const results: PhaseRunResult[] = [];\n // Nodes barred from flattening after a revert — persists across sweeps/phases.\n const flattenBarred = new Set<IRNodeId>();\n\n for (const phase of PHASE_ORDER) {\n const patterns = patternsForPhase(passes, phase);\n const budget = cfg.phases[phase] ?? cfg.maxIterations;\n const s: PhaseLoopState = {\n iterations: 0,\n converged: false,\n haltReason: 'converged',\n touched: new Set(),\n diagnostics: [],\n seen: new Set(),\n };\n\n if (patterns.length === 0) {\n s.converged = true;\n results.push(finalizePhase(phase, s, budget, cfg.onBudgetExhausted));\n continue;\n }\n\n while (s.iterations < budget) {\n s.iterations += 1;\n const applied = runSweep(\n state,\n patterns,\n ctx,\n factory,\n phase,\n s.iterations,\n s.touched,\n s.diagnostics,\n flattenBarred,\n );\n\n if (applied === 0) {\n s.converged = true;\n break;\n }\n\n if (cfg.detectOscillation) {\n const fp = docFingerprint(state.doc);\n if (s.seen.has(fp)) {\n s.haltReason = 'oscillation';\n s.diagnostics.push({\n code: 'DF_FIXPOINT_OSCILLATION',\n severity: 'warn',\n message: `phase '${phase}' oscillated; halting`,\n phase,\n iteration: s.iterations,\n });\n break;\n }\n s.seen.add(fp);\n }\n }\n\n results.push(finalizePhase(phase, s, budget, cfg.onBudgetExhausted));\n }\n\n return { doc: state.doc, results };\n}\n\n/** A {@link PassManager} that runs the given passes (carried on the manager instance). */\nexport function createPassManager(passes: readonly Pass[]): PassManager {\n return {\n run(doc: IRDocument, ctx: ApplyContext, config?: FixpointConfig): readonly PhaseRunResult[] {\n return runPasses(doc, passes, ctx, config).results;\n },\n };\n}\n","/**\n * @domflax/core — the pure, single-file pipeline.\n *\n * Wires injected interfaces together: {@link Frontend} → resolve → {@link PassManager} →\n * {@link Backend}. Core itself stays dependency-free; the resolver, frontend, and backend are all\n * supplied by the caller, so no heavy third-party libs ever reach this package.\n */\n\nimport type {\n ApplyContext,\n Backend,\n BackendContext,\n CodegenResult,\n Diagnostic,\n EditPlan,\n Frontend,\n FrontendParseContext,\n IRDocument,\n IRElement,\n PassPhase,\n Pipeline,\n PipelineInput,\n PipelineOutput,\n PipelineStats,\n SourceSpan,\n StyleMap,\n SyntheticClass,\n SyntheticSink,\n} from './types';\n\nimport { elementIds, getElement } from './builders';\nimport { createNullSelectorIndex, runPasses } from './pass-manager';\n\n/* ───────────────────────── synthetic sink ───────────────────────── */\n\n/** A minimal in-memory {@link SyntheticSink}: dedupes by className, drains in insertion order. */\nexport function createSyntheticSink(): SyntheticSink {\n const map = new Map<string, SyntheticClass>();\n return {\n register(s: SyntheticClass): string {\n if (!map.has(s.className)) map.set(s.className, s);\n return s.className;\n },\n drain(): readonly SyntheticClass[] {\n return [...map.values()];\n },\n };\n}\n\n/* ───────────────────────── resolve step ───────────────────────── */\n\nfunction staticClassTokens(el: IRElement): string[] {\n const out: string[] = [];\n for (const seg of el.classes.segments) {\n if (seg.kind === 'static') for (const t of seg.tokens) out.push(t.value);\n }\n return out;\n}\n\n/**\n * Populate each element's `computed` StyleMap from its author classes via the injected resolver.\n * Opaque/spread elements and elements without static classes are left untouched. Resolver throws\n * are isolated into diagnostics (a stub resolver may legitimately be NotImplemented).\n */\nfunction resolveStyles(\n doc: IRDocument,\n input: PipelineInput,\n diagnostics: Diagnostic[],\n): void {\n const { resolver, normalizer } = input;\n for (const id of elementIds(doc)) {\n const el = getElement(doc, id);\n if (!el || el.classes.opaque) continue;\n const tokens = staticClassTokens(el);\n if (tokens.length === 0) continue;\n try {\n const result = resolver.resolve({\n classes: tokens,\n element: {\n tagName: el.tag,\n namespace: el.namespace === 'svg' ? 'svg' : 'html',\n },\n });\n let styles: StyleMap = result.styles;\n try {\n styles = normalizer.normalizeStyleMap(styles);\n } catch {\n /* normalizer is optional/stubbed — keep raw styles */\n }\n el.computed = styles;\n for (const w of result.warnings) {\n diagnostics.push({\n code: 'DF_STYLE_CONFLICT_UNRESOLVED',\n severity: w.severity,\n message: w.message,\n nodeId: id,\n });\n }\n } catch (err) {\n diagnostics.push({\n code: 'DF_OP_PRECONDITION_FAILED',\n severity: 'debug',\n message: `resolve skipped for <${el.tag}>: ${String((err as Error)?.message ?? err)}`,\n nodeId: id,\n cause: err,\n });\n }\n }\n}\n\n/* ───────────────────────── the pipeline ───────────────────────── */\n\nconst ZERO_ITERATIONS: Readonly<Record<PassPhase, number>> = {\n flatten: 0,\n compress: 0,\n extract: 0,\n};\n\nclass DefaultPipeline implements Pipeline {\n run(input: PipelineInput): PipelineOutput {\n const startedAt = now();\n const diagnostics: Diagnostic[] = [];\n const report = (d: Diagnostic): void => {\n diagnostics.push(d);\n input.reporter?.report(d);\n };\n\n // 1. PARSE ────────────────────────────────────────────────────────────\n const parseCtx: FrontendParseContext = {\n id: input.id,\n kind: input.kind,\n resolver: input.resolver,\n normalizer: input.normalizer,\n config: { preserveComments: input.config?.preserveComments ?? true },\n onDiagnostic: report,\n };\n if (input.babelAst !== undefined) parseCtx.babelAst = input.babelAst;\n\n const parsed = input.frontend.parse(input.code, parseCtx);\n for (const d of parsed.diagnostics) report(d);\n const doc = parsed.doc;\n const nodesIn = doc.nodes.size;\n\n // 2. RESOLVE ──────────────────────────────────────────────────────────\n resolveStyles(doc, input, diagnostics);\n\n // 3. PASSES (fixpoint per phase) ──────────────────────────────────────\n const ctx: ApplyContext = {\n doc,\n safetyCeiling: input.config?.safety ?? 2,\n normalizer: input.normalizer,\n selectors: createNullSelectorIndex(),\n resolver: input.resolver,\n };\n const { doc: optimized, results } = runPasses(doc, input.passes, ctx, fixpointFrom(input));\n\n let opsApplied = 0;\n const iterations: Record<PassPhase, number> = { ...ZERO_ITERATIONS };\n for (const r of results) {\n iterations[r.phase] = r.iterations;\n for (const d of r.diagnostics) {\n diagnostics.push(d);\n input.reporter?.report(d);\n }\n opsApplied += r.touched.size;\n }\n\n // 4. PRINT ────────────────────────────────────────────────────────────\n const editPlan: EditPlan = {\n moduleId: input.id,\n ops: [],\n provenance: new Map(),\n };\n const backendCtx: BackendContext = {\n normalizer: input.normalizer,\n resolver: input.resolver,\n sink: createSyntheticSink(),\n eol: eolOf(optimized),\n onDiagnostic: report,\n };\n const printed: CodegenResult = input.backend.print(optimized, editPlan, backendCtx);\n for (const d of printed.diagnostics) {\n diagnostics.push(d);\n input.reporter?.report(d);\n }\n\n // 5. ASSEMBLE OUTPUT ──────────────────────────────────────────────────\n const stats: PipelineStats = {\n nodesIn,\n nodesOut: optimized.nodes.size,\n opsApplied,\n iterations,\n durationMs: now() - startedAt,\n };\n const touched: readonly SourceSpan[] = printed.edits.map((e) => e.span);\n\n return {\n code: printed.code,\n map: printed.map,\n changed: printed.code !== input.code,\n touched,\n diagnostics,\n stats,\n doc: optimized,\n editPlan,\n };\n }\n}\n\nfunction fixpointFrom(input: PipelineInput): import('./types').FixpointConfig | undefined {\n const fp = input.config?.fixpoint;\n if (!fp) return undefined;\n return {\n maxIterations: fp.maxIterations ?? 16,\n phases: fp.phases ?? {},\n onBudgetExhausted: fp.onBudgetExhausted ?? 'warn',\n detectOscillation: fp.detectOscillation ?? true,\n };\n}\n\nfunction eolOf(doc: IRDocument): '\\n' | '\\r\\n' {\n for (const src of doc.sources.values()) return src.eol;\n return '\\n';\n}\n\n// `performance` is a host global (node20 / browser) not covered by the ES2023 lib;\n// declared minimally so the runtime feature-detection below stays type-safe.\ndeclare const performance: { now(): number } | undefined;\n\nfunction now(): number {\n return typeof performance !== 'undefined' && typeof performance.now === 'function'\n ? performance.now()\n : Date.now();\n}\n\n/** Build the pure single-file {@link Pipeline}. */\nexport function createPipeline(): Pipeline {\n return new DefaultPipeline();\n}\n","/**\n * @domflax/core — the shared reverse-emit step (computed → className).\n *\n * The backend re-prints `className` from each element's {@link ClassList}, but the pass manager\n * records optimized styles on `computed`. This module folds those optimized computed styles back\n * into the element's static class tokens, and is the SINGLE source of truth shared by every\n * orchestrator (the `domflax` meta package, `@domflax/cli`, and the pattern auto-test harness) so\n * their pipelines cannot diverge.\n *\n * ## REPLACE, not append\n *\n * For every TOUCHED, rewritable (non-opaque, non-dynamic) element we ask the resolver for the\n * MINIMAL class set reproducing the element's FULL computed style (`resolver.emit(el.computed)`),\n * then REPLACE the element's static tokens with it — rather than appending. Replacing is what lets\n * a compress pass actually shorten output: `px-4 py-4` collapses to `p-4`, equal `w/h` to `size-*`,\n * the four insets to `inset-0`, and fully-overridden duplicates simply disappear.\n *\n * ## Droppability gate (never lose a load-bearing class)\n *\n * A token is only removed when `resolver.selectorUsage(token).droppable` is true — i.e. it is a\n * plain, resolver-owned utility whose entire contribution is reproducible from `computed`. Tokens\n * that are unknown to the resolver, opaque (combinator/at-rule utilities whose effect never folds\n * onto the element's own box), variant-bound, or referenced by a custom-CSS selector are NOT\n * droppable and are preserved verbatim. As a safety net, if `emit` produces nothing at all we leave\n * the element's tokens untouched (a resolver that failed to load must never erase classes).\n */\n\nimport { elementIds, getElement } from './builders';\nimport { createSyntheticSink } from './pipeline';\nimport type {\n ClassList,\n ClassSegment,\n ClassToken,\n EmitContext,\n IRDocument,\n StyleNormalizer,\n StyleResolver,\n} from './types';\n\n/** All static class tokens of a {@link ClassList}, in source order. */\nfunction staticTokensOf(cl: ClassList): string[] {\n const out: string[] = [];\n for (const seg of cl.segments) {\n if (seg.kind === 'static') for (const t of seg.tokens) out.push(t.value);\n }\n return out;\n}\n\n/** A rewritable static {@link ClassList} over `tokens`, preserving the previous list's spans. */\nfunction staticClassList(prev: ClassList, tokens: readonly string[]): ClassList {\n const classTokens: ClassToken[] = tokens.map((value) => ({ value }));\n const seg: ClassSegment = { kind: 'static', tokens: classTokens };\n return {\n form: 'string-literal',\n segments: [seg],\n valueSpan: prev.valueSpan,\n attrSpan: prev.attrSpan,\n hasDynamic: false,\n opaque: false,\n rewritable: true,\n };\n}\n\n/** Two token lists are equal iff same length and same tokens in the same order. */\nfunction sameTokens(a: readonly string[], b: readonly string[]): boolean {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i += 1) if (a[i] !== b[i]) return false;\n return true;\n}\n\n/**\n * Fold every TOUCHED, rewritable element's optimized computed style back into the MINIMAL static\n * class-token set (see module docs). Mutates `doc` in place.\n */\nexport function syncClassesFromComputed(\n doc: IRDocument,\n resolver: StyleResolver,\n norm: StyleNormalizer,\n): void {\n const sink = createSyntheticSink();\n for (const id of elementIds(doc)) {\n const el = getElement(doc, id);\n if (!el || !el.meta.touched) continue;\n if (el.classes.opaque || el.classes.hasDynamic) continue;\n\n const tokens = staticTokensOf(el.classes);\n\n // Minimal class set reproducing the FULL computed style.\n const ctx: EmitContext = { normalizer: norm, sink };\n const emitted = resolver.emit(el.computed, ctx).classes;\n // A resolver that reverse-synthesized nothing must never erase the element's classes.\n if (emitted.length === 0) continue;\n\n const emittedSet = new Set(emitted);\n const next: string[] = [];\n const seen = new Set<string>();\n\n // 1. Keep each existing token that is either NOT droppable (unknown / opaque / variant /\n // selector-bound) or still part of the emitted minimal set — preserving source order.\n for (const t of tokens) {\n if (seen.has(t)) continue;\n const keep = emittedSet.has(t) || !resolver.selectorUsage(t).droppable;\n if (keep) {\n next.push(t);\n seen.add(t);\n }\n }\n // 2. Append any newly-emitted classes not already present, in emit order.\n for (const c of emitted) {\n if (seen.has(c)) continue;\n next.push(c);\n seen.add(c);\n }\n\n if (sameTokens(next, tokens)) continue; // no churn when nothing actually changed\n el.classes = staticClassList(el.classes, next);\n }\n}\n","/**\n * @domflax/pattern-kit — the shared StyleMap normalizer.\n *\n * A single, syntactic-only {@link StyleNormalizer} implementation that core, the patterns, and the\n * verifier all reuse so they agree, byte-for-byte, on what two style declarations \"mean\". It NEVER\n * resolves initial/inherited/computed defaults (that is the verifier's job) — it only:\n *\n * • canonicalizes colors (`transparent` ⇒ `rgba(0, 0, 0, 0)`, hex lower-cased + 3→6 expanded,\n * `rgb()/rgba()/hsl()/hsla()` argument spacing normalized),\n * • canonicalizes units (whitespace collapsed, zero-lengths `0px`/`0%`/… ⇒ `0`),\n * • expands a fixed set of box shorthands to longhands (`padding`/`margin`/`inset`/`border-width`\n * into their four sides, `gap` into `row-gap`/`column-gap`),\n * • orders declarations by property for stable comparison.\n *\n * Dependency-free: only `@domflax/core` (types + the StyleMap builder helpers).\n */\n\nimport type {\n CssProperty,\n CssValue,\n ConditionKey,\n InheritedPropertyTable,\n StyleBlock,\n StyleDecl,\n StyleMap,\n StyleNormalizer,\n} from '@domflax/core';\n\nimport { conditionKey, emptyStyleMap } from '@domflax/core';\n\n/* ───────────────────────── inherited-property table ───────────────────────── */\n\n/**\n * Canonical, versioned set of inherited CSS longhands. Any author custom property (`--*`) is\n * also treated as inherited via the `isInherited` predicate.\n */\nconst INHERITED_PROPERTIES: readonly string[] = [\n 'azimuth',\n 'border-collapse',\n 'border-spacing',\n 'caption-side',\n 'color',\n 'cursor',\n 'direction',\n 'empty-cells',\n 'font-family',\n 'font-feature-settings',\n 'font-kerning',\n 'font-size',\n 'font-size-adjust',\n 'font-stretch',\n 'font-style',\n 'font-variant',\n 'font-variant-caps',\n 'font-variant-numeric',\n 'font-weight',\n 'hyphens',\n 'letter-spacing',\n 'line-height',\n 'list-style-image',\n 'list-style-position',\n 'list-style-type',\n 'orphans',\n 'overflow-wrap',\n 'quotes',\n 'tab-size',\n 'text-align',\n 'text-align-last',\n 'text-decoration-color',\n 'text-indent',\n 'text-justify',\n 'text-rendering',\n 'text-shadow',\n 'text-transform',\n 'text-underline-position',\n 'visibility',\n 'white-space',\n 'widows',\n 'word-break',\n 'word-spacing',\n 'writing-mode',\n '-webkit-font-smoothing',\n];\n\nfunction createInheritedTable(): InheritedPropertyTable {\n const properties = new Set<CssProperty>(INHERITED_PROPERTIES as unknown as CssProperty[]);\n return {\n version: 'domflax-inherited@1',\n properties,\n isInherited(property: CssProperty): boolean {\n // Author custom properties (`--*`) inherit by definition.\n return String(property).startsWith('--') || properties.has(property);\n },\n };\n}\n\n/* ───────────────────────── value canonicalization ───────────────────────── */\n\nconst ZERO_LENGTH_RE =\n /\\b0(?:px|em|rem|ex|ch|vh|vw|vmin|vmax|vi|vb|pt|pc|cm|mm|in|q|lh|rlh|fr|deg|rad|turn|s|ms|%)\\b/g;\n\nconst FUNC_ARGS_RE = /\\b(rgba?|hsla?|hwb|lab|lch|oklab|oklch)\\(([^()]*)\\)/gi;\n\nconst RELATIVE_UNIT_RE = /(?:\\d*\\.?\\d+)(?:em|ex|ch|lh)\\b|%/i;\n\n/**\n * Pure, syntactic value canonicalization. Idempotent: `canon(canon(v)) === canon(v)`.\n */\nfunction canonValue(raw: string): string {\n let v = raw.trim().replace(/\\s+/g, ' ');\n\n // Lower-case hex colors (#abc / #aabbcc / #aabbccff).\n v = v.replace(/#([0-9a-fA-F]{3,8})\\b/g, (_m, hex: string) => '#' + hex.toLowerCase());\n\n // Expand 3-digit hex (#abc → #aabbcc) — only when exactly 3 hex digits.\n v = v.replace(\n /#([0-9a-f])([0-9a-f])([0-9a-f])(?![0-9a-f])/g,\n (_m, r: string, g: string, b: string) => `#${r}${r}${g}${g}${b}${b}`,\n );\n\n // Canonical fully-transparent color.\n v = v.replace(/\\btransparent\\b/gi, 'rgba(0, 0, 0, 0)');\n v = v.replace(/#00000000\\b/g, 'rgba(0, 0, 0, 0)');\n\n // Collapse zero lengths/angles/times to a bare `0`.\n v = v.replace(ZERO_LENGTH_RE, '0');\n\n // Normalize the argument spacing of color/space functions: single space after each comma.\n v = v.replace(FUNC_ARGS_RE, (_m, fn: string, args: string) => {\n const parts = args\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n return `${fn.toLowerCase()}(${parts.join(', ')})`;\n });\n\n return v;\n}\n\n/** True when the (canonicalized) value uses a parent-relative unit (em/ex/ch/lh/%). */\nfunction isRelativeValue(value: string): boolean {\n return RELATIVE_UNIT_RE.test(value);\n}\n\n/* ───────────────────────── shorthand expansion ───────────────────────── */\n\n/** Box-model shorthands whose 1–4 value form expands to four explicit sides. */\nconst BOX_SIDES: Readonly<Record<string, readonly [string, string, string, string]>> = {\n padding: ['padding-top', 'padding-right', 'padding-bottom', 'padding-left'],\n margin: ['margin-top', 'margin-right', 'margin-bottom', 'margin-left'],\n inset: ['top', 'right', 'bottom', 'left'],\n 'border-width': [\n 'border-top-width',\n 'border-right-width',\n 'border-bottom-width',\n 'border-left-width',\n ],\n 'border-style': [\n 'border-top-style',\n 'border-right-style',\n 'border-bottom-style',\n 'border-left-style',\n ],\n 'border-color': [\n 'border-top-color',\n 'border-right-color',\n 'border-bottom-color',\n 'border-left-color',\n ],\n};\n\n/** Split on top-level whitespace, keeping `fn(a, b)` groups intact. */\nfunction splitTopLevel(value: string): string[] {\n const out: string[] = [];\n let depth = 0;\n let cur = '';\n for (const ch of value) {\n if (ch === '(') depth += 1;\n else if (ch === ')') depth = Math.max(0, depth - 1);\n if (depth === 0 && /\\s/.test(ch)) {\n if (cur.length > 0) {\n out.push(cur);\n cur = '';\n }\n continue;\n }\n cur += ch;\n }\n if (cur.length > 0) out.push(cur);\n return out;\n}\n\n/** Map a 1–4 value box shorthand onto its [top, right, bottom, left] sides. */\nfunction boxFourSides(values: readonly string[]): [string, string, string, string] {\n const [a, b, c, d] = values;\n switch (values.length) {\n case 1:\n return [a!, a!, a!, a!];\n case 2:\n return [a!, b!, a!, b!];\n case 3:\n return [a!, b!, c!, b!];\n default:\n return [a!, b!, c!, d!];\n }\n}\n\n/** Expand one declaration into longhand `[property, value]` pairs (single pair if not shorthand). */\nfunction expandShorthand(prop: string, value: string): Array<[string, string]> {\n const box = BOX_SIDES[prop];\n if (box) {\n const parts = splitTopLevel(value);\n if (parts.length >= 1 && parts.length <= 4) {\n const sides = boxFourSides(parts);\n return box.map((p, i) => [p, sides[i]!] as [string, string]);\n }\n return [[prop, value]];\n }\n\n if (prop === 'gap' || prop === 'grid-gap') {\n const parts = splitTopLevel(value);\n if (parts.length === 1) {\n return [\n ['row-gap', parts[0]!],\n ['column-gap', parts[0]!],\n ];\n }\n if (parts.length === 2) {\n return [\n ['row-gap', parts[0]!],\n ['column-gap', parts[1]!],\n ];\n }\n return [[prop, value]];\n }\n\n return [[prop, value]];\n}\n\n/* ───────────────────────── the normalizer ───────────────────────── */\n\nfunction makeDecl(\n table: InheritedPropertyTable,\n prop: string,\n rawValue: string,\n important: boolean,\n): StyleDecl {\n const property = prop.trim().toLowerCase() as CssProperty;\n const value = canonValue(rawValue) as CssValue;\n return {\n property,\n value,\n important,\n relativeToParent: isRelativeValue(value),\n inherited: table.isInherited(property),\n };\n}\n\nexport function createNormalizer(): StyleNormalizer {\n const inherited = createInheritedTable();\n\n const normalizeDeclaration = (\n prop: string,\n value: string,\n important: boolean,\n ): readonly StyleDecl[] => {\n const p = prop.trim().toLowerCase();\n const expanded = expandShorthand(p, value.trim());\n return expanded.map(([lp, lv]) => makeDecl(inherited, lp, lv, important));\n };\n\n const normalizeValue = (prop: CssProperty, raw: string): CssValue => {\n void prop;\n return canonValue(raw) as CssValue;\n };\n\n const normalizeStyleMap = (sm: StyleMap): StyleMap => {\n const blocks = new Map<ConditionKey, StyleBlock>();\n for (const block of sm.blocks.values()) {\n const decls = new Map<CssProperty, StyleDecl>();\n // Re-canonicalize every value and re-key (the decls are already longhand).\n for (const decl of block.decls.values()) {\n const next: StyleDecl = {\n ...decl,\n value: canonValue(String(decl.value)) as CssValue,\n relativeToParent: isRelativeValue(String(decl.value)),\n inherited: inherited.isInherited(decl.property),\n };\n decls.set(next.property, next);\n }\n // Property-sorted for deterministic iteration/serialization.\n const sorted = new Map<CssProperty, StyleDecl>(\n [...decls.entries()].sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)),\n );\n const key = conditionKey(block.condition);\n blocks.set(key, { condition: block.condition, decls: sorted });\n }\n return { blocks };\n };\n\n const equals = (a: StyleMap, b: StyleMap): boolean => {\n const na = normalizeStyleMap(a);\n const nb = normalizeStyleMap(b);\n if (na.blocks.size !== nb.blocks.size) return false;\n for (const [key, blockA] of na.blocks) {\n const blockB = nb.blocks.get(key);\n if (!blockB) return false;\n if (blockA.decls.size !== blockB.decls.size) return false;\n for (const [prop, declA] of blockA.decls) {\n const declB = blockB.decls.get(prop);\n if (!declB) return false;\n if (declA.value !== declB.value || declA.important !== declB.important) return false;\n }\n }\n return true;\n };\n\n return {\n version: 'domflax-normalizer@1',\n normalizeDeclaration,\n normalizeValue,\n normalizeStyleMap,\n equals,\n inherited,\n };\n}\n\n/** The shared, process-wide normalizer instance reused by core / patterns / verify. */\nexport const normalizer: StyleNormalizer = createNormalizer();\n\n/* ───────────────────────── superset helper (used by `computed()` matcher) ───────────────────────── */\n\n/**\n * True when `full` contains every declaration of `partial` with an equal normalized value\n * (a per-condition, per-declaration superset test). Both maps are normalized first so the\n * comparison is meaning-based, not string-based. Empty `partial` ⇒ always `true`.\n */\nexport function isStyleSuperset(\n full: StyleMap,\n partial: StyleMap,\n norm: StyleNormalizer = normalizer,\n): boolean {\n const nf = norm.normalizeStyleMap(full);\n const np = norm.normalizeStyleMap(partial);\n for (const [key, want] of np.blocks) {\n const have = nf.blocks.get(key) ?? nf.blocks.get(conditionKey(want.condition));\n if (!have) return false;\n for (const [prop, decl] of want.decls) {\n const got = have.decls.get(prop);\n if (!got || got.value !== decl.value) return false;\n }\n }\n return true;\n}\n\n/** Re-exported for callers that want to (de)construct keys without importing core directly. */\nexport { emptyStyleMap };\n","/**\n * @domflax/pattern-kit — composable matcher vocabulary.\n *\n * A {@link Matcher} is a PURE predicate over a node + its {@link MatchContext}. Matchers never\n * mutate; they only read the (DeepReadonly) IR and the precomputed targeting/selector facts the\n * context exposes. Authors compose them with {@link and}/{@link or}/{@link not} and feed the\n * result into a pattern's `evaluate`.\n *\n * Style-aware matchers (`computed`, `hasOwnVisualStyle`) reason over the NORMALIZED StyleMap via\n * the shared normalizer in `./normalize`, so they query meaning, not raw CSS strings.\n */\n\nimport type {\n DeepReadonly,\n ElementLike,\n IRElement,\n IRNode,\n IRNodeId,\n MatchContext,\n NodeLike,\n StyleMap,\n} from '@domflax/core';\n\nimport { isStyleSuperset, normalizer } from './normalize';\n\n/** A pure predicate: does `node` satisfy this condition in the given match context? */\nexport type Matcher = (node: NodeLike, ctx: MatchContext) => boolean;\n\n/* ───────────────────────── internal helpers ───────────────────────── */\n\nfunction asElement(node: NodeLike): DeepReadonly<IRElement> | null {\n const n = node as DeepReadonly<IRNode>;\n return n.kind === 'element' ? (n as DeepReadonly<IRElement>) : null;\n}\n\nfunction elementChildrenOf(\n el: DeepReadonly<IRElement>,\n ctx: MatchContext,\n): DeepReadonly<IRElement>[] {\n const out: DeepReadonly<IRElement>[] = [];\n for (const childId of el.children) {\n const child = ctx.doc.nodes.get(childId);\n if (child && child.kind === 'element') out.push(child as DeepReadonly<IRElement>);\n }\n return out;\n}\n\n/* ───────────────────────── boolean combinators ───────────────────────── */\n\n/** Logical AND. Empty list ⇒ always matches. Short-circuits on the first failure. */\nexport function and(...matchers: readonly Matcher[]): Matcher {\n return (node, ctx) => matchers.every((m) => m(node, ctx));\n}\n\n/** Logical OR. Empty list ⇒ never matches. Short-circuits on the first success. */\nexport function or(...matchers: readonly Matcher[]): Matcher {\n return (node, ctx) => matchers.some((m) => m(node, ctx));\n}\n\n/** Logical NOT. */\nexport function not(matcher: Matcher): Matcher {\n return (node, ctx) => !matcher(node, ctx);\n}\n\n/* ───────────────────────── structural matchers ───────────────────────── */\n\n/** Matches any element; with `tag`, only elements whose (case-insensitive) tag equals it. */\nexport function isElement(tag?: string): Matcher {\n const want = tag?.toLowerCase();\n return (node) => {\n const el = asElement(node);\n if (!el) return false;\n return want === undefined || el.tag.toLowerCase() === want;\n };\n}\n\n/** Matches an element with exactly one ELEMENT child (text/expr/comment children ignored). */\nexport const hasSingleElementChild: Matcher = (node, ctx) => {\n const el = asElement(node);\n if (!el) return false;\n return elementChildrenOf(el, ctx).length === 1;\n};\n\n/* ───────────────────────── style matchers ───────────────────────── */\n\n/**\n * Matches when the node's computed StyleMap is a SUPERSET of `partial` — i.e. every declaration\n * in `partial` is present in `node.computed` with an equal normalized value. Comparison is\n * meaning-based (both sides normalized first). Empty `partial` always matches.\n */\nexport function computed(partial: StyleMap): Matcher {\n return (node, ctx) => {\n const el = asElement(node);\n if (!el) return false;\n const full = ctx.computedOf(el as unknown as NodeLike) ?? (el.computed as StyleMap);\n return isStyleSuperset(full as StyleMap, partial, normalizer);\n };\n}\n\n/** Visual (paint-establishing) properties that count as \"own visual style\", beyond pure layout. */\nconst VISUAL_PROPERTIES: ReadonlySet<string> = new Set<string>([\n 'background',\n 'background-color',\n 'background-image',\n 'border-top-width',\n 'border-right-width',\n 'border-bottom-width',\n 'border-left-width',\n 'border-top-style',\n 'border-right-style',\n 'border-bottom-style',\n 'border-left-style',\n 'border-top-color',\n 'border-right-color',\n 'border-bottom-color',\n 'border-left-color',\n 'border-radius',\n 'box-shadow',\n 'outline',\n 'outline-width',\n 'outline-style',\n 'outline-color',\n 'text-shadow',\n 'filter',\n 'backdrop-filter',\n 'mix-blend-mode',\n 'opacity',\n]);\n\n/** Values that mean \"no paint\" — a visual property set to one of these does NOT count. */\nconst EMPTY_VISUAL_VALUES: ReadonlySet<string> = new Set<string>([\n 'none',\n '0',\n 'normal',\n 'transparent',\n 'rgba(0, 0, 0, 0)',\n 'initial',\n 'unset',\n 'auto',\n]);\n\n/**\n * Matches when the element paints something of its own: a meaningful background, border, shadow,\n * outline, filter, etc. across ANY style condition. Honours the frontend-set `meta.hasOwnVisualStyle`\n * fast-path, then falls back to scanning the normalized computed StyleMap.\n */\nexport const hasOwnVisualStyle: Matcher = (node, ctx) => {\n const el = asElement(node);\n if (!el) return false;\n if (el.meta.hasOwnVisualStyle) return true;\n\n const computedMap = ctx.computedOf(el as unknown as NodeLike) ?? (el.computed as StyleMap);\n const norm = normalizer.normalizeStyleMap(computedMap as StyleMap);\n for (const block of norm.blocks.values()) {\n for (const decl of block.decls.values()) {\n if (!VISUAL_PROPERTIES.has(String(decl.property))) continue;\n if (!EMPTY_VISUAL_VALUES.has(String(decl.value))) return true;\n }\n }\n return false;\n};\n\n/* ───────────────────────── opacity-barrier / meta matchers ───────────────────────── */\n\n/** Element carries a `ref` (hard opacity barrier). */\nexport const hasRef: Matcher = (node) => asElement(node)?.meta.hasRef ?? false;\n\n/** Element has event handlers (onClick, …). */\nexport const hasEventHandlers: Matcher = (node) => asElement(node)?.meta.hasEventHandlers ?? false;\n\n/** Element has dynamic children (mapped/conditional islands). */\nexport const hasDynamicChildren: Matcher = (node) =>\n asElement(node)?.meta.hasDynamicChildren ?? false;\n\n/** Element's class list contains a dynamic segment (template/expr) → not freely rewritable. */\nexport const hasDynamicClasses: Matcher = (node) => asElement(node)?.classes.hasDynamic ?? false;\n\n/**\n * Element's class list is wholly dynamic / spread-derived (`classes.opaque`, or spread attrs) — its\n * concrete tokens can't be seen or statically rewritten, so a class-rewriting (compress) pattern\n * must decline. Delegates to the context's authoritative {@link MatchContext.isOpaque}.\n */\nexport const opaque: Matcher = (node, ctx) => {\n const el = asElement(node);\n if (!el) return false;\n return ctx.isOpaque(el as unknown as ElementLike);\n};\n\n/**\n * Element is the subject of a combinator selector (`>`/`+`/`~`). Honours the frontend-set meta\n * flag and the precomputed {@link SelectorIndex} in the context.\n */\nexport const targetedByCombinator: Matcher = (node, ctx) => {\n const el = asElement(node);\n if (!el) return false;\n if (el.meta.targetedByCombinator) return true;\n // `el.id` is a branded number; DeepReadonly widens the brand, so re-narrow for the index call.\n return ctx.selectors.targetedByCombinator(el.id as unknown as IRNodeId);\n};\n","/**\n * @domflax/pattern-kit — `validatePattern` (INTERNAL).\n *\n * A small, eager validator + identity wrapper that turns a lowered {@link Pattern} spec into a\n * frozen, contract-checked Pattern. Catching shape errors here (bad category/phase, missing\n * `evaluate`, out-of-range safety) keeps the pass-manager's hot loop free of defensive checks and\n * gives authors an immediate, actionable error at module-load time.\n *\n * This is the PRIVATE lower-level core: it is consumed only by the declarative\n * {@link import('./pattern').definePattern} authoring surface (which compiles a high-level config\n * down to a {@link Pattern} and then runs it through this validator). It is intentionally NOT part\n * of the public package surface — authors use `definePattern` instead.\n */\n\nimport type { PassPhase, Pattern, SafetyLevel } from '@domflax/core';\n\nconst PHASES: ReadonlySet<PassPhase> = new Set<PassPhase>(['flatten', 'compress', 'extract']);\nconst SAFETY_LEVELS: ReadonlySet<SafetyLevel> = new Set<SafetyLevel>([0, 1, 2, 3]);\n\nfunction fail(name: string, why: string): never {\n throw new Error(`definePattern(${name || '<anonymous>'}): ${why}`);\n}\n\n/**\n * Validate and freeze a {@link Pattern}. Throws on any contract violation; otherwise returns the\n * (shallow-frozen) spec unchanged so it can be registered into a {@link Pass}. INTERNAL — see the\n * module header; authors call the declarative {@link import('./pattern').definePattern}.\n */\nexport function validatePattern(spec: Pattern): Pattern {\n if (spec == null || typeof spec !== 'object') {\n throw new Error('definePattern: spec must be an object');\n }\n\n const name = spec.name;\n if (typeof name !== 'string' || name.length === 0) {\n fail(String(name), 'name must be a non-empty string');\n }\n\n if (typeof spec.category !== 'string' || !spec.category.includes('/')) {\n fail(name, `category must be a \"<phase>/<slug>\" string (got ${JSON.stringify(spec.category)})`);\n }\n\n const phase = spec.category.split('/', 1)[0] as PassPhase;\n if (!PHASES.has(phase)) {\n fail(name, `category phase must be one of flatten|compress|extract (got \"${phase}\")`);\n }\n\n if (!SAFETY_LEVELS.has(spec.safety)) {\n fail(name, `safety must be 0|1|2|3 (got ${JSON.stringify(spec.safety)})`);\n }\n\n if (typeof spec.evaluate !== 'function') {\n fail(name, 'evaluate must be a function');\n }\n\n if (spec.priority !== undefined && !Number.isFinite(spec.priority)) {\n fail(name, 'priority must be a finite number when provided');\n }\n\n return Object.freeze({ ...spec });\n}\n","/**\n * @domflax/pattern-kit — `definePattern()`: THE declarative pattern-authoring surface.\n *\n * `definePattern(config)` is the single public way to author a rewrite pattern: definition AND its\n * tests are co-located in one call. It compiles down to the private lower-level\n * {@link import('./define').validatePattern}/{@link Pattern} contract (it never replaces the\n * engine). Authors describe the match as a plain DATA object and the rewrite as a named RECIPE; this\n * module maps each key to the existing matcher combinators and op-draft factories, auto-applies the\n * phase-appropriate safety guards (the full opacity-barrier + selector set for `flatten/*`; the\n * narrower class-rewrite-safety set for `compress/*`) so authors never hand-write them, and threads\n * `doc`/`test` through. Two escape hatches — a `match` predicate and a `rewrite` function — keep\n * exotic patterns (e.g. ones anchored on a parent fragment) expressible.\n *\n * The co-located {@link PatternTest} (`provider`/`cssFiles`/`cases`/`noMatch`/`custom`) is carried on\n * the compiled {@link AuthoredPattern} as `.test`, where the generic harness (`./testing`) reads it:\n * each `case` asserts `before → after`, each `noMatch` asserts the input is left unchanged, and the\n * optional `custom` hook runs arbitrary assertions against the built transform.\n *\n * `style` blocks in the declarative match (and in `childGains`/`mergeStyle` recipes) are PLAIN\n * objects (camelCase or kebab keys) auto-normalized into a superset StyleMap via the shared\n * normalizer — authors never import the normalizer or hand-build a StyleMap.\n *\n * `pattern` remains exported as a DEPRECATED alias of `definePattern` for backward compatibility.\n */\n\nimport type {\n Captures,\n ConditionKey,\n CssProperty,\n DeepReadonly,\n IRElement,\n IRNode,\n IRNodeId,\n MatchContext,\n MatchResult,\n NodeLike,\n NodeMeta,\n PassCategory,\n PassPhase,\n Pattern,\n PatternDoc,\n PreconditionSketch,\n RewriteFactory,\n RewriteOpDraft,\n SafetyLevel,\n StyleBlock,\n StyleDecl,\n StyleMap,\n StyleOrigin,\n StyleConflictPolicy,\n} from '@domflax/core';\nimport { BASE_CONDITION, conditionKey } from '@domflax/core';\n\nimport {\n and,\n computed,\n hasDynamicChildren,\n hasDynamicClasses,\n hasEventHandlers,\n hasOwnVisualStyle,\n hasRef,\n hasSingleElementChild,\n isElement,\n not,\n opaque,\n targetedByCombinator,\n type Matcher,\n} from './combinators';\nimport { validatePattern } from './define';\nimport { normalizer } from './normalize';\n\n/* ───────────────────────── public config shapes ───────────────────────── */\n\n/** A plain CSS style object: camelCase or kebab-case keys, string or number values. */\nexport type PlainStyle = Readonly<Record<string, string | number>>;\n\n/**\n * Declarative match as DATA. Every key maps to one of the existing matcher combinators; an empty\n * object matches any element. Use the `match` FUNCTION escape hatch for anything not expressible\n * here (relational/ancestor/sibling shapes, parent-anchored patterns, …).\n */\nexport interface DeclarativeMatch {\n /** Restrict to a tag (case-insensitive). Omit to match any element. */\n readonly tag?: string;\n /** Computed style the node must be a SUPERSET of (plain object, auto-normalized). */\n readonly style?: PlainStyle;\n /** Require exactly one ELEMENT child. */\n readonly onlyChild?: 'element';\n /** Require the element to paint nothing of its own (no own visual style). */\n readonly paintsNothing?: boolean;\n /** Extra, hand-written predicate AND-ed into the declarative match. */\n readonly where?: Matcher | readonly Matcher[];\n}\n\n/** Escape hatch: a raw match predicate (no auto-guards are added). */\nexport type MatchFn = (node: NodeLike, ctx: MatchContext) => boolean;\n\n/**\n * Flatten recipe: fold inherited styles onto the sole element child (default on), optionally merge\n * `childGains` onto it, then unwrap the node (id-preserving). Mirrors the flatten exemplars.\n */\nexport interface FlattenIntoRecipe {\n readonly flattenInto: 'child';\n /** Plain style merged onto the surviving child (source-wins) before unwrap. */\n readonly childGains?: PlainStyle;\n /** Fold inheritable declarations onto the child first. Default `true`. */\n readonly foldInherited?: boolean;\n}\n\n/** Compress recipe: rebuild the element's class StyleMap; return `null` to decline. */\nexport interface RewriteClassesRecipe {\n readonly rewriteClasses: (computed: StyleMap, ctx: MatchContext) => StyleMap | null;\n /** Keep opaque/selector-bound tokens verbatim. Default `true`. */\n readonly preserveOpaque?: boolean;\n}\n\n/** Compress recipe: drop fully-overridden class tokens (provenance is pruned automatically). */\nexport interface DropClassesRecipe {\n readonly dropClasses: (computed: StyleMap, ctx: MatchContext) => Iterable<string>;\n /** Keep opaque/selector-bound tokens verbatim. Default `true`. */\n readonly preserveOpaque?: boolean;\n}\n\n/** Merge a literal plain style onto the matched element. */\nexport interface MergeStyleRecipe {\n readonly mergeStyle: PlainStyle;\n readonly onConflict?: StyleConflictPolicy;\n}\n\nexport type RewriteRecipe =\n | FlattenIntoRecipe\n | RewriteClassesRecipe\n | DropClassesRecipe\n | MergeStyleRecipe;\n\n/** Escape hatch: a raw rewrite that returns op drafts (or `null`/`[]` for no-op). */\nexport type RewriteFn = (\n ctx: MatchContext,\n rw: RewriteFactory,\n) => readonly RewriteOpDraft[] | null;\n\n/** A single positive before→after assertion run through the pattern's built transform. */\nexport interface PatternTestCase {\n readonly name?: string;\n readonly before: string;\n readonly after: string;\n}\n\n/** Helpers handed to a {@link PatternTest.custom} hook (the built transform + expectation sugar). */\nexport interface TestHelpers {\n /** Run the pattern's transform on `code` (default filename `'X.tsx'`). */\n readonly transform: (code: string, filename?: string) => string;\n /** Assert `before` transforms to `after` (whitespace-normalized). */\n readonly expectTransforms: (before: string, after: string) => void;\n /** Assert `code` is left unchanged (whitespace-normalized). */\n readonly expectUnchanged: (code: string) => void;\n}\n\n/**\n * Co-located test spec for a pattern. The generic harness (`./testing`) builds a transform for the\n * declared `provider` (default `'tailwind'`; `'custom'` resolves the listed `cssFiles`), then runs\n * every `case` (`before → after`), every `noMatch` (left unchanged), and the optional `custom` hook.\n */\nexport interface PatternTest {\n /** Which style provider the harness builds the transform from. Default `'tailwind'`. */\n readonly provider?: 'tailwind' | 'custom';\n /** For `provider: 'custom'` — the project stylesheet paths backing the CSS resolver. */\n readonly cssFiles?: readonly string[];\n /** Positive before→after assertions. */\n readonly cases?: readonly PatternTestCase[];\n /** Inputs the pattern must leave UNCHANGED (barriers, non-matching shapes, safety reverts). */\n readonly noMatch?: readonly string[];\n /** Arbitrary extra assertions against the built transform. */\n readonly custom?: (h: TestHelpers) => void;\n}\n\nexport interface PatternConfig {\n readonly name: string;\n readonly category: PassCategory;\n readonly safety: SafetyLevel;\n readonly priority?: number;\n readonly precondition?: PreconditionSketch;\n readonly doc?: PatternDoc;\n /** Co-located tests consumed by the generic harness (`./testing`). */\n readonly test?: PatternTest;\n /** Declarative match DATA, or a raw predicate escape hatch. Defaults to \"any element\". */\n readonly match?: DeclarativeMatch | MatchFn;\n /** A named rewrite recipe, or a raw op-draft factory escape hatch. */\n readonly rewrite: RewriteRecipe | RewriteFn;\n}\n\n/** A {@link Pattern} that also carries its co-located {@link PatternTest} for the test harness. */\nexport interface AuthoredPattern<C extends Captures = Captures> extends Pattern {\n readonly test?: PatternTest;\n evaluate(ctx: MatchContext, rw: RewriteFactory): MatchResult<C> | null;\n}\n\n/* ───────────────────────── plain-style → StyleMap ───────────────────────── */\n\nfunction camelToKebab(key: string): string {\n if (key.startsWith('--')) return key; // custom property — leave verbatim\n return key.replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`);\n}\n\n/** Build a single-(base-)condition StyleMap from a plain style object via the shared normalizer. */\nfunction plainToStyleMap(style: PlainStyle): StyleMap {\n const decls = new Map<CssProperty, StyleDecl>();\n for (const [rawKey, rawValue] of Object.entries(style)) {\n const prop = camelToKebab(rawKey);\n for (const decl of normalizer.normalizeDeclaration(prop, String(rawValue), false)) {\n decls.set(decl.property, decl);\n }\n }\n const block: StyleBlock = { condition: BASE_CONDITION, decls };\n return { blocks: new Map<ConditionKey, StyleBlock>([[conditionKey(BASE_CONDITION), block]]) };\n}\n\n/* ───────────────────────── local meta / selector matchers ───────────────────────── */\n\nfunction asElement(node: NodeLike): DeepReadonly<IRElement> | null {\n const n = node as DeepReadonly<IRNode>;\n return n.kind === 'element' ? (n as DeepReadonly<IRElement>) : null;\n}\n\nfunction metaFlag(flag: keyof NodeMeta): Matcher {\n return (node) => Boolean(asElement(node)?.meta[flag]);\n}\n\n/** Element renders raw/`dangerouslySetInnerHTML` markup — a hard opacity barrier. */\nconst hasRawHtml: Matcher = metaFlag('hasDangerousHtml');\n\n/**\n * Unwrapping/removing this node would change the combinator / structural-pseudo match-set of itself,\n * its child, or a former sibling. Empty `reparentImpact` ⇒ structurally safe to hoist.\n */\nconst affectsSelectorMatching: Matcher = (node, ctx) => {\n const el = asElement(node);\n if (!el) return false;\n return ctx.selectors.reparentImpact(el.id as unknown as IRNodeId).size > 0;\n};\n\n/**\n * The opacity-barrier + selector-safety guards every `flatten/*` pattern must carry. Auto-applied to\n * the declarative match so authors never hand-write them (the flatten exemplars spell them out).\n *\n * Flatten UNWRAPS the element (moving its children into a new parent and dropping its box), so every\n * opacity barrier matters: a ref, event handler, dynamic child, or raw HTML on the wrapper — or any\n * selector the reparent would disturb — makes the flatten unsafe.\n */\nconst FLATTEN_GUARDS: Matcher = and(\n not(hasRef),\n not(hasEventHandlers),\n not(hasDynamicChildren),\n not(hasRawHtml),\n not(targetedByCombinator),\n not(affectsSelectorMatching),\n);\n\n/**\n * The guards every `compress/*` pattern must carry. Compress ONLY ever rewrites the element's OWN\n * class tokens (e.g. `px-4 py-4 → p-4`) — it never touches the element's structure, children, or\n * identity. A dynamic `{expr}` child, a ref, an event handler, or `dangerouslySetInnerHTML` is\n * therefore wholly unaffected by a class-only change, so — unlike flatten — those opacity barriers\n * must NOT gate compress. Compress is gated ONLY on what actually makes a class rewrite unsafe:\n * • a className we can't statically rewrite — a dynamic segment ({@link hasDynamicClasses}) or a\n * wholly dynamic / spread-derived list ({@link opaque}); and\n * • the selector-safety guard — a class a CSS combinator selector structurally depends on\n * ({@link targetedByCombinator}) must not be dropped or rewritten.\n */\nconst COMPRESS_GUARDS: Matcher = and(\n not(hasDynamicClasses),\n not(opaque),\n not(targetedByCombinator),\n);\n\n/* ───────────────────────── match compilation ───────────────────────── */\n\n/** The auto-applied guard set for a pattern's phase (compress vs flatten get different barriers). */\nfunction autoGuardsFor(category: PassCategory): Matcher | null {\n switch (category.split('/', 1)[0] as PassPhase) {\n case 'flatten':\n return FLATTEN_GUARDS;\n case 'compress':\n return COMPRESS_GUARDS;\n default:\n return null;\n }\n}\n\nfunction compileDeclarativeMatch(m: DeclarativeMatch): Matcher {\n const parts: Matcher[] = [isElement(m.tag)];\n if (m.style) parts.push(computed(plainToStyleMap(m.style)));\n if (m.onlyChild === 'element') parts.push(hasSingleElementChild);\n if (m.paintsNothing) parts.push(not(hasOwnVisualStyle));\n if (m.where) {\n const extra = Array.isArray(m.where) ? (m.where as readonly Matcher[]) : [m.where as Matcher];\n for (const w of extra) parts.push(w);\n }\n return and(...parts);\n}\n\nfunction compileMatch(\n match: DeclarativeMatch | MatchFn | undefined,\n category: PassCategory,\n): MatchFn {\n // Escape hatch: a raw predicate takes full control (no auto-guards).\n if (typeof match === 'function') return match;\n\n const declarative = compileDeclarativeMatch(match ?? {});\n const guards = autoGuardsFor(category);\n const guarded = guards ? and(declarative, guards) : declarative;\n return (node, ctx) => guarded(node, ctx);\n}\n\n/* ───────────────────────── rewrite compilation ───────────────────────── */\n\n/** Clone `sm`, pruning every `shadowed` provenance entry that references a dropped class token. */\nfunction pruneShadowed(sm: StyleMap, drop: ReadonlySet<string>): StyleMap {\n const blocks = new Map<ConditionKey, StyleBlock>();\n for (const [key, block] of sm.blocks) {\n const decls = new Map<CssProperty, StyleDecl>();\n for (const [prop, decl] of block.decls) {\n const filtered = (decl.shadowed ?? []).filter(\n (o) => !(o.kind === 'class' && drop.has(o.className)),\n );\n const rest: StyleDecl = { ...decl };\n delete (rest as { shadowed?: readonly StyleOrigin[] }).shadowed;\n const next: StyleDecl = filtered.length > 0 ? { ...rest, shadowed: filtered } : rest;\n decls.set(prop, next);\n }\n blocks.set(key, { condition: block.condition, decls });\n }\n return { blocks };\n}\n\nfunction compileFlattenInto(recipe: FlattenIntoRecipe): RewriteFn {\n const childGains = recipe.childGains ? plainToStyleMap(recipe.childGains) : null;\n const fold = recipe.foldInherited !== false;\n return (ctx, rw) => {\n const wrapper = ctx.node;\n const child = ctx.onlyElementChild();\n if (!child) return null;\n const ops: RewriteOpDraft[] = [];\n if (fold) ops.push(rw.foldInheritedStyles(wrapper, child, { conditions: 'all' }));\n if (childGains) ops.push(rw.mergeStyle(child, null, childGains, 'source-wins'));\n ops.push(rw.unwrap(wrapper));\n return ops;\n };\n}\n\nfunction compileRewrite(rewrite: RewriteRecipe | RewriteFn): RewriteFn {\n if (typeof rewrite === 'function') return rewrite;\n\n if ('flattenInto' in rewrite) return compileFlattenInto(rewrite);\n\n if ('rewriteClasses' in rewrite) {\n const preserveOpaque = rewrite.preserveOpaque ?? true;\n return (ctx, rw) => {\n const next = rewrite.rewriteClasses(ctx.computed(), ctx);\n if (!next) return null;\n return [rw.setClassList(ctx.node, next, preserveOpaque)];\n };\n }\n\n if ('dropClasses' in rewrite) {\n const preserveOpaque = rewrite.preserveOpaque ?? true;\n return (ctx, rw) => {\n const drop = new Set<string>(rewrite.dropClasses(ctx.computed(), ctx));\n if (drop.size === 0) return null;\n return [rw.setClassList(ctx.node, pruneShadowed(ctx.computed(), drop), preserveOpaque)];\n };\n }\n\n // MergeStyleRecipe\n const style = plainToStyleMap(rewrite.mergeStyle);\n const onConflict = rewrite.onConflict ?? 'abort';\n return (ctx, rw) => [rw.mergeStyle(ctx.node, null, style, onConflict)];\n}\n\n/* ───────────────────────── the public factory ───────────────────────── */\n\n/**\n * THE declarative pattern-authoring function. Compile a {@link PatternConfig} (definition + co-located\n * {@link PatternTest}) into a validated {@link AuthoredPattern}: a normal {@link Pattern} (registerable\n * into any {@link import('@domflax/core').Pass}) that also exposes its `test` for the generic harness.\n */\nexport function definePattern(config: PatternConfig): AuthoredPattern {\n const matchFn = compileMatch(config.match, config.category);\n const rewriteFn = compileRewrite(config.rewrite);\n\n const spec: AuthoredPattern = {\n name: config.name,\n category: config.category,\n safety: config.safety,\n priority: config.priority,\n precondition: config.precondition,\n doc: config.doc,\n test: config.test,\n evaluate(ctx: MatchContext, rw: RewriteFactory): MatchResult | null {\n if (!matchFn(ctx.node as unknown as NodeLike, ctx)) return null;\n const ops = rewriteFn(ctx, rw);\n if (!ops || ops.length === 0) return null;\n return { ops };\n },\n };\n\n // `validatePattern` validates + freezes; the spread preserves `test` at runtime.\n return validatePattern(spec) as AuthoredPattern;\n}\n\n/**\n * @deprecated Use {@link definePattern}. Retained as a thin alias for backward compatibility.\n */\nexport const pattern = definePattern;\n","/**\n * @domflax/patterns — flatten pattern: `display-contents-wrapper`.\n *\n * Collapses a wrapper that has explicitly opted OUT of generating a box:\n *\n * <div style=\"display:contents\"><Child/></div> → <Child/>\n *\n * `display:contents` makes an element generate NO box of its own — its children render exactly as if\n * they were direct children of the element's parent. A `display:contents` wrapper with a single\n * element child is therefore already a layout passthrough: it contributes nothing to flow, paint\n * (a contents box paints nothing), formatting, stacking, or containing-block resolution. Removing it\n * and hoisting the child produces a tree that is layout-identical — the wrapper's only remaining\n * effect was inheritance, which is preserved by folding inheritable declarations onto the child first.\n *\n * This is the safest possible wrapper-elimination: the box being removed provably did not exist.\n * The opacity-barrier + selector-safety guards (ref/handlers/dynamic-children/raw-html/combinator/\n * reparent-impact) are auto-applied for every `flatten/*` pattern; the `where` predicates add the\n * passthrough-specific requirements (no own attrs / dynamic-or-spread classes, no `var()` coupling,\n * not a component, not a structural-pseudo subject).\n *\n * (Chosen as the safe variant of the size-hoisting \"full-size passthrough\" idea: hoisting an explicit\n * `width/height:100%` onto a child is only sound when the child is block-level and unsized, which is\n * not knowable from the wrapper alone — whereas a `display:contents` box is a passthrough by definition.)\n */\n\nimport type {\n DeepReadonly,\n IRElement,\n IRNode,\n IRNodeId,\n NodeLike,\n NodeMeta,\n} from '@domflax/core';\n\nimport { definePattern, hasDynamicClasses, not, type Matcher } from '@domflax/pattern-kit';\n\n/* ───────────────────────── local meta/attr/selector matchers ───────────────────────── */\n\nfunction asEl(node: NodeLike): DeepReadonly<IRElement> | null {\n const n = node as DeepReadonly<IRNode>;\n return n.kind === 'element' ? (n as DeepReadonly<IRElement>) : null;\n}\n\nfunction metaOf(node: NodeLike): DeepReadonly<NodeMeta> | null {\n return asEl(node)?.meta ?? null;\n}\n\n/**\n * Element exposes custom properties to a descendant — removing its box could sever a `var()` coupling,\n * so it is NOT a free passthrough. (A `display:contents` box establishes no formatting/stacking/box\n * context and is no containing block, so those flags need not be checked.)\n */\nconst declaresCustomProperties: Matcher = (node) => metaOf(node)?.declaresCustomProperties ?? false;\n\n/** Hard opacity barriers beyond the auto-applied set: spread attrs, component identity. */\nconst hasSpreadAttrs: Matcher = (node) => metaOf(node)?.hasSpreadAttrs ?? false;\nconst isComponentNode: Matcher = (node) => metaOf(node)?.isComponent ?? false;\n\n/** Element carries own attributes (id / data-* / …) beyond its class list — possible selector/JS hook. */\nconst hasOwnAttrs: Matcher = (node) => {\n const el = asEl(node);\n if (!el) return false;\n return el.attrs.entries.size > 0 || el.attrs.spreads.length > 0;\n};\n\n/**\n * Element is the subject of a structural pseudo (`:first/:last/:only/:nth-*`). Honours the meta flag\n * and the precomputed {@link SelectorIndex}.\n */\nconst targetedByStructuralPseudo: Matcher = (node, ctx) => {\n const el = asEl(node);\n if (!el) return false;\n if (el.meta.targetedByStructuralPseudo) return true;\n return ctx.selectors.targetedByStructuralPseudo(el.id as unknown as IRNodeId);\n};\n\n/* ───────────────────────── the pattern ───────────────────────── */\n\n/**\n * Flatten a `display:contents` wrapper (a box that generates no box) into its sole element child,\n * folding any inheritable styles down first so inherited values survive the removal.\n */\nexport const displayContentsWrapper = definePattern({\n name: 'display-contents-wrapper',\n category: 'flatten/display-contents-wrapper',\n safety: 2,\n doc: {\n title: 'Flatten display:contents wrapper',\n summary:\n 'A div with display:contents (which generates no box) wrapping a single element child, with ' +\n 'no own visual style, no attributes beyond an inert class, and no opacity barriers, is removed; ' +\n 'its sole child is hoisted in its place.',\n before: '<div style=\"display:contents\"><Child/></div>',\n after: '<Child/>',\n safetyRationale:\n 'A display:contents element generates no box at all, so its children already render as direct ' +\n \"children of its parent; removing it is layout-identical. It paints nothing, establishes no \" +\n 'formatting/stacking/box context, is no containing block, carries no ' +\n 'ref/handlers/dynamic-children/html/spread/component identity, owns no targetable attrs / ' +\n 'custom-property coupling, and is not a combinator/structural-pseudo subject; inheritable ' +\n 'styles are folded onto the child before removal.',\n },\n match: {\n tag: 'div',\n style: { display: 'contents' },\n onlyChild: 'element',\n paintsNothing: true,\n where: [\n not(declaresCustomProperties),\n not(hasOwnAttrs),\n not(hasDynamicClasses),\n not(hasSpreadAttrs),\n not(isComponentNode),\n not(targetedByStructuralPseudo),\n ],\n },\n rewrite: { flattenInto: 'child' },\n test: {\n cases: [\n {\n // `display:contents` generates no box, so removing it is provably layout-identical → the\n // wrapper is flattened even under the conservative gate; the child is hoisted.\n before: '<div className=\"contents\"><a className=\"text-blue-500\">Link</a></div>',\n after: '<a className=\"text-blue-500\">Link</a>',\n },\n ],\n noMatch: [\n // A ref pins the wrapper's element identity (a hard opacity barrier) → not a passthrough.\n '<div className=\"contents\" ref={rootRef}><a className=\"text-blue-500\">Link</a></div>',\n ],\n },\n});\n","/**\n * @domflax/patterns — flatten pattern: `empty-style-div`.\n *\n * Collapses the most common piece of structural noise of all: a `<div>` whose ONLY role is to wrap\n * a single child while contributing nothing to layout or paint —\n *\n * <div><Child/></div> (no styles at all)\n * <div style=\"display:block\"><Child/></div> (the default; still a no-op box)\n *\n * Such a div is layout-neutral: it is a plain block box with no own visual style, establishes no\n * box / formatting / stacking context, is not a containing block, and declares no custom properties\n * a descendant might read. Its box is therefore indistinguishable from \"not being there\", so it can\n * be unwrapped into its sole child.\n *\n * Authored with the declarative {@link definePattern} API. The opacity-barrier + selector-safety\n * guards (ref/handlers/dynamic-children/raw-html/combinator/reparent-impact) are applied\n * automatically for every `flatten/*` pattern; the `where` predicates below add the LAYOUT-neutrality\n * requirements specific to this pattern (no non-block display, no box/formatting/stacking context, no\n * containing block, no custom-property coupling, no structural-pseudo targeting).\n */\n\nimport type {\n CssProperty,\n DeepReadonly,\n IRElement,\n IRNode,\n IRNodeId,\n NodeLike,\n NodeMeta,\n StyleMap,\n} from '@domflax/core';\n\nimport { definePattern, not, type Matcher } from '@domflax/pattern-kit';\n\n/* ───────────────────────── local matcher helpers ───────────────────────── */\n\n/** Narrow a NodeLike to a (readonly) element, or null. */\nfunction asEl(node: NodeLike): DeepReadonly<IRElement> | null {\n const n = node as DeepReadonly<IRNode>;\n return n.kind === 'element' ? (n as DeepReadonly<IRElement>) : null;\n}\n\n/** A boolean `meta` flag, lifted into a {@link Matcher}. Mirrors how core's combinators read meta. */\nfunction metaFlag(flag: keyof NodeMeta): Matcher {\n return (node) => Boolean(asEl(node)?.meta[flag]);\n}\n\n/** Wrapper establishes an intrinsic/explicit box (sizing) — NOT layout-neutral. */\nconst establishesBox = metaFlag('establishesBox');\n/** Wrapper establishes a formatting context (flex/grid/flow-root/…) — NOT layout-neutral. */\nconst establishesFormattingContext = metaFlag('establishesFormattingContext');\n/** Wrapper establishes a stacking context (transform/opacity<1/z-index/…) — NOT layout-neutral. */\nconst establishesStackingContext = metaFlag('establishesStackingContext');\n/** Wrapper is the containing block for abs/fixed descendants — removing it would reposition them. */\nconst isContainingBlock = metaFlag('isContainingBlock');\n/** Wrapper sets `--*` custom properties a descendant reads (author-var coupling). */\nconst declaresCustomProperties = metaFlag('declaresCustomProperties');\n\n/**\n * Wrapper is a structural-pseudo target (:first/:last/:only/:nth-child/-of-type). Honours the\n * frontend-set meta flag and the precomputed {@link SelectorIndex}. Unwrapping such a node would\n * change a selector's match-set.\n */\nconst targetedByStructuralPseudo: Matcher = (node, ctx) => {\n const el = asEl(node);\n if (!el) return false;\n if (el.meta.targetedByStructuralPseudo) return true;\n return ctx.selectors.targetedByStructuralPseudo(el.id as unknown as IRNodeId);\n};\n\nconst DISPLAY = 'display' as CssProperty;\n\n/**\n * True when the wrapper sets `display` to anything other than the block default in ANY condition.\n * An `inline`/`inline-block`/`flex`/`grid`/`contents`/`none` div is NOT layout-neutral — its box (or\n * lack of one) participates in layout differently from its surviving child.\n */\nconst hasNonBlockDisplay: Matcher = (node, ctx) => {\n const el = asEl(node);\n if (!el) return false;\n const sm: StyleMap = ctx.computedOf(el as unknown as NodeLike) ?? (el.computed as StyleMap);\n for (const block of sm.blocks.values()) {\n const decl = block.decls.get(DISPLAY);\n if (decl && String(decl.value) !== 'block') return true;\n }\n return false;\n};\n\n/* ───────────────────────── the pattern ───────────────────────── */\n\n/**\n * Flatten a layout-neutral, style-free `<div>` wrapper into its sole element child.\n */\nexport const emptyStyleDiv = definePattern({\n name: 'empty-style-div',\n category: 'flatten/empty-style-div',\n safety: 1,\n doc: {\n title: 'Flatten empty-style div wrapper',\n summary:\n 'A layout-neutral div (display:block default, no box/visual styles) that wraps a single ' +\n 'child is removed; the child is hoisted into its place.',\n before: '<div><Child/></div>',\n after: '<Child/>',\n safetyRationale:\n 'Wrapper is a plain block box that paints nothing, establishes no box/formatting/stacking ' +\n 'context, is no containing block, has no custom-property coupling, carries no ' +\n 'ref/handlers/dynamic children/raw HTML, and is neither a combinator subject nor a ' +\n 'structural-pseudo target; inheritable styles are folded onto the child before removal.',\n },\n match: {\n tag: 'div',\n onlyChild: 'element',\n paintsNothing: true,\n where: [\n not(hasNonBlockDisplay),\n not(establishesBox),\n not(establishesFormattingContext),\n not(establishesStackingContext),\n not(isContainingBlock),\n not(declaresCustomProperties),\n not(targetedByStructuralPseudo),\n ],\n },\n rewrite: { flattenInto: 'child' },\n test: {\n cases: [\n {\n // A layout-neutral, style-free block div is a provably-safe flatten → removed, child hoisted.\n before: '<div><span className=\"bg-red-200\">Hi</span></div>',\n after: '<span className=\"bg-red-200\">Hi</span>',\n },\n ],\n noMatch: [\n // The wrapper paints its own background (own visual style) → not layout-neutral, kept.\n '<div className=\"bg-blue-500\"><span className=\"bg-red-200\">Hi</span></div>',\n ],\n },\n});\n","/**\n * @domflax/patterns — flatten pattern: `flex-center-wrapper`.\n *\n * Collapses the ubiquitous \"centering wrapper\" idiom\n *\n * <div style=\"display:flex; align-items:center; justify-content:center\"><Child/></div>\n *\n * into its sole child, pushing the centering intent down onto the child as `place-self: center`.\n * The wrapper only exists to center one element; once `place-self:center` lives on the child the\n * wrapper is pure structural noise and can go.\n *\n * Authored with the declarative {@link definePattern} API: the match is the flex-centering\n * computed-style signature on a single-element-child `<div>` that paints nothing of its own; the\n * recipe folds inheritable styles onto the child, grants it `place-self:center`, then unwraps the\n * wrapper (id-preserving). The opacity-barrier + selector-safety guards are applied automatically by\n * the `definePattern` factory for every `flatten/*` pattern.\n */\n\nimport { definePattern } from '@domflax/pattern-kit';\n\n/**\n * Flatten a flex-centering `<div>` wrapper into its sole element child, granting the child\n * `place-self:center`.\n */\nexport const flexCenterWrapper = definePattern({\n name: 'flex-center-wrapper',\n category: 'flatten/flex-center-wrapper',\n safety: 2,\n doc: {\n title: 'Flatten flex-centering wrapper',\n summary:\n 'A div that only centers a single child (display:flex; align-items:center; ' +\n 'justify-content:center) is removed; the child gains place-self:center.',\n before: '<div style=\"display:flex;align-items:center;justify-content:center\"><Child/></div>',\n after: '<Child style=\"place-self:center\"/>',\n safetyRationale:\n 'Wrapper paints nothing, carries no ref/handlers/dynamic children, and is not a combinator ' +\n 'subject; inheritable styles are folded onto the child before removal.',\n },\n match: {\n tag: 'div',\n style: { display: 'flex', alignItems: 'center', justifyContent: 'center' },\n onlyChild: 'element',\n paintsNothing: true,\n },\n rewrite: {\n flattenInto: 'child',\n childGains: { placeSelf: 'center' },\n },\n // Collapsing a flex-centering wrapper to `place-self:center` on the child only stays centered when\n // the child's NEW parent is flex/grid; moreover the wrapper's own `display:flex` establishes a\n // formatting context. Both make this a `needs-verification` flatten, which the conservative\n // production gate (`'provably-safe'`, used by the harness) intentionally REVERTS — so every case\n // here is a no-match: the wrapper is preserved. Op-level rewrite correctness (purity, id-preserving\n // unwrap, opacity-barrier safety) is still asserted by the invariant suite over every pattern.\n test: {\n noMatch: [\n // Even under a static flex/grid parent the centering flatten is not provably layout-neutral\n // (the wrapper itself establishes a flex formatting context) → left unchanged.\n '<div className=\"grid\">' +\n '<div className=\"flex items-center justify-center\"><span className=\"bg-red-200\">x</span></div>' +\n '</div>',\n // Non-flex/grid parent (document root): place-self centering would not hold → left unchanged.\n '<div className=\"flex justify-center items-center\"><div className=\"bg-red-200\">Hello</div></div>',\n // onClick is a hard opacity barrier → the wrapper is load-bearing regardless of the gate.\n '<div className=\"flex justify-center items-center\" onClick={handleClick}>' +\n '<div className=\"bg-red-200\">Hello</div>' +\n '</div>',\n ],\n },\n});\n","/**\n * @domflax/patterns — flatten pattern: `inline-flex-center-wrapper`.\n *\n * Collapses the inline-flex flavour of the \"centering wrapper\" idiom\n *\n * <div style=\"display:inline-flex; align-items:center; justify-content:center\"><Child/></div>\n *\n * into its sole child, pushing the centering intent down onto the child as `place-self: center`.\n * Like its block-level `flex-center-wrapper` sibling the wrapper only exists to center one element;\n * once `place-self:center` lives on the child the wrapper is pure structural noise and can go.\n *\n * Authored with the declarative {@link definePattern} API: the match is the inline-flex-centering\n * computed-style signature on a single-element-child `<div>` that paints nothing of its own; the\n * recipe folds inheritable styles onto the child, grants it `place-self:center`, then unwraps the\n * wrapper (id-preserving). The opacity-barrier + selector-safety guards are applied automatically by\n * the `definePattern` factory for every `flatten/*` pattern.\n */\n\nimport { definePattern } from '@domflax/pattern-kit';\n\n/**\n * Flatten an inline-flex-centering `<div>` wrapper into its sole element child, granting the child\n * `place-self:center`.\n */\nexport const inlineFlexCenterWrapper = definePattern({\n name: 'inline-flex-center-wrapper',\n category: 'flatten/inline-flex-center-wrapper',\n safety: 2,\n doc: {\n title: 'Flatten inline-flex-centering wrapper',\n summary:\n 'A div that only centers a single child (display:inline-flex; align-items:center; ' +\n 'justify-content:center) is removed; the child gains place-self:center.',\n before:\n '<div style=\"display:inline-flex;align-items:center;justify-content:center\"><Child/></div>',\n after: '<Child style=\"place-self:center\"/>',\n safetyRationale:\n 'Wrapper paints nothing, carries no ref/handlers/dynamic children, and is not a combinator ' +\n 'subject; inheritable styles are folded onto the child before removal.',\n },\n match: {\n tag: 'div',\n style: { display: 'inline-flex', alignItems: 'center', justifyContent: 'center' },\n onlyChild: 'element',\n paintsNothing: true,\n },\n rewrite: {\n flattenInto: 'child',\n childGains: { placeSelf: 'center' },\n },\n // Like its block-level sibling, this centering flatten is `needs-verification` (the wrapper's own\n // `display:inline-flex` establishes a formatting context, and place-self centering only holds under\n // a flex/grid parent), so the conservative production gate (`'provably-safe'`) REVERTS it — every\n // case here is a no-match. Op-level correctness is covered by the invariant suite.\n test: {\n noMatch: [\n // Even under a static flex/grid parent the centering flatten is not provably layout-neutral.\n '<div className=\"grid\">' +\n '<div className=\"inline-flex items-center justify-center\"><span className=\"bg-red-200\">x</span></div>' +\n '</div>',\n // Non-flex/grid parent (document root) → left unchanged.\n '<div className=\"inline-flex justify-center items-center\"><div className=\"bg-red-200\">Hello</div></div>',\n // onClick is a hard opacity barrier → the wrapper is load-bearing regardless of the gate.\n '<div className=\"inline-flex justify-center items-center\" onClick={handleClick}>' +\n '<div className=\"bg-red-200\">Hello</div>' +\n '</div>',\n ],\n },\n});\n","/**\n * @domflax/patterns — flatten pattern: `nested-flex-merge`.\n *\n * Collapses a redundant nesting of two flex containers\n *\n * <div style=\"display:flex; align-items:center; gap:8px\">\n * <div style=\"display:flex; flex-direction:column\"> … </div>\n * </div>\n *\n * where the OUTER flex container's sole element child is ITSELF a flex container, into a single\n * flex container that carries the union of both elements' flex declarations. The outer wrapper's\n * box is then structural noise (it paints nothing and only establishes a flex context that the\n * merged child now also establishes), so it is removed.\n *\n * Authored with the declarative {@link pattern} API: the match is a flex `<div>` with a single\n * element child painting nothing of its own (auto-guarded against opacity barriers / combinator\n * targeting like every `flatten/*` pattern). The value-relational reasoning — the child must also\n * be a (non-combinator) flex container, the wrapper must carry only transferable flex/inheritable\n * declarations, and the two must not conflict on any shared flex property — lives in the `rewrite`\n * op-draft factory escape hatch, which folds inherited styles, transfers the wrapper's flex\n * declarations onto the child (target-wins), then unwraps the wrapper.\n */\n\nimport type {\n ConditionKey,\n CssProperty,\n MatchContext,\n NodeLike,\n RewriteFactory,\n RewriteOpDraft,\n StyleBlock,\n StyleDecl,\n StyleMap,\n} from '@domflax/core';\nimport { BASE_CONDITION, conditionKey } from '@domflax/core';\n\nimport {\n and,\n computed,\n definePattern,\n isElement,\n normalizer,\n not,\n targetedByCombinator,\n type Matcher,\n} from '@domflax/pattern-kit';\n\n/* ───────────────────────── style fixtures ───────────────────────── */\n\n/** Build a single-(base-)condition StyleMap from raw `[property, value]` pairs via the shared normalizer. */\nfunction baseConditionStyleMap(decls: readonly (readonly [string, string])[]): StyleMap {\n const map = new Map<CssProperty, StyleDecl>();\n for (const [prop, value] of decls) {\n for (const decl of normalizer.normalizeDeclaration(prop, value, false)) {\n map.set(decl.property, decl);\n }\n }\n const block: StyleBlock = { condition: BASE_CONDITION, decls: map };\n const blocks = new Map<ConditionKey, StyleBlock>([[conditionKey(BASE_CONDITION), block]]);\n return { blocks };\n}\n\n/** Both containers must declare `display:flex` (the matched signature). */\nconst DISPLAY_FLEX: StyleMap = baseConditionStyleMap([['display', 'flex']]);\n\n/**\n * The flex-CONTAINER property set this pattern is allowed to transfer from the wrapper onto the\n * child. (Longhands only, since the shared normalizer expands `gap` → `row-gap`/`column-gap`.)\n */\nconst FLEX_CONTAINER_PROPERTIES: ReadonlySet<string> = new Set<string>([\n 'display',\n 'flex-direction',\n 'flex-wrap',\n 'justify-content',\n 'align-items',\n 'align-content',\n 'place-content',\n 'place-items',\n 'row-gap',\n 'column-gap',\n]);\n\n/* ───────────────────────── style reasoning helpers (pure) ───────────────────────── */\n\n/**\n * True iff every declaration on the wrapper is either a transferable flex-container property or an\n * inheritable property (which we fold onto the child). If the wrapper carries anything else\n * (padding/margin/sizing/position/…), removing its box would change layout, so the merge is unsafe.\n */\nfunction outerMergeSafe(sm: StyleMap): boolean {\n const norm = normalizer.normalizeStyleMap(sm);\n for (const block of norm.blocks.values()) {\n for (const decl of block.decls.values()) {\n if (FLEX_CONTAINER_PROPERTIES.has(String(decl.property))) continue;\n if (decl.inherited) continue;\n return false;\n }\n }\n return true;\n}\n\n/**\n * True iff the two containers disagree on any shared flex-container property (in any matching\n * condition) — e.g. `flex-direction:row` vs `flex-direction:column`. Such a conflict makes the\n * merge ambiguous, so the pattern skips.\n */\nfunction flexConflict(outer: StyleMap, inner: StyleMap): boolean {\n const a = normalizer.normalizeStyleMap(outer);\n const b = normalizer.normalizeStyleMap(inner);\n for (const [key, blockA] of a.blocks) {\n const blockB = b.blocks.get(key);\n if (!blockB) continue;\n for (const [prop, declA] of blockA.decls) {\n if (!FLEX_CONTAINER_PROPERTIES.has(String(prop))) continue;\n const declB = blockB.decls.get(prop);\n if (declB && declB.value !== declA.value) return true;\n }\n }\n return false;\n}\n\n/** Project the wrapper's transferable flex-container declarations into a fresh StyleMap. */\nfunction extractFlexStyle(sm: StyleMap): StyleMap {\n const blocks = new Map<ConditionKey, StyleBlock>();\n for (const [key, block] of sm.blocks) {\n const decls = new Map<CssProperty, StyleDecl>();\n for (const [prop, decl] of block.decls) {\n if (FLEX_CONTAINER_PROPERTIES.has(String(prop))) decls.set(prop, decl);\n }\n if (decls.size > 0) blocks.set(key, { condition: block.condition, decls });\n }\n return { blocks };\n}\n\n/** The inner (surviving) flex container: also a flex `<div>`, and not a combinator subject (it is reparented). */\nconst isInnerFlex: Matcher = and(\n isElement('div'),\n computed(DISPLAY_FLEX),\n not(targetedByCombinator),\n);\n\n/* ───────────────────────── the pattern ───────────────────────── */\n\n/**\n * Flatten a flex container whose sole child is a compatible flex container into a single container.\n */\nexport const nestedFlexMerge = definePattern({\n name: 'nested-flex-merge',\n category: 'flatten/nested-flex-merge',\n safety: 2,\n doc: {\n title: 'Merge nested flex containers',\n summary:\n 'A flex container whose only child is itself a flex container with non-conflicting flex ' +\n 'properties is collapsed into one; the wrapper is removed and its flex declarations merge ' +\n 'onto the surviving child.',\n before:\n '<div style=\"display:flex;align-items:center;gap:8px\">' +\n '<div style=\"display:flex;flex-direction:column\"/></div>',\n after: '<div style=\"display:flex;flex-direction:column;align-items:center;gap:8px\"/>',\n safetyRationale:\n 'The wrapper paints nothing, declares only flex-container/inheritable properties, carries no ' +\n 'ref/handlers/dynamic children, and is not a combinator subject; the two containers do not ' +\n 'conflict on any flex property, so the union is unambiguous and lossless.',\n },\n match: {\n tag: 'div',\n style: { display: 'flex' },\n onlyChild: 'element',\n paintsNothing: true,\n },\n rewrite: (ctx: MatchContext, rw: RewriteFactory): readonly RewriteOpDraft[] | null => {\n const outer = ctx.node;\n const inner = ctx.onlyElementChild();\n if (!inner) return null;\n if (!isInnerFlex(inner as unknown as NodeLike, ctx)) return null;\n\n const outerStyle = ctx.computed();\n const innerStyle = ctx.computedOf(inner as unknown as NodeLike);\n\n // The wrapper must carry nothing that would be lost when its box is removed …\n if (!outerMergeSafe(outerStyle)) return null;\n // … and the two containers must agree on every shared flex property.\n if (flexConflict(outerStyle, innerStyle)) return null;\n\n return [\n // 1. Preserve inheritable values (color/font/…) by folding them onto the child first.\n rw.foldInheritedStyles(outer, inner, { conditions: 'all' }),\n // 2. Transfer the wrapper's flex-container declarations onto the child (target-wins keeps the\n // child's value for any shared property — identical anyway, we proved non-conflict).\n rw.mergeStyle(inner, null, extractFlexStyle(outerStyle), 'target-wins'),\n // 3. Remove the wrapper (structural-safe; hoists the child and preserves its IRNodeId).\n rw.unwrap(outer),\n ];\n },\n // Merging the outer flex container into the inner removes the outer's box, but a `display:flex`\n // wrapper establishes a formatting context, so this is a `needs-verification` flatten that the\n // conservative production gate (`'provably-safe'`) REVERTS — every case here is a no-match. The\n // merge's op-level correctness (purity, id-preserving unwrap, opacity-barrier safety) is asserted\n // by the invariant suite over every pattern.\n test: {\n noMatch: [\n // The merge is real but not provably layout-neutral (the wrapper establishes a flex context),\n // so under the conservative gate the nested containers are left in place.\n '<div className=\"flex items-center gap-2\" data-x=\"1\"><div className=\"flex flex-col\">X</div></div>',\n // A non-flex wrapper does not match the flex-container signature → left unchanged anyway.\n '<div className=\"block bg-blue-500\"><div className=\"flex flex-col\">X</div></div>',\n ],\n },\n});\n","/**\n * @domflax/patterns — flatten pattern: `nested-grid-merge`.\n *\n * Collapses a redundant nesting of two grid containers\n *\n * <div style=\"display:grid; gap:8px\">\n * <div style=\"display:grid; grid-template-columns:1fr 1fr\"> … </div>\n * </div>\n *\n * where the OUTER grid container's sole element child is ITSELF a grid container, into a single grid\n * container carrying the union of both elements' grid declarations. The outer wrapper's box is then\n * structural noise (it paints nothing and only establishes a grid context the merged child now also\n * establishes), so it is removed.\n *\n * This is the grid analogue of `nested-flex-merge`. The declarative match is a grid `<div>` with a\n * single element child painting nothing of its own (auto-guarded against opacity barriers / combinator\n * targeting like every `flatten/*` pattern). The value-relational reasoning — the child must also be a\n * (non-combinator) grid container, the wrapper must carry only transferable grid/inheritable\n * declarations, and the two must not conflict on any shared grid property — lives in the `rewrite`\n * op-draft factory escape hatch, which folds inherited styles, transfers the wrapper's grid\n * declarations onto the child (target-wins), then unwraps the wrapper.\n */\n\nimport type {\n ConditionKey,\n CssProperty,\n MatchContext,\n NodeLike,\n RewriteFactory,\n RewriteOpDraft,\n StyleBlock,\n StyleDecl,\n StyleMap,\n} from '@domflax/core';\nimport { BASE_CONDITION, conditionKey } from '@domflax/core';\n\nimport {\n and,\n computed,\n definePattern,\n isElement,\n normalizer,\n not,\n targetedByCombinator,\n type Matcher,\n} from '@domflax/pattern-kit';\n\n/* ───────────────────────── style fixtures ───────────────────────── */\n\n/** Build a single-(base-)condition StyleMap from raw `[property, value]` pairs via the shared normalizer. */\nfunction baseConditionStyleMap(decls: readonly (readonly [string, string])[]): StyleMap {\n const map = new Map<CssProperty, StyleDecl>();\n for (const [prop, value] of decls) {\n for (const decl of normalizer.normalizeDeclaration(prop, value, false)) {\n map.set(decl.property, decl);\n }\n }\n const block: StyleBlock = { condition: BASE_CONDITION, decls: map };\n const blocks = new Map<ConditionKey, StyleBlock>([[conditionKey(BASE_CONDITION), block]]);\n return { blocks };\n}\n\n/** Both containers must declare `display:grid` (the matched signature). */\nconst DISPLAY_GRID: StyleMap = baseConditionStyleMap([['display', 'grid']]);\n\n/**\n * The grid-CONTAINER property set this pattern is allowed to transfer from the wrapper onto the child.\n * (Longhands only, since the shared normalizer expands `gap` → `row-gap`/`column-gap`.)\n */\nconst GRID_CONTAINER_PROPERTIES: ReadonlySet<string> = new Set<string>([\n 'display',\n 'grid-template-columns',\n 'grid-template-rows',\n 'grid-template-areas',\n 'grid-auto-columns',\n 'grid-auto-rows',\n 'grid-auto-flow',\n 'justify-content',\n 'align-content',\n 'place-content',\n 'justify-items',\n 'align-items',\n 'place-items',\n 'row-gap',\n 'column-gap',\n]);\n\n/* ───────────────────────── style reasoning helpers (pure) ───────────────────────── */\n\n/**\n * True iff every declaration on the wrapper is either a transferable grid-container property or an\n * inheritable property (which we fold onto the child). If the wrapper carries anything else\n * (padding/margin/sizing/position/…), removing its box would change layout, so the merge is unsafe.\n */\nfunction outerMergeSafe(sm: StyleMap): boolean {\n const norm = normalizer.normalizeStyleMap(sm);\n for (const block of norm.blocks.values()) {\n for (const decl of block.decls.values()) {\n if (GRID_CONTAINER_PROPERTIES.has(String(decl.property))) continue;\n if (decl.inherited) continue;\n return false;\n }\n }\n return true;\n}\n\n/**\n * True iff the two containers disagree on any shared grid-container property (in any matching\n * condition) — e.g. `grid-template-columns:1fr` vs `1fr 1fr`. Such a conflict makes the merge\n * ambiguous, so the pattern skips.\n */\nfunction gridConflict(outer: StyleMap, inner: StyleMap): boolean {\n const a = normalizer.normalizeStyleMap(outer);\n const b = normalizer.normalizeStyleMap(inner);\n for (const [key, blockA] of a.blocks) {\n const blockB = b.blocks.get(key);\n if (!blockB) continue;\n for (const [prop, declA] of blockA.decls) {\n if (!GRID_CONTAINER_PROPERTIES.has(String(prop))) continue;\n const declB = blockB.decls.get(prop);\n if (declB && declB.value !== declA.value) return true;\n }\n }\n return false;\n}\n\n/** Project the wrapper's transferable grid-container declarations into a fresh StyleMap. */\nfunction extractGridStyle(sm: StyleMap): StyleMap {\n const blocks = new Map<ConditionKey, StyleBlock>();\n for (const [key, block] of sm.blocks) {\n const decls = new Map<CssProperty, StyleDecl>();\n for (const [prop, decl] of block.decls) {\n if (GRID_CONTAINER_PROPERTIES.has(String(prop))) decls.set(prop, decl);\n }\n if (decls.size > 0) blocks.set(key, { condition: block.condition, decls });\n }\n return { blocks };\n}\n\n/** The inner (surviving) grid container: also a grid `<div>`, and not a combinator subject (it is reparented). */\nconst isInnerGrid: Matcher = and(\n isElement('div'),\n computed(DISPLAY_GRID),\n not(targetedByCombinator),\n);\n\n/* ───────────────────────── the pattern ───────────────────────── */\n\n/**\n * Flatten a grid container whose sole child is a compatible grid container into a single container.\n */\nexport const nestedGridMerge = definePattern({\n name: 'nested-grid-merge',\n category: 'flatten/nested-grid-merge',\n safety: 2,\n doc: {\n title: 'Merge nested grid containers',\n summary:\n 'A grid container whose only child is itself a grid container with non-conflicting grid ' +\n 'properties is collapsed into one; the wrapper is removed and its grid declarations merge ' +\n 'onto the surviving child.',\n before:\n '<div style=\"display:grid;gap:8px\">' +\n '<div style=\"display:grid;grid-template-columns:1fr 1fr\"/></div>',\n after: '<div style=\"display:grid;grid-template-columns:1fr 1fr;gap:8px\"/>',\n safetyRationale:\n 'The wrapper paints nothing, declares only grid-container/inheritable properties, carries no ' +\n 'ref/handlers/dynamic children, and is not a combinator subject; the two containers do not ' +\n 'conflict on any grid property, so the union is unambiguous and lossless.',\n },\n match: {\n tag: 'div',\n style: { display: 'grid' },\n onlyChild: 'element',\n paintsNothing: true,\n },\n rewrite: (ctx: MatchContext, rw: RewriteFactory): readonly RewriteOpDraft[] | null => {\n const outer = ctx.node;\n const inner = ctx.onlyElementChild();\n if (!inner) return null;\n if (!isInnerGrid(inner as unknown as NodeLike, ctx)) return null;\n\n const outerStyle = ctx.computed();\n const innerStyle = ctx.computedOf(inner as unknown as NodeLike);\n\n // The wrapper must carry nothing that would be lost when its box is removed …\n if (!outerMergeSafe(outerStyle)) return null;\n // … and the two containers must agree on every shared grid property.\n if (gridConflict(outerStyle, innerStyle)) return null;\n\n return [\n // 1. Preserve inheritable values (color/font/…) by folding them onto the child first.\n rw.foldInheritedStyles(outer, inner, { conditions: 'all' }),\n // 2. Transfer the wrapper's grid-container declarations onto the child (target-wins keeps the\n // child's value for any shared property — identical anyway, we proved non-conflict).\n rw.mergeStyle(inner, null, extractGridStyle(outerStyle), 'target-wins'),\n // 3. Remove the wrapper (structural-safe; hoists the child and preserves its IRNodeId).\n rw.unwrap(outer),\n ];\n },\n // Like its flex sibling, this merge removes the outer container's box, but a `display:grid` wrapper\n // establishes a formatting context, so it is a `needs-verification` flatten that the conservative\n // production gate (`'provably-safe'`) REVERTS — every case here is a no-match. Op-level correctness\n // is asserted by the invariant suite over every pattern.\n test: {\n noMatch: [\n // The merge is real but not provably layout-neutral (the wrapper establishes a grid context),\n // so under the conservative gate the nested containers are left in place.\n '<div className=\"grid gap-2\" data-x=\"1\"><div className=\"grid grid-cols-2\">X</div></div>',\n // A non-grid wrapper does not match the grid-container signature → left unchanged anyway.\n '<div className=\"block bg-blue-500\"><div className=\"grid grid-cols-2\">X</div></div>',\n ],\n },\n});\n","/**\n * @domflax/patterns — flatten pattern: `passthrough-wrapper`.\n *\n * Collapses a purely-structural wrapper that exists for no reason at all:\n *\n * <div><Child/></div>\n *\n * The wrapper paints nothing, establishes no box / formatting / stacking context, carries no\n * attributes beyond an (optional) inert class, holds exactly one element child, and is free of every\n * opacity barrier (ref / event-handlers / dynamic children / dangerous html / spread / component).\n * Such a `<div>` is pure DOM noise: removing it and hoisting the child is invisible to both paint\n * and layout.\n *\n * Authored with the declarative {@link definePattern} API. The opacity-barrier + selector-safety\n * guards (ref/handlers/dynamic-children/raw-html/combinator/reparent-impact) are applied\n * automatically for every `flatten/*` pattern; the `where` predicates add the passthrough-specific\n * requirements (no box/formatting/stacking context, no own attrs, no dynamic/spread classes, not a\n * component, not a structural-pseudo subject).\n */\n\nimport type {\n DeepReadonly,\n IRElement,\n IRNode,\n IRNodeId,\n NodeLike,\n NodeMeta,\n} from '@domflax/core';\n\nimport { definePattern, hasDynamicClasses, not, type Matcher } from '@domflax/pattern-kit';\n\n/* ───────────────────────── local meta/attr/selector matchers ───────────────────────── */\n\nfunction metaOf(node: NodeLike): DeepReadonly<NodeMeta> | null {\n const n = node as DeepReadonly<IRNode>;\n return n.kind === 'element' ? (n as DeepReadonly<IRElement>).meta : null;\n}\n\nfunction elementOf(node: NodeLike): DeepReadonly<IRElement> | null {\n const n = node as DeepReadonly<IRNode>;\n return n.kind === 'element' ? (n as DeepReadonly<IRElement>) : null;\n}\n\n/**\n * Element establishes some box / formatting / stacking context, is a containing block, or exposes\n * custom properties to a descendant — any of which means removing its box could shift layout or\n * break a `var()` coupling, so it is NOT a passthrough.\n */\nconst establishesContext: Matcher = (node) => {\n const m = metaOf(node);\n if (!m) return false;\n return (\n m.establishesBox ||\n m.establishesFormattingContext ||\n m.establishesStackingContext ||\n m.isContainingBlock ||\n m.declaresCustomProperties\n );\n};\n\n/** Hard opacity barriers beyond the auto-applied set: spread attrs, component identity. */\nconst hasSpreadAttrs: Matcher = (node) => metaOf(node)?.hasSpreadAttrs ?? false;\nconst isComponentNode: Matcher = (node) => metaOf(node)?.isComponent ?? false;\n\n/** Element carries own attributes (id / data-* / …) beyond its class list — possible selector/JS hook. */\nconst hasOwnAttrs: Matcher = (node) => {\n const el = elementOf(node);\n if (!el) return false;\n return el.attrs.entries.size > 0 || el.attrs.spreads.length > 0;\n};\n\n/**\n * Element is the subject of a structural pseudo (`:first/:last/:only/:nth-*`). Honours the meta flag\n * and the precomputed {@link SelectorIndex}.\n */\nconst targetedByStructuralPseudo: Matcher = (node, ctx) => {\n const el = elementOf(node);\n if (!el) return false;\n if (el.meta.targetedByStructuralPseudo) return true;\n return ctx.selectors.targetedByStructuralPseudo(el.id as unknown as IRNodeId);\n};\n\n/* ───────────────────────── the pattern ───────────────────────── */\n\n/**\n * Flatten a do-nothing `<div>` wrapper into its sole element child, folding any inheritable styles\n * down first so inherited values survive the box removal.\n */\nexport const passthroughWrapper = definePattern({\n name: 'passthrough-wrapper',\n category: 'flatten/passthrough-wrapper',\n safety: 2,\n doc: {\n title: 'Flatten passthrough wrapper',\n summary:\n 'A div with no own visual/box style, no attributes beyond an inert class, exactly one ' +\n 'element child, and no opacity barriers is removed; its sole child is hoisted in its place.',\n before: '<div><Child/></div>',\n after: '<Child/>',\n safetyRationale:\n 'Wrapper paints nothing and establishes no layout/paint/var context, carries no ' +\n 'ref/handlers/dynamic-children/html/spread/component identity, owns no targetable attrs, ' +\n 'and is not a combinator/structural-pseudo subject (reparenting changes no match-set); ' +\n 'inheritable styles are folded onto the child before removal.',\n },\n match: {\n tag: 'div',\n onlyChild: 'element',\n paintsNothing: true,\n where: [\n not(establishesContext),\n not(hasOwnAttrs),\n not(hasDynamicClasses),\n not(hasSpreadAttrs),\n not(isComponentNode),\n not(targetedByStructuralPseudo),\n ],\n },\n rewrite: { flattenInto: 'child' },\n test: {\n cases: [\n {\n // A plain, style-free wrapper paints nothing and establishes no context → a provably-safe\n // flatten under the conservative gate: the wrapper is removed and its sole child hoisted.\n before: '<div><a className=\"bg-red-200\">Link</a></div>',\n after: '<a className=\"bg-red-200\">Link</a>',\n },\n ],\n noMatch: [\n // A ref pins the wrapper's element identity (a hard opacity barrier) → not a passthrough.\n '<div ref={rootRef}><a className=\"bg-red-200\">Link</a></div>',\n // A `display:flex` wrapper establishes a formatting context, so removing its box is NOT\n // provably layout-neutral → the conservative gate leaves it in place.\n '<div className=\"flex\"><a className=\"bg-red-200\">Link</a></div>',\n ],\n },\n});\n","/**\n * @domflax/patterns — flatten pattern: `redundant-fragment`.\n *\n * Collapses a fragment that wraps exactly one child\n *\n * <><Child/></> → <Child/>\n *\n * A fragment renders no box of its own, so a fragment whose sole purpose is to wrap a single node\n * is pure structural noise: splicing the child up into the fragment's slot is invisible in both\n * the rendered DOM and the project's CSS cascade.\n *\n * Anchoring: the pass manager only visits ELEMENT nodes (see core's `elementIds`), never fragments,\n * so this pattern is anchored on the fragment's sole *element* child and removes the PARENT fragment.\n * Because the match is PARENT-anchored (and reads a fragment's `meta`, which the element-only\n * combinator vocabulary cannot inspect), it uses the declarative API's two escape hatches: a raw\n * `match` predicate and a raw `rewrite` op-draft factory.\n */\n\nimport type {\n DeepReadonly,\n ElementLike,\n IRNode,\n IRNodeId,\n MatchContext,\n NodeLike,\n RewriteFactory,\n RewriteOpDraft,\n} from '@domflax/core';\n\nimport { definePattern } from '@domflax/pattern-kit';\n\n/* ───────────────────────── match predicate (escape hatch) ───────────────────────── */\n\n/**\n * Matches an element whose PARENT is a redundant, unwrappable fragment: a non-root fragment with\n * exactly one child (this element), free of every opacity barrier and CSS-targeting coupling.\n */\nfunction parentIsRedundantFragment(node: NodeLike, ctx: MatchContext): boolean {\n const el = node as DeepReadonly<IRNode>;\n if (el.kind !== 'element') return false;\n\n const parentId = el.parent;\n if (parentId == null) return false;\n\n const parent = ctx.doc.nodes.get(parentId);\n if (!parent || parent.kind !== 'fragment') return false;\n\n // Never unwrap the document root (it must always be a fragment — IRDocument invariant).\n if (parent.parent == null) return false;\n\n // Exactly one child (counting EVERY kind) ⇒ the anchor element is the fragment's sole child.\n if (parent.children.length !== 1) return false;\n\n // Hard opacity barriers on the fragment: keyed `<Fragment key>`, ref/handlers/dynamic children/\n // dangerous HTML/spread/component identity. Any of these means the fragment is load-bearing.\n const m = parent.meta;\n if (\n m.hasKey ||\n m.hasRef ||\n m.hasEventHandlers ||\n m.hasDynamicChildren ||\n m.hasDangerousHtml ||\n m.hasSpreadAttrs ||\n m.isComponent\n ) {\n return false;\n }\n\n // CSS-selector safety: the fragment (or its reparented child) must not move any combinator /\n // structural-pseudo match-set. Honour both the frontend-set meta flags and the SelectorIndex.\n if (m.targetedByCombinator || m.targetedByStructuralPseudo) return false;\n const fid = parentId as unknown as IRNodeId;\n if (ctx.selectors.targetedByCombinator(fid) || ctx.selectors.targetedByStructuralPseudo(fid)) {\n return false;\n }\n if (ctx.selectors.reparentImpact(fid).size > 0) return false;\n\n return true;\n}\n\n/* ───────────────────────── the pattern ───────────────────────── */\n\n/**\n * Flatten a fragment that wraps exactly one child into that child.\n *\n * Safety level 1 (`safe`): a purely structural, style-free, selector-transparent cleanup.\n */\nexport const redundantFragment = definePattern({\n name: 'redundant-fragment',\n category: 'flatten/redundant-fragment',\n safety: 1,\n doc: {\n title: 'Flatten redundant single-child fragment',\n summary:\n 'A fragment whose only child is a single node is removed; the child is spliced up into the ' +\n \"fragment's slot, preserving its IRNodeId, siblings, attributes and the CSS cascade.\",\n before: '<><Child/></>',\n after: '<Child/>',\n safetyRationale:\n 'A fragment paints nothing and renders no box; with exactly one child its removal changes ' +\n 'no sibling/structural-pseudo match-set. Keyed fragments and fragments carrying ' +\n 'ref/handlers/dynamic-children/raw-html/spread are excluded as opacity barriers.',\n },\n match: parentIsRedundantFragment,\n rewrite: (ctx: MatchContext, rw: RewriteFactory): readonly RewriteOpDraft[] | null => {\n const parentId = ctx.node.parent;\n if (parentId == null) return null;\n const fragment = ctx.doc.nodes.get(parentId);\n if (!fragment || fragment.kind !== 'fragment') return null;\n // Splice the sole child up into the fragment's slot, deleting ONLY the fragment node.\n return [rw.unwrap(fragment as unknown as ElementLike)];\n },\n test: {\n cases: [\n {\n // A fragment renders no box, so unwrapping a single-child fragment is always layout-identical\n // → a provably-safe flatten: the child is spliced up into the fragment's slot.\n before: '<><span className=\"bg-red-200\">Hi</span></>',\n after: '<span className=\"bg-red-200\">Hi</span>',\n },\n ],\n noMatch: [\n // Two children ⇒ not a single-child fragment, so the fragment is load-bearing and stays.\n '<><span className=\"bg-red-200\">A</span><span className=\"bg-green-200\">B</span></>',\n ],\n },\n});\n","/**\n * @domflax/patterns — flatten pattern: `redundant-inline-wrapper`.\n *\n * Collapses a purely-structural INLINE wrapper:\n *\n * <span><Child/></span> (display:inline, no own style)\n *\n * An inline `<span>` that paints nothing, establishes no box / formatting / stacking context, carries\n * no attributes beyond an (optional) inert class, declares no custom properties, and holds exactly one\n * element child is pure inline noise. An empty inline box merely wraps its child's box; removing it and\n * hoisting the child leaves both paint and layout untouched (the surviving child folds the inheritable\n * declarations the span carried).\n *\n * This is the inline sibling of `passthrough-wrapper` (which targets `<div>`): the same opacity-barrier\n * + selector-safety guards are auto-applied by the `pattern()` factory for every `flatten/*` pattern;\n * the `where` predicates add the inline-passthrough requirements (display must be the inline default,\n * no box/formatting/stacking context or var coupling, no own attrs / dynamic-or-spread classes, not a\n * component, not a structural-pseudo subject).\n */\n\nimport type {\n CssProperty,\n DeepReadonly,\n IRElement,\n IRNode,\n IRNodeId,\n NodeLike,\n NodeMeta,\n StyleMap,\n} from '@domflax/core';\n\nimport { definePattern, hasDynamicClasses, not, type Matcher } from '@domflax/pattern-kit';\n\n/* ───────────────────────── local meta/attr/selector matchers ───────────────────────── */\n\nfunction asEl(node: NodeLike): DeepReadonly<IRElement> | null {\n const n = node as DeepReadonly<IRNode>;\n return n.kind === 'element' ? (n as DeepReadonly<IRElement>) : null;\n}\n\nfunction metaOf(node: NodeLike): DeepReadonly<NodeMeta> | null {\n return asEl(node)?.meta ?? null;\n}\n\n/**\n * Element establishes some box / formatting / stacking context, is a containing block, or exposes\n * custom properties to a descendant — removing its box could shift layout or sever a `var()` coupling,\n * so it is NOT an inline passthrough.\n */\nconst establishesContext: Matcher = (node) => {\n const m = metaOf(node);\n if (!m) return false;\n return (\n m.establishesBox ||\n m.establishesFormattingContext ||\n m.establishesStackingContext ||\n m.isContainingBlock ||\n m.declaresCustomProperties\n );\n};\n\n/** Hard opacity barriers beyond the auto-applied set: spread attrs, component identity. */\nconst hasSpreadAttrs: Matcher = (node) => metaOf(node)?.hasSpreadAttrs ?? false;\nconst isComponentNode: Matcher = (node) => metaOf(node)?.isComponent ?? false;\n\n/** Element carries own attributes (id / data-* / …) beyond its class list — possible selector/JS hook. */\nconst hasOwnAttrs: Matcher = (node) => {\n const el = asEl(node);\n if (!el) return false;\n return el.attrs.entries.size > 0 || el.attrs.spreads.length > 0;\n};\n\n/**\n * Element is the subject of a structural pseudo (`:first/:last/:only/:nth-*`). Honours the meta flag\n * and the precomputed {@link SelectorIndex}.\n */\nconst targetedByStructuralPseudo: Matcher = (node, ctx) => {\n const el = asEl(node);\n if (!el) return false;\n if (el.meta.targetedByStructuralPseudo) return true;\n return ctx.selectors.targetedByStructuralPseudo(el.id as unknown as IRNodeId);\n};\n\nconst DISPLAY = 'display' as CssProperty;\n\n/**\n * Element sets `display` to anything other than the inline default in ANY condition. An\n * inline-block / block / flex / grid / contents span is NOT an inline passthrough — its box (or lack\n * of one) participates in layout differently from a bare inline box.\n */\nconst hasNonInlineDisplay: Matcher = (node, ctx) => {\n const el = asEl(node);\n if (!el) return false;\n const sm: StyleMap = ctx.computedOf(el as unknown as NodeLike) ?? (el.computed as StyleMap);\n for (const block of sm.blocks.values()) {\n const decl = block.decls.get(DISPLAY);\n if (decl && String(decl.value) !== 'inline') return true;\n }\n return false;\n};\n\n/* ───────────────────────── the pattern ───────────────────────── */\n\n/**\n * Flatten a do-nothing inline `<span>` wrapper into its sole element child, folding any inheritable\n * styles down first so inherited values survive the box removal.\n */\nexport const redundantInlineWrapper = definePattern({\n name: 'redundant-inline-wrapper',\n category: 'flatten/redundant-inline-wrapper',\n safety: 2,\n doc: {\n title: 'Flatten redundant inline wrapper',\n summary:\n 'An inline span with no own visual/box style, no attributes beyond an inert class, exactly ' +\n 'one element child, and no opacity barriers is removed; its sole child is hoisted in its place.',\n before: '<span><Child/></span>',\n after: '<Child/>',\n safetyRationale:\n 'An empty inline box paints nothing and establishes no layout/paint/var context; with the ' +\n 'inline default display and a single element child its removal changes no paint and no flow. ' +\n 'The span carries no ref/handlers/dynamic-children/html/spread/component identity, owns no ' +\n 'targetable attrs, and is not a combinator/structural-pseudo subject; inheritable styles are ' +\n 'folded onto the child before removal.',\n },\n match: {\n tag: 'span',\n onlyChild: 'element',\n paintsNothing: true,\n where: [\n not(hasNonInlineDisplay),\n not(establishesContext),\n not(hasOwnAttrs),\n not(hasDynamicClasses),\n not(hasSpreadAttrs),\n not(isComponentNode),\n not(targetedByStructuralPseudo),\n ],\n },\n rewrite: { flattenInto: 'child' },\n test: {\n cases: [\n {\n // An empty inline span paints nothing and establishes no context → a provably-safe flatten:\n // the span is removed and its sole child hoisted in place.\n before: '<span><a className=\"text-blue-500\">Link</a></span>',\n after: '<a className=\"text-blue-500\">Link</a>',\n },\n ],\n noMatch: [\n // A ref pins the span's element identity (a hard opacity barrier) → not a passthrough.\n '<span ref={spanRef}><a className=\"text-blue-500\">Link</a></span>',\n // The span paints its own background (own visual style) → kept.\n '<span className=\"bg-green-200\"><a className=\"text-blue-500\">Link</a></span>',\n // Non-inline display (inline-block) participates in layout differently → kept.\n '<span className=\"inline-block\"><a className=\"text-blue-500\">Link</a></span>',\n ],\n },\n});\n","/**\n * @domflax/patterns — compress pattern: `border-radius-shorthand`.\n *\n * Collapses an element whose four corner radii are expressed as separate longhand declarations and\n * are ALL EQUAL into the single CSS `border-radius` shorthand:\n *\n * border-top-left-radius:0.5rem; border-top-right-radius:0.5rem;\n * border-bottom-right-radius:0.5rem; border-bottom-left-radius:0.5rem\n * ⇒ border-radius:0.5rem (Tailwind `rounded-lg`)\n *\n * The IR's computed StyleMap keeps each corner as its own longhand (Tailwind's `rounded-tl-*` /\n * `rounded-tr-*` / … each resolve to one corner property). This pass runs the collapse in reverse on\n * the computed map ONLY when all four corners share one value — the single case that maps cleanly to\n * a single Tailwind utility (the CSS 2-value `border-radius` form is DIAGONAL, which has no clean\n * `rounded-*` edge utility, so per-corner differences are intentionally left alone). Rebuilding the\n * map with one `border-radius` decl lets the minimizing reverse-emit pick the single `rounded-*`\n * token covering all four corners instead of two edge tokens.\n *\n * Authored with the declarative {@link pattern} API: `definePattern` auto-applies the compress safety guards — a dynamic or opaque class list\n * and combinator-subject selectors are excluded (a ref / event handler / dynamic child / dangerous\n * HTML never blocks a class-only rewrite); the\n * `rewriteClasses` recipe rebuilds the class StyleMap, declining (`null`) unless the four corners are\n * present, concrete, equal, and share an `!important` flag.\n */\n\nimport type { ConditionKey, CssProperty, CssValue, StyleBlock, StyleDecl, StyleMap } from '@domflax/core';\nimport { BASE_CONDITION, conditionKey } from '@domflax/core';\n\nimport { definePattern } from '@domflax/pattern-kit';\n\n/* ───────────────────────── corner analysis ───────────────────────── */\n\n/** The four corner-radius longhands. */\nconst CORNERS = [\n 'border-top-left-radius',\n 'border-top-right-radius',\n 'border-bottom-right-radius',\n 'border-bottom-left-radius',\n] as const satisfies readonly string[];\n\nconst CORNER_SET: ReadonlySet<string> = new Set<string>(CORNERS);\n\nconst BASE_KEY: ConditionKey = conditionKey(BASE_CONDITION);\n\nconst RADIUS = 'border-radius' as CssProperty;\n\n/** CSS-wide keywords for which a corner collapse is pointless or unsound. */\nconst NON_COLLAPSIBLE_VALUES: ReadonlySet<string> = new Set<string>([\n 'initial',\n 'inherit',\n 'unset',\n 'revert',\n 'revert-layer',\n]);\n\n/** The single value all four corners fold into (carrying important / relative-unit flags). */\ninterface RadiusFold {\n readonly value: string;\n readonly important: boolean;\n readonly relative: boolean;\n}\n\n/**\n * Inspect the BASE-condition block of `sm` and, iff all four corner longhands are present, share a\n * uniform `!important` flag, hold a concrete (non-keyword) value, and are ALL EQUAL, return that\n * value. Returns `null` when the corners cannot fold to one `border-radius`.\n */\nfunction analyzeRadius(sm: StyleMap): RadiusFold | null {\n const block = sm.blocks.get(BASE_KEY);\n if (!block) return null;\n\n const corners: StyleDecl[] = [];\n for (const corner of CORNERS) {\n const decl = block.decls.get(corner as CssProperty);\n if (!decl) return null;\n corners.push(decl);\n }\n\n // A shorthand cannot carry per-corner `!important`; only fold a uniform flag.\n const important = corners[0]!.important;\n if (!corners.every((d) => d.important === important)) return null;\n\n const value = String(corners[0]!.value);\n if (NON_COLLAPSIBLE_VALUES.has(value)) return null;\n if (!corners.every((d) => String(d.value) === value)) return null;\n\n const relative = corners.some((d) => d.relativeToParent);\n return { value, important, relative };\n}\n\n/* ───────────────────────── style rebuild ───────────────────────── */\n\n/** Rebuild `sm` with the four BASE-block corner longhands replaced by one `border-radius` decl. */\nfunction withFoldedRadius(sm: StyleMap, fold: RadiusFold): StyleMap {\n const blocks = new Map<ConditionKey, StyleBlock>();\n for (const [key, block] of sm.blocks) {\n if (key !== BASE_KEY) {\n blocks.set(key, block);\n continue;\n }\n const decls = new Map<CssProperty, StyleDecl>();\n for (const [prop, decl] of block.decls) {\n if (CORNER_SET.has(String(prop))) continue; // drop the four corner longhands\n decls.set(prop, decl);\n }\n const shorthand: StyleDecl = {\n property: RADIUS,\n value: fold.value as CssValue,\n important: fold.important,\n relativeToParent: fold.relative,\n inherited: false, // border-radius is never inherited\n };\n decls.set(shorthand.property, shorthand);\n blocks.set(key, { condition: block.condition, decls });\n }\n return { blocks };\n}\n\n/* ───────────────────────── the pattern ───────────────────────── */\n\n/** Fold four equal corner radii into the single `border-radius` shorthand. */\nexport const borderRadiusShorthand = definePattern({\n name: 'border-radius-shorthand',\n category: 'compress/border-radius-shorthand',\n safety: 1,\n doc: {\n title: 'Collapse equal corner radii into border-radius',\n summary:\n 'An element whose four corner radii (border-*-radius longhands) are all equal is rewritten to ' +\n 'the single Tailwind rounded-* utility (border-radius === the four equal corners).',\n before: '<div class=\"rounded-tl-lg rounded-tr-lg rounded-br-lg rounded-bl-lg\"/>',\n after: '<div class=\"rounded-lg\"/>',\n safetyRationale:\n '`border-radius` is value-identical to four equal corner radii — a class-only change. It is safe ' +\n 'even on an element with a ref, event handler, dynamic child, or dangerouslySetInnerHTML — a ' +\n 'className rewrite touches none of them; only a dynamic/opaque class list or a combinator-subject ' +\n 'class is excluded, so no behaviour or project selector is disturbed.',\n },\n rewrite: {\n rewriteClasses(computed: StyleMap): StyleMap | null {\n const fold = analyzeRadius(computed);\n return fold ? withFoldedRadius(computed, fold) : null;\n },\n },\n test: {\n cases: [\n {\n // The four equal corner longhands collapse to a `border-radius` decl at the IR level; the\n // minimizing reverse-emit then picks the single shortest utility (`rounded-lg`) that reproduces\n // it, replacing the four `rounded-{tl,tr,br,bl}-lg` tokens. `bg-red-200` is preserved.\n before: '<div className=\"rounded-tl-lg rounded-tr-lg rounded-br-lg rounded-bl-lg bg-red-200\">box</div>',\n after: '<div className=\"bg-red-200 rounded-lg\">box</div>',\n },\n ],\n // Corners differ (top corners vs bottom corners) → no all-equal collapse.\n noMatch: ['<div className=\"rounded-t-lg rounded-b-sm bg-red-200\">box</div>'],\n },\n});\n","/**\n * @domflax/patterns — compress pattern: `border-shorthand`.\n *\n * Collapses an element whose four border-side WIDTHS are expressed as separate longhand declarations\n * back into the shortest equivalent `border-width` shorthand:\n *\n * border-top-width:2px; border-right-width:2px; border-bottom-width:2px; border-left-width:2px\n * ⇒ border-width:2px (Tailwind `border-2`)\n *\n * border-top-width:2px; border-bottom-width:2px; border-left-width:4px; border-right-width:4px\n * ⇒ border-width:2px 4px (Tailwind `border-y-2 border-x-4`)\n *\n * Tailwind's per-side / per-axis width utilities (`border-t-*`, `border-x-*`, …) each resolve to the\n * matching `border-*-width` longhand(s); the shared normalizer keeps them longhand. This pass runs\n * the expansion in reverse on the computed map ONLY when the four widths fold cleanly into a 1- or\n * 2-value form — i.e. `top===bottom` AND `left===right`. Rebuilding the map with one `border-width`\n * shorthand lets the minimizing reverse-emit pick the single/paired utility (`border-2`, or\n * `border-x-* border-y-*`) instead of four per-side tokens. Only WIDTH is folded — border style and\n * color are independent longhands the resolver carries separately, so this never disturbs them.\n *\n * Authored with the declarative {@link pattern} API: `definePattern` auto-applies the compress safety guards — a dynamic or opaque class list\n * and combinator-subject selectors are excluded (a ref / event handler / dynamic child / dangerous\n * HTML never blocks a class-only rewrite); the `rewriteClasses`\n * recipe rebuilds the class StyleMap, declining (`null`) unless the four widths fold cleanly.\n */\n\nimport type { ConditionKey, CssProperty, CssValue, StyleBlock, StyleDecl, StyleMap } from '@domflax/core';\nimport { BASE_CONDITION, conditionKey } from '@domflax/core';\n\nimport { definePattern } from '@domflax/pattern-kit';\n\n/* ───────────────────────── border-width analysis ───────────────────────── */\n\n/** The four border-width longhands, in CSS shorthand order: top, right, bottom, left. */\nconst WIDTH_SIDES = [\n 'border-top-width',\n 'border-right-width',\n 'border-bottom-width',\n 'border-left-width',\n] as const satisfies readonly string[];\n\nconst WIDTH_SIDE_SET: ReadonlySet<string> = new Set<string>(WIDTH_SIDES);\n\nconst BASE_KEY: ConditionKey = conditionKey(BASE_CONDITION);\n\nconst BORDER_WIDTH = 'border-width' as CssProperty;\n\n/** The collapsed shorthand the four widths fold into (carrying important / relative-unit flags). */\ninterface WidthFold {\n readonly value: string; // 1-value (`2px`) or 2-value (`2px 4px`) form\n readonly important: boolean;\n readonly relative: boolean;\n}\n\n/**\n * Inspect the BASE-condition block of `sm` and, iff all four border-width longhands are present,\n * share a uniform `!important` flag, and form matching x/y pairs (`top===bottom` AND `left===right`),\n * return the shortest equivalent shorthand value. Returns `null` when the sides cannot fold.\n */\nfunction analyzeWidth(sm: StyleMap): WidthFold | null {\n const block = sm.blocks.get(BASE_KEY);\n if (!block) return null;\n\n const sides: StyleDecl[] = [];\n for (const side of WIDTH_SIDES) {\n const decl = block.decls.get(side as CssProperty);\n if (!decl) return null;\n sides.push(decl);\n }\n const [top, right, bottom, left] = sides as [StyleDecl, StyleDecl, StyleDecl, StyleDecl];\n\n // A shorthand cannot carry per-side `!important`; only fold a uniform flag.\n if (\n !(\n top.important === right.important &&\n right.important === bottom.important &&\n bottom.important === left.important\n )\n ) {\n return null;\n }\n\n const tv = String(top.value);\n const rv = String(right.value);\n const bv = String(bottom.value);\n const lv = String(left.value);\n\n // Only the `border-*` (all equal) and `border-x-* border-y-*` (matching pairs) shapes are in scope.\n if (tv !== bv || lv !== rv) return null;\n\n const value = tv === lv ? tv : `${tv} ${lv}`;\n const relative = sides.some((d) => d.relativeToParent);\n return { value, important: top.important, relative };\n}\n\n/* ───────────────────────── style rebuild ───────────────────────── */\n\n/** Rebuild `sm` with the four BASE-block border-width longhands replaced by one shorthand. */\nfunction withFoldedWidth(sm: StyleMap, fold: WidthFold): StyleMap {\n const blocks = new Map<ConditionKey, StyleBlock>();\n for (const [key, block] of sm.blocks) {\n if (key !== BASE_KEY) {\n blocks.set(key, block);\n continue;\n }\n const decls = new Map<CssProperty, StyleDecl>();\n for (const [prop, decl] of block.decls) {\n if (WIDTH_SIDE_SET.has(String(prop))) continue; // drop the four width longhands\n decls.set(prop, decl);\n }\n const shorthand: StyleDecl = {\n property: BORDER_WIDTH,\n value: fold.value as CssValue,\n important: fold.important,\n relativeToParent: fold.relative,\n inherited: false, // border-width is never inherited\n };\n decls.set(shorthand.property, shorthand);\n blocks.set(key, { condition: block.condition, decls });\n }\n return { blocks };\n}\n\n/* ───────────────────────── the pattern ───────────────────────── */\n\n/** Compress an element's four equal/paired border-width longhands into the shortest shorthand. */\nexport const borderShorthand = definePattern({\n name: 'border-shorthand',\n category: 'compress/border-shorthand',\n safety: 1,\n doc: {\n title: 'Collapse border-width longhands to shorthand',\n summary:\n 'Equal border width on all four sides (or matching x/y pairs) expressed as separate longhand ' +\n 'declarations is collapsed to the shortest equivalent border-width shorthand (border-* / ' +\n 'border-x-* border-y-*).',\n before: '<div class=\"border-t-2 border-r-2 border-b-2 border-l-2\"/>',\n after: '<div class=\"border-2\"/>',\n safetyRationale:\n 'A value-preserving re-serialization of the same computed border widths (style/color longhands ' +\n 'untouched) — a class-only change. It is safe even on an element with a ref, event handler, dynamic ' +\n 'child, or dangerouslySetInnerHTML — a className rewrite touches none of them; only a ' +\n 'dynamic/opaque class list or a combinator-subject class is excluded, so no behaviour or project ' +\n 'selector is disturbed.',\n },\n rewrite: {\n rewriteClasses(computed: StyleMap): StyleMap | null {\n const fold = analyzeWidth(computed);\n return fold ? withFoldedWidth(computed, fold) : null;\n },\n },\n test: {\n cases: [\n {\n // The four equal width longhands collapse to a `border-width` shorthand at the IR level, and the\n // minimizing reverse-emit picks the single shortest utility (`border-2`) that reproduces it,\n // replacing the four `border-{t,r,b,l}-2` tokens. `bg-red-200` is preserved.\n before: '<div className=\"border-t-2 border-r-2 border-b-2 border-l-2 bg-red-200\">box</div>',\n after: '<div className=\"bg-red-200 border-2\">box</div>',\n },\n ],\n // Asymmetric widths (top != bottom) cannot fold into a shorthand.\n noMatch: ['<div className=\"border-t-2 border-r-4 border-b-8 border-l-4 bg-red-200\">box</div>'],\n },\n});\n","/**\n * @domflax/patterns — compress pattern: `dedupe-classes`.\n *\n * Removes duplicate / fully-overridden class tokens that resolve to the same property where a\n * LATER token wins, leaving the minimal set of tokens with an IDENTICAL computed style. The\n * canonical case:\n *\n * <p class=\"text-sm text-lg\">…</p> → <p class=\"text-lg\">…</p>\n *\n * Both `text-sm` and `text-lg` set `font-size`; resolution already made `text-lg` win, so the\n * computed `font-size` is `text-lg`'s value and `text-sm` contributes NOTHING to the final\n * computed style. The earlier token is pure noise and can be dropped without changing a pixel.\n *\n * How redundancy is detected (purely from the already-resolved, normalized computed StyleMap):\n * • every declaration carries provenance — `origin` (the winning token) and `shadowed`\n * (the tokens it overrode);\n * • a class token is FULLY OVERRIDDEN iff it appears in some declaration's `shadowed` list but\n * is NOT the winning `origin` of any declaration across ANY style condition. Such a token can\n * be deleted with zero effect on the computed style.\n *\n * Authored with the declarative {@link pattern} API: `definePattern` auto-applies the compress safety guards — a dynamic or opaque class list\n * and combinator-subject selectors are excluded (a ref / event handler / dynamic child / dangerous\n * HTML never blocks a class-only rewrite); the `dropClasses` recipe returns the set of\n * fully-overridden, resolver-droppable tokens to delete (their `shadowed` provenance is pruned\n * automatically before the minimal class StyleMap is re-installed).\n */\n\nimport type { MatchContext, StyleMap } from '@domflax/core';\n\nimport { definePattern } from '@domflax/pattern-kit';\n\n/* ───────────────────────── provenance analysis ───────────────────────── */\n\n/** Winners (tokens that win some declaration) and shadowed (tokens overridden somewhere). */\nfunction findRedundantClasses(computed: StyleMap): {\n winners: ReadonlySet<string>;\n shadowed: ReadonlySet<string>;\n} {\n const winners = new Set<string>();\n const shadowed = new Set<string>();\n for (const block of computed.blocks.values()) {\n for (const decl of block.decls.values()) {\n if (decl.origin && decl.origin.kind === 'class') winners.add(decl.origin.className);\n for (const o of decl.shadowed ?? []) {\n if (o.kind === 'class') shadowed.add(o.className);\n }\n }\n }\n return { winners, shadowed };\n}\n\n/* ───────────────────────── the pattern ───────────────────────── */\n\n/**\n * Collapse a class list to the minimal token set that yields an identical computed style, by\n * dropping tokens whose declarations are fully overridden by later tokens.\n */\nexport const dedupeClasses = definePattern({\n name: 'dedupe-classes',\n category: 'compress/dedupe-classes',\n safety: 1,\n doc: {\n title: 'Dedupe fully-overridden class tokens',\n summary:\n 'Drops class tokens whose every declaration is overridden by a later token resolving to the ' +\n 'same property; the surviving token set produces a byte-for-byte identical computed style.',\n before: '<p class=\"text-sm text-lg\" />',\n after: '<p class=\"text-lg\" />',\n safetyRationale:\n 'A fully-overridden token contributes nothing to the computed style in any condition, so removing ' +\n 'it changes no pixels — a class-only change. It is safe even on an element with a ref, event ' +\n 'handler, dynamic child, or dangerouslySetInnerHTML — a className rewrite touches none of them; ' +\n 'only a dynamic/opaque class list or a combinator-subject class is excluded, so no behaviour or ' +\n 'project selector is disturbed.',\n },\n rewrite: {\n dropClasses(computed: StyleMap, ctx: MatchContext): Iterable<string> {\n const { winners, shadowed } = findRedundantClasses(computed);\n const drop = new Set<string>();\n for (const cls of shadowed) {\n // A token that still wins SOME property elsewhere is not redundant — keep it.\n if (winners.has(cls)) continue;\n // Selector-membership safety: only drop a token referenced purely as a plain subject.\n if (!ctx.resolver.selectorUsage(cls).droppable) continue;\n drop.add(cls);\n }\n return drop;\n },\n },\n test: {\n cases: [\n {\n // `text-sm` is fully overridden by `text-lg` (both set font-size + line-height). The resolver\n // records that shadowing in provenance and reports the Tailwind utility as droppable, so the\n // pattern drops `text-sm`; the reverse-emit then re-derives the minimal set (`text-lg`).\n before: '<p className=\"text-sm text-lg\">Hi</p>',\n after: '<p className=\"text-lg\">Hi</p>',\n },\n ],\n // Both tokens win a distinct property (no full override) → nothing to dedupe.\n noMatch: ['<p className=\"text-lg font-bold\">Hi</p>'],\n },\n});\n","/**\n * @domflax/patterns — compress pattern: `gap-shorthand`.\n *\n * Collapses an element whose grid/flex gutters are expressed as two equal axis longhands back into\n * the single `gap` shorthand:\n *\n * row-gap:16px; column-gap:16px ⇒ gap:16px (Tailwind `gap-x-4 gap-y-4` → `gap-4`)\n *\n * The IR's computed StyleMap is canonically LONGHAND (the shared normalizer expands the `gap`\n * shorthand into `row-gap` + `column-gap` at parse time). This pass runs the expansion in reverse on\n * the computed map ONLY when both axes carry the SAME value and `!important` flag — i.e. when the two\n * gutters genuinely fold into a single-value `gap`. When the axes differ it declines, leaving the two\n * longhands verbatim (an asymmetric gutter has no equivalent single-value shorthand).\n *\n * Authored with the declarative {@link pattern} API: `definePattern` auto-applies the compress safety guards — a dynamic or opaque class list\n * and combinator-subject selectors are excluded (a ref / event handler / dynamic child / dangerous\n * HTML never blocks a class-only rewrite); the\n * `rewriteClasses` recipe rebuilds the class StyleMap, declining (`null`) unless the two axis gaps\n * are present, equal, and share an `!important` flag.\n */\n\nimport type { ConditionKey, CssProperty, CssValue, StyleBlock, StyleDecl, StyleMap } from '@domflax/core';\nimport { BASE_CONDITION, conditionKey } from '@domflax/core';\n\nimport { definePattern } from '@domflax/pattern-kit';\n\n/* ───────────────────────── property handles ───────────────────────── */\n\nconst ROW_GAP = 'row-gap' as CssProperty;\nconst COLUMN_GAP = 'column-gap' as CssProperty;\nconst GAP = 'gap' as CssProperty;\n\nconst BASE_KEY: ConditionKey = conditionKey(BASE_CONDITION);\n\n/* ───────────────────────── helpers ───────────────────────── */\n\n/**\n * Rebuild the computed StyleMap with the BASE block's `row-gap`/`column-gap` pair replaced by a\n * single `gap` declaration; all other conditions/blocks are preserved verbatim. The synthesized\n * `gap` decl is set LITERALLY (not via the normalizer, which would re-expand it back into the two\n * axis longhands), so the emit side re-expands and matches the single `gap-*` utility.\n */\nfunction withGapShorthand(sm: StyleMap, gapDecl: StyleDecl): StyleMap {\n const blocks = new Map<ConditionKey, StyleBlock>();\n for (const [key, block] of sm.blocks) {\n if (key !== BASE_KEY) {\n blocks.set(key, block);\n continue;\n }\n const decls = new Map<CssProperty, StyleDecl>();\n for (const [prop, decl] of block.decls) {\n if (prop === ROW_GAP || prop === COLUMN_GAP) continue; // drop the two axis longhands\n decls.set(prop, decl);\n }\n decls.set(gapDecl.property, gapDecl);\n blocks.set(key, { condition: block.condition, decls });\n }\n return { blocks };\n}\n\n/* ───────────────────────── the pattern ───────────────────────── */\n\n/** Fold an equal `row-gap`/`column-gap` pair into the single `gap` shorthand. */\nexport const gapShorthand = definePattern({\n name: 'gap-shorthand',\n category: 'compress/gap-shorthand',\n safety: 1,\n doc: {\n title: 'Collapse equal row/column gap into the `gap` shorthand',\n summary:\n 'An element whose computed row-gap and column-gap are equal has the two axis longhands ' +\n 'collapsed into a single-value `gap` shorthand (Tailwind gap-x-* gap-y-* → gap-*).',\n before: '<div style=\"row-gap:16px;column-gap:16px\"/>',\n after: '<div style=\"gap:16px\"/>',\n safetyRationale:\n 'A single-value `gap` is value-identical to an equal row-gap+column-gap pair — a class-only change. ' +\n 'It is safe even on an element with a ref, event handler, dynamic child, or dangerouslySetInnerHTML ' +\n '— a className rewrite touches none of them; only a dynamic/opaque class list or a ' +\n 'combinator-subject class is excluded, so no behaviour or project selector is disturbed.',\n },\n rewrite: {\n rewriteClasses(computed: StyleMap): StyleMap | null {\n const base = computed.blocks.get(BASE_KEY);\n if (!base) return null;\n\n const rowGap = base.decls.get(ROW_GAP);\n const colGap = base.decls.get(COLUMN_GAP);\n if (!rowGap || !colGap) return null;\n\n // A single-value `gap` cannot carry per-axis `!important` or differing values.\n if (rowGap.important !== colGap.important) return null;\n if (rowGap.value !== colGap.value) return null;\n\n const gapDecl: StyleDecl = {\n property: GAP,\n value: rowGap.value as CssValue,\n important: rowGap.important,\n relativeToParent: rowGap.relativeToParent || colGap.relativeToParent,\n inherited: false, // gap is not an inherited property\n };\n return withGapShorthand(computed, gapDecl);\n },\n },\n test: {\n cases: [\n {\n // Equal row/column gap collapse to a `gap` decl at the IR level; the minimizing reverse-emit\n // re-expands `gap` to row-gap+column-gap and picks the single utility covering both (`gap-4`),\n // replacing the `gap-x-4`+`gap-y-4` pair. `bg-red-200` is preserved.\n before: '<div className=\"gap-x-4 gap-y-4 bg-red-200\">box</div>',\n after: '<div className=\"bg-red-200 gap-4\">box</div>',\n },\n ],\n // Unequal axes (row-gap != column-gap) have no single-value `gap` equivalent → not collapsed.\n noMatch: ['<div className=\"gap-x-2 gap-y-4 bg-red-200\">box</div>'],\n },\n});\n","/**\n * @domflax/patterns — compress pattern: `inset-shorthand`.\n *\n * Recompacts the four physical inset longhands (`top`/`right`/`bottom`/`left`) on an element's\n * computed style back into the tightest CSS shorthand the values allow:\n *\n * • all four equal → `inset: <v>`\n * • top == bottom (a matching pair) → `inset-block: <v>` (Tailwind `inset-y-*`)\n * • left == right (a matching pair) → `inset-inline: <v>` (Tailwind `inset-x-*`)\n *\n * The two axis collapses are independent: an element whose `top == bottom` but `left != right`\n * collapses only the block axis and keeps the `left`/`right` longhands verbatim. When nothing\n * collapses (all four distinct, or fewer than a full pair present) the pattern declines.\n *\n * Authored with the declarative {@link pattern} API: `definePattern` auto-applies the compress safety guards — a dynamic or opaque class list\n * and combinator-subject selectors are excluded (a ref / event handler / dynamic child / dangerous\n * HTML never blocks a class-only rewrite); the `rewriteClasses` recipe rebuilds the class\n * StyleMap, declining (`null`) unless at least one inset axis collapses.\n */\n\nimport type { ConditionKey, CssProperty, StyleBlock, StyleDecl, StyleMap } from '@domflax/core';\nimport { BASE_CONDITION_KEY } from '@domflax/core';\n\nimport { normalizer, definePattern } from '@domflax/pattern-kit';\n\n/* ───────────────────────── property handles ───────────────────────── */\n\nconst TOP = 'top' as CssProperty;\nconst RIGHT = 'right' as CssProperty;\nconst BOTTOM = 'bottom' as CssProperty;\nconst LEFT = 'left' as CssProperty;\nconst INSET = 'inset' as CssProperty;\nconst INSET_BLOCK = 'inset-block' as CssProperty; // top + bottom (Tailwind inset-y)\nconst INSET_INLINE = 'inset-inline' as CssProperty; // left + right (Tailwind inset-x)\n\n/* ───────────────────────── value helpers ───────────────────────── */\n\n/** Two side-decls collapse only if they agree on BOTH normalized value and `!important`. */\nfunction sameSide(a: StyleDecl | undefined, b: StyleDecl | undefined): boolean {\n return a !== undefined && b !== undefined && a.value === b.value && a.important === b.important;\n}\n\n/** Re-key a decl onto a new property, recomputing its inherited flag for that property. */\nfunction asProperty(src: StyleDecl, property: CssProperty): StyleDecl {\n return { ...src, property, inherited: normalizer.inherited.isInherited(property) };\n}\n\n/** Rebuild `src` with the base block's decls replaced; all other condition blocks pass through. */\nfunction withBaseDecls(src: StyleMap, baseDecls: ReadonlyMap<CssProperty, StyleDecl>): StyleMap {\n const blocks = new Map<ConditionKey, StyleBlock>();\n for (const [key, block] of src.blocks) {\n const decls =\n key === BASE_CONDITION_KEY ? baseDecls : new Map<CssProperty, StyleDecl>(block.decls);\n blocks.set(key, { condition: block.condition, decls });\n }\n return { blocks };\n}\n\n/* ───────────────────────── the pattern ───────────────────────── */\n\n/**\n * Collapse equal/paired physical inset longhands into the `inset` / `inset-block` / `inset-inline`\n * shorthands on an element's computed style.\n */\nexport const insetShorthand = definePattern({\n name: 'inset-shorthand',\n category: 'compress/inset-shorthand',\n safety: 2,\n doc: {\n title: 'Compress inset longhands into a shorthand',\n summary:\n 'top/right/bottom/left set to one value collapse to `inset`; a matching top/bottom or ' +\n 'left/right pair collapses to `inset-block` / `inset-inline` (Tailwind inset-y / inset-x).',\n before: '<div style=\"top:10px;right:10px;bottom:10px;left:10px\"/>',\n after: '<div style=\"inset:10px\"/>',\n safetyRationale:\n 'Meaning-preserving inset shorthand compaction — a class-only change. It is safe even on an element ' +\n 'with a ref, event handler, dynamic child, or dangerouslySetInnerHTML — a className rewrite touches ' +\n 'none of them; only a dynamic/opaque class list or a combinator-subject class is excluded, so no ' +\n 'behaviour or project selector is disturbed.',\n },\n rewrite: {\n rewriteClasses(computed: StyleMap): StyleMap | null {\n const base = computed.blocks.get(BASE_CONDITION_KEY);\n if (!base) return null;\n\n const top = base.decls.get(TOP);\n const right = base.decls.get(RIGHT);\n const bottom = base.decls.get(BOTTOM);\n const left = base.decls.get(LEFT);\n\n const next = new Map<CssProperty, StyleDecl>(base.decls);\n\n // 1. All four sides equal → single `inset`.\n if (top && sameSide(top, right) && sameSide(top, bottom) && sameSide(top, left)) {\n next.delete(TOP);\n next.delete(RIGHT);\n next.delete(BOTTOM);\n next.delete(LEFT);\n next.set(INSET, asProperty(top, INSET));\n } else {\n let collapsed = false;\n // 2a. Block axis: top == bottom → `inset-block`.\n if (sameSide(top, bottom)) {\n next.delete(TOP);\n next.delete(BOTTOM);\n next.set(INSET_BLOCK, asProperty(top!, INSET_BLOCK));\n collapsed = true;\n }\n // 2b. Inline axis: left == right → `inset-inline`.\n if (sameSide(left, right)) {\n next.delete(LEFT);\n next.delete(RIGHT);\n next.set(INSET_INLINE, asProperty(left!, INSET_INLINE));\n collapsed = true;\n }\n if (!collapsed) return null; // nothing to compress — decline\n }\n\n return withBaseDecls(computed, next);\n },\n },\n test: {\n cases: [\n {\n // The four equal inset longhands collapse to an `inset` shorthand at the IR level; the\n // minimizing reverse-emit expands it back to top/right/bottom/left and picks the single utility\n // covering all four (`inset-0`), replacing the four physical-side tokens. `bg-red-200` survives.\n before: '<div className=\"top-0 right-0 bottom-0 left-0 bg-red-200\">box</div>',\n after: '<div className=\"bg-red-200 inset-0\">box</div>',\n },\n ],\n // No matching inset pair (all four distinct) → nothing collapses.\n noMatch: ['<div className=\"top-0 right-1 bottom-2 left-3 bg-red-200\">box</div>'],\n },\n});\n","/**\n * @domflax/patterns — compress pattern: `margin-shorthand`.\n *\n * Collapses the four explicit margin longhands\n *\n * margin-top / margin-right / margin-bottom / margin-left\n *\n * back into a single CSS `margin` shorthand declaration on the SAME element (the margin analogue of\n * `padding-shorthand`, covering the `m` / `mx` / `my` collapse), choosing the shortest legal\n * 1–4-value form:\n *\n * • all four equal → `margin: <v>` (the `m` case)\n * • top==bottom and left==right → `margin: <y> <x>` (the `my`/`mx` case)\n * • left==right (top!=bottom) → `margin: <t> <x> <b>`\n * • otherwise → `margin: <t> <r> <b> <l>`\n *\n * It is a pure representation change: the resolved box model is identical, only the declaration\n * count shrinks from four to one, which the backend can then re-emit as a single shorthand utility.\n *\n * Authored with the declarative {@link pattern} API: `definePattern` auto-applies the compress safety guards — a dynamic or opaque class list\n * and combinator-subject selectors are excluded (a ref / event handler / dynamic child / dangerous\n * HTML never blocks a class-only rewrite); the `rewriteClasses` recipe rebuilds the class\n * StyleMap, declining (`null`) unless all four margin longhands are present with a uniform\n * (non-)`!important` flag.\n */\n\nimport type { ConditionKey, CssProperty, CssValue, StyleBlock, StyleDecl, StyleMap } from '@domflax/core';\nimport { BASE_CONDITION, conditionKey } from '@domflax/core';\n\nimport { definePattern } from '@domflax/pattern-kit';\n\n/* ───────────────────────── constants / helpers ───────────────────────── */\n\n/** The four margin longhands, in CSS shorthand order (top, right, bottom, left). */\nconst MARGIN_SIDES = [\n 'margin-top',\n 'margin-right',\n 'margin-bottom',\n 'margin-left',\n] as const satisfies readonly string[];\n\nconst MARGIN_SIDE_SET: ReadonlySet<string> = new Set(MARGIN_SIDES);\n\nconst BASE_KEY: ConditionKey = conditionKey(BASE_CONDITION);\n\n/** Collapse four side values into the shortest legal CSS `margin` shorthand value string. */\nfunction collapseMarginValue(top: string, right: string, bottom: string, left: string): string {\n if (right === left) {\n if (top === bottom) {\n return top === right ? top : `${top} ${right}`;\n }\n return `${top} ${right} ${bottom}`;\n }\n return `${top} ${right} ${bottom} ${left}`;\n}\n\n/** Rebuild the computed StyleMap with the four BASE-block margin longhands replaced by `margin`. */\nfunction withFoldedMargin(sm: StyleMap, marginDecl: StyleDecl): StyleMap {\n const blocks = new Map<ConditionKey, StyleBlock>();\n for (const [key, block] of sm.blocks) {\n if (key !== BASE_KEY) {\n blocks.set(key, block);\n continue;\n }\n const decls = new Map<CssProperty, StyleDecl>();\n for (const [prop, decl] of block.decls) {\n if (!MARGIN_SIDE_SET.has(String(prop))) decls.set(prop, decl);\n }\n decls.set(marginDecl.property, marginDecl);\n blocks.set(key, { condition: block.condition, decls });\n }\n return { blocks };\n}\n\n/* ───────────────────────── the pattern ───────────────────────── */\n\n/**\n * Fold four margin longhands into one `margin` shorthand on the element's base style block.\n */\nexport const marginShorthand = definePattern({\n name: 'margin-shorthand',\n category: 'compress/margin-shorthand',\n safety: 2,\n doc: {\n title: 'Compress margin longhands into the `margin` shorthand',\n summary:\n 'An element with margin-top/right/bottom/left all set has them collapsed into the shortest ' +\n 'legal `margin` shorthand (the m / mx / my forms); meaning is preserved, declaration count drops.',\n before: '<div style=\"margin-top:8px;margin-right:8px;margin-bottom:8px;margin-left:8px\"/>',\n after: '<div style=\"margin:8px\"/>',\n safetyRationale:\n 'A pure representation change of the same computed margins (no pixels move) — a class-only change. ' +\n 'It is safe even on an element with a ref, event handler, dynamic child, or dangerouslySetInnerHTML ' +\n '— a className rewrite touches none of them; only a dynamic/opaque class list or a ' +\n 'combinator-subject class is excluded, so no behaviour or project selector is disturbed.',\n },\n rewrite: {\n rewriteClasses(computed: StyleMap): StyleMap | null {\n const base = computed.blocks.get(BASE_KEY);\n if (!base) return null;\n\n // Require all four longhands present in the base block (the `m` collapse only touches base).\n const sides = MARGIN_SIDES.map((p) => base.decls.get(p as CssProperty));\n if (sides.some((d) => d === undefined)) return null;\n const [mt, mr, mb, ml] = sides as readonly StyleDecl[];\n\n // A shorthand can only carry a uniform `!important`; mixing would change cascade behaviour.\n if (mt.important || mr.important || mb.important || ml.important) return null;\n\n const value = collapseMarginValue(\n String(mt.value),\n String(mr.value),\n String(mb.value),\n String(ml.value),\n );\n\n const marginDecl: StyleDecl = {\n property: 'margin' as CssProperty,\n value: value as CssValue,\n important: false,\n relativeToParent:\n mt.relativeToParent || mr.relativeToParent || mb.relativeToParent || ml.relativeToParent,\n inherited: false, // margin is not an inherited property\n };\n\n return withFoldedMargin(computed, marginDecl);\n },\n },\n test: {\n cases: [\n {\n // The four equal margin longhands collapse to a `margin` shorthand at the IR level, and the\n // minimizing reverse-emit picks the single shortest utility (`m-2`) reproducing it, replacing\n // the four `m{t,r,b,l}-2` tokens. `bg-red-200` is preserved.\n before: '<div className=\"mt-2 mr-2 mb-2 ml-2 bg-red-200\">box</div>',\n after: '<div className=\"bg-red-200 m-2\">box</div>',\n },\n ],\n // Only two margin sides set → the four-longhand `margin` collapse does not apply.\n noMatch: ['<div className=\"mt-2 mb-2 bg-red-200\">box</div>'],\n },\n});\n","/**\n * @domflax/patterns — compress pattern: `overflow-shorthand`.\n *\n * Collapses an element whose two overflow axes are expressed as equal longhands back into the single\n * `overflow` shorthand:\n *\n * overflow-x:auto; overflow-y:auto ⇒ overflow:auto (Tailwind `overflow-x-auto overflow-y-auto`\n * → `overflow-auto`)\n *\n * Unlike the box shorthands, the shared normalizer leaves `overflow-x` / `overflow-y` as independent\n * longhands (it does not synthesize an `overflow` shorthand), so an element styled with two equal\n * axis utilities keeps two separate declarations until this pass folds them. The fold runs ONLY when\n * both axes carry the SAME value and `!important` flag; an asymmetric pair (`overflow-x !==\n * overflow-y`) has no single-keyword `overflow` equivalent and is declined.\n *\n * Authored with the declarative {@link pattern} API: `definePattern` auto-applies the compress safety guards — a dynamic or opaque class list\n * and combinator-subject selectors are excluded (a ref / event handler / dynamic child / dangerous\n * HTML never blocks a class-only rewrite); the\n * `rewriteClasses` recipe rebuilds the class StyleMap, declining (`null`) unless both overflow axes\n * are present, equal, and share an `!important` flag.\n */\n\nimport type { ConditionKey, CssProperty, CssValue, StyleBlock, StyleDecl, StyleMap } from '@domflax/core';\nimport { BASE_CONDITION, conditionKey } from '@domflax/core';\n\nimport { definePattern } from '@domflax/pattern-kit';\n\n/* ───────────────────────── property handles ───────────────────────── */\n\nconst OVERFLOW_X = 'overflow-x' as CssProperty;\nconst OVERFLOW_Y = 'overflow-y' as CssProperty;\nconst OVERFLOW = 'overflow' as CssProperty;\n\nconst BASE_KEY: ConditionKey = conditionKey(BASE_CONDITION);\n\n/* ───────────────────────── helpers ───────────────────────── */\n\n/**\n * Rebuild the computed StyleMap with the BASE block's `overflow-x`/`overflow-y` pair replaced by a\n * single `overflow` declaration; all other conditions/blocks are preserved verbatim.\n */\nfunction withOverflowShorthand(sm: StyleMap, overflowDecl: StyleDecl): StyleMap {\n const blocks = new Map<ConditionKey, StyleBlock>();\n for (const [key, block] of sm.blocks) {\n if (key !== BASE_KEY) {\n blocks.set(key, block);\n continue;\n }\n const decls = new Map<CssProperty, StyleDecl>();\n for (const [prop, decl] of block.decls) {\n if (prop === OVERFLOW_X || prop === OVERFLOW_Y) continue; // drop the two axis longhands\n decls.set(prop, decl);\n }\n decls.set(overflowDecl.property, overflowDecl);\n blocks.set(key, { condition: block.condition, decls });\n }\n return { blocks };\n}\n\n/* ───────────────────────── the pattern ───────────────────────── */\n\n/** Fold an equal `overflow-x`/`overflow-y` pair into the single `overflow` shorthand. */\nexport const overflowShorthand = definePattern({\n name: 'overflow-shorthand',\n category: 'compress/overflow-shorthand',\n safety: 1,\n doc: {\n title: 'Collapse equal overflow axes into the `overflow` shorthand',\n summary:\n 'An element whose computed overflow-x and overflow-y are equal has the two axis longhands ' +\n 'collapsed into a single `overflow` shorthand (Tailwind overflow-x-* overflow-y-* → overflow-*).',\n before: '<div style=\"overflow-x:auto;overflow-y:auto\"/>',\n after: '<div style=\"overflow:auto\"/>',\n safetyRationale:\n 'A single-keyword `overflow` is value-identical to equal overflow-x+overflow-y — a class-only ' +\n 'change. It is safe even on an element with a ref, event handler, dynamic child, or ' +\n 'dangerouslySetInnerHTML — a className rewrite touches none of them; only a dynamic/opaque class ' +\n 'list or a combinator-subject class is excluded, so no behaviour or project selector is disturbed.',\n },\n rewrite: {\n rewriteClasses(computed: StyleMap): StyleMap | null {\n const base = computed.blocks.get(BASE_KEY);\n if (!base) return null;\n\n const overflowX = base.decls.get(OVERFLOW_X);\n const overflowY = base.decls.get(OVERFLOW_Y);\n if (!overflowX || !overflowY) return null;\n\n // The single-keyword shorthand cannot carry per-axis `!important` or differing values.\n if (overflowX.important !== overflowY.important) return null;\n if (overflowX.value !== overflowY.value) return null;\n\n const overflowDecl: StyleDecl = {\n property: OVERFLOW,\n value: overflowX.value as CssValue,\n important: overflowX.important,\n relativeToParent: overflowX.relativeToParent || overflowY.relativeToParent,\n inherited: false, // overflow is not an inherited property\n };\n return withOverflowShorthand(computed, overflowDecl);\n },\n },\n test: {\n cases: [\n {\n // Equal overflow axes collapse to an `overflow` decl at the IR level; the minimizing\n // reverse-emit picks the single utility covering both (`overflow-auto`), replacing the\n // `overflow-x-auto`+`overflow-y-auto` pair. `bg-red-200` is preserved.\n before: '<div className=\"overflow-x-auto overflow-y-auto bg-red-200\">box</div>',\n after: '<div className=\"bg-red-200 overflow-auto\">box</div>',\n },\n ],\n // Mismatched axes (overflow-x != overflow-y) have no single-keyword equivalent → not collapsed.\n noMatch: ['<div className=\"overflow-x-auto overflow-y-hidden bg-red-200\">box</div>'],\n },\n});\n","/**\n * @domflax/patterns — compress pattern: `overscroll-behavior-shorthand`.\n *\n * Collapses an element whose two overscroll-behavior axes are expressed as separate longhand\n * declarations and are EQUAL into the single CSS `overscroll-behavior` shorthand:\n *\n * overscroll-behavior-x:contain; overscroll-behavior-y:contain\n * ⇒ overscroll-behavior:contain (Tailwind `overscroll-x-contain overscroll-y-contain` → `overscroll-contain`)\n *\n * Tailwind's `overscroll-x-*` / `overscroll-y-*` utilities each resolve to the matching\n * `overscroll-behavior-{x,y}` axis longhand, and the shared normalizer keeps `overscroll-behavior`\n * un-expanded (it is NOT one of the box/gap shorthands the normalizer splits). So only the equal-axis\n * form maps cleanly to a single `overscroll-*` utility. This pass runs the collapse in reverse on the\n * computed map ONLY when both axes carry the SAME value and `!important` flag, replacing them with one\n * `overscroll-behavior` decl so the minimizing reverse-emit can pick a single `overscroll-*` token\n * instead of two axis tokens. When the axes differ it declines, leaving the two longhands verbatim.\n *\n * Authored with the declarative {@link pattern} API: `definePattern` auto-applies the compress safety guards — a dynamic or opaque class list\n * and combinator-subject selectors are excluded (a ref / event handler / dynamic child / dangerous\n * HTML never blocks a class-only rewrite); the\n * `rewriteClasses` recipe rebuilds the class StyleMap, declining (`null`) unless both axes are\n * present, concrete, equal, and share an `!important` flag.\n */\n\nimport type { ConditionKey, CssProperty, CssValue, StyleBlock, StyleDecl, StyleMap } from '@domflax/core';\nimport { BASE_CONDITION, conditionKey } from '@domflax/core';\n\nimport { definePattern } from '@domflax/pattern-kit';\n\n/* ───────────────────────── property handles ───────────────────────── */\n\nconst OVERSCROLL_X = 'overscroll-behavior-x' as CssProperty;\nconst OVERSCROLL_Y = 'overscroll-behavior-y' as CssProperty;\nconst OVERSCROLL = 'overscroll-behavior' as CssProperty;\n\nconst BASE_KEY: ConditionKey = conditionKey(BASE_CONDITION);\n\n/** CSS-wide keywords for which an axis collapse is pointless or unsound. */\nconst NON_COLLAPSIBLE_VALUES: ReadonlySet<string> = new Set<string>([\n 'initial',\n 'inherit',\n 'unset',\n 'revert',\n 'revert-layer',\n]);\n\n/* ───────────────────────── helpers ───────────────────────── */\n\n/**\n * Rebuild the computed StyleMap with the BASE block's overscroll-behavior x/y pair replaced by a\n * single `overscroll-behavior` declaration; all other conditions/blocks are preserved verbatim. The\n * synthesized shorthand decl is set LITERALLY (the normalizer leaves `overscroll-behavior` intact),\n * so the emit side matches the single `overscroll-*` utility.\n */\nfunction withOverscrollShorthand(sm: StyleMap, shorthand: StyleDecl): StyleMap {\n const blocks = new Map<ConditionKey, StyleBlock>();\n for (const [key, block] of sm.blocks) {\n if (key !== BASE_KEY) {\n blocks.set(key, block);\n continue;\n }\n const decls = new Map<CssProperty, StyleDecl>();\n for (const [prop, decl] of block.decls) {\n if (prop === OVERSCROLL_X || prop === OVERSCROLL_Y) continue; // drop the two axis longhands\n decls.set(prop, decl);\n }\n decls.set(shorthand.property, shorthand);\n blocks.set(key, { condition: block.condition, decls });\n }\n return { blocks };\n}\n\n/* ───────────────────────── the pattern ───────────────────────── */\n\n/** Fold an equal overscroll-behavior x/y pair into the single `overscroll-behavior` shorthand. */\nexport const overscrollBehaviorShorthand = definePattern({\n name: 'overscroll-behavior-shorthand',\n category: 'compress/overscroll-behavior-shorthand',\n safety: 1,\n doc: {\n title: 'Collapse equal overscroll-behavior axes into overscroll-behavior',\n summary:\n 'An element whose computed overscroll-behavior-x and overscroll-behavior-y are equal has the ' +\n 'two axis longhands collapsed into a single `overscroll-behavior` shorthand (Tailwind ' +\n 'overscroll-x-* overscroll-y-* → overscroll-*).',\n before: '<div style=\"overscroll-behavior-x:contain;overscroll-behavior-y:contain\"/>',\n after: '<div class=\"overscroll-contain\"/>',\n safetyRationale:\n '`overscroll-behavior` is value-identical to an equal x+y axis pair — a class-only change. It is ' +\n 'safe even on an element with a ref, event handler, dynamic child, or dangerouslySetInnerHTML — a ' +\n 'className rewrite touches none of them; only a dynamic/opaque class list or a combinator-subject ' +\n 'class is excluded, so no behaviour or project selector is disturbed.',\n },\n rewrite: {\n rewriteClasses(computed: StyleMap): StyleMap | null {\n const base = computed.blocks.get(BASE_KEY);\n if (!base) return null;\n\n const x = base.decls.get(OVERSCROLL_X);\n const y = base.decls.get(OVERSCROLL_Y);\n if (!x || !y) return null;\n\n // A single shorthand cannot carry per-axis `!important` or differing values.\n if (x.important !== y.important) return null;\n const value = String(x.value);\n if (NON_COLLAPSIBLE_VALUES.has(value)) return null;\n if (value !== String(y.value)) return null;\n\n const shorthand: StyleDecl = {\n property: OVERSCROLL,\n value: x.value as CssValue,\n important: x.important,\n relativeToParent: x.relativeToParent || y.relativeToParent,\n inherited: false, // overscroll-behavior is not an inherited property\n };\n return withOverscrollShorthand(computed, shorthand);\n },\n },\n test: {\n cases: [\n {\n // Equal x/y axes collapse to an `overscroll-behavior` decl at the IR level; the minimizing\n // reverse-emit picks the single utility covering both (`overscroll-contain`), replacing the\n // `overscroll-x-contain`+`overscroll-y-contain` pair. `bg-red-200` is preserved.\n before: '<div className=\"overscroll-x-contain overscroll-y-contain bg-red-200\">box</div>',\n after: '<div className=\"bg-red-200 overscroll-contain\">box</div>',\n },\n ],\n // Axes differ (x != y) → no equal-axis collapse.\n noMatch: ['<div className=\"overscroll-x-contain overscroll-y-auto bg-red-200\">box</div>'],\n },\n});\n","/**\n * @domflax/patterns — compress pattern: `padding-shorthand`.\n *\n * Collapses an element whose four padding sides are expressed as separate longhand declarations\n * back into the shortest equivalent shorthand:\n *\n * padding-top:16px; padding-right:16px; padding-bottom:16px; padding-left:16px\n * ⇒ padding:16px (Tailwind `p-4`)\n *\n * padding-top:8px; padding-bottom:8px; padding-left:16px; padding-right:16px\n * ⇒ padding:8px 16px (Tailwind `px-4 py-2`)\n *\n * The IR's computed StyleMap is canonically LONGHAND (the shared normalizer expands every box\n * shorthand at parse time). This pass runs the expansion in reverse on the computed map ONLY when\n * the four sides fold cleanly into a 1- or 2-value form — i.e. `top===bottom` AND `left===right`.\n *\n * Authored with the declarative {@link pattern} API: `definePattern` auto-applies the compress safety guards — a dynamic or opaque class list\n * and combinator-subject selectors are excluded (a ref / event handler / dynamic child / dangerous\n * HTML never blocks a class-only rewrite); the `rewriteClasses`\n * recipe rebuilds the class StyleMap, declining (`null`) unless the four sides fold cleanly.\n */\n\nimport type { ConditionKey, CssProperty, CssValue, StyleBlock, StyleDecl, StyleMap } from '@domflax/core';\nimport { BASE_CONDITION, conditionKey } from '@domflax/core';\n\nimport { definePattern } from '@domflax/pattern-kit';\n\n/* ───────────────────────── padding analysis ───────────────────────── */\n\n/** The four padding longhands, in CSS shorthand order: top, right, bottom, left. */\nconst PADDING_SIDES = [\n 'padding-top',\n 'padding-right',\n 'padding-bottom',\n 'padding-left',\n] as const;\n\nconst PADDING_SIDE_SET: ReadonlySet<string> = new Set<string>(PADDING_SIDES);\n\nconst BASE_KEY: ConditionKey = conditionKey(BASE_CONDITION);\n\n/** The collapsed shorthand the four sides fold into (carrying important / relative-unit flags). */\ninterface PaddingFold {\n readonly value: string; // 1-value (`16px`) or 2-value (`8px 16px`) form\n readonly important: boolean;\n readonly relative: boolean;\n}\n\n/**\n * Inspect the BASE-condition block of `sm` and, iff all four padding longhands are present, share a\n * uniform `!important` flag, and form matching x/y pairs (`top===bottom` AND `left===right`), return\n * the shortest equivalent shorthand value. Returns `null` when the sides cannot fold.\n */\nfunction analyzePadding(sm: StyleMap): PaddingFold | null {\n const block = sm.blocks.get(BASE_KEY);\n if (!block) return null;\n\n const sides: StyleDecl[] = [];\n for (const side of PADDING_SIDES) {\n const decl = block.decls.get(side as CssProperty);\n if (!decl) return null;\n sides.push(decl);\n }\n const [top, right, bottom, left] = sides as [StyleDecl, StyleDecl, StyleDecl, StyleDecl];\n\n // A shorthand cannot carry per-side `!important`; only fold a uniform flag.\n if (\n !(\n top.important === right.important &&\n right.important === bottom.important &&\n bottom.important === left.important\n )\n ) {\n return null;\n }\n\n const tv = String(top.value);\n const rv = String(right.value);\n const bv = String(bottom.value);\n const lv = String(left.value);\n\n // Only the `p-*` (all equal) and `px-* py-*` (matching pairs) shapes are in scope.\n if (tv !== bv || lv !== rv) return null;\n\n const value = tv === lv ? tv : `${tv} ${lv}`;\n const relative = sides.some((d) => d.relativeToParent);\n return { value, important: top.important, relative };\n}\n\n/* ───────────────────────── style rebuild ───────────────────────── */\n\n/** Rebuild `sm` with the four BASE-block padding longhands replaced by one `padding` shorthand. */\nfunction withFoldedPadding(sm: StyleMap, fold: PaddingFold): StyleMap {\n const blocks = new Map<ConditionKey, StyleBlock>();\n for (const [key, block] of sm.blocks) {\n if (key !== BASE_KEY) {\n blocks.set(key, block);\n continue;\n }\n const decls = new Map<CssProperty, StyleDecl>();\n for (const [prop, decl] of block.decls) {\n if (PADDING_SIDE_SET.has(String(prop))) continue; // drop the four longhands\n decls.set(prop, decl);\n }\n const shorthand: StyleDecl = {\n property: 'padding' as CssProperty,\n value: fold.value as CssValue,\n important: fold.important,\n relativeToParent: fold.relative,\n inherited: false, // padding is never inherited\n };\n decls.set(shorthand.property, shorthand);\n blocks.set(key, { condition: block.condition, decls });\n }\n return { blocks };\n}\n\n/* ───────────────────────── the pattern ───────────────────────── */\n\n/**\n * Compress an element's four equal/paired padding longhands into the shortest `padding` shorthand.\n */\nexport const paddingShorthand = definePattern({\n name: 'padding-shorthand',\n category: 'compress/padding-shorthand',\n safety: 1,\n doc: {\n title: 'Collapse padding longhands to shorthand',\n summary:\n 'Equal padding on all four sides (or matching x/y pairs) expressed as separate longhand ' +\n 'declarations is collapsed to the shortest equivalent padding shorthand (p-* / px-* py-*).',\n before: '<div class=\"pt-4 pr-4 pb-4 pl-4\"/>',\n after: '<div class=\"p-4\"/>',\n safetyRationale:\n 'A value-preserving re-serialization of the same computed padding on the same node — a class-only ' +\n 'change. It is safe even on an element with a ref, event handler, dynamic child, or ' +\n 'dangerouslySetInnerHTML — a className rewrite touches none of them; only a dynamic/opaque class ' +\n 'list or a combinator-subject class is excluded, so no behaviour or project selector is disturbed.',\n },\n rewrite: {\n rewriteClasses(computed: StyleMap): StyleMap | null {\n const fold = analyzePadding(computed);\n return fold ? withFoldedPadding(computed, fold) : null;\n },\n },\n test: {\n cases: [\n {\n // The four equal padding longhands collapse to a `padding` shorthand at the IR level, and the\n // minimizing reverse-emit picks the single shortest utility (`p-4`) that reproduces it,\n // replacing the four `p{t,r,b,l}-4` tokens. `bg-red-200` is preserved (its order is stable).\n before: '<div className=\"pt-4 pr-4 pb-4 pl-4 bg-red-200\">box</div>',\n after: '<div className=\"bg-red-200 p-4\">box</div>',\n },\n {\n // A dynamic `{x}` child no longer blocks compress: only the element's OWN class tokens are\n // rewritten (px-4 py-4 → p-4); the dynamic child is untouched by a class-only change. This is\n // the real-app common case (most elements have dynamic content).\n before: '<div className=\"px-4 py-4\">{x}</div>',\n after: '<div className=\"p-4\">{x}</div>',\n },\n ],\n // Asymmetric padding (top != bottom) cannot fold into a shorthand → left unchanged.\n noMatch: ['<div className=\"pt-2 pr-4 pb-8 pl-4 bg-red-200\">box</div>'],\n },\n});\n","/**\n * @domflax/patterns — compress pattern: `place-shorthand`.\n *\n * Recompacts the grid/flex alignment longhands on an element's computed style into the CSS `place-*`\n * shorthands whenever the two axes of a pair agree:\n *\n * • align-items == justify-items → `place-items: <v>` (Tailwind `items-* justify-items-*`)\n * • align-content == justify-content → `place-content: <v>` (Tailwind `content-* justify-*`)\n *\n * The two collapses are INDEPENDENT: an element whose items pair agrees but whose content pair does\n * not collapses only `place-items` and keeps the content longhands verbatim. The shared normalizer\n * leaves all four alignment properties as independent longhands (it synthesizes no `place-*`\n * shorthand), so an element styled with two matching axis utilities keeps the longhands until this\n * pass folds them. When neither pair agrees the pattern declines.\n *\n * Authored with the declarative {@link pattern} API: `definePattern` auto-applies the compress safety guards — a dynamic or opaque class list\n * and combinator-subject selectors are excluded (a ref / event handler / dynamic child / dangerous\n * HTML never blocks a class-only rewrite); the\n * `rewriteClasses` recipe rebuilds the class StyleMap, declining (`null`) unless at least one\n * alignment pair collapses.\n */\n\nimport type { ConditionKey, CssProperty, CssValue, StyleBlock, StyleDecl, StyleMap } from '@domflax/core';\nimport { BASE_CONDITION, conditionKey } from '@domflax/core';\n\nimport { definePattern } from '@domflax/pattern-kit';\n\n/* ───────────────────────── property handles ───────────────────────── */\n\nconst ALIGN_ITEMS = 'align-items' as CssProperty;\nconst JUSTIFY_ITEMS = 'justify-items' as CssProperty;\nconst PLACE_ITEMS = 'place-items' as CssProperty;\n\nconst ALIGN_CONTENT = 'align-content' as CssProperty;\nconst JUSTIFY_CONTENT = 'justify-content' as CssProperty;\nconst PLACE_CONTENT = 'place-content' as CssProperty;\n\nconst BASE_KEY: ConditionKey = conditionKey(BASE_CONDITION);\n\n/* ───────────────────────── helpers ───────────────────────── */\n\n/** Two alignment decls collapse only if they agree on BOTH normalized value and `!important`. */\nfunction samePair(a: StyleDecl | undefined, b: StyleDecl | undefined): boolean {\n return a !== undefined && b !== undefined && a.value === b.value && a.important === b.important;\n}\n\n/** Build a `place-*` shorthand decl carrying the (uniform) value/`!important` of its axis pair. */\nfunction placeDecl(property: CssProperty, align: StyleDecl): StyleDecl {\n return {\n property,\n value: align.value as CssValue,\n important: align.important,\n relativeToParent: false, // alignment keywords (center/start/stretch/…) are not length-relative\n inherited: false, // none of the place-* alignment properties are inherited\n };\n}\n\n/** Rebuild `sm` with the base block's decls replaced; all other condition blocks pass through. */\nfunction withBaseDecls(sm: StyleMap, baseDecls: ReadonlyMap<CssProperty, StyleDecl>): StyleMap {\n const blocks = new Map<ConditionKey, StyleBlock>();\n for (const [key, block] of sm.blocks) {\n const decls =\n key === BASE_KEY ? new Map<CssProperty, StyleDecl>(baseDecls) : block.decls;\n blocks.set(key, { condition: block.condition, decls });\n }\n return { blocks };\n}\n\n/* ───────────────────────── the pattern ───────────────────────── */\n\n/** Fold matching align/justify pairs into the `place-items` / `place-content` shorthands. */\nexport const placeShorthand = definePattern({\n name: 'place-shorthand',\n category: 'compress/place-shorthand',\n safety: 1,\n doc: {\n title: 'Collapse matching alignment pairs into `place-*` shorthands',\n summary:\n 'When align-items equals justify-items they collapse to `place-items`; when align-content ' +\n 'equals justify-content they collapse to `place-content`. The two collapses are independent.',\n before: '<div style=\"align-items:center;justify-items:center\"/>',\n after: '<div style=\"place-items:center\"/>',\n safetyRationale:\n 'A `place-*` shorthand is value-identical to its equal align/justify pair — a class-only change. It ' +\n 'is safe even on an element with a ref, event handler, dynamic child, or dangerouslySetInnerHTML — ' +\n 'a className rewrite touches none of them; only a dynamic/opaque class list or a combinator-subject ' +\n 'class is excluded, so no behaviour or project selector is disturbed.',\n },\n rewrite: {\n rewriteClasses(computed: StyleMap): StyleMap | null {\n const base = computed.blocks.get(BASE_KEY);\n if (!base) return null;\n\n const alignItems = base.decls.get(ALIGN_ITEMS);\n const justifyItems = base.decls.get(JUSTIFY_ITEMS);\n const alignContent = base.decls.get(ALIGN_CONTENT);\n const justifyContent = base.decls.get(JUSTIFY_CONTENT);\n\n const next = new Map<CssProperty, StyleDecl>(base.decls);\n let collapsed = false;\n\n // 1. Items axis: align-items == justify-items → `place-items`.\n if (samePair(alignItems, justifyItems)) {\n next.delete(ALIGN_ITEMS);\n next.delete(JUSTIFY_ITEMS);\n next.set(PLACE_ITEMS, placeDecl(PLACE_ITEMS, alignItems!));\n collapsed = true;\n }\n // 2. Content axis: align-content == justify-content → `place-content`.\n if (samePair(alignContent, justifyContent)) {\n next.delete(ALIGN_CONTENT);\n next.delete(JUSTIFY_CONTENT);\n next.set(PLACE_CONTENT, placeDecl(PLACE_CONTENT, alignContent!));\n collapsed = true;\n }\n\n if (!collapsed) return null; // nothing to compress — decline\n return withBaseDecls(computed, next);\n },\n },\n test: {\n cases: [\n {\n // The matching items pair collapses to a `place-items` decl at the IR level; the minimizing\n // reverse-emit picks the single utility covering both (`place-items-center`), replacing the\n // `items-center`+`justify-items-center` pair. `bg-red-200` is preserved.\n before: '<div className=\"items-center justify-items-center bg-red-200\">box</div>',\n after: '<div className=\"bg-red-200 place-items-center\">box</div>',\n },\n ],\n // Mismatched alignment (align-items != justify-items, no content pair) → nothing collapses.\n noMatch: ['<div className=\"items-center justify-items-start bg-red-200\">box</div>'],\n },\n});\n","/**\n * @domflax/patterns — compress pattern: `scroll-margin-shorthand`.\n *\n * Collapses an element whose four scroll-margin sides are expressed as separate longhand\n * declarations and are ALL EQUAL into the single CSS `scroll-margin` shorthand:\n *\n * scroll-margin-top:1rem; scroll-margin-right:1rem;\n * scroll-margin-bottom:1rem; scroll-margin-left:1rem\n * ⇒ scroll-margin:1rem (Tailwind `scroll-m-4`)\n *\n * Tailwind's `scroll-mt-*` / `scroll-mx-*` / … utilities each resolve to the matching\n * `scroll-margin-*` longhand(s), and the shared normalizer keeps `scroll-margin` un-expanded (it is\n * NOT one of the box shorthands the normalizer splits). So only the all-equal (1-value) form maps\n * cleanly to a single `scroll-m-*` utility — the 2-value (`scroll-mx`/`scroll-my`) shape is left to\n * the resolver's own reverse-emit. This pass runs the collapse in reverse on the computed map ONLY\n * when all four sides share one value, replacing them with one `scroll-margin` decl so the minimizing\n * reverse-emit can pick a single `scroll-m-*` token instead of two axis tokens.\n *\n * Authored with the declarative {@link pattern} API: `definePattern` auto-applies the compress safety guards — a dynamic or opaque class list\n * and combinator-subject selectors are excluded (a ref / event handler / dynamic child / dangerous\n * HTML never blocks a class-only rewrite); the\n * `rewriteClasses` recipe rebuilds the class StyleMap, declining (`null`) unless the four sides are\n * present, concrete, equal, and share an `!important` flag.\n */\n\nimport type { ConditionKey, CssProperty, CssValue, StyleBlock, StyleDecl, StyleMap } from '@domflax/core';\nimport { BASE_CONDITION, conditionKey } from '@domflax/core';\n\nimport { definePattern } from '@domflax/pattern-kit';\n\n/* ───────────────────────── scroll-margin analysis ───────────────────────── */\n\n/** The four scroll-margin longhands. */\nconst SCROLL_MARGIN_SIDES = [\n 'scroll-margin-top',\n 'scroll-margin-right',\n 'scroll-margin-bottom',\n 'scroll-margin-left',\n] as const satisfies readonly string[];\n\nconst SIDE_SET: ReadonlySet<string> = new Set<string>(SCROLL_MARGIN_SIDES);\n\nconst BASE_KEY: ConditionKey = conditionKey(BASE_CONDITION);\n\nconst SCROLL_MARGIN = 'scroll-margin' as CssProperty;\n\n/** CSS-wide keywords for which a side collapse is pointless or unsound. */\nconst NON_COLLAPSIBLE_VALUES: ReadonlySet<string> = new Set<string>([\n 'initial',\n 'inherit',\n 'unset',\n 'revert',\n 'revert-layer',\n]);\n\n/** The single value all four sides fold into (carrying important / relative-unit flags). */\ninterface ScrollMarginFold {\n readonly value: string;\n readonly important: boolean;\n readonly relative: boolean;\n}\n\n/**\n * Inspect the BASE-condition block of `sm` and, iff all four scroll-margin longhands are present,\n * share a uniform `!important` flag, hold a concrete (non-keyword) value, and are ALL EQUAL, return\n * that value. Returns `null` when the sides cannot fold to one `scroll-margin`.\n */\nfunction analyzeScrollMargin(sm: StyleMap): ScrollMarginFold | null {\n const block = sm.blocks.get(BASE_KEY);\n if (!block) return null;\n\n const sides: StyleDecl[] = [];\n for (const side of SCROLL_MARGIN_SIDES) {\n const decl = block.decls.get(side as CssProperty);\n if (!decl) return null;\n sides.push(decl);\n }\n\n // A shorthand cannot carry per-side `!important`; only fold a uniform flag.\n const important = sides[0]!.important;\n if (!sides.every((d) => d.important === important)) return null;\n\n const value = String(sides[0]!.value);\n if (NON_COLLAPSIBLE_VALUES.has(value)) return null;\n if (!sides.every((d) => String(d.value) === value)) return null;\n\n const relative = sides.some((d) => d.relativeToParent);\n return { value, important, relative };\n}\n\n/* ───────────────────────── style rebuild ───────────────────────── */\n\n/** Rebuild `sm` with the four BASE-block scroll-margin longhands replaced by one shorthand decl. */\nfunction withFoldedScrollMargin(sm: StyleMap, fold: ScrollMarginFold): StyleMap {\n const blocks = new Map<ConditionKey, StyleBlock>();\n for (const [key, block] of sm.blocks) {\n if (key !== BASE_KEY) {\n blocks.set(key, block);\n continue;\n }\n const decls = new Map<CssProperty, StyleDecl>();\n for (const [prop, decl] of block.decls) {\n if (SIDE_SET.has(String(prop))) continue; // drop the four longhands\n decls.set(prop, decl);\n }\n const shorthand: StyleDecl = {\n property: SCROLL_MARGIN,\n value: fold.value as CssValue,\n important: fold.important,\n relativeToParent: fold.relative,\n inherited: false, // scroll-margin is never inherited\n };\n decls.set(shorthand.property, shorthand);\n blocks.set(key, { condition: block.condition, decls });\n }\n return { blocks };\n}\n\n/* ───────────────────────── the pattern ───────────────────────── */\n\n/** Fold four equal scroll-margin sides into the single `scroll-margin` shorthand. */\nexport const scrollMarginShorthand = definePattern({\n name: 'scroll-margin-shorthand',\n category: 'compress/scroll-margin-shorthand',\n safety: 1,\n doc: {\n title: 'Collapse equal scroll-margin sides into scroll-margin',\n summary:\n 'An element whose four scroll-margin sides are all equal is rewritten to the single Tailwind ' +\n 'scroll-m-* utility (scroll-margin === the four equal sides).',\n before: '<div class=\"scroll-mt-4 scroll-mr-4 scroll-mb-4 scroll-ml-4\"/>',\n after: '<div class=\"scroll-m-4\"/>',\n safetyRationale:\n '`scroll-margin` is value-identical to four equal scroll-margin sides — a class-only change. It is ' +\n 'safe even on an element with a ref, event handler, dynamic child, or dangerouslySetInnerHTML — a ' +\n 'className rewrite touches none of them; only a dynamic/opaque class list or a combinator-subject ' +\n 'class is excluded, so no behaviour or project selector is disturbed.',\n },\n rewrite: {\n rewriteClasses(computed: StyleMap): StyleMap | null {\n const fold = analyzeScrollMargin(computed);\n return fold ? withFoldedScrollMargin(computed, fold) : null;\n },\n },\n test: {\n cases: [\n {\n // The four equal scroll-margin longhands collapse to a `scroll-margin` decl at the IR level; the\n // minimizing reverse-emit then picks the single shortest utility (`scroll-m-4`) that reproduces\n // it, replacing the four `scroll-m{t,r,b,l}-4` tokens. `bg-red-200` is preserved.\n before: '<div className=\"scroll-mt-4 scroll-mr-4 scroll-mb-4 scroll-ml-4 bg-red-200\">box</div>',\n after: '<div className=\"bg-red-200 scroll-m-4\">box</div>',\n },\n ],\n // Sides differ (top != bottom) → no all-equal collapse.\n noMatch: ['<div className=\"scroll-mt-2 scroll-mr-4 scroll-mb-8 scroll-ml-4 bg-red-200\">box</div>'],\n },\n});\n","/**\n * @domflax/patterns — compress pattern: `scroll-padding-shorthand`.\n *\n * Collapses an element whose four scroll-padding sides are expressed as separate longhand\n * declarations and are ALL EQUAL into the single CSS `scroll-padding` shorthand:\n *\n * scroll-padding-top:1rem; scroll-padding-right:1rem;\n * scroll-padding-bottom:1rem; scroll-padding-left:1rem\n * ⇒ scroll-padding:1rem (Tailwind `scroll-p-4`)\n *\n * Tailwind's `scroll-pt-*` / `scroll-px-*` / … utilities each resolve to the matching\n * `scroll-padding-*` longhand(s), and the shared normalizer keeps `scroll-padding` un-expanded (it is\n * NOT one of the box shorthands the normalizer splits). So only the all-equal (1-value) form maps\n * cleanly to a single `scroll-p-*` utility — the 2-value (`scroll-px`/`scroll-py`) shape is left to\n * the resolver's own reverse-emit. This pass runs the collapse in reverse on the computed map ONLY\n * when all four sides share one value, replacing them with one `scroll-padding` decl so the minimizing\n * reverse-emit can pick a single `scroll-p-*` token instead of two axis tokens.\n *\n * Authored with the declarative {@link pattern} API: `definePattern` auto-applies the compress safety guards — a dynamic or opaque class list\n * and combinator-subject selectors are excluded (a ref / event handler / dynamic child / dangerous\n * HTML never blocks a class-only rewrite); the\n * `rewriteClasses` recipe rebuilds the class StyleMap, declining (`null`) unless the four sides are\n * present, concrete, equal, and share an `!important` flag.\n */\n\nimport type { ConditionKey, CssProperty, CssValue, StyleBlock, StyleDecl, StyleMap } from '@domflax/core';\nimport { BASE_CONDITION, conditionKey } from '@domflax/core';\n\nimport { definePattern } from '@domflax/pattern-kit';\n\n/* ───────────────────────── scroll-padding analysis ───────────────────────── */\n\n/** The four scroll-padding longhands. */\nconst SCROLL_PADDING_SIDES = [\n 'scroll-padding-top',\n 'scroll-padding-right',\n 'scroll-padding-bottom',\n 'scroll-padding-left',\n] as const satisfies readonly string[];\n\nconst SIDE_SET: ReadonlySet<string> = new Set<string>(SCROLL_PADDING_SIDES);\n\nconst BASE_KEY: ConditionKey = conditionKey(BASE_CONDITION);\n\nconst SCROLL_PADDING = 'scroll-padding' as CssProperty;\n\n/** CSS-wide keywords for which a side collapse is pointless or unsound. */\nconst NON_COLLAPSIBLE_VALUES: ReadonlySet<string> = new Set<string>([\n 'initial',\n 'inherit',\n 'unset',\n 'revert',\n 'revert-layer',\n]);\n\n/** The single value all four sides fold into (carrying important / relative-unit flags). */\ninterface ScrollPaddingFold {\n readonly value: string;\n readonly important: boolean;\n readonly relative: boolean;\n}\n\n/**\n * Inspect the BASE-condition block of `sm` and, iff all four scroll-padding longhands are present,\n * share a uniform `!important` flag, hold a concrete (non-keyword) value, and are ALL EQUAL, return\n * that value. Returns `null` when the sides cannot fold to one `scroll-padding`.\n */\nfunction analyzeScrollPadding(sm: StyleMap): ScrollPaddingFold | null {\n const block = sm.blocks.get(BASE_KEY);\n if (!block) return null;\n\n const sides: StyleDecl[] = [];\n for (const side of SCROLL_PADDING_SIDES) {\n const decl = block.decls.get(side as CssProperty);\n if (!decl) return null;\n sides.push(decl);\n }\n\n // A shorthand cannot carry per-side `!important`; only fold a uniform flag.\n const important = sides[0]!.important;\n if (!sides.every((d) => d.important === important)) return null;\n\n const value = String(sides[0]!.value);\n if (NON_COLLAPSIBLE_VALUES.has(value)) return null;\n if (!sides.every((d) => String(d.value) === value)) return null;\n\n const relative = sides.some((d) => d.relativeToParent);\n return { value, important, relative };\n}\n\n/* ───────────────────────── style rebuild ───────────────────────── */\n\n/** Rebuild `sm` with the four BASE-block scroll-padding longhands replaced by one shorthand decl. */\nfunction withFoldedScrollPadding(sm: StyleMap, fold: ScrollPaddingFold): StyleMap {\n const blocks = new Map<ConditionKey, StyleBlock>();\n for (const [key, block] of sm.blocks) {\n if (key !== BASE_KEY) {\n blocks.set(key, block);\n continue;\n }\n const decls = new Map<CssProperty, StyleDecl>();\n for (const [prop, decl] of block.decls) {\n if (SIDE_SET.has(String(prop))) continue; // drop the four longhands\n decls.set(prop, decl);\n }\n const shorthand: StyleDecl = {\n property: SCROLL_PADDING,\n value: fold.value as CssValue,\n important: fold.important,\n relativeToParent: fold.relative,\n inherited: false, // scroll-padding is never inherited\n };\n decls.set(shorthand.property, shorthand);\n blocks.set(key, { condition: block.condition, decls });\n }\n return { blocks };\n}\n\n/* ───────────────────────── the pattern ───────────────────────── */\n\n/** Fold four equal scroll-padding sides into the single `scroll-padding` shorthand. */\nexport const scrollPaddingShorthand = definePattern({\n name: 'scroll-padding-shorthand',\n category: 'compress/scroll-padding-shorthand',\n safety: 1,\n doc: {\n title: 'Collapse equal scroll-padding sides into scroll-padding',\n summary:\n 'An element whose four scroll-padding sides are all equal is rewritten to the single Tailwind ' +\n 'scroll-p-* utility (scroll-padding === the four equal sides).',\n before: '<div class=\"scroll-pt-4 scroll-pr-4 scroll-pb-4 scroll-pl-4\"/>',\n after: '<div class=\"scroll-p-4\"/>',\n safetyRationale:\n '`scroll-padding` is value-identical to four equal scroll-padding sides — a class-only change. It ' +\n 'is safe even on an element with a ref, event handler, dynamic child, or dangerouslySetInnerHTML — ' +\n 'a className rewrite touches none of them; only a dynamic/opaque class list or a combinator-subject ' +\n 'class is excluded, so no behaviour or project selector is disturbed.',\n },\n rewrite: {\n rewriteClasses(computed: StyleMap): StyleMap | null {\n const fold = analyzeScrollPadding(computed);\n return fold ? withFoldedScrollPadding(computed, fold) : null;\n },\n },\n test: {\n cases: [\n {\n // The four equal scroll-padding longhands collapse to a `scroll-padding` decl at the IR level;\n // the minimizing reverse-emit then picks the single shortest utility (`scroll-p-4`) that\n // reproduces it, replacing the four `scroll-p{t,r,b,l}-4` tokens. `bg-red-200` is preserved.\n before: '<div className=\"scroll-pt-4 scroll-pr-4 scroll-pb-4 scroll-pl-4 bg-red-200\">box</div>',\n after: '<div className=\"bg-red-200 scroll-p-4\">box</div>',\n },\n ],\n // Sides differ (top != bottom) → no all-equal collapse.\n noMatch: ['<div className=\"scroll-pt-2 scroll-pr-4 scroll-pb-8 scroll-pl-4 bg-red-200\">box</div>'],\n },\n});\n","/**\n * @domflax/patterns — compress pattern: `size-shorthand`.\n *\n * Collapses an element whose computed `width` and `height` are EQUAL into the single Tailwind\n * `size-*` utility:\n *\n * <div style=\"width:1rem; height:1rem\"/> → <div class=\"size-4\"/>\n *\n * At the IR level we work over the normalized computed StyleMap (CSS longhands), so the pattern\n * recognizes the `width === height` shape in the BASE condition and rebuilds the element's class\n * StyleMap with a single `size` declaration (the resolver reverse-emits the concrete `size-*` token\n * at codegen). Both longhands are removed and replaced by the merged `size` decl, so the rewrite is\n * idempotent — once collapsed there is no `width`+`height` pair left to re-match.\n *\n * Authored with the declarative {@link pattern} API: `definePattern` auto-applies the compress safety guards — a dynamic or opaque class list\n * and combinator-subject selectors are excluded (a ref / event handler / dynamic child / dangerous\n * HTML never blocks a class-only rewrite); the\n * `rewriteClasses` recipe rebuilds the class StyleMap, returning `null` (decline) unless the BASE\n * width/height are equal, concrete, and share an `!important` flag.\n */\n\nimport type { ConditionKey, CssProperty, StyleBlock, StyleDecl, StyleMap } from '@domflax/core';\nimport { BASE_CONDITION, conditionKey } from '@domflax/core';\n\nimport { normalizer, definePattern } from '@domflax/pattern-kit';\n\nconst WIDTH = 'width' as CssProperty;\nconst HEIGHT = 'height' as CssProperty;\nconst SIZE = 'size' as CssProperty;\n\n/** Values for which collapsing the two axes is pointless or unsound (no concrete equal extent). */\nconst NON_COLLAPSIBLE_VALUES: ReadonlySet<string> = new Set<string>(['auto', 'initial', 'unset']);\n\n/* ───────────────────────── helpers ───────────────────────── */\n\n/** Read the BASE-condition block of the node's normalized computed StyleMap, if any. */\nfunction baseBlock(sm: StyleMap): StyleBlock | undefined {\n return sm.blocks.get(conditionKey(BASE_CONDITION));\n}\n\n/**\n * Rebuild the computed StyleMap with the BASE block's `width`/`height` pair replaced by a single\n * `size` declaration; all other conditions/blocks are preserved verbatim.\n */\nfunction withSizeShorthand(sm: StyleMap, value: string, important: boolean): StyleMap {\n const baseKey = conditionKey(BASE_CONDITION);\n const blocks = new Map<ConditionKey, StyleBlock>();\n for (const [key, block] of sm.blocks) {\n if (key !== baseKey) {\n blocks.set(key, block);\n continue;\n }\n const decls = new Map<CssProperty, StyleDecl>(block.decls);\n decls.delete(WIDTH);\n decls.delete(HEIGHT);\n for (const decl of normalizer.normalizeDeclaration(String(SIZE), value, important)) {\n decls.set(decl.property, decl);\n }\n blocks.set(key, { condition: block.condition, decls });\n }\n return { blocks };\n}\n\n/* ───────────────────────── the pattern ───────────────────────── */\n\n/** Fold equal `width`/`height` into the `size-*` utility. */\nexport const sizeShorthand = definePattern({\n name: 'size-shorthand',\n category: 'compress/size-shorthand',\n safety: 2,\n doc: {\n title: 'Collapse equal width/height into size-*',\n summary:\n 'An element whose computed width and height are equal is rewritten to the single Tailwind ' +\n 'size-* utility (size-* === width + height at the same value).',\n before: '<div style=\"width:1rem;height:1rem\"/>',\n after: '<div class=\"size-4\"/>',\n safetyRationale:\n '`size-*` is value-identical to equal width+height — a class-only change. It is safe even on an ' +\n 'element with a ref, event handler, dynamic child, or dangerouslySetInnerHTML — a className rewrite ' +\n 'touches none of them; only a dynamic/opaque class list or a combinator-subject class is excluded, ' +\n 'so no behaviour or project selector is disturbed.',\n },\n rewrite: {\n rewriteClasses(computed: StyleMap): StyleMap | null {\n const base = baseBlock(computed);\n const w = base?.decls.get(WIDTH);\n const h = base?.decls.get(HEIGHT);\n if (!w || !h) return null;\n if (w.important !== h.important) return null;\n if (NON_COLLAPSIBLE_VALUES.has(String(w.value))) return null;\n if (w.value !== h.value) return null;\n return withSizeShorthand(computed, String(w.value), w.important);\n },\n },\n test: {\n cases: [\n {\n // Equal width/height collapse to a `size` decl at the IR level; the minimizing reverse-emit\n // expands `size` back to width+height, finds the single utility covering both (`size-10`), and\n // replaces the `h-10`+`w-10` pair with it. `bg-red-200` is preserved.\n before: '<div className=\"h-10 w-10 bg-red-200\">box</div>',\n after: '<div className=\"bg-red-200 size-10\">box</div>',\n },\n ],\n // Width and height differ → no equal-axis collapse.\n noMatch: ['<div className=\"h-10 w-20 bg-red-200\">box</div>'],\n },\n});\n","/**\n * AUTO-GENERATED by `scripts/gen-registry.mjs` — DO NOT EDIT BY HAND.\n *\n * Regenerate with `npm run generate` (also runs automatically before build/typecheck/test).\n * Patterns are discovered by the `*.pattern.ts` file convention under `src/library/flatten`\n * and `src/library/compress`; the array below is sorted flatten-before-compress.\n */\n\nimport type { Pattern } from '@domflax/core';\n\nimport { displayContentsWrapper } from './library/flatten/display-contents-wrapper.pattern';\nimport { emptyStyleDiv } from './library/flatten/empty-style-div.pattern';\nimport { flexCenterWrapper } from './library/flatten/flex-center-wrapper.pattern';\nimport { inlineFlexCenterWrapper } from './library/flatten/inline-flex-center-wrapper.pattern';\nimport { nestedFlexMerge } from './library/flatten/nested-flex-merge.pattern';\nimport { nestedGridMerge } from './library/flatten/nested-grid-merge.pattern';\nimport { passthroughWrapper } from './library/flatten/passthrough-wrapper.pattern';\nimport { redundantFragment } from './library/flatten/redundant-fragment.pattern';\nimport { redundantInlineWrapper } from './library/flatten/redundant-inline-wrapper.pattern';\nimport { borderRadiusShorthand } from './library/compress/border-radius-shorthand.pattern';\nimport { borderShorthand } from './library/compress/border-shorthand.pattern';\nimport { dedupeClasses } from './library/compress/dedupe-classes.pattern';\nimport { gapShorthand } from './library/compress/gap-shorthand.pattern';\nimport { insetShorthand } from './library/compress/inset-shorthand.pattern';\nimport { marginShorthand } from './library/compress/margin-shorthand.pattern';\nimport { overflowShorthand } from './library/compress/overflow-shorthand.pattern';\nimport { overscrollBehaviorShorthand } from './library/compress/overscroll-behavior-shorthand.pattern';\nimport { paddingShorthand } from './library/compress/padding-shorthand.pattern';\nimport { placeShorthand } from './library/compress/place-shorthand.pattern';\nimport { scrollMarginShorthand } from './library/compress/scroll-margin-shorthand.pattern';\nimport { scrollPaddingShorthand } from './library/compress/scroll-padding-shorthand.pattern';\nimport { sizeShorthand } from './library/compress/size-shorthand.pattern';\n\nexport {\n displayContentsWrapper,\n emptyStyleDiv,\n flexCenterWrapper,\n inlineFlexCenterWrapper,\n nestedFlexMerge,\n nestedGridMerge,\n passthroughWrapper,\n redundantFragment,\n redundantInlineWrapper,\n borderRadiusShorthand,\n borderShorthand,\n dedupeClasses,\n gapShorthand,\n insetShorthand,\n marginShorthand,\n overflowShorthand,\n overscrollBehaviorShorthand,\n paddingShorthand,\n placeShorthand,\n scrollMarginShorthand,\n scrollPaddingShorthand,\n sizeShorthand,\n};\n\n/** Every built-in pattern, in registration order (flatten patterns before compress). */\nexport const builtinPatterns: readonly Pattern[] = [\n displayContentsWrapper,\n emptyStyleDiv,\n flexCenterWrapper,\n inlineFlexCenterWrapper,\n nestedFlexMerge,\n nestedGridMerge,\n passthroughWrapper,\n redundantFragment,\n redundantInlineWrapper,\n borderRadiusShorthand,\n borderShorthand,\n dedupeClasses,\n gapShorthand,\n insetShorthand,\n marginShorthand,\n overflowShorthand,\n overscrollBehaviorShorthand,\n paddingShorthand,\n placeShorthand,\n scrollMarginShorthand,\n scrollPaddingShorthand,\n sizeShorthand,\n];\n\nexport default builtinPatterns;\n","/**\n * @domflax/resolver-tailwind — tiny dependency-free hash for cache-busting fingerprints.\n */\n\n/** Tiny, dependency-free FNV-1a string hash (hex). Used to derive the cache-busting fingerprint. */\nexport function fnv1a(input: string): string {\n let h = 0x811c9dc5;\n for (let i = 0; i < input.length; i += 1) {\n h ^= input.charCodeAt(i);\n h = Math.imul(h, 0x01000193);\n }\n return (h >>> 0).toString(16).padStart(8, '0');\n}\n","/**\n * @domflax/resolver-tailwind — emit-side shorthand expansion + residual synthesis.\n */\n\nimport type {\n CssProperty,\n EmitContext,\n StyleBlock,\n StyleDecl,\n StyleMap,\n SyntheticClass,\n} from '@domflax/core';\nimport { BASE_CONDITION, conditionKey } from '@domflax/core';\nimport { normalizer } from '@domflax/pattern-kit';\n\nimport { fnv1a } from './fingerprint';\n\n/**\n * Expand a single computed declaration into the canonical LONGHAND `[property, value]` pairs the\n * reverse index is keyed on. The shared normalizer already expands the physical box shorthands\n * (`padding`/`margin`/`inset`/`border-*`); we additionally expand the few logical shorthands the\n * compress passes synthesize that the normalizer leaves intact (`size`, `inset-block`,\n * `inset-inline`). Values are re-canonicalized via the normalizer so they match the index exactly.\n */\nexport function expandForEmit(\n norm: { normalizeDeclaration: typeof normalizer.normalizeDeclaration },\n prop: string,\n value: string,\n important: boolean,\n): Array<readonly [CssProperty, string]> {\n const pairsFor = (p: string, v: string): Array<readonly [CssProperty, string]> =>\n norm.normalizeDeclaration(p, v, important).map((d) => [d.property, String(d.value)] as const);\n\n if (prop === 'size') {\n return [...pairsFor('width', value), ...pairsFor('height', value)];\n }\n if (prop === 'inset-block' || prop === 'inset-inline') {\n const parts = value.split(/\\s+/).filter((s) => s.length > 0);\n const a = parts[0] ?? value;\n const b = parts[1] ?? a;\n const sides = prop === 'inset-block' ? (['top', 'bottom'] as const) : (['left', 'right'] as const);\n return [...pairsFor(sides[0], a), ...pairsFor(sides[1], b)];\n }\n return pairsFor(prop, value);\n}\n\n/** Build a residual {@link SyntheticClass} for declarations no utility covered; `null` on failure. */\nexport function synthesizeResidual(\n remaining: ReadonlyMap<CssProperty, string>,\n ctx: EmitContext,\n): SyntheticClass | undefined {\n if (remaining.size === 0) return undefined;\n const norm = ctx.normalizer ?? normalizer;\n const decls = new Map<CssProperty, StyleDecl>();\n for (const [prop, value] of remaining) {\n for (const decl of norm.normalizeDeclaration(String(prop), value, false)) {\n decls.set(decl.property, decl);\n }\n }\n const block: StyleBlock = { condition: BASE_CONDITION, decls };\n const styleMap: StyleMap = { blocks: new Map([[conditionKey(BASE_CONDITION), block]]) };\n const css = [...remaining].map(([p, v]) => `${p}:${v}`).join(';');\n const className = `df-${fnv1a(css)}`;\n const synthetic: SyntheticClass = { className, decls: styleMap, css: `.${className}{${css}}` };\n try {\n ctx.sink.register(synthetic);\n } catch {\n /* a sink that rejects registration must not break emit */\n }\n return synthetic;\n}\n","/**\n * @domflax/resolver-tailwind — engine loading (synchronous v3 internals).\n *\n * The forward/reverse engine lives in tailwindcss' CommonJS internals. We load them through\n * `createRequire` (rather than `import`) so the exact same code path works whether this module is\n * bundled to ESM or CJS, and so the untyped internal subpaths don't need ambient declarations.\n *\n * CRITICAL (bundling): tailwindcss must be resolved from the CONSUMER'S project, NOT from the file\n * this module happens to live in. When `domflax` inlines this resolver into its own bundle\n * (`noExternal: [/^@domflax\\//]`), a require based on the bundle's location (`__filename`) would\n * look for `tailwindcss` next to `domflax/dist`, where it does not exist — so the engine silently\n * failed to load and `emit`'s reverse index came up empty. Instead we root the require in the user's\n * project (an explicit project root, then `process.cwd()`), exactly how prettier-plugin-tailwindcss\n * and the Tailwind IntelliSense engine locate a project's Tailwind. The bundle/source location is\n * kept only as a last-resort fallback (covers the non-bundled / in-repo dev case). The first base\n * from which `tailwindcss/package.json` resolves wins.\n */\n\nimport { createRequire } from 'node:module';\nimport * as path from 'node:path';\n\nimport type { TailwindResolverConfig } from './config';\nimport type { TwContext, TwEngine, TwNode } from './types';\n\n/**\n * This module's own location, used as a last-resort require base. esbuild substitutes a real\n * `__filename` in a CJS bundle; in an ESM bundle `__filename` is undefined and we fall back to\n * `import.meta.url` (a `file://` URL, which `createRequire` accepts).\n */\nfunction moduleBase(): string {\n return typeof __filename === 'string' ? __filename : import.meta.url;\n}\n\n/**\n * Build a `require` rooted in the consumer's project so engine resolution is independent of where\n * this (possibly bundled) module physically lives. Returns `null` if `tailwindcss` resolves from no\n * candidate base.\n */\nfunction projectRequire(projectRoot?: string): NodeRequire | null {\n const bases: string[] = [];\n // A real file name is irrelevant — `createRequire` only uses the containing directory for\n // resolution; the file need not exist.\n if (projectRoot) bases.push(path.join(projectRoot, '__domflax__.js'));\n bases.push(path.join(process.cwd(), '__domflax__.js'));\n bases.push(moduleBase());\n for (const base of bases) {\n try {\n const candidate = createRequire(base);\n candidate.resolve('tailwindcss/package.json');\n return candidate;\n } catch {\n /* try the next base */\n }\n }\n return null;\n}\n\n/** Build a synchronous Tailwind v3 engine for the given resolved config; returns `null` on failure. */\nexport function loadEngine(options: TailwindResolverConfig): TwEngine | null {\n const req = projectRequire(options.projectRoot);\n if (!req) return null;\n try {\n const resolveConfig = req('tailwindcss/resolveConfig.js') as (c: unknown) => unknown;\n const { createContext } = req('tailwindcss/lib/lib/setupContextUtils.js') as {\n createContext: (config: unknown) => TwContext;\n };\n const { generateRules } = req('tailwindcss/lib/lib/generateRules.js') as {\n generateRules: (candidates: Set<string>, context: TwContext) => Array<[number, TwNode]>;\n };\n const pkg = req('tailwindcss/package.json') as { version: string };\n\n let userConfig: unknown = options.config ?? { content: [{ raw: '' }] };\n if (options.configPath !== undefined) {\n const loadConfig = req('tailwindcss/loadConfig.js') as (p: string) => unknown;\n userConfig = loadConfig(options.configPath);\n }\n const resolved = resolveConfig(userConfig);\n const context = createContext(resolved);\n\n return {\n version: pkg.version,\n context,\n generate(candidates: readonly string[]): TwNode[] {\n const rules = generateRules(new Set(candidates), context);\n return rules.map(([, node]) => node);\n },\n };\n } catch {\n return null;\n }\n}\n","/**\n * @domflax/resolver-tailwind — selector / condition parsing.\n */\n\nimport type { StyleCondition } from '@domflax/core';\n\n/** Pseudo-elements that Tailwind may emit with a legacy single colon. */\nconst LEGACY_PSEUDO_ELEMENTS = new Set([\n ':before',\n ':after',\n ':first-line',\n ':first-letter',\n]);\n\nexport type ParsedSelector =\n | { readonly kind: 'simple'; readonly states: readonly string[]; readonly pseudoElement: string }\n | { readonly kind: 'complex' };\n\n/**\n * Parse a generated selector into a {@link StyleCondition} fragment. Accepts ONLY a single class\n * selector optionally followed by pseudo-class / pseudo-element parts (`.x`, `.x:hover`,\n * `.x::before`, `.x:focus:hover`). Anything with a combinator, a second compound class, an attribute\n * selector, or a selector list is `complex` (⇒ opaque) because its declarations do not apply to the\n * element's own box.\n */\nexport function parseSelector(selector: string): ParsedSelector {\n const sel = selector.trim();\n if (sel.length === 0 || sel[0] !== '.') return { kind: 'complex' };\n\n // Consume the class identifier, honoring CSS backslash escapes (`\\:`, `\\/`, `\\[`, …).\n let i = 1;\n for (; i < sel.length; i += 1) {\n const c = sel[i]!;\n if (c === '\\\\') {\n i += 1; // skip the escaped char\n continue;\n }\n if (c === ':' || c === '.' || c === '[' || c === ' ' || c === '>' || c === '+' || c === '~' || c === ',') {\n break;\n }\n }\n\n const remainder = sel.slice(i);\n if (remainder.length === 0) {\n return { kind: 'simple', states: [], pseudoElement: '' };\n }\n // The remainder must be EXCLUSIVELY pseudo parts — no combinator / compound / attribute follows.\n if (!/^(?:::?[-a-z]+(?:\\([^()]*\\))?)+$/i.test(remainder)) {\n return { kind: 'complex' };\n }\n\n const parts = remainder.match(/::?[-a-z]+(?:\\([^()]*\\))?/gi) ?? [];\n const states: string[] = [];\n let pseudoElement = '';\n for (const part of parts) {\n if (part.startsWith('::') || LEGACY_PSEUDO_ELEMENTS.has(part)) {\n pseudoElement = part.startsWith('::') ? part : `:${part}`;\n } else {\n states.push(part);\n }\n }\n return { kind: 'simple', states, pseudoElement };\n}\n\nexport function makeCondition(media: string, states: readonly string[], pseudoElement: string): StyleCondition {\n return {\n media,\n states: [...new Set(states)].sort(),\n pseudoElement,\n };\n}\n\n/** Recover a class name from a simple `.escaped-class` selector, or `null` if it isn't simple. */\nexport function unescapeClass(selector: string): string | null {\n const sel = selector.trim();\n if (sel[0] !== '.') return null;\n let out = '';\n for (let i = 1; i < sel.length; i += 1) {\n const c = sel[i]!;\n if (c === '\\\\') {\n i += 1;\n if (i < sel.length) out += sel[i];\n continue;\n }\n if (c === ':' || c === '.' || c === '[' || c === ' ' || c === '>' || c === '+' || c === '~' || c === ',') {\n return null; // not a bare single-class selector\n }\n out += c;\n }\n return out.length > 0 ? out : null;\n}\n","/**\n * @domflax/resolver-tailwind — rule extraction (engine nodes → usable blocks).\n */\n\nimport type { OpaqueToken, StyleCondition } from '@domflax/core';\n\nimport { makeCondition, parseSelector } from './selector';\nimport type { TwGeneratedAtRule, TwGeneratedDecl, TwGeneratedRule, TwNode } from './types';\n\nexport interface ExtractedBlock {\n readonly condition: StyleCondition;\n readonly decls: ReadonlyArray<readonly [string, string, boolean]>;\n}\n\nexport interface ExtractedToken {\n /** Usable (BASE + supported-variant) blocks. */\n readonly blocks: readonly ExtractedBlock[];\n /** True if the engine emitted at least one rule for the token (even an opaque one). */\n readonly produced: boolean;\n /** Set when the token only resolves via combinator / unsupported at-rule selectors. */\n readonly opaque?: OpaqueToken;\n}\n\n/** Collect every leaf `rule` node together with the `@media` stack that wraps it. */\nfunction collectRules(\n node: TwNode,\n mediaStack: readonly string[],\n inUnsupportedAtRule: boolean,\n out: Array<{ rule: TwGeneratedRule; media: readonly string[]; unsupported: boolean }>,\n): void {\n if (node.type === 'rule') {\n out.push({ rule: node as TwGeneratedRule, media: mediaStack, unsupported: inUnsupportedAtRule });\n return;\n }\n if (node.type === 'atrule') {\n const at = node as TwGeneratedAtRule;\n const children = at.nodes ?? [];\n if (at.name === 'media') {\n const nextStack = at.params ? [...mediaStack, at.params] : mediaStack;\n for (const child of children) collectRules(child, nextStack, inUnsupportedAtRule, out);\n } else {\n // @supports / @container / etc. — recurse but flag as unsupported (⇒ opaque).\n for (const child of children) collectRules(child, mediaStack, true, out);\n }\n }\n}\n\n/** Extract usable blocks + opacity info for a single candidate token from its generated nodes. */\nexport function extractToken(token: string, nodes: readonly TwNode[]): ExtractedToken {\n if (nodes.length === 0) return { blocks: [], produced: false };\n\n const leaves: Array<{ rule: TwGeneratedRule; media: readonly string[]; unsupported: boolean }> = [];\n for (const node of nodes) collectRules(node, [], false, leaves);\n\n const blocks: ExtractedBlock[] = [];\n let sawComplex = false;\n\n for (const { rule, media, unsupported } of leaves) {\n const parsed = parseSelector(rule.selector);\n if (parsed.kind === 'complex' || unsupported) {\n sawComplex = true;\n continue;\n }\n const decls: Array<readonly [string, string, boolean]> = [];\n for (const child of rule.nodes ?? []) {\n if (child.type !== 'decl') continue; // skip @defaults markers, comments, nested rules\n const d = child as TwGeneratedDecl;\n if (typeof d.value !== 'string') continue;\n decls.push([d.prop, d.value, d.important === true]);\n }\n if (decls.length === 0) continue;\n const mediaQuery = media.join(' and ');\n blocks.push({ condition: makeCondition(mediaQuery, parsed.states, parsed.pseudoElement), decls });\n }\n\n const opaque: OpaqueToken | undefined =\n sawComplex && blocks.length === 0\n ? { token, reason: 'combinator-variant', detail: 'utility targets descendants/siblings, not its own box' }\n : undefined;\n\n return { blocks, produced: true, opaque };\n}\n","/**\n * @domflax/resolver-tailwind — CSS serialization for `cssFor`.\n */\n\nimport type { TwGeneratedAtRule, TwGeneratedDecl, TwGeneratedRule, TwNode } from './types';\n\n/** Serialize one engine-emitted node (rule / atrule / decl) into plain CSS text. */\nexport function serializeCssNode(node: TwNode): string {\n if (node.type === 'decl') {\n const d = node as TwGeneratedDecl;\n if (typeof d.value !== 'string') return '';\n return `${d.prop}:${d.value}${d.important === true ? ' !important' : ''}`;\n }\n if (node.type === 'rule') {\n const r = node as TwGeneratedRule;\n const body = (r.nodes ?? [])\n .map((c) => serializeCssNode(c))\n .filter((s) => s.length > 0)\n .join(';');\n return `${r.selector}{${body}}`;\n }\n if (node.type === 'atrule') {\n const a = node as TwGeneratedAtRule;\n const body = (a.nodes ?? [])\n .map((c) => serializeCssNode(c))\n .filter((s) => s.length > 0)\n .join('');\n return `@${a.name} ${a.params}{${body}}`;\n }\n return '';\n}\n","/**\n * @domflax/resolver-tailwind — StyleMap assembly + provenance helpers.\n */\n\nimport type {\n CssProperty,\n StyleBlock,\n StyleCondition,\n StyleDecl,\n StyleMap,\n StyleOrigin,\n} from '@domflax/core';\nimport { conditionKey, emptyStyleMap } from '@domflax/core';\nimport { normalizer } from '@domflax/pattern-kit';\n\nexport function buildStyleMap(\n blockMaps: Map<string, { condition: StyleCondition; decls: Map<CssProperty, StyleDecl> }>,\n): StyleMap {\n if (blockMaps.size === 0) return emptyStyleMap();\n const blocks = new Map<ReturnType<typeof conditionKey>, StyleBlock>();\n for (const { condition, decls } of blockMaps.values()) {\n if (decls.size === 0) continue;\n blocks.set(conditionKey(condition), { condition, decls });\n }\n if (blocks.size === 0) return emptyStyleMap();\n return normalizer.normalizeStyleMap({ blocks });\n}\n\n/**\n * The shadow chain a newly-winning declaration inherits when it overrides `prev` on the same\n * property: everything `prev` already shadowed, plus `prev`'s own origin (now shadowed too). Deduped\n * by class name and restricted to class origins (the only kind `dedupe-classes` acts on).\n */\nexport function shadowedBy(prev: StyleDecl): readonly StyleOrigin[] | undefined {\n const out: StyleOrigin[] = [];\n const seen = new Set<string>();\n const add = (o: StyleOrigin | undefined): void => {\n if (!o || o.kind !== 'class' || seen.has(o.className)) return;\n seen.add(o.className);\n out.push(o);\n };\n for (const o of prev.shadowed ?? []) add(o);\n add(prev.origin);\n return out.length > 0 ? out : undefined;\n}\n","/**\n * @domflax/resolver-tailwind — conservative {@link SelectorUsage} constants.\n */\n\nimport type { SelectorUsage } from '@domflax/core';\n\n/**\n * A conservative, never-droppable {@link SelectorUsage}. Until a real project selector graph exists\n * we must assume a class could be referenced in any unsafe position, so nothing is safe to rewrite.\n */\nexport const OPAQUE_USAGE: SelectorUsage = {\n asSubject: true,\n asAncestor: true,\n asCompound: true,\n asSibling: true,\n asHasArgument: true,\n asStructural: true,\n droppable: false,\n};\n\n/**\n * A plain-subject {@link SelectorUsage}: the class is a resolver-owned, base-only utility whose\n * whole effect is reproducible from `computed`, so it is safe to drop/replace during reverse-emit.\n */\nexport const DROPPABLE_USAGE: SelectorUsage = {\n asSubject: true,\n asAncestor: false,\n asCompound: false,\n asSibling: false,\n asHasArgument: false,\n asStructural: false,\n droppable: true,\n};\n","/**\n * @domflax/resolver-tailwind — the {@link StyleResolver} implementation + public factory.\n */\n\nimport type {\n CssProperty,\n EmitContext,\n EmitResult,\n OpaqueToken,\n ResolveInput,\n ResolveResult,\n SelectorUsage,\n StyleCondition,\n StyleDecl,\n StyleMap,\n StyleOrigin,\n StyleResolver,\n} from '@domflax/core';\nimport { BASE_CONDITION, conditionKey } from '@domflax/core';\nimport { normalizer } from '@domflax/pattern-kit';\n\nimport type { TailwindResolverConfig } from './config';\nimport { expandForEmit, synthesizeResidual } from './emit';\nimport { loadEngine } from './engine';\nimport type { ExtractedToken } from './extract';\nimport { extractToken } from './extract';\nimport { fnv1a } from './fingerprint';\nimport { parseSelector, unescapeClass } from './selector';\nimport { serializeCssNode } from './serialize';\nimport { buildStyleMap, shadowedBy } from './stylemap';\nimport type { TwEngine, TwGeneratedDecl, TwGeneratedRule } from './types';\nimport { DROPPABLE_USAGE, OPAQUE_USAGE } from './usage';\n\nclass TailwindResolver implements StyleResolver {\n readonly id = 'tailwind';\n readonly provider: string;\n readonly fingerprint: string;\n\n readonly #engine: TwEngine | null;\n /** Per-token extraction cache (engine output is pure for a fixed config). */\n readonly #tokenCache = new Map<string, ExtractedToken>();\n /** Per-class-set forward-resolution cache. */\n readonly #resolveCache = new Map<string, ResolveResult>();\n /** Lazily built reverse index for {@link emit}. */\n #reverseIndex: ReadonlyArray<readonly [string, ReadonlyMap<CssProperty, string>]> | null = null;\n\n constructor(config: TailwindResolverConfig = {}) {\n this.#engine = loadEngine(config);\n this.provider =\n config.provider ?? (this.#engine ? `tailwindcss@${this.#engine.version}` : 'tailwindcss');\n const seed = JSON.stringify(config.config ?? {}) + (config.configPath ?? '');\n this.fingerprint = config.fingerprint ?? `${this.provider}/${fnv1a(seed)}`;\n }\n\n /** Engine-backed, cached single-token extraction. */\n #extract(token: string): ExtractedToken {\n const cached = this.#tokenCache.get(token);\n if (cached) return cached;\n let result: ExtractedToken;\n if (!this.#engine) {\n result = { blocks: [], produced: false };\n } else {\n try {\n result = extractToken(token, this.#engine.generate([token]));\n } catch {\n result = { blocks: [], produced: false };\n }\n }\n this.#tokenCache.set(token, result);\n return result;\n }\n\n owns(token: string): boolean {\n if (token.length === 0) return false;\n return this.#extract(token).produced;\n }\n\n resolve(input: ResolveInput): ResolveResult {\n const key = JSON.stringify(input.classes);\n const cached = this.#resolveCache.get(key);\n if (cached) return cached;\n\n // condition-key → { condition, longhand decls }. Iterating classes in source order means later\n // utilities overwrite earlier ones on the same property (equal-specificity cascade).\n const blockMaps = new Map<\n string,\n { condition: StyleCondition; decls: Map<CssProperty, StyleDecl> }\n >();\n const resolved: string[] = [];\n const unknown: string[] = [];\n const opaque: OpaqueToken[] = [];\n\n input.classes.forEach((token, tokenIndex) => {\n const extracted = this.#extract(token);\n if (!extracted.produced) {\n unknown.push(token);\n return;\n }\n if (extracted.opaque) opaque.push(extracted.opaque);\n if (extracted.blocks.length === 0) return; // produced only opaque rules\n\n const origin: StyleOrigin = { kind: 'class', tokenIndex, className: token };\n let contributed = false;\n for (const block of extracted.blocks) {\n const ck = conditionKey(block.condition);\n let bucket = blockMaps.get(ck);\n if (!bucket) {\n bucket = { condition: block.condition, decls: new Map() };\n blockMaps.set(ck, bucket);\n }\n for (const [prop, value, important] of block.decls) {\n for (const decl of normalizer.normalizeDeclaration(prop, value, important)) {\n // Record provenance: a LATER token on the same property shadows the earlier one. The\n // overridden origin (plus anything it already shadowed) is carried in `shadowed`, which\n // is exactly what the `dedupe-classes` pattern reads to find fully-overridden tokens.\n // This only enriches decl metadata — the resolved VALUES are unchanged.\n const prev = bucket.decls.get(decl.property);\n const shadowed = prev ? shadowedBy(prev) : undefined;\n bucket.decls.set(decl.property, shadowed ? { ...decl, origin, shadowed } : { ...decl, origin });\n contributed = true;\n }\n }\n }\n if (contributed) resolved.push(token);\n });\n\n const result: ResolveResult = {\n styles: buildStyleMap(blockMaps),\n resolved,\n unknown,\n opaque,\n warnings: [],\n };\n this.#resolveCache.set(key, result);\n return result;\n }\n\n /**\n * Lazily build the reverse index from the engine's own enumerable class list. Each indexable\n * utility maps to its NORMALIZED BASE longhand declarations (property → canonical value). Utilities\n * with variant conditions, combinator selectors, or no BASE declarations are skipped. Sorted by\n * declaration count (desc) so greedier (shorthand-like) utilities are tried first.\n */\n #buildReverseIndex(): ReadonlyArray<readonly [string, ReadonlyMap<CssProperty, string>]> {\n if (this.#reverseIndex) return this.#reverseIndex;\n const index: Array<readonly [string, Map<CssProperty, string>]> = [];\n if (this.#engine) {\n try {\n const classes = this.#engine.context\n .getClassList()\n .filter((c): c is string => typeof c === 'string');\n const nodes = this.#engine.generate(classes);\n // Re-extract per class would be costly; instead group decls by their (single) class selector.\n for (const node of nodes) {\n if (node.type !== 'rule') continue; // skip @media / @keyframes wrappers (⇒ variants only)\n const rule = node as TwGeneratedRule;\n const parsed = parseSelector(rule.selector);\n if (parsed.kind !== 'simple' || parsed.states.length > 0 || parsed.pseudoElement !== '') {\n continue; // BASE-only\n }\n const className = unescapeClass(rule.selector);\n if (className === null) continue;\n const decls = new Map<CssProperty, string>();\n for (const child of rule.nodes ?? []) {\n if (child.type !== 'decl') continue;\n const d = child as TwGeneratedDecl;\n if (typeof d.value !== 'string') continue;\n for (const decl of normalizer.normalizeDeclaration(d.prop, d.value, d.important === true)) {\n decls.set(decl.property, String(decl.value));\n }\n }\n if (decls.size > 0) index.push([className, decls]);\n }\n } catch {\n /* leave index empty on failure — emit degrades to a no-op */\n }\n }\n index.sort((a, b) => b[1].size - a[1].size || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));\n this.#reverseIndex = index;\n return index;\n }\n\n emit(styles: StyleMap, ctx: EmitContext): EmitResult {\n const norm = ctx.normalizer ?? normalizer;\n const normalized = norm.normalizeStyleMap(styles);\n const base = normalized.blocks.get(conditionKey(BASE_CONDITION));\n if (!base || base.decls.size === 0) return { classes: [], exact: true, warnings: [] };\n\n // Only the BASE block is reverse-synthesized (see module LIMITATION). Any non-base condition\n // present in the target means we cannot be exact.\n const hasNonBase = normalized.blocks.size > 1;\n\n // The target longhand map. The IR's compress passes hand us SHORTHAND properties (`padding`,\n // `margin`, `inset`, `inset-block`, `inset-inline`, `size`); we expand them to the same longhand\n // basis the reverse index is keyed on, so a single shorthand utility (`p-4`, `size-4`, `inset-0`)\n // can cover them.\n const target = new Map<CssProperty, string>();\n for (const [prop, decl] of base.decls) {\n for (const [lp, lv] of expandForEmit(norm, String(prop), String(decl.value), decl.important)) {\n target.set(lp, lv);\n }\n }\n\n // Keep only utilities every one of whose declarations matches the target (an exact-fit subset);\n // emitting a utility that sets an unwanted property/value would change the computed style.\n const candidates: Array<readonly [string, ReadonlyMap<CssProperty, string>]> = [];\n for (const entry of this.#buildReverseIndex()) {\n const [, declMap] = entry;\n if (declMap.size === 0 || declMap.size > target.size) continue;\n let fits = true;\n for (const [prop, value] of declMap) {\n if (target.get(prop) !== value) {\n fits = false;\n break;\n }\n }\n if (fits) candidates.push(entry);\n }\n\n // Greedy set-cover: repeatedly take the candidate covering the MOST still-needed declarations,\n // so a shorthand (`p-4`, 4 decls) beats `px-4`+`py-4`. Ties break toward the tighter decl-set\n // then lexicographically, for deterministic output.\n const remaining = new Map(target);\n const classes: string[] = [];\n while (remaining.size > 0) {\n let best: readonly [string, ReadonlyMap<CssProperty, string>] | null = null;\n let bestCover = 0;\n for (const entry of candidates) {\n const [token, declMap] = entry;\n let cover = 0;\n for (const prop of declMap.keys()) if (remaining.has(prop)) cover += 1;\n if (cover === 0) continue;\n const better =\n best === null ||\n cover > bestCover ||\n (cover === bestCover && declMap.size < best[1].size) ||\n (cover === bestCover && declMap.size === best[1].size && token < best[0]);\n if (better) {\n best = entry;\n bestCover = cover;\n }\n }\n if (!best) break; // nothing covers any still-needed declaration → residual\n classes.push(best[0]);\n for (const prop of best[1].keys()) remaining.delete(prop);\n }\n\n const exact = remaining.size === 0 && !hasNonBase;\n if (remaining.size === 0) return { classes, exact, warnings: [] };\n\n // Surface what no utility could cover as a residual synthetic (never thrown, never invented).\n const residual = synthesizeResidual(remaining, ctx);\n return residual\n ? { classes, residual, exact, warnings: [] }\n : { classes, exact, warnings: [] };\n }\n\n /**\n * Generate a CSS stylesheet that defines `classes`, so a verifier can render a subtree with the\n * real Tailwind styling applied. Backed by the same engine `resolve` uses (`generate(candidates)`),\n * serialized to plain CSS. Returns `''` when the engine is unavailable or generates nothing.\n */\n cssFor(classes: readonly string[]): string {\n if (!this.#engine) return '';\n const tokens = [...new Set(classes)].filter((c) => c.length > 0);\n if (tokens.length === 0) return '';\n try {\n return this.#engine\n .generate(tokens)\n .map((n) => serializeCssNode(n))\n .filter((s) => s.length > 0)\n .join('\\n');\n } catch {\n return '';\n }\n }\n\n selectorUsage(token: string): SelectorUsage {\n // No project selector graph yet, so we cannot know how a CUSTOM (non-Tailwind) class is\n // referenced — treat it as load-bearing (preserved verbatim). A resolver-OWNED utility, by\n // contrast, is safe to drop/replace iff its whole effect is reproducible from `computed`: it\n // must be a plain (non-opaque) utility contributing ONLY base-condition declarations. Opaque\n // (combinator/at-rule) and variant-bound utilities are kept, because `emit` cannot rebuild them.\n const ex = this.#extract(token);\n if (!ex.produced || ex.opaque) return OPAQUE_USAGE;\n const baseOnly =\n ex.blocks.length > 0 &&\n ex.blocks.every((b) => conditionKey(b.condition) === conditionKey(BASE_CONDITION));\n if (!baseOnly) return OPAQUE_USAGE;\n return DROPPABLE_USAGE;\n }\n}\n\n/** Factory: build a Tailwind-backed {@link StyleResolver}. */\nexport function createTailwindResolver(config?: TailwindResolverConfig): StyleResolver {\n return new TailwindResolver(config);\n}\n","/* ────────────────────────────────────────────────────────────────────────── *\n * Resolver identity + selector classification constants\n * ────────────────────────────────────────────────────────────────────────── */\n\n/** Stable resolver id surfaced on {@link StyleResolver.id}. */\nexport const CSS_RESOLVER_ID = 'css';\n\n/** Provider tag surfaced on {@link StyleResolver.provider}. */\nexport const CSS_RESOLVER_PROVIDER = 'custom-css';\n\n/** Version stamp for the index/cascade machinery; bump when its semantics change (cache-busting). */\nexport const ENGINE_VERSION = 'css-index@1';\n\n/** Structural pseudo-classes — their presence makes a class structurally targeted (review-1 blocker). */\nexport const STRUCTURAL_PSEUDOS: ReadonlySet<string> = new Set([\n ':nth-child',\n ':nth-last-child',\n ':first-child',\n ':last-child',\n ':only-child',\n ':nth-of-type',\n ':nth-last-of-type',\n ':first-of-type',\n ':last-of-type',\n ':only-of-type',\n]);\n\n/** Functional pseudos whose argument is itself a selector list — opaque to forward resolution. */\nexport const FUNCTIONAL_PSEUDOS: ReadonlySet<string> = new Set([\n ':not',\n ':is',\n ':where',\n ':has',\n ':matches',\n]);\n\n/** Legacy single-colon pseudo-ELEMENTS that the parser may not flag via `isPseudoElement`. */\nexport const LEGACY_PSEUDO_ELEMENTS: ReadonlySet<string> = new Set([\n ':before',\n ':after',\n ':first-line',\n ':first-letter',\n]);\n","import { createRequire } from 'node:module';\nimport * as path from 'node:path';\nimport type { Root as PostcssRoot } from 'postcss';\nimport type selectorParser from 'postcss-selector-parser';\n\n/* ────────────────────────────────────────────────────────────────────────── *\n * Lazy engine loading (postcss + postcss-selector-parser)\n * ────────────────────────────────────────────────────────────────────────── *\n *\n * postcss and postcss-selector-parser are OPTIONAL peers of the published `domflax` package: a\n * Tailwind-only user need not install them. They must therefore be loaded LAZILY (only when this\n * resolver is actually constructed) and from the CONSUMER'S project — never via a static top-level\n * `import`, which would (a) crash on module load for a postcss-less install and (b), once this\n * resolver is inlined into domflax's bundle, resolve relative to `domflax/dist` instead of the\n * user's project. We root the require in `process.cwd()` (or an explicit project root), exactly as\n * the Tailwind resolver does, with the bundle/source location as a last-resort fallback.\n */\n\n/** This module's own location — esbuild fills `__filename` in CJS; ESM falls back to `import.meta.url`. */\nexport function moduleBase(): string {\n return typeof __filename === 'string' ? __filename : import.meta.url;\n}\n\n/** The single postcss entry point this resolver calls at runtime. */\nexport type PostcssParseApi = (css: string, opts?: { from?: string }) => PostcssRoot;\n\n/** The subset of the postcss-selector-parser API this resolver calls at runtime (guards preserve narrowing). */\nexport interface SelectorParserApi {\n (): { astSync(selector: string): selectorParser.Root };\n isClassName(n: selectorParser.Node): n is selectorParser.ClassName;\n isTag(n: selectorParser.Node): n is selectorParser.Tag;\n isIdentifier(n: selectorParser.Node): n is selectorParser.Identifier;\n isAttribute(n: selectorParser.Node): n is selectorParser.Attribute;\n isUniversal(n: selectorParser.Node): n is selectorParser.Universal;\n isNesting(n: selectorParser.Node): n is selectorParser.Nesting;\n isPseudo(n: selectorParser.Node): n is selectorParser.Pseudo;\n isPseudoClass(n: selectorParser.Node): n is selectorParser.Pseudo;\n isPseudoElement(n: selectorParser.Node): n is selectorParser.Pseudo;\n isCombinator(n: selectorParser.Node): n is selectorParser.Combinator;\n}\n\nexport interface PostcssEngine {\n readonly parse: PostcssParseApi;\n readonly selectorParser: SelectorParserApi;\n}\n\n/** Resolve postcss + postcss-selector-parser from the consumer's project; `null` if unavailable. */\nexport function loadPostcssEngine(projectRoot?: string): PostcssEngine | null {\n const bases: string[] = [];\n if (projectRoot) bases.push(path.join(projectRoot, '__domflax__.js'));\n bases.push(path.join(process.cwd(), '__domflax__.js'));\n bases.push(moduleBase());\n for (const base of bases) {\n try {\n const req = createRequire(base);\n req.resolve('postcss');\n req.resolve('postcss-selector-parser');\n const postcss = req('postcss') as { parse: PostcssParseApi };\n const raw = req('postcss-selector-parser') as SelectorParserApi & { default?: SelectorParserApi };\n // postcss-selector-parser is CJS with a default export under interop; accept both shapes.\n const selector = raw.default ?? raw;\n return { parse: postcss.parse, selectorParser: selector };\n } catch {\n /* try the next base */\n }\n }\n return null;\n}\n\n/* ────────────────────────────────────────────────────────────────────────── *\n * Lazily-loaded postcss engine (module singleton)\n * ────────────────────────────────────────────────────────────────────────── */\n\n/** Runtime postcss `parse`, populated on first resolver construction. */\nexport let pc: PostcssParseApi | null = null;\n/** Runtime postcss-selector-parser, populated on first resolver construction. */\nexport let sp: SelectorParserApi | null = null;\n\n/** Ensure the postcss engine is loaded; throws a clear error if the optional peers are absent. */\nexport function ensurePostcss(projectRoot?: string): void {\n if (pc && sp) return;\n const engine = loadPostcssEngine(projectRoot);\n if (!engine) {\n throw new Error(\n '@domflax/resolver-css requires \"postcss\" and \"postcss-selector-parser\" to be installed in ' +\n 'your project (they are optional peer dependencies of domflax, loaded only when the custom-CSS ' +\n 'provider is used). Install them with: npm install postcss postcss-selector-parser',\n );\n }\n pc = engine.parse;\n sp = engine.selectorParser;\n}\n","import type { AtRule, Rule } from 'postcss';\nimport type { RawDecl } from './types';\n\n/* ────────────────────────────────────────────────────────────────────────── *\n * postcss helpers\n * ────────────────────────────────────────────────────────────────────────── */\n\ninterface MediaContext {\n readonly media: string;\n /** True when the rule lives under an at-rule that is not a style context (keyframes/font-face). */\n readonly skip: boolean;\n}\n\n/** Walk a rule's at-rule ancestry, collecting `@media` params and detecting non-style contexts. */\nexport function mediaContext(rule: Rule): MediaContext {\n const parts: string[] = [];\n let skip = false;\n let parent = rule.parent;\n while (parent && parent.type === 'atrule') {\n const at = parent as AtRule;\n const name = at.name.toLowerCase();\n if (name === 'media') parts.unshift(at.params.trim().replace(/\\s+/g, ' '));\n else if (name === 'keyframes' || name.endsWith('keyframes') || name === 'font-face') skip = true;\n parent = parent.parent;\n }\n return { media: parts.join(' and '), skip };\n}\n\n/** A rule's direct declarations, in source order, as raw `[prop, value, important]` triples. */\nexport function collectDecls(rule: Rule): RawDecl[] {\n const out: RawDecl[] = [];\n for (const node of rule.nodes) {\n if (node.type === 'decl') out.push([node.prop, node.value, node.important === true]);\n }\n return out;\n}\n","import { readFileSync } from 'node:fs';\nimport { ENGINE_VERSION } from './constants';\nimport type { CssFile } from './types';\n\n/* ────────────────────────────────────────────────────────────────────────── *\n * Misc helpers\n * ────────────────────────────────────────────────────────────────────────── */\n\n/** Cheap, allocation-free CSS-identifier check used by {@link CustomCSSResolver.owns}. */\nexport function isPlainClassToken(token: string): boolean {\n return token.length > 0 && !/[\\s.#>+~:[\\]()]/.test(token);\n}\n\n/** Read a CSS file from disk; surfaces unreadable paths as a clear input error. */\nexport function readCssPath(path: string): CssFile {\n try {\n return { id: path, css: readFileSync(path, 'utf8') };\n } catch (cause) {\n throw new Error(`resolver-css: cannot read CSS file \"${path}\"`, { cause });\n }\n}\n\n/**\n * Derive a deterministic fingerprint from the provider tag, engine version, and each file's id +\n * length. Cheap and good enough to bust downstream caches when the source CSS set changes.\n */\nexport function deriveFingerprint(provider: string, files: readonly CssFile[]): string {\n const parts = files.map((f) => `${f.id}:${f.css.length}`).sort();\n return `${provider}/${ENGINE_VERSION}::${parts.join('|')}`;\n}\n","import type selectorParser from 'postcss-selector-parser';\nimport { LEGACY_PSEUDO_ELEMENTS } from './constants';\nimport { sp } from './engine';\n\n/* ────────────────────────────────────────────────────────────────────────── *\n * Selector helpers\n * ────────────────────────────────────────────────────────────────────────── */\n\nexport interface Compound {\n /** The combinator immediately to this compound's LEFT (`null` for the first compound). */\n readonly leftCombinator: string | null;\n readonly nodes: readonly selectorParser.Node[];\n}\n\n/** Split a selector's flat node list into compounds delimited by combinator nodes. */\nexport function splitCompounds(selector: selectorParser.Selector): Compound[] {\n const compounds: Compound[] = [];\n let current: selectorParser.Node[] = [];\n let leftCombinator: string | null = null;\n for (const node of selector.nodes) {\n if (sp!.isCombinator(node)) {\n compounds.push({ leftCombinator, nodes: current });\n current = [];\n leftCombinator = combinatorValue(node);\n } else {\n current.push(node);\n }\n }\n compounds.push({ leftCombinator, nodes: current });\n return compounds;\n}\n\n/** A combinator's normalized value — descendant combinators are a single space. */\nfunction combinatorValue(node: selectorParser.Combinator): string {\n const v = node.value;\n return v.trim() === '' ? ' ' : v.trim();\n}\n\n/** The pseudo's lower-cased name including its leading colon(s), without any argument. */\nexport function pseudoName(node: selectorParser.Pseudo): string {\n return node.value.toLowerCase();\n}\n\nexport function isPseudoElement(node: selectorParser.Pseudo): boolean {\n return sp!.isPseudoElement(node) || LEGACY_PSEUDO_ELEMENTS.has(pseudoName(node));\n}\n\n/** Canonicalize a pseudo-element to the modern double-colon form (e.g. `:before` → `::before`). */\nexport function normalizePseudoElement(node: selectorParser.Pseudo): string {\n const name = pseudoName(node);\n return name.startsWith('::') ? name : `::${name.replace(/^:/, '')}`;\n}\n","import type {\n ConditionKey,\n CssProperty,\n EmitContext,\n EmitResult,\n ResolveInput,\n ResolveResult,\n SelectorUsage,\n StyleBlock,\n StyleCondition,\n StyleDecl,\n StyleMap,\n StyleOrigin,\n StyleResolver,\n} from '@domflax/core';\nimport { conditionKey, emptyStyleMap } from '@domflax/core';\nimport { normalizer } from '@domflax/pattern-kit';\nimport type selectorParser from 'postcss-selector-parser';\nimport {\n CSS_RESOLVER_ID,\n CSS_RESOLVER_PROVIDER,\n FUNCTIONAL_PSEUDOS,\n STRUCTURAL_PSEUDOS,\n} from './constants';\nimport { ensurePostcss, pc, sp } from './engine';\nimport { collectDecls, mediaContext } from './postcss-helpers';\nimport { deriveFingerprint, isPlainClassToken, readCssPath } from './misc-helpers';\nimport {\n isPseudoElement,\n normalizePseudoElement,\n pseudoName,\n splitCompounds,\n} from './selector-helpers';\nimport type {\n CssFile,\n CssResolverOptions,\n MutableUsage,\n RawDecl,\n ReverseEntry,\n RuleEntry,\n} from './types';\n\n/* ────────────────────────────────────────────────────────────────────────── *\n * CustomCSSResolver\n * ────────────────────────────────────────────────────────────────────────── */\n\n/**\n * Resolves plain CSS classes against a fixed set of project stylesheets parsed with postcss.\n */\nexport class CustomCSSResolver implements StyleResolver {\n public readonly id: string = CSS_RESOLVER_ID;\n public readonly provider: string = CSS_RESOLVER_PROVIDER;\n public readonly fingerprint: string;\n\n readonly #files: readonly CssFile[];\n /** Forward map: class token → simple-`.class` rule contributions (source order). */\n readonly #classIndex = new Map<string, RuleEntry[]>();\n /** Selector-participation facts per class token. */\n readonly #usage = new Map<string, MutableUsage>();\n /** Every class referenced anywhere in the stylesheets (forward-resolvable or not). */\n readonly #known = new Set<string>();\n /** Distinct COMPLEX selectors (combinator or structural pseudo), sorted. */\n readonly #complex: readonly string[];\n\n #reverse: readonly ReverseEntry[] | null = null;\n\n public constructor(cssFiles: readonly CssFile[] = [], options: CssResolverOptions = {}) {\n ensurePostcss(options.projectRoot);\n const fromDisk = (options.files ?? []).map(readCssPath);\n this.#files = [...cssFiles, ...fromDisk];\n this.fingerprint = options.fingerprint ?? deriveFingerprint(this.provider, this.#files);\n\n const complex = new Set<string>();\n let order = 0;\n for (const file of this.#files) {\n order = this.#indexFile(file, order, complex);\n }\n this.#complex = [...complex].sort();\n }\n\n /** The stylesheets this resolver was constructed with (raw sources + any read from disk). */\n public get files(): readonly CssFile[] {\n return this.#files;\n }\n\n /** Owns any plain class token referenced by one of {@link files}. */\n public owns(token: string): boolean {\n return isPlainClassToken(token) && this.#known.has(token);\n }\n\n public resolve(input: ResolveInput): ResolveResult {\n const styles = this.#resolveTokens(input.classes, input.classes);\n const resolved: string[] = [];\n const unknown: string[] = [];\n for (const token of input.classes) {\n if (this.#classIndex.has(token)) resolved.push(token);\n else unknown.push(token);\n }\n return { styles, resolved, unknown, opaque: [], warnings: [] };\n }\n\n public emit(styles: StyleMap, ctx: EmitContext): EmitResult {\n const norm = ctx.normalizer ?? normalizer;\n const remaining = new Map<string, string>();\n for (const [ck, block] of norm.normalizeStyleMap(styles).blocks) {\n for (const [prop, decl] of block.decls) {\n remaining.set(`${ck} ${prop}`, String(decl.value));\n }\n }\n if (remaining.size === 0) return { classes: [], exact: true, warnings: [] };\n\n const classes: string[] = [];\n // Greedy set-cover: larger classes first so the emitted set stays minimal.\n for (const { token, keyed } of this.#reverseIndex()) {\n let matches = true;\n for (const [key, value] of keyed) {\n if (remaining.get(key) !== value) {\n matches = false;\n break;\n }\n }\n if (!matches) continue;\n classes.push(token);\n for (const key of keyed.keys()) remaining.delete(key);\n if (remaining.size === 0) break;\n }\n\n // Unmatched declarations are left as-is (no synthetic residual) — surfaced via `exact:false`.\n return { classes, exact: remaining.size === 0, warnings: [] };\n }\n\n /**\n * Return a CSS stylesheet defining the given class tokens, so a verifier can render a subtree with\n * the project's real styling applied. The source stylesheets ARE the definition, so we hand back\n * their concatenation verbatim (every relevant rule — including combinator/structural selectors —\n * is preserved). `classes` is accepted for interface parity but the full source is always returned.\n */\n public cssFor(_classes: readonly string[]): string {\n return this.#files.map((f) => f.css).join('\\n');\n }\n\n public selectorUsage(token: string): SelectorUsage {\n const u = this.#usage.get(token);\n if (!u) {\n return {\n asSubject: false,\n asAncestor: false,\n asCompound: false,\n asSibling: false,\n asHasArgument: false,\n asStructural: false,\n droppable: true,\n };\n }\n return {\n asSubject: u.asSubject,\n asAncestor: u.asAncestor,\n asCompound: u.asCompound,\n asSibling: u.asSibling,\n asHasArgument: u.asHasArgument,\n asStructural: u.asStructural,\n // Safe to drop/rename only when every reference is the lone subject of a bare `.x {}`.\n droppable: u.referenced && !u.loadBearing,\n };\n }\n\n /**\n * The distinct COMPLEX selectors found across all stylesheets — anything containing a combinator\n * (descendant / `>` / `+` / `~`) or a structural pseudo (`:nth-child`, `:first-child`, …). Feeds\n * domflax's CSS-selector-safety guard.\n */\n public complexSelectors(): readonly string[] {\n return this.#complex;\n }\n\n /* ─────────────────────────── internals ─────────────────────────── */\n\n /** Parse one stylesheet and fold its rules into the indexes. Returns the advanced order counter. */\n #indexFile(file: CssFile, startOrder: number, complex: Set<string>): number {\n let order = startOrder;\n let root;\n try {\n root = pc!(file.css, { from: file.id });\n } catch {\n // Malformed CSS contributes nothing (never throws — only clear input errors do).\n return order;\n }\n\n root.walkRules((rule) => {\n const media = mediaContext(rule);\n if (media.skip) return; // inside @keyframes / @font-face etc. — not class rules\n const decls = collectDecls(rule);\n\n let ast;\n try {\n ast = sp!().astSync(rule.selector);\n } catch {\n return;\n }\n\n for (const sel of ast.nodes) {\n const thisOrder = order;\n this.#analyzeSelector(sel as selectorParser.Selector, media.media, decls, thisOrder, complex);\n }\n order += 1;\n });\n\n return order;\n }\n\n /** Analyze one comma-segment selector: forward indexing, usage facts, complex detection. */\n #analyzeSelector(\n selector: selectorParser.Selector,\n media: string,\n decls: readonly RawDecl[],\n order: number,\n complex: Set<string>,\n ): void {\n const compounds = splitCompounds(selector);\n let hasCombinator = false;\n let hasStructural = false;\n\n compounds.forEach((compound, index) => {\n const isSubject = index === compounds.length - 1;\n const rightCombinator = index < compounds.length - 1 ? compounds[index + 1]!.leftCombinator : null;\n if (rightCombinator) hasCombinator = true;\n\n const classes = compound.nodes.filter((n) => sp!.isClassName(n));\n const otherSimple = compound.nodes.some(\n (n) =>\n sp!.isTag(n) ||\n sp!.isIdentifier(n) ||\n sp!.isAttribute(n) ||\n sp!.isUniversal(n) ||\n sp!.isNesting(n),\n );\n const pseudos = compound.nodes.filter((n) => sp!.isPseudo(n));\n const structuralPseudo = pseudos.some((p) => STRUCTURAL_PSEUDOS.has(pseudoName(p)));\n const functionalPseudo = pseudos.some((p) => FUNCTIONAL_PSEUDOS.has(pseudoName(p)));\n const statePseudos = pseudos.filter(\n (p) =>\n sp!.isPseudoClass(p) &&\n !STRUCTURAL_PSEUDOS.has(pseudoName(p)) &&\n !FUNCTIONAL_PSEUDOS.has(pseudoName(p)),\n );\n const elementPseudos = pseudos.filter((p) => isPseudoElement(p));\n const qualified = classes.length > 1 || otherSimple || functionalPseudo || statePseudos.length > 0;\n\n if (structuralPseudo) hasStructural = true;\n\n for (const cls of classes) {\n const token = cls.value;\n this.#known.add(token);\n const u = this.#getUsage(token);\n u.referenced = true;\n if (isSubject) u.asSubject = true;\n if (rightCombinator === ' ' || rightCombinator === '>') u.asAncestor = true;\n if (rightCombinator === '+' || rightCombinator === '~') u.asSibling = true;\n if (qualified) u.asCompound = true;\n if (structuralPseudo) u.asStructural = true;\n if (rightCombinator !== null || qualified || structuralPseudo || elementPseudos.length > 0) {\n u.loadBearing = true;\n }\n\n // Forward indexing: a single bare `.class` compound, optionally qualified by state\n // pseudo-classes and/or a pseudo-element, with NO other simple selector and NO\n // structural/functional pseudo and NO combinator on this compound's right edge.\n const forwardEligible =\n compounds.length === 1 &&\n classes.length === 1 &&\n !otherSimple &&\n !structuralPseudo &&\n !functionalPseudo &&\n elementPseudos.length <= 1;\n if (forwardEligible && decls.length > 0) {\n const condition: StyleCondition = {\n media,\n states: statePseudos.map(pseudoName).sort(),\n pseudoElement: elementPseudos.length === 1 ? normalizePseudoElement(elementPseudos[0]!) : '',\n };\n this.#addRuleEntry(token, { order, token, condition, decls });\n }\n }\n\n // Classes nested inside selector-argument pseudos (:has/:is/:where/:not) are references too.\n for (const p of pseudos) {\n const isHas = pseudoName(p) === ':has';\n p.walkClasses((inner) => {\n const token = inner.value;\n this.#known.add(token);\n const u = this.#getUsage(token);\n u.referenced = true;\n u.loadBearing = true;\n if (isHas) u.asHasArgument = true;\n });\n }\n });\n\n if (hasCombinator || hasStructural) {\n complex.add(selector.toString().trim());\n }\n }\n\n #addRuleEntry(token: string, entry: RuleEntry): void {\n const list = this.#classIndex.get(token);\n if (list) list.push(entry);\n else this.#classIndex.set(token, [entry]);\n }\n\n #getUsage(token: string): MutableUsage {\n let u = this.#usage.get(token);\n if (!u) {\n u = {\n referenced: false,\n asSubject: false,\n asAncestor: false,\n asCompound: false,\n asSibling: false,\n asHasArgument: false,\n asStructural: false,\n loadBearing: false,\n };\n this.#usage.set(token, u);\n }\n return u;\n }\n\n /**\n * Resolve a set of tokens into a normalized condition-keyed StyleMap. `tokenList` is the original\n * class list (for per-declaration `tokenIndex` provenance); `request` is the set being resolved.\n */\n #resolveTokens(request: readonly string[], tokenList: readonly string[]): StyleMap {\n const entries: RuleEntry[] = [];\n for (const token of new Set(request)) {\n const list = this.#classIndex.get(token);\n if (list) entries.push(...list);\n }\n if (entries.length === 0) return emptyStyleMap();\n\n // Equal-specificity single-class rules cascade by source order — later wins.\n entries.sort((a, b) => a.order - b.order);\n\n const acc = new Map<ConditionKey, { condition: StyleCondition; decls: Map<CssProperty, StyleDecl> }>();\n for (const entry of entries) {\n const key = conditionKey(entry.condition);\n let block = acc.get(key);\n if (!block) {\n block = { condition: entry.condition, decls: new Map() };\n acc.set(key, block);\n }\n const tokenIndex = tokenList.indexOf(entry.token);\n const origin: StyleOrigin = { kind: 'class', tokenIndex, className: entry.token };\n for (const [prop, value, important] of entry.decls) {\n for (const decl of normalizer.normalizeDeclaration(prop, value, important)) {\n block.decls.set(decl.property, { ...decl, origin });\n }\n }\n }\n\n const rawBlocks = new Map<ConditionKey, StyleBlock>();\n for (const [key, block] of acc) {\n if (block.decls.size === 0) continue;\n rawBlocks.set(key, { condition: block.condition, decls: block.decls });\n }\n if (rawBlocks.size === 0) return emptyStyleMap();\n return normalizer.normalizeStyleMap({ blocks: rawBlocks });\n }\n\n /** Build (once) the reverse index used by {@link emit}. */\n #reverseIndex(): readonly ReverseEntry[] {\n if (this.#reverse) return this.#reverse;\n const out: ReverseEntry[] = [];\n for (const token of this.#classIndex.keys()) {\n const styles = this.#resolveTokens([token], [token]);\n const keyed = new Map<string, string>();\n for (const [ck, block] of styles.blocks) {\n for (const [prop, decl] of block.decls) keyed.set(`${ck} ${prop}`, String(decl.value));\n }\n if (keyed.size > 0) out.push({ token, keyed });\n }\n // Larger declaration sets first → greedy minimal cover in `emit`.\n out.sort((a, b) => b.keyed.size - a.keyed.size);\n this.#reverse = out;\n return out;\n }\n}\n\n/* ────────────────────────────────────────────────────────────────────────── *\n * Factory\n * ────────────────────────────────────────────────────────────────────────── */\n\n/**\n * Construct a {@link CustomCSSResolver} from raw CSS sources and/or file paths.\n *\n * @param cssFiles raw stylesheets (`{ id, css }`) — pass `[]` when loading only from disk.\n * @param options optional disk paths (`files`) and/or an explicit `fingerprint`.\n */\nexport function createCssResolver(\n cssFiles: readonly CssFile[] = [],\n options?: CssResolverOptions,\n): StyleResolver {\n return new CustomCSSResolver(cssFiles, options);\n}\n","/**\n * domflax — public meta package.\n *\n * Re-exports the entire `@domflax/core` public API (types + reference runtime) and the built-in\n * `@domflax/patterns` library, then layers thin, framework-agnostic build adapters on top\n * (`vite()` / `webpack()`) plus a programmatic `createDomflax()` factory.\n *\n * Each adapter runs the SAME single-file engine as {@link createDomflax} (JSX/TSX frontend + lazy\n * Tailwind/CSS resolver → core pass manager → reverse-emit → JSX backend). The adapters are\n * structurally typed against their bundlers — they never hard-depend on `vite` or `webpack`.\n *\n * Future deps (intentionally NOT imported yet — they land in a later stage):\n * - `@domflax/frontend-html` — HTML / Astro-static frontend feeding the pipeline.\n * - `@domflax/backend-*` — additional surgical codegen backends.\n */\n\nimport { createPipeline } from '@domflax/core';\nimport type {\n EncodedSourceMap,\n Pattern,\n Pipeline,\n SafetyLevel,\n StyleResolver,\n} from '@domflax/core';\nimport { builtinPatterns } from '@domflax/patterns';\nimport { createTailwindResolver } from '@domflax/resolver-tailwind';\nimport { createCssResolver } from '@domflax/resolver-css';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nimport { jsxKindOf, runJsxPipeline } from './pipeline-run';\n\n// ── Re-export the public surface ──────────────────────────────────────────────────────────────\nexport * from '@domflax/core';\nexport * from '@domflax/patterns';\n\n/* ────────────────────────────────────────────────────────────────────────── *\n * Options\n * ────────────────────────────────────────────────────────────────────────── */\n\n/** How class names resolve to computed styles. */\nexport type DomflaxProvider = 'auto' | 'tailwind' | 'custom';\n\n/** Public adapter/factory options (mirrors the documented `domflax({...})` surface). */\nexport interface DomflaxOptions {\n /** Resolution strategy. Defaults to `'auto'`. */\n readonly provider?: DomflaxProvider;\n /** Stylesheets to parse when `provider` is `'custom'`. */\n readonly cssFiles?: readonly string[];\n /** Preview changes without rewriting source. */\n readonly dryRun?: boolean;\n /** Optimization aggressiveness handed to the pass manager (0 lint … 3 aggressive). */\n readonly safety?: SafetyLevel;\n /** File globs/extensions the adapters should consider. Defaults to jsx/tsx/html. */\n readonly include?: readonly string[];\n}\n\n/** Fully-resolved options with defaults applied. */\nexport interface ResolvedDomflaxOptions {\n readonly provider: DomflaxProvider;\n readonly cssFiles: readonly string[];\n readonly dryRun: boolean;\n readonly safety: SafetyLevel;\n readonly include: readonly string[];\n}\n\nconst DEFAULT_INCLUDE: readonly string[] = ['.jsx', '.tsx', '.html'];\n\nfunction resolveOptions(options: DomflaxOptions): ResolvedDomflaxOptions {\n return {\n provider: options.provider ?? 'auto',\n cssFiles: options.cssFiles ?? [],\n dryRun: options.dryRun ?? false,\n safety: options.safety ?? 2,\n include: options.include ?? DEFAULT_INCLUDE,\n };\n}\n\n/** True when `id` is a file domflax knows how to transform. */\nfunction isSupported(id: string, include: readonly string[]): boolean {\n // Strip query suffixes bundlers append (e.g. `App.tsx?used`).\n const clean = id.split('?', 1)[0] ?? id;\n return include.some((ext) => clean.endsWith(ext));\n}\n\n/* ────────────────────────────────────────────────────────────────────────── *\n * Programmatic instance\n * ────────────────────────────────────────────────────────────────────────── */\n\n/** Result of a single-file transform. `map` is null until codegen lands. */\nexport interface DomflaxTransformResult {\n readonly code: string;\n readonly map: EncodedSourceMap | null;\n}\n\n/**\n * A configured domflax engine. Holds the wired core {@link Pipeline}, the passthrough\n * {@link StyleResolver}, and the built-in {@link Pattern} set, and exposes a single-file\n * `transform`.\n */\nexport interface Domflax {\n readonly options: ResolvedDomflaxOptions;\n readonly pipeline: Pipeline;\n readonly resolver: StyleResolver;\n readonly patterns: readonly Pattern[];\n /**\n * Transform one file (SYNCHRONOUS, fully static, never launches a browser). For `.jsx`/`.tsx` this\n * runs the full pipeline (parse → resolve → flatten[provably-safe only] → reverse-emit → print);\n * every other (or unsupported) file is returned unchanged. Only provably layout-neutral flattens are\n * applied — domflax never changes rendering.\n */\n transform(code: string, id: string): DomflaxTransformResult;\n}\n\n/**\n * Build a configured domflax engine.\n *\n * Wires a real single-file pipeline: the JSX/TSX frontend + a Tailwind resolver feed the core pass\n * manager (running {@link builtinPatterns}), whose output is reverse-emitted back to class tokens\n * and re-printed by the JSX backend. Non-jsx/tsx files pass through unchanged.\n */\n/**\n * Build the {@link StyleResolver} for the chosen provider. The heavy engine each resolver wraps\n * (Tailwind v3 / postcss) is loaded LAZILY — at the moment this factory runs — and resolved from the\n * CONSUMER'S project, NOT from domflax's (possibly bundled) location. Both engines are OPTIONAL peer\n * dependencies of the published `domflax`: a Tailwind-only user never triggers a postcss load, and a\n * custom-CSS-only user never triggers a Tailwind load, because only the selected branch constructs.\n */\nfunction createResolver(resolved: ResolvedDomflaxOptions): StyleResolver {\n if (resolved.provider === 'custom') {\n return createCssResolver([], { files: resolved.cssFiles });\n }\n // 'auto' and 'tailwind' both resolve against the project's Tailwind engine.\n return createTailwindResolver();\n}\n\nexport function createDomflax(options: DomflaxOptions = {}): Domflax {\n const resolved = resolveOptions(options);\n const pipeline = createPipeline();\n const patterns = builtinPatterns;\n\n // Construct the resolver lazily so neither optional engine (Tailwind / postcss) is loaded until a\n // file is actually transformed (and only the engine for the selected provider is ever loaded).\n let cachedResolver: StyleResolver | null = null;\n const getResolver = (): StyleResolver => (cachedResolver ??= createResolver(resolved));\n\n return {\n options: resolved,\n pipeline,\n get resolver(): StyleResolver {\n return getResolver();\n },\n patterns,\n transform(code: string, id: string): DomflaxTransformResult {\n if (!isSupported(id, resolved.include)) return { code, map: null };\n const kind = jsxKindOf(id);\n // Non-jsx/tsx supported files (e.g. .html) stay passthrough — no HTML frontend wired yet.\n if (kind === null) return { code, map: null };\n const out = runJsxPipeline(code, id, kind, getResolver(), patterns, resolved.safety);\n return { code: out, map: null };\n },\n };\n}\n\n/* ────────────────────────────────────────────────────────────────────────── *\n * Build adapters (framework-agnostic, structurally-typed shapes)\n * ────────────────────────────────────────────────────────────────────────── */\n\n/**\n * Minimal Vite-plugin shape. Declared locally so this adapter does NOT depend on `vite`'s types\n * (an optional, type-only peer). Structurally compatible with Vite's `Plugin` for the hooks domflax\n * uses: `enforce: 'pre'` runs domflax before Vite's JSX→`createElement` transform, and `transform`\n * is Vite's per-file source hook. Returning `null` is Vite's \"no change\" signal.\n */\nexport interface DomflaxVitePlugin {\n readonly name: string;\n readonly enforce: 'pre';\n /** Vite's per-file source hook. Fully synchronous and browser-free. */\n transform(code: string, id: string): DomflaxTransformResult | null;\n}\n\n/**\n * Vite adapter. Returns a real Vite `Plugin` (`enforce: 'pre'`) whose `transform` runs the domflax\n * engine on `.jsx`/`.tsx` modules — strips any bundler query suffix (e.g. `App.tsx?used`) before\n * matching, returns `{ code, map }` when the source changed, and `null` (Vite's unchanged signal)\n * for unchanged sources and for any non-jsx/tsx module.\n *\n * @example\n * ```js\n * // vite.config.js\n * import domflax from 'domflax';\n * export default { plugins: [domflax.vite({ provider: 'tailwind' })] };\n * ```\n */\nexport function vite(options: DomflaxOptions = {}): DomflaxVitePlugin {\n const engine = createDomflax(options);\n return {\n name: 'domflax',\n enforce: 'pre',\n transform(code: string, id: string): DomflaxTransformResult | null {\n if (!isSupported(id, engine.options.include)) return null;\n const out = engine.transform(code, id);\n // Signal \"no change\" to Vite when the source round-tripped unchanged.\n return out.code === code ? null : out;\n },\n };\n}\n\n/* ── webpack / Next.js ──────────────────────────────────────────────────────────────────────── */\n\n/** A `module.rule` `use` entry: an absolute loader path plus the options forwarded to it. */\ninterface DomflaxRuleUse {\n readonly loader: string;\n readonly options: DomflaxOptions;\n}\n\n/** The slice of a webpack `module.rule` domflax appends. */\ninterface DomflaxModuleRule {\n readonly test: RegExp;\n readonly enforce: 'pre';\n readonly exclude: RegExp;\n readonly use: readonly DomflaxRuleUse[];\n}\n\n/** Anything carrying a `module.rules` array — both a webpack `Compiler.options` and Next's bare config. */\ninterface DomflaxWebpackModuleHost {\n module?: { rules?: unknown[] };\n}\n\n/**\n * Minimal webpack-compiler shape. Declared locally so this adapter does NOT depend on `webpack`'s\n * types. domflax only needs to push a rule onto the host's `module.rules`.\n *\n * `apply` accepts BOTH shapes: a real webpack `Compiler` (rules live under `compiler.options.module`)\n * AND the bare `config` object Next.js hands you from `webpack(config)` (rules live directly under\n * `config.module`). It duck-types `compiler.options ?? compiler` to find the right host.\n */\nexport interface DomflaxWebpackCompiler extends DomflaxWebpackModuleHost {\n options?: DomflaxWebpackModuleHost;\n}\n\n/**\n * Minimal webpack-plugin shape. `apply(compiler)` is the webpack plugin entry point.\n */\nexport interface DomflaxWebpackPlugin {\n readonly name: string;\n apply(compiler: DomflaxWebpackCompiler): void;\n}\n\n/** `.jsx`/`.tsx` modules only (combinator-free with the JSX frontend; `.js`/`.ts` are skipped). */\nconst WEBPACK_JSX_TEST = /\\.[jt]sx$/;\n\n/**\n * Absolute path to the bundled webpack loader (`./webpack-loader`). Resolved lazily against THIS\n * module's location so it works whether `domflax` is loaded as ESM (`dist/index.js`) or CJS\n * (`dist/index.cjs`) — both sit beside `dist/webpack-loader.cjs`. webpack requires loaders via\n * CommonJS, so we always point at the `.cjs` output.\n */\nfunction webpackLoaderPath(): string {\n const here = dirname(fileURLToPath(import.meta.url));\n return join(here, 'webpack-loader.cjs');\n}\n\n/**\n * webpack adapter (also the Next.js path). Returns a plugin whose `apply(compiler)` injects a\n * pre-enforced `module.rule` that invokes the domflax {@link ./webpack-loader loader} on every\n * `.jsx`/`.tsx` module. The loader runs the SAME lazy engine as {@link createDomflax} (no eager\n * Tailwind/postcss load).\n *\n * Next.js wiring (`next.config.js`) — Next exposes the underlying webpack config via `webpack(config)`:\n * ```js\n * // next.config.js\n * const domflax = require('domflax');\n * module.exports = {\n * webpack(config) {\n * domflax.webpack({ provider: 'tailwind' }).apply(config);\n * return config;\n * },\n * };\n * ```\n * `apply(compiler)` is intentionally duck-typed on `compiler.options.module.rules`, so it accepts\n * both a real webpack `Compiler` and the bare `config` object Next.js hands you.\n *\n * Caveat: this targets the webpack builder only. **Turbopack is not yet supported** — it does not\n * accept arbitrary webpack loaders, so the `next.config.js` wiring above is a no-op under\n * `next dev --turbopack`. Run domflax through the webpack builder until Turbopack exposes a loader API.\n */\nexport function webpack(options: DomflaxOptions = {}): DomflaxWebpackPlugin {\n // Validate options eagerly (parity with the other adapters); the resolver stays lazy.\n createDomflax(options);\n return {\n name: 'domflax',\n apply(compiler: DomflaxWebpackCompiler): void {\n // Real webpack passes a `Compiler` (rules under `.options.module`); Next's `webpack(config)`\n // passes the bare config (rules under `.module`). Duck-type to the right host.\n const host: DomflaxWebpackModuleHost = compiler.options ?? compiler;\n const mod = (host.module ??= {});\n const rules = (mod.rules ??= []);\n const rule: DomflaxModuleRule = {\n test: WEBPACK_JSX_TEST,\n enforce: 'pre',\n exclude: /node_modules/,\n use: [{ loader: webpackLoaderPath(), options }],\n };\n rules.push(rule);\n },\n };\n}\n\n/**\n * The default-export namespace. Exposes the build adapters and the programmatic factory as an OBJECT\n * so the documented `import domflax from 'domflax'; domflax.vite()` / `domflax.webpack()` works (and a\n * CommonJS `const domflax = require('domflax'); domflax.vite()` too). The named exports\n * (`createDomflax`, `vite`, `webpack`, …) remain available for direct import.\n */\nexport interface DomflaxDefault {\n createDomflax(options?: DomflaxOptions): Domflax;\n vite(options?: DomflaxOptions): DomflaxVitePlugin;\n webpack(options?: DomflaxOptions): DomflaxWebpackPlugin;\n}\n\n/** Default export: an object exposing `vite`, `webpack`, and the programmatic `createDomflax`. */\nconst domflax: DomflaxDefault = { createDomflax, vite, webpack };\nexport default domflax;\n","/**\n * @domflax/frontend-jsx — AST interop, constants, and pure classification helpers.\n *\n * Stateless building blocks shared by the JSX parse pass: the `@babel/traverse`\n * default-export normalization, the frontend's fixed constants, and the pure\n * name/classification/JSX-discovery helpers (no closure state, no document mutation).\n */\n\nimport babelTraverse from '@babel/traverse';\nimport type {\n JSXAttribute,\n JSXElement,\n JSXFragment,\n JSXIdentifier,\n JSXMemberExpression,\n JSXNamespacedName,\n Node as BabelNode,\n} from '@babel/types';\n\nimport type { ClassListForm, ExprKind, FileKind, SourceFileId } from '@domflax/core';\n\n/* ───────────────────────── @babel/traverse interop ───────────────────────── */\n\n// `@babel/traverse` is published as CJS (`module.exports = traverse; exports.default = traverse`).\n// Under an ESM default import the value may be the function OR `{ default: fn }` depending on the\n// interop layer (Node ESM vs. esbuild vs. tsup), so normalize defensively.\nexport const traverse = (\n typeof babelTraverse === 'function'\n ? babelTraverse\n : (babelTraverse as unknown as { default: typeof babelTraverse }).default\n) as typeof babelTraverse;\n\n/** Languages this frontend claims. JSX/TSX only; HTML is owned by a sibling frontend. */\nexport const JSX_LANGS: readonly FileKind[] = ['jsx', 'tsx'];\n\n/** The single registered source file id (one parse == one module). */\nexport const FILE_ID = 1 as SourceFileId;\n\n/** Marker payload stored for every interned expression so the backend can re-print it. */\nexport interface ExprPayload {\n readonly text: string;\n readonly spread: boolean;\n}\n\n/* ───────────────────────── name + classification helpers ───────────────────────── */\n\nexport type JSXName = JSXIdentifier | JSXMemberExpression | JSXNamespacedName;\n\nexport function jsxName(node: JSXName): string {\n switch (node.type) {\n case 'JSXIdentifier':\n return node.name;\n case 'JSXMemberExpression':\n return `${jsxName(node.object)}.${node.property.name}`;\n case 'JSXNamespacedName':\n return `${node.namespace.name}:${node.name.name}`;\n }\n}\n\n/** Component vs. intrinsic: capitalized identifier or member expression ⇒ component. */\nexport function isComponentName(node: JSXName): boolean {\n if (node.type === 'JSXMemberExpression') return true;\n if (node.type === 'JSXNamespacedName') return false;\n return /^[A-Z]/.test(node.name);\n}\n\nexport function attrName(name: JSXAttribute['name']): string {\n return name.type === 'JSXNamespacedName'\n ? `${name.namespace.name}:${name.name.name}`\n : name.name;\n}\n\nexport function exprKind(node: BabelNode): ExprKind {\n switch (node.type) {\n case 'CallExpression':\n case 'OptionalCallExpression':\n return 'call';\n case 'MemberExpression':\n case 'OptionalMemberExpression':\n return 'member';\n case 'ConditionalExpression':\n case 'LogicalExpression':\n return 'conditional';\n case 'TemplateLiteral':\n case 'TaggedTemplateExpression':\n return 'template';\n case 'Identifier':\n return 'identifier';\n case 'SpreadElement':\n return 'spread';\n default:\n return 'other';\n }\n}\n\n/** Map a dynamic className expression to the closest {@link ClassListForm}. */\nexport function classFormOf(node: BabelNode): ClassListForm {\n switch (node.type) {\n case 'TemplateLiteral':\n case 'TaggedTemplateExpression':\n return 'template-literal';\n case 'CallExpression':\n case 'OptionalCallExpression':\n return 'call';\n case 'ConditionalExpression':\n case 'LogicalExpression':\n return 'conditional';\n case 'MemberExpression':\n case 'OptionalMemberExpression':\n case 'Identifier':\n return 'member';\n default:\n return 'call';\n }\n}\n\n/**\n * Find the OUTERMOST JSXElement/JSXFragment nodes that a dynamic expression renders, so the frontend\n * can lower JSX nested inside `{…}` holes — `.map`/`.filter`/`.forEach((x) => <jsx/>)` callbacks,\n * `&&`/`||` logical expressions, ternaries, and parenthesized/cast wrappers — into REAL IR element\n * nodes. The dynamic scaffolding around them (the call itself, the conditions, `{expr}` holes) stays\n * opaque; only the renderable JSX is surfaced so the pass manager descends into and optimizes it.\n *\n * Only the outermost JSX is collected: `buildElement`/`buildFragment` recurse into the\n * descendants themselves, so we must NOT descend past a JSX boundary here (that would double-register\n * inner elements).\n */\nexport function findNestedJsxRoots(root: BabelNode): (JSXElement | JSXFragment)[] {\n const out: (JSXElement | JSXFragment)[] = [];\n const seen = new Set<BabelNode>();\n\n const visit = (n: BabelNode | null | undefined): void => {\n if (!n || seen.has(n)) return;\n seen.add(n);\n switch (n.type) {\n case 'JSXElement':\n case 'JSXFragment':\n out.push(n); // outermost renderable JSX — buildElement/buildFragment recurse from here\n return;\n case 'ParenthesizedExpression':\n case 'TSNonNullExpression':\n case 'TSAsExpression':\n case 'TSSatisfiesExpression':\n case 'TSTypeAssertion':\n visit(n.expression);\n return;\n case 'LogicalExpression':\n visit(n.left);\n visit(n.right);\n return;\n case 'ConditionalExpression':\n visit(n.consequent);\n visit(n.alternate);\n return;\n case 'SequenceExpression':\n for (const e of n.expressions) visit(e);\n return;\n case 'CallExpression':\n case 'OptionalCallExpression':\n // `.map`/`.filter`/`.forEach(cb)` etc. — descend into the call arguments (the callbacks),\n // never the callee (that is the `items.map` member access, which renders nothing).\n for (const a of n.arguments) visit(a as BabelNode);\n return;\n case 'ArrowFunctionExpression':\n case 'FunctionExpression':\n visit(n.body);\n return;\n case 'BlockStatement':\n for (const s of n.body) visit(s);\n return;\n case 'ReturnStatement':\n visit(n.argument);\n return;\n case 'IfStatement':\n visit(n.consequent);\n visit(n.alternate);\n return;\n case 'ArrayExpression':\n for (const el of n.elements) visit(el as BabelNode);\n return;\n default:\n return;\n }\n };\n\n visit(root);\n return out;\n}\n\nexport function looksLikeJsx(id: string, code: string): boolean {\n if (/\\.[jt]sx$/i.test(id)) return true;\n return /<\\/?[A-Za-z][\\w.-]*|<>/.test(code);\n}\n","/**\n * @domflax/frontend-jsx — the JSX/TSX → IR parse pass.\n *\n * Walks a Babel AST (`@babel/parser` → `@babel/traverse`) and lowers JSXElement /\n * JSXFragment / JSXText / JSXExpressionContainer / JSXSpreadChild nodes into the\n * `@domflax/core` IR. ALL dynamic JavaScript stays out of the structural IR: every\n * expression container, spread, and dynamic className/child is interned into the\n * document's {@link ExprRegistry} as an opaque {@link ExprRef} (with its verbatim source\n * slice as payload), and only its source span survives in the tree.\n *\n * Static `class`/`className` literals are split into {@link ClassToken}s on a static\n * {@link ClassSegment}; a non-string-literal className becomes a single dynamic segment\n * (opaque, never optimized). Static classes are resolved through the supplied\n * {@link StyleResolver} + {@link StyleNormalizer} into `element.computed` so downstream\n * patterns can match on resolved style.\n *\n * NodeMeta opacity barriers populated here: hasRef (`ref=`), hasEventHandlers (`on*=`),\n * hasKey (`key=`), hasSpreadAttrs (`{...x}`), hasDangerousHtml\n * (`dangerouslySetInnerHTML=`), hasDynamicChildren (any expression / spread child),\n * isComponent (capitalized / member tag). \"hasDynamicClasses\" is carried on the\n * {@link ClassList} itself (`hasDynamic` / `opaque`), not on NodeMeta.\n */\n\nimport { parse as babelParse } from '@babel/parser';\nimport type { NodePath } from '@babel/traverse';\nimport type {\n Expression,\n JSXAttribute,\n JSXElement,\n JSXEmptyExpression,\n JSXFragment,\n JSXOpeningElement,\n Node as BabelNode,\n} from '@babel/types';\n\nimport type {\n AttrMap,\n AttrValue,\n ClassList,\n ClassSegment,\n ClassToken,\n Diagnostic,\n ExprRef,\n FrontendParseContext,\n IRDocument,\n IRElement,\n IRFragment,\n IRNamespace,\n IRNodeId,\n MutableBackrefTable,\n NodeMeta,\n ParseResult,\n SourceFile,\n SourceSpan,\n StyleMap,\n} from '@domflax/core';\nimport {\n createDocument,\n createElement,\n createExpr,\n createFragment,\n createText,\n defaultMeta,\n emptyClassList,\n emptyStyleMap,\n} from '@domflax/core';\n\nimport type { ExprPayload } from './frontend-ast';\nimport {\n FILE_ID,\n attrName,\n classFormOf,\n exprKind,\n findNestedJsxRoots,\n isComponentName,\n jsxName,\n traverse,\n} from './frontend-ast';\n\nexport function doParse(code: string, ctx: FrontendParseContext): ParseResult {\n const diagnostics: Diagnostic[] = [];\n const doc: IRDocument = createDocument('jsx');\n const backref = doc.backref as MutableBackrefTable;\n\n const ast = babelParse(code, {\n sourceType: 'module',\n plugins: ['jsx', 'typescript'],\n });\n\n const eol: '\\n' | '\\r\\n' = code.includes('\\r\\n') ? '\\r\\n' : '\\n';\n const sourceFile: SourceFile = {\n id: FILE_ID,\n path: ctx.id,\n text: code,\n frontend: 'jsx',\n eol,\n indentUnit: ' ',\n native: ast,\n };\n doc.sources.set(FILE_ID, sourceFile);\n\n /* ----- span helpers (close over `code`) ----- */\n\n const spanOf = (node: BabelNode): SourceSpan | null => {\n if (node.start == null || node.end == null) return null;\n const span: SourceSpan = {\n file: FILE_ID,\n start: node.start,\n end: node.end,\n startLoc: node.loc\n ? { line: node.loc.start.line, column: node.loc.start.column }\n : undefined,\n endLoc: node.loc ? { line: node.loc.end.line, column: node.loc.end.column } : undefined,\n };\n return span;\n };\n\n const sliceOf = (node: BabelNode): string =>\n node.start == null || node.end == null ? '' : code.slice(node.start, node.end);\n\n /** Intern an expression as an opaque ExprRef, recording its verbatim source slice. */\n const internExpr = (node: Expression | JSXEmptyExpression, spread: boolean): ExprRef => {\n const payload: ExprPayload = { text: sliceOf(node), spread };\n return doc.exprs.intern({\n span: spanOf(node) ?? { file: FILE_ID, start: 0, end: 0 },\n kind: exprKind(node),\n payload,\n });\n };\n\n /* ----- class list ----- */\n\n const splitTokens = (raw: string): ClassToken[] =>\n raw\n .split(/\\s+/)\n .filter((t) => t.length > 0)\n .map((value) => ({ value }) as ClassToken);\n\n const buildClassList = (attr: JSXAttribute): ClassList => {\n const attrSpan = spanOf(attr) ?? undefined;\n const v = attr.value;\n\n const staticList = (tokens: ClassToken[], valueSpan: SourceSpan | null): ClassList => {\n const seg: ClassSegment = { kind: 'static', span: valueSpan ?? undefined, tokens };\n return {\n form: 'string-literal',\n segments: [seg],\n valueSpan,\n attrSpan,\n hasDynamic: false,\n opaque: false,\n rewritable: true,\n };\n };\n\n if (v == null) return staticList([], null);\n\n if (v.type === 'StringLiteral') {\n return staticList(splitTokens(v.value), spanOf(v));\n }\n\n if (v.type === 'JSXExpressionContainer') {\n const expr = v.expression;\n // `className={\"a b\"}` is still a static string literal.\n if (expr.type === 'StringLiteral') {\n return staticList(splitTokens(expr.value), spanOf(expr));\n }\n if (expr.type === 'JSXEmptyExpression') return staticList([], null);\n const ref = internExpr(expr, false);\n const valueSpan = spanOf(expr);\n const seg: ClassSegment = { kind: 'dynamic', span: valueSpan ?? undefined, expr: ref };\n return {\n form: classFormOf(expr),\n segments: [seg],\n valueSpan,\n attrSpan,\n hasDynamic: true,\n opaque: true,\n rewritable: false,\n };\n }\n\n return emptyClassList();\n };\n\n const staticTokensOf = (classes: ClassList): string[] => {\n const out: string[] = [];\n for (const seg of classes.segments) {\n if (seg.kind === 'static') for (const t of seg.tokens) out.push(t.value);\n }\n return out;\n };\n\n /* ----- attribute value ----- */\n\n const buildAttrValue = (attr: JSXAttribute): AttrValue => {\n const v = attr.value;\n if (v == null) return { kind: 'static', value: true, span: spanOf(attr) ?? undefined };\n if (v.type === 'StringLiteral') {\n return { kind: 'static', value: v.value, span: spanOf(v) ?? undefined };\n }\n if (v.type === 'JSXExpressionContainer') {\n if (v.expression.type === 'JSXEmptyExpression') {\n return { kind: 'static', value: true, span: spanOf(v) ?? undefined };\n }\n return { kind: 'dynamic', expr: internExpr(v.expression, false), span: spanOf(v) ?? undefined };\n }\n // JSXElement / JSXFragment used as an attribute value → opaque expression.\n return { kind: 'dynamic', expr: internExpr(v as Expression, false), span: spanOf(v) ?? undefined };\n };\n\n /* ----- node builders ----- */\n\n const buildNestedRoot = (jsx: JSXElement | JSXFragment, parentId: IRNodeId): IRNodeId =>\n jsx.type === 'JSXFragment' ? buildFragment(jsx, parentId) : buildElement(jsx, parentId);\n\n /** Lower a single JSX child, appending the resulting IR node id(s) onto `out`. */\n const appendChild = (\n node: JSXElement['children'][number],\n parentId: IRNodeId,\n out: IRNodeId[],\n ): void => {\n switch (node.type) {\n case 'JSXText': {\n const id = doc.alloc.next();\n doc.nodes.set(\n id,\n createText(id, node.value, {\n parent: parentId,\n span: spanOf(node),\n collapsible: /^\\s*$/.test(node.value),\n }),\n );\n out.push(id);\n return;\n }\n case 'JSXExpressionContainer': {\n const expr = node.expression;\n if (expr.type === 'JSXEmptyExpression') return; // `{/* comment */}`\n // A container whose WHOLE expression is a JSX node (`{<X/>}`) renders that node directly —\n // lower it as a real element so passes can optimize it (no opaque wrapper needed).\n if (expr.type === 'JSXElement' || expr.type === 'JSXFragment') {\n out.push(buildNestedRoot(expr, parentId));\n return;\n }\n // Otherwise the expression itself stays OPAQUE — the `.map`/condition/`{expr}` hole is\n // interned and preserved verbatim by the backend …\n const id = doc.alloc.next();\n const ref = internExpr(expr, false);\n doc.nodes.set(id, createExpr(id, ref, { parent: parentId, span: spanOf(node) }));\n out.push(id);\n // … but any JSX nested INSIDE it (map/filter callbacks, `&&`/`||`, ternary, parens) is\n // lowered to real element nodes (with their true source spans) so the pass manager descends\n // into and optimizes them too.\n for (const jsx of findNestedJsxRoots(expr)) out.push(buildNestedRoot(jsx, parentId));\n return;\n }\n case 'JSXSpreadChild': {\n const id = doc.alloc.next();\n const ref = internExpr(node.expression, true);\n doc.nodes.set(id, createExpr(id, ref, { parent: parentId, span: spanOf(node) }));\n out.push(id);\n for (const jsx of findNestedJsxRoots(node.expression)) {\n out.push(buildNestedRoot(jsx, parentId));\n }\n return;\n }\n case 'JSXElement':\n out.push(buildElement(node, parentId));\n return;\n case 'JSXFragment':\n out.push(buildFragment(node, parentId));\n return;\n default:\n return;\n }\n };\n\n const buildFragment = (node: JSXFragment, parentId: IRNodeId): IRNodeId => {\n const id = doc.alloc.next();\n const children: IRNodeId[] = [];\n for (const c of node.children) appendChild(c, id, children);\n doc.nodes.set(id, createFragment(id, { children, parent: parentId, span: spanOf(node) }));\n backref.set(id, {\n nodeId: id,\n span: spanOf(node) ?? { file: FILE_ID, start: 0, end: 0 },\n openTagSpan: spanOf(node.openingFragment),\n closeTagSpan: spanOf(node.closingFragment),\n innerSpan: null,\n selfClosing: false,\n });\n return id;\n };\n\n const buildElement = (node: JSXElement, parentId: IRNodeId): IRNodeId => {\n const id = doc.alloc.next();\n const opening: JSXOpeningElement = node.openingElement;\n const tag = jsxName(opening.name);\n const component = isComponentName(opening.name);\n\n const meta: NodeMeta = defaultMeta();\n meta.isComponent = component;\n\n let classes: ClassList = emptyClassList();\n const entries = new Map<string, AttrValue>();\n const order: string[] = [];\n const spreads: ExprRef[] = [];\n\n for (const attr of opening.attributes) {\n if (attr.type === 'JSXSpreadAttribute') {\n spreads.push(internExpr(attr.argument, true));\n meta.hasSpreadAttrs = true;\n continue;\n }\n const name = attrName(attr.name);\n if (name === 'className' || name === 'class') {\n classes = buildClassList(attr);\n continue;\n }\n if (name === 'ref') meta.hasRef = true;\n else if (name === 'key') meta.hasKey = true;\n else if (name === 'dangerouslySetInnerHTML') meta.hasDangerousHtml = true;\n else if (/^on[A-Z]/.test(name)) meta.hasEventHandlers = true;\n entries.set(name, buildAttrValue(attr));\n order.push(name);\n }\n\n const attrs: AttrMap = { entries, spreads, order };\n\n const children: IRNodeId[] = [];\n for (const c of node.children) appendChild(c, id, children);\n for (const cid of children) {\n const cn = doc.nodes.get(cid);\n if (cn && cn.kind === 'expr') {\n meta.hasDynamicChildren = true;\n break;\n }\n }\n\n // Resolve static classes (+ tag) into computed style via the injected resolver/normalizer.\n let computed: StyleMap = emptyStyleMap();\n if (!classes.hasDynamic) {\n const tokens = staticTokensOf(classes);\n if (tokens.length > 0) {\n const res = ctx.resolver.resolve({\n classes: tokens,\n element: { tagName: tag, namespace: component ? undefined : 'html' },\n });\n computed = ctx.normalizer.normalizeStyleMap(res.styles);\n for (const w of res.warnings) {\n diagnostics.push({\n code: 'DF_STYLE_CONFLICT_UNRESOLVED',\n severity: w.severity,\n message: w.message,\n nodeId: id,\n });\n }\n }\n }\n\n const namespace: IRNamespace = component ? 'component' : 'html';\n const el: IRElement = createElement(id, {\n tag,\n namespace,\n isComponent: component,\n selfClosing: opening.selfClosing,\n classes,\n computed,\n attrs,\n children,\n parent: parentId,\n span: spanOf(node),\n meta,\n });\n doc.nodes.set(id, el);\n\n const inner =\n children.length > 0\n ? spanOf(node.children[0]! as BabelNode) && spanOf(node.children.at(-1)! as BabelNode)\n ? {\n file: FILE_ID,\n start: spanOf(node.children[0]! as BabelNode)!.start,\n end: spanOf(node.children.at(-1)! as BabelNode)!.end,\n }\n : null\n : null;\n backref.set(id, {\n nodeId: id,\n span: spanOf(node) ?? { file: FILE_ID, start: 0, end: 0 },\n openTagSpan: spanOf(opening),\n closeTagSpan: node.closingElement ? spanOf(node.closingElement) : null,\n innerSpan: inner,\n selfClosing: opening.selfClosing,\n });\n return id;\n };\n\n /* ----- collect the outermost JSX islands and attach them to the root fragment ----- */\n\n const roots: (JSXElement | JSXFragment)[] = [];\n traverse(ast, {\n JSXElement(path: NodePath<JSXElement>) {\n roots.push(path.node);\n path.skip();\n },\n JSXFragment(path: NodePath<JSXFragment>) {\n roots.push(path.node);\n path.skip();\n },\n });\n\n const rootFrag = doc.nodes.get(doc.root) as IRFragment;\n for (const r of roots) {\n const id = r.type === 'JSXFragment' ? buildFragment(r, doc.root) : buildElement(r, doc.root);\n rootFrag.children.push(id);\n }\n\n return { doc, diagnostics };\n}\n","/**\n * @domflax/frontend-jsx — Babel JSX/TSX → IR frontend.\n *\n * Walks a Babel AST (`@babel/parser` → `@babel/traverse`) and lowers JSXElement /\n * JSXFragment / JSXText / JSXExpressionContainer / JSXSpreadChild nodes into the\n * `@domflax/core` IR. ALL dynamic JavaScript stays out of the structural IR: every\n * expression container, spread, and dynamic className/child is interned into the\n * document's {@link ExprRegistry} as an opaque {@link ExprRef} (with its verbatim source\n * slice as payload), and only its source span survives in the tree.\n *\n * Static `class`/`className` literals are split into {@link ClassToken}s on a static\n * {@link ClassSegment}; a non-string-literal className becomes a single dynamic segment\n * (opaque, never optimized). Static classes are resolved through the supplied\n * {@link StyleResolver} + {@link StyleNormalizer} into `element.computed` so downstream\n * patterns can match on resolved style.\n *\n * NodeMeta opacity barriers populated here: hasRef (`ref=`), hasEventHandlers (`on*=`),\n * hasKey (`key=`), hasSpreadAttrs (`{...x}`), hasDangerousHtml\n * (`dangerouslySetInnerHTML=`), hasDynamicChildren (any expression / spread child),\n * isComponent (capitalized / member tag). \"hasDynamicClasses\" is carried on the\n * {@link ClassList} itself (`hasDynamic` / `opaque`), not on NodeMeta.\n *\n * The pure AST/classification helpers live in `./frontend-ast`; the parse pass itself\n * lives in `./frontend-parse`. This module is the public assembly point.\n */\n\nimport type { Frontend, FrontendParseContext, ParseResult } from '@domflax/core';\n\nimport { JSX_LANGS, looksLikeJsx } from './frontend-ast';\nimport { doParse } from './frontend-parse';\n\nexport const jsxFrontend: Frontend = {\n name: 'babel-jsx',\n langs: JSX_LANGS,\n canParse(id: string, code: string): boolean {\n return looksLikeJsx(id, code);\n },\n parse(code: string, ctx: FrontendParseContext): ParseResult {\n return doParse(code, ctx);\n },\n};\n\n/** Factory mirror — returns a fresh handle to the (stateless) JSX frontend. */\nexport function createJsxFrontend(): Frontend {\n return jsxFrontend;\n}\n","/**\n * @domflax/frontend-jsx — IR → JSX/TSX backend (SURGICAL, full-module round-trip).\n *\n * The pass manager mutates a tree of JSX *islands* that were lowered from a complete module\n * (imports, `export default function`, hooks, `return (…)`, `{expr}` holes, comments, …). The\n * backend's job is to emit a COMPLETE, valid module — not just the JSX subtree. It does this by\n * starting from the element's ORIGINAL verbatim source (retained on {@link SourceFile.text}) and\n * applying ONLY the diffs the passes produced, via `magic-string`:\n *\n * • CLASS CHANGE — for every surviving element whose static class list differs from its source\n * text, overwrite just the `class`/`className` attribute VALUE span (quotes included) with the\n * new tokens. If the element gained classes but had no class attribute, insert one on the\n * opening tag.\n * • UNWRAP (flatten) — when a wrapper element/fragment was removed but its children survived,\n * delete ONLY the wrapper's open- and close-tag spans; the children (and their entire subtrees,\n * including dynamic `{expr}` holes and `key=`) are preserved verbatim.\n * • FULL REMOVAL — when a node was removed with no surviving descendant, delete its whole span.\n *\n * Every other byte — imports, exports, function declarations, returns, hooks, `{expr}` holes,\n * whitespace, comments, attribute ordering — is left exactly as authored. Output is\n * `magicString.toString()`: a complete module.\n *\n * Fallback: a document with no retained source (e.g. a hand-synthesized IR) cannot be spliced, so\n * it falls back to a clean structural re-print ({@link rePrint}).\n */\n\nimport MagicString from 'magic-string';\n\nimport type {\n AttrValue,\n Backend,\n BackendContext,\n Backref,\n ClassList,\n CodegenResult,\n EditPlan,\n ExprRef,\n FileKind,\n IRDocument,\n IRElement,\n IRNode,\n IRNodeId,\n SourceFile,\n SourceSpan,\n} from '@domflax/core';\n\nconst JSX_LANGS: readonly FileKind[] = ['jsx', 'tsx'];\n\ninterface ExprPayload {\n readonly text: string;\n readonly spread: boolean;\n}\n\n/* ───────────────────────── shared expr/class helpers ───────────────────────── */\n\n/** Recover an interned expression's source text (payload first, span-slice fallback). */\nfunction exprText(doc: IRDocument, ref: ExprRef): ExprPayload {\n const rec = doc.exprs.get(ref);\n const payload = rec?.payload as Partial<ExprPayload> | undefined;\n if (payload && typeof payload.text === 'string') {\n return { text: payload.text, spread: payload.spread === true };\n }\n if (rec) {\n const sf = doc.sources.get(rec.span.file);\n if (sf) return { text: sf.text.slice(rec.span.start, rec.span.end), spread: false };\n }\n return { text: '', spread: false };\n}\n\n/** All static class tokens of a {@link ClassList}, in order. */\nfunction staticTokensOf(classes: ClassList): string[] {\n const out: string[] = [];\n for (const seg of classes.segments) {\n if (seg.kind === 'static') for (const t of seg.tokens) out.push(t.value);\n }\n return out;\n}\n\n/* ───────────────────────── surgical (magic-string) codegen ───────────────────────── */\n\n/** Pick the single retained source file this document was parsed from (if any). */\nfunction primarySource(doc: IRDocument): SourceFile | null {\n for (const sf of doc.sources.values()) {\n if (typeof sf.text === 'string' && sf.text.length > 0) return sf;\n }\n return null;\n}\n\n/** Collect every node reachable from the root of the (mutated) tree. */\nfunction collectKept(doc: IRDocument): IRNode[] {\n const out: IRNode[] = [];\n const seen = new Set<IRNodeId>();\n const visit = (id: IRNodeId): void => {\n if (seen.has(id)) return;\n seen.add(id);\n const n = doc.nodes.get(id);\n if (!n) return;\n out.push(n);\n if (n.kind === 'element' || n.kind === 'fragment') for (const c of n.children) visit(c);\n };\n visit(doc.root);\n return out;\n}\n\n/** Span `a` strictly contains span `b` (same file, b nested inside, not identical). */\nfunction strictlyContains(a: SourceSpan, b: SourceSpan): boolean {\n if (a.file !== b.file) return false;\n if (a.start <= b.start && b.end <= a.end) return !(a.start === b.start && a.end === b.end);\n return false;\n}\n\ninterface RemovedRegion {\n readonly backref: Backref;\n /** A surviving node nested inside this region ⇒ this was an UNWRAP (keep inner, drop tags). */\n readonly unwrapped: boolean;\n}\n\n/**\n * Apply the class-list diff for a single surviving element. Returns true if an edit was made.\n */\nfunction editClasses(ms: MagicString, doc: IRDocument, sf: SourceFile, el: IRElement): boolean {\n const classes = el.classes;\n // Wholly dynamic / opaque class lists are never rewritten by the passes — leave verbatim.\n if (classes.hasDynamic || classes.opaque) return false;\n\n const tokens = staticTokensOf(classes);\n const valueSpan = classes.valueSpan;\n\n if (valueSpan && valueSpan.file === sf.id) {\n const current = sf.text.slice(valueSpan.start, valueSpan.end);\n // Preserve the original quote style; default to double quotes when we can't detect one.\n const quote = current.startsWith(\"'\") ? \"'\" : '\"';\n const next = `${quote}${tokens.join(' ')}${quote}`;\n if (current !== next) {\n ms.overwrite(valueSpan.start, valueSpan.end, next);\n return true;\n }\n return false;\n }\n\n // No class attribute originally, but the passes added classes ⇒ insert one on the opening tag.\n if (tokens.length === 0) return false;\n if (el.isComponent) return false; // never synthesize className onto an opaque component\n const back = doc.backref.get(el.id);\n const openTag = back?.openTagSpan;\n if (!openTag || openTag.file !== sf.id) return false;\n // Insert immediately after the tag name: `<tag‸ …`.\n const insertAt = openTag.start + 1 + el.tag.length;\n ms.appendLeft(insertAt, ` className=\"${tokens.join(' ')}\"`);\n return true;\n}\n\n/**\n * Extract a `key=…` attribute (verbatim, e.g. `key={f.id}` or `key=\"row\"`) from an opening-tag's\n * source text, or null when the tag carries no key. Brace/quote-aware so `key={f.id}` with nested\n * braces is captured whole. Requires whitespace before `key` so `data-key=` / `aria-keyshortcuts=`\n * never false-match.\n */\nfunction extractKeyAttr(openTag: string): string | null {\n const m = /(^|\\s)key\\s*=\\s*/.exec(openTag);\n if (!m) return null;\n const keyStart = m.index + m[1].length;\n let i = m.index + m[0].length;\n const ch = openTag[i];\n if (ch === '{') {\n let depth = 0;\n for (; i < openTag.length; i += 1) {\n const c = openTag[i];\n if (c === '{') depth += 1;\n else if (c === '}') {\n depth -= 1;\n if (depth === 0) {\n i += 1;\n break;\n }\n }\n }\n } else if (ch === '\"' || ch === \"'\") {\n const q = ch;\n i += 1;\n for (; i < openTag.length; i += 1) {\n if (openTag[i] === q) {\n i += 1;\n break;\n }\n }\n } else {\n for (; i < openTag.length; i += 1) {\n if (/[\\s>/]/.test(openTag[i]!)) break;\n }\n }\n return openTag.slice(keyStart, i);\n}\n\n/**\n * KEY SAFETY: when an UNWRAPPED wrapper carried a React `key`, that key must not vanish with the\n * deleted tags. If the wrapper had exactly one surviving (maximal) element child and that child has\n * no key of its own, transfer the wrapper's `key=…` verbatim onto the survivor's opening tag.\n * Conservative: anything ambiguous (no surviving element child, multiple survivors, child already\n * keyed) is left untouched (the flatten pattern is expected to have refused such a case).\n */\nfunction transferKeyOnUnwrap(\n ms: MagicString,\n doc: IRDocument,\n sf: SourceFile,\n region: Backref,\n kept: readonly IRNode[],\n): void {\n const open = region.openTagSpan;\n if (!open || open.file !== sf.id) return;\n const keyAttr = extractKeyAttr(sf.text.slice(open.start, open.end));\n if (!keyAttr) return;\n\n const inside: IRElement[] = [];\n for (const n of kept) {\n if (n.kind !== 'element' || !n.span || n.span.file !== sf.id) continue;\n if (strictlyContains(region.span, n.span)) inside.push(n);\n }\n // Keep only the topmost survivors (not nested inside another survivor of this region).\n const maximal = inside.filter(\n (n) => !inside.some((o) => o !== n && o.span && n.span && strictlyContains(o.span, n.span)),\n );\n if (maximal.length !== 1) return;\n\n const child = maximal[0]!;\n const childOpen = doc.backref.get(child.id)?.openTagSpan;\n if (!childOpen || childOpen.file !== sf.id) return;\n if (extractKeyAttr(sf.text.slice(childOpen.start, childOpen.end))) return; // already keyed\n\n // Insert immediately after the child's tag name: `<tag‸ …`.\n ms.appendLeft(childOpen.start + 1 + child.tag.length, ` ${keyAttr}`);\n}\n\n/** Surgical full-module codegen. Returns null when the document has no retained source. */\nfunction surgicalPrint(doc: IRDocument): string | null {\n const sf = primarySource(doc);\n if (!sf) return null;\n\n const ms = new MagicString(sf.text);\n\n const kept = collectKept(doc);\n const keptSpans: SourceSpan[] = [];\n for (const n of kept) if (n.span && n.span.file === sf.id) keptSpans.push(n.span);\n\n // 1) Structural removals. A node present in the backref table but absent from the live node map\n // was removed by the passes. Classify each as an UNWRAP (a surviving node nests inside it) or\n // a FULL removal (nothing survived inside).\n const removed: RemovedRegion[] = [];\n for (const id of backrefIds(doc)) {\n if (doc.nodes.has(id)) continue; // still live\n const back = doc.backref.get(id);\n if (!back || back.span.file !== sf.id) continue;\n const unwrapped = keptSpans.some((k) => strictlyContains(back.span, k));\n removed.push({ backref: back, unwrapped });\n }\n\n // Skip any removed region nested inside a FULL-removal region (its bytes are already deleted by\n // the ancestor) — this keeps every delete disjoint, which magic-string requires.\n const fullRemovals = removed.filter((r) => !r.unwrapped).map((r) => r.backref.span);\n for (const r of removed) {\n const span = r.backref.span;\n const coveredByFull = fullRemovals.some((f) => f !== span && strictlyContains(f, span));\n if (coveredByFull) continue;\n\n if (r.unwrapped) {\n // KEY SAFETY: salvage a `key=…` off the wrapper onto its surviving child before deleting tags.\n transferKeyOnUnwrap(ms, doc, sf, r.backref, kept);\n // Delete only the wrapper's tags; keep its (surviving) inner content verbatim.\n const open = r.backref.openTagSpan;\n const close = r.backref.closeTagSpan;\n if (open && open.file === sf.id && open.end > open.start) ms.remove(open.start, open.end);\n if (close && close.file === sf.id && close.end > close.start) {\n ms.remove(close.start, close.end);\n }\n } else {\n ms.remove(span.start, span.end);\n }\n }\n\n // 2) Class-list diffs on every surviving element.\n for (const n of kept) {\n if (n.kind === 'element') editClasses(ms, doc, sf, n);\n }\n\n return ms.toString();\n}\n\n/** All ids the backref table knows about (every originally-parsed element / fragment). */\nfunction backrefIds(doc: IRDocument): IRNodeId[] {\n // The backref table is shared verbatim from parse time; collect ids by scanning original spans we\n // recorded for live + removed nodes. We don't have a public iterator, so reconstruct the universe\n // from the live nodes plus their (now-removed) original ancestry isn't possible directly — instead\n // ask the table for each id we can reach. The table exposes `get`; the set of candidate ids is the\n // contiguous allocation range [1, alloc.peek). Scanning that range is O(n) and dependency-free.\n const out: IRNodeId[] = [];\n const max = doc.alloc.peek as unknown as number;\n for (let i = 1; i < max; i += 1) {\n const id = i as IRNodeId;\n if (doc.backref.get(id)) out.push(id);\n }\n return out;\n}\n\n/* ───────────────────────── structural re-print (fallback) ───────────────────────── */\n\n/** Re-build the `className=…` attribute (or null when the element has no class list). */\nfunction classText(doc: IRDocument, classes: ClassList): string | null {\n if (classes.form === 'absent' || classes.segments.length === 0) return null;\n\n const dynamic = classes.segments.find((s) => s.kind === 'dynamic');\n if (dynamic && dynamic.kind === 'dynamic') {\n return `className={${exprText(doc, dynamic.expr).text}}`;\n }\n\n const tokens = staticTokensOf(classes);\n return `className=\"${tokens.join(' ')}\"`;\n}\n\nfunction attrText(doc: IRDocument, name: string, value: AttrValue): string {\n if (value.kind === 'static') {\n if (value.value === true) return name;\n if (value.value === false) return '';\n return `${name}=\"${String(value.value)}\"`;\n }\n return `${name}={${exprText(doc, value.expr).text}}`;\n}\n\nfunction printElement(doc: IRDocument, el: IRElement): string {\n const parts: string[] = [];\n\n const cls = classText(doc, el.classes);\n if (cls !== null) parts.push(cls);\n\n for (const name of el.attrs.order) {\n const v = el.attrs.entries.get(name);\n if (!v) continue;\n const text = attrText(doc, name, v);\n if (text.length > 0) parts.push(text);\n }\n\n for (const ref of el.attrs.spreads) parts.push(`{...${exprText(doc, ref).text}}`);\n\n const attrStr = parts.length > 0 ? ` ${parts.join(' ')}` : '';\n const tag = el.tag;\n\n if (el.children.length === 0) {\n return el.selfClosing ? `<${tag}${attrStr} />` : `<${tag}${attrStr}></${tag}>`;\n }\n\n const inner = el.children.map((c) => printNode(doc, c)).join('');\n return `<${tag}${attrStr}>${inner}</${tag}>`;\n}\n\nfunction printNode(doc: IRDocument, id: IRNodeId): string {\n const node = doc.nodes.get(id);\n if (!node) return '';\n switch (node.kind) {\n case 'text':\n return node.value;\n case 'comment':\n return `{/*${node.value}*/}`;\n case 'expr': {\n const { text, spread } = exprText(doc, node.expr);\n return spread ? `{...${text}}` : `{${text}}`;\n }\n case 'fragment':\n return `<>${node.children.map((c) => printNode(doc, c)).join('')}</>`;\n case 'element':\n return printElement(doc, node);\n }\n}\n\nfunction rePrint(doc: IRDocument): string {\n const root = doc.nodes.get(doc.root);\n if (!root || root.kind !== 'fragment') return printNode(doc, doc.root);\n return root.children.map((c) => printNode(doc, c)).join('');\n}\n\n/* ───────────────────────── public backend ───────────────────────── */\n\nfunction doPrint(doc: IRDocument): string {\n const surgical = surgicalPrint(doc);\n return surgical ?? rePrint(doc);\n}\n\nexport const jsxBackend: Backend = {\n name: 'babel-jsx',\n langs: JSX_LANGS,\n print(doc: IRDocument, _plan: EditPlan, _ctx: BackendContext): CodegenResult {\n const code = doPrint(doc);\n return { code, map: null, edits: [], diagnostics: [] };\n },\n};\n\n/** Factory mirror — returns a fresh handle to the (stateless) JSX backend. */\nexport function createJsxBackend(): Backend {\n return jsxBackend;\n}\n","/**\n * domflax — the single-file JSX/TSX pipeline runner (parse → resolve → flatten → reverse-emit →\n * print), split out of `index.ts` so the meta package's barrel + adapters stay focused.\n *\n * {@link runJsxPipeline} is SYNC and fully static (gate `'provably-safe'`): it never changes rendering\n * and never launches a browser.\n */\n\nimport {\n buildSelectorIndex,\n createSyntheticSink,\n runPasses,\n syncClassesFromComputed,\n} from '@domflax/core';\nimport type {\n ApplyContext,\n FileKind,\n FlattenGate,\n IRDocument,\n Pass,\n PassCategory,\n PassPhase,\n Pattern,\n SafetyLevel,\n StyleResolver,\n} from '@domflax/core';\nimport { createJsxBackend, createJsxFrontend } from '@domflax/frontend-jsx';\nimport { normalizer } from '@domflax/pattern-kit';\n\n/** `.tsx`/`.jsx` ⇒ the matching {@link FileKind}; anything else ⇒ null (no JSX frontend). */\nexport function jsxKindOf(id: string): FileKind | null {\n const clean = id.split('?', 1)[0] ?? id;\n if (clean.endsWith('.tsx')) return 'tsx';\n if (clean.endsWith('.jsx')) return 'jsx';\n return null;\n}\n\n/** First registered source's EOL, defaulting to `\\n`. */\nfunction eolOf(doc: IRDocument): '\\n' | '\\r\\n' {\n for (const src of doc.sources.values()) return src.eol;\n return '\\n';\n}\n\n/** Group the flat pattern list into one {@link Pass} per {@link PassPhase} (derived from category). */\nfunction buildPasses(patterns: readonly Pattern[]): Pass[] {\n const byPhase = new Map<PassPhase, Pattern[]>();\n for (const p of patterns) {\n const phase = (p.category.split('/', 1)[0] ?? 'flatten') as PassPhase;\n let bucket = byPhase.get(phase);\n if (!bucket) {\n bucket = [];\n byPhase.set(phase, bucket);\n }\n bucket.push(p);\n }\n const passes: Pass[] = [];\n for (const [phase, pats] of byPhase) {\n passes.push({ phase, category: `${phase}/builtin` as PassCategory, patterns: pats });\n }\n return passes;\n}\n\n/** The parsed, authorized doc + the apply context + grouped passes, shared by sync + async runs. */\ninterface PreparedRun {\n readonly doc: IRDocument;\n readonly ctx: ApplyContext;\n readonly passes: readonly Pass[];\n}\n\n/** PARSE (JSX → IR, resolving classes onto `computed`) + AUTHORIZE + build the apply context. */\nfunction preparePipeline(\n code: string,\n id: string,\n kind: FileKind,\n resolver: StyleResolver,\n patterns: readonly Pattern[],\n safety: SafetyLevel,\n gate: FlattenGate,\n): PreparedRun {\n const parsed = createJsxFrontend().parse(code, {\n id,\n kind,\n resolver,\n normalizer,\n config: {},\n onDiagnostic: () => {},\n });\n const doc = parsed.doc;\n\n // AUTHORIZE — the JSX frontend defaults every node's safety floor to 0. The orchestrator opens the\n // floor to the max; the configured ceiling + each pattern's opacity predicates are the real gate.\n for (const node of doc.nodes.values()) node.meta.safetyFloor = 3;\n\n const ctx: ApplyContext = {\n doc,\n safetyCeiling: safety,\n normalizer,\n // Real CSS-selector-safety index from the active resolver: a wrapper a combinator/structural\n // selector depends on is flagged so the flatten guards refuse to flatten it. Tailwind (no\n // complexSelectors) degrades to the null index — behaviour unchanged.\n selectors: buildSelectorIndex(doc, resolver),\n resolver,\n gate,\n };\n return { doc, ctx, passes: buildPasses(patterns) };\n}\n\n/** REVERSE-EMIT optimized computed styles back into class tokens, then PRINT IR → JSX/TSX text. */\nfunction finishPipeline(optimized: IRDocument, id: string, resolver: StyleResolver): string {\n syncClassesFromComputed(optimized, resolver, normalizer);\n const printed = createJsxBackend().print(\n optimized,\n { moduleId: id, ops: [], provenance: new Map() },\n {\n normalizer,\n resolver,\n sink: createSyntheticSink(),\n eol: eolOf(optimized),\n onDiagnostic: () => {},\n },\n );\n return printed.code;\n}\n\n/** SYNC full pipeline (gate `'provably-safe'` — never changes rendering, never launches a browser). */\nexport function runJsxPipeline(\n code: string,\n id: string,\n kind: FileKind,\n resolver: StyleResolver,\n patterns: readonly Pattern[],\n safety: SafetyLevel,\n): string {\n const { doc, ctx, passes } = preparePipeline(code, id, kind, resolver, patterns, safety, 'provably-safe');\n const { doc: optimized } = runPasses(doc, passes, ctx);\n return finishPipeline(optimized, id, resolver);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACKA,IAAM,mBA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M,IAAI,MAAM,YAAY,GAAG,UAAU,SAAS,MAAM;AACnF,aAAO,EAAE,MAAM,KAAK,KAAK,KAAK;AAAA,IAChC;AAAA,EACF;AACF;;;ApDnIA,IAAM,UAAU,oBAAI,IAAqB;AAEzC,SAAS,UAAU,SAAkC;AACnD,QAAM,MAAM,KAAK,UAAU,WAAW,CAAC,CAAC;AACxC,MAAI,SAAS,QAAQ,IAAI,GAAG;AAC5B,MAAI,CAAC,QAAQ;AACX,aAAS,cAAc,OAAO;AAC9B,YAAQ,IAAI,KAAK,MAAM;AAAA,EACzB;AACA,SAAO;AACT;AAMe,SAAR,cAA2D,QAAwB;AACxF,QAAM,UAAU,KAAK,aAAa,KAAK,CAAC;AACxC,QAAM,SAAS,UAAU,OAAO;AAChC,SAAO,OAAO,UAAU,QAAQ,KAAK,YAAY,EAAE;AACrD;","names":["childIds","isInherited","normalizer","normalizer","asElement","asEl","metaFlag","declaresCustomProperties","targetedByStructuralPseudo","DISPLAY","baseConditionStyleMap","outerMergeSafe","metaOf","hasSpreadAttrs","isComponentNode","hasOwnAttrs","targetedByStructuralPseudo","asEl","metaOf","establishesContext","hasSpreadAttrs","isComponentNode","hasOwnAttrs","targetedByStructuralPseudo","DISPLAY","computed","BASE_KEY","computed","computed","BASE_KEY","computed","computed","BASE_KEY","computed","BASE_KEY","computed","BASE_KEY","NON_COLLAPSIBLE_VALUES","computed","BASE_KEY","computed","BASE_KEY","withBaseDecls","computed","BASE_KEY","NON_COLLAPSIBLE_VALUES","computed","SIDE_SET","BASE_KEY","NON_COLLAPSIBLE_VALUES","computed","NON_COLLAPSIBLE_VALUES","computed","opaque","opaque","LEGACY_PSEUDO_ELEMENTS","import_node_module","path","moduleBase","path","LEGACY_PSEUDO_ELEMENTS","babelTraverse","babelParse","staticTokensOf","computed","path","JSX_LANGS","staticTokensOf","MagicString","eolOf"]}
1
+ {"version":3,"sources":["../src/webpack-loader.ts","../../../node_modules/tsup/assets/cjs_shims.js","../../core/src/builders.ts","../../core/src/ops/runtime.ts","../../core/src/ops/apply.ts","../../core/src/pass-context.ts","../../core/src/flatten-safety.ts","../../core/src/pass-manager.ts","../../core/src/pipeline.ts","../../core/src/reverse-emit.ts","../../core/src/compress-engine.ts","../../pattern-kit/src/normalize.ts","../../pattern-kit/src/combinators.ts","../../pattern-kit/src/define.ts","../../pattern-kit/src/pattern.ts","../../patterns/src/library/flex/flex-center-wrapper.pattern.ts","../../patterns/src/library/fragment/redundant-fragment.pattern.ts","../../patterns/src/library/grid/grid-center-wrapper.pattern.ts","../../patterns/src/library/wrapper/display-contents-wrapper.pattern.ts","../../patterns/src/library/wrapper/empty-style-div.pattern.ts","../../patterns/src/library/wrapper/inherited-only-wrapper.pattern.ts","../../patterns/src/library/wrapper/passthrough-wrapper.pattern.ts","../../patterns/src/library/wrapper/redundant-inline-wrapper.pattern.ts","../../patterns/src/_registry.generated.ts","../../resolver-tailwind/src/tailwind/fingerprint.ts","../../resolver-tailwind/src/tailwind/emit.ts","../../resolver-tailwind/src/tailwind/engine.ts","../../resolver-tailwind/src/tailwind/engine-v4.ts","../../resolver-tailwind/src/tailwind/v4-bridge.ts","../../resolver-tailwind/src/tailwind/v4-css.ts","../../resolver-tailwind/src/tailwind/selector.ts","../../resolver-tailwind/src/tailwind/extract.ts","../../resolver-tailwind/src/tailwind/serialize.ts","../../resolver-tailwind/src/tailwind/stylemap.ts","../../resolver-tailwind/src/tailwind/usage.ts","../../resolver-tailwind/src/tailwind/resolver.ts","../../resolver-css/src/constants.ts","../../resolver-css/src/engine.ts","../../resolver-css/src/postcss-helpers.ts","../../resolver-css/src/misc-helpers.ts","../../resolver-css/src/selector-helpers.ts","../../resolver-css/src/resolver.ts","../src/index.ts","../../frontend-html/src/backend.ts","../../frontend-html/src/parse.ts","../../frontend-html/src/walk.ts","../../frontend-html/src/index.ts","../../frontend-jsx/src/frontend-ast.ts","../../frontend-jsx/src/frontend-parse.ts","../../frontend-jsx/src/frontend.ts","../../frontend-jsx/src/backend.ts","../src/pipeline-run.ts","../src/summary.ts"],"sourcesContent":["/**\n * domflax webpack loader.\n *\n * A genuine webpack loader module: webpack requires this file by absolute path (wired by the\n * `domflax.webpack()` plugin, see {@link ./index.webpack}) and invokes the default export once per\n * matched `.jsx`/`.tsx` module. It runs the SAME single-file engine as {@link createDomflax} — so the\n * heavy Tailwind/postcss engines stay LAZY (constructed on first transform, only for the selected\n * provider), exactly as in the Vite adapter and the programmatic API.\n *\n * The loader is intentionally synchronous (the transform is a pure CPU function with no source map\n * yet) and structurally typed against webpack: it depends only on a minimal local `LoaderContext`\n * shape, never on the `webpack` package itself.\n */\nimport { createDomflax } from './index';\nimport type { Domflax, DomflaxOptions } from './index';\nimport { accumulateOnCompilation } from './summary';\n\n/**\n * The slice of webpack's `LoaderContext` the domflax loader touches. Declared locally so this module\n * does not hard-depend on `webpack` types.\n */\nexport interface DomflaxLoaderContext {\n /** Absolute path of the module being transformed (no query suffix). */\n readonly resourcePath: string;\n /** Loader options passed via the `module.rule` `use[].options` entry. */\n getOptions?(): DomflaxOptions | undefined;\n /**\n * webpack's current `Compilation` (private-but-stable loader-context field). domflax stashes the\n * per-build stat accumulator here so the plugin's `done` hook — living in a separate bundle — can\n * read it back. Optional/duck-typed so the loader never hard-depends on webpack.\n */\n readonly _compilation?: unknown;\n}\n\n/**\n * Engine cache keyed by the serialized options, so a build reuses one configured engine (and its\n * one lazily-loaded resolver) across every transformed file instead of rebuilding per module.\n */\nconst engines = new Map<string, Domflax>();\n\nfunction engineFor(options: DomflaxOptions): Domflax {\n const key = JSON.stringify(options ?? {});\n let engine = engines.get(key);\n if (!engine) {\n engine = createDomflax(options);\n engines.set(key, engine);\n }\n return engine;\n}\n\n/**\n * webpack loader entry point. Returns the (possibly rewritten) source; non-jsx/tsx or unchanged\n * modules round-trip through {@link Domflax.transform} unchanged.\n */\nexport default function domflaxLoader(this: DomflaxLoaderContext, source: string): string {\n const options = this.getOptions?.() ?? {};\n const engine = engineFor(options);\n const out = engine.transform(source, this.resourcePath);\n // Bridge to the plugin: stash this file's delta on the webpack compilation for the `done` hook.\n accumulateOnCompilation(this._compilation, out.stats, out.code !== source);\n return out.code;\n}\n","// Shim globals in cjs bundle\n// There's a weird bug that esbuild will always inject importMetaUrl\n// if we export it as `const importMetaUrl = ... __filename ...`\n// But using a function will not cause this issue\n\nconst getImportMetaUrl = () => \n typeof document === \"undefined\" \n ? new URL(`file:${__filename}`).href \n : (document.currentScript && document.currentScript.tagName.toUpperCase() === 'SCRIPT') \n ? document.currentScript.src \n : new URL(\"main.js\", document.baseURI).href;\n\nexport const importMetaUrl = /* @__PURE__ */ getImportMetaUrl()\n","/**\n * @domflax/core — runtime builders + traversal.\n *\n * Pure, dependency-free helpers to construct IR nodes, assemble an {@link IRDocument},\n * and walk the tree honouring {@link VisitSignal}. No heavy third-party deps: only the\n * type contract in `./types`.\n */\n\nimport type {\n AttrMap,\n Backref,\n BackrefTable,\n ClassList,\n ConditionKey,\n CssProperty,\n ExprRecord,\n ExprRef,\n ExprRegistry,\n FrontendKind,\n IdAllocator,\n IRComment,\n IRDocument,\n IRElement,\n IRExpr,\n IRFragment,\n IRNamespace,\n IRNode,\n IRNodeId,\n IRText,\n InlineStyle,\n NodeMeta,\n SafetyLevel,\n SourceSpan,\n StyleBlock,\n StyleCondition,\n StyleMap,\n Visitor,\n VisitContext,\n VisitSignal,\n} from './types';\n\n/* ───────────────────────── id / registry primitives ───────────────────────── */\n\n/** Monotonic IRNodeId allocator. `peek` reports the id `next()` would return. */\nexport function createIdAllocator(start = 1): IdAllocator {\n let n = start;\n return {\n next(): IRNodeId {\n const id = n;\n n += 1;\n return id as IRNodeId;\n },\n get peek(): IRNodeId {\n return n as IRNodeId;\n },\n };\n}\n\n/** Minimal in-memory ExprRegistry. */\nexport function createExprRegistry(start = 1): ExprRegistry {\n const map = new Map<ExprRef, ExprRecord>();\n let n = start;\n return {\n get(r: ExprRef): ExprRecord | undefined {\n return map.get(r);\n },\n intern(rec: Omit<ExprRecord, 'ref'>): ExprRef {\n const ref = n as ExprRef;\n n += 1;\n map.set(ref, { ...rec, ref });\n return ref;\n },\n releasePayloads(): void {\n for (const [k, v] of map) map.set(k, { ...v, payload: undefined });\n },\n };\n}\n\n/** Mutable BackrefTable: frontends register backrefs as they parse. */\nexport interface MutableBackrefTable extends BackrefTable {\n set(id: IRNodeId, backref: Backref): void;\n}\n\nexport function createBackrefTable(): MutableBackrefTable {\n const map = new Map<IRNodeId, Backref>();\n return {\n get(id: IRNodeId): Backref | undefined {\n return map.get(id);\n },\n span(id: IRNodeId): SourceSpan | null {\n return map.get(id)?.span ?? null;\n },\n childrenSpan(id: IRNodeId): SourceSpan | null {\n return map.get(id)?.innerSpan ?? null;\n },\n set(id: IRNodeId, backref: Backref): void {\n map.set(id, backref);\n },\n };\n}\n\n/* ───────────────────────── default sub-structures ───────────────────────── */\n\n/** A NodeMeta with every barrier/flag cleared. */\nexport function defaultMeta(safetyFloor: SafetyLevel = 0): NodeMeta {\n return {\n hasRef: false,\n hasEventHandlers: false,\n hasKey: false,\n hasSpreadAttrs: false,\n hasDynamicChildren: false,\n isComponent: false,\n hasDangerousHtml: false,\n hasUnresolvedClasses: false,\n targetedByCombinator: false,\n targetedByStructuralPseudo: false,\n selectorDependents: 0,\n hasOwnVisualStyle: false,\n establishesBox: false,\n establishesStackingContext: false,\n isContainingBlock: false,\n establishesFormattingContext: false,\n declaresCustomProperties: false,\n whitespaceSensitive: false,\n touched: false,\n styleDirty: false,\n synthetic: false,\n safetyFloor,\n };\n}\n\n/** Canonical base style condition (`media:'' states:[] pseudoElement:''`). */\nexport const BASE_CONDITION: StyleCondition = { media: '', states: [], pseudoElement: '' };\n\n/** Stable serialization of a StyleCondition into a ConditionKey. */\nexport function conditionKey(c: StyleCondition): ConditionKey {\n const states = [...c.states].sort().join(',');\n return `${c.media}|${states}|${c.pseudoElement}` as ConditionKey;\n}\n\nexport const BASE_CONDITION_KEY: ConditionKey = conditionKey(BASE_CONDITION);\n\n/** An empty StyleMap (no blocks). */\nexport function emptyStyleMap(): StyleMap {\n return { blocks: new Map<ConditionKey, StyleBlock>() };\n}\n\n/** An empty (absent) ClassList. */\nexport function emptyClassList(): ClassList {\n return {\n form: 'absent',\n segments: [],\n valueSpan: null,\n hasDynamic: false,\n opaque: false,\n rewritable: false,\n };\n}\n\n/** An empty AttrMap. */\nexport function emptyAttrMap(): AttrMap {\n return { entries: new Map(), spreads: [], order: [] };\n}\n\n/** An empty InlineStyle. */\nexport function emptyInlineStyle(): InlineStyle {\n return { decls: new Map<CssProperty, never>() as InlineStyle['decls'], dynamic: null };\n}\n\n/* ───────────────────────── node factories ───────────────────────── */\n\nexport interface ElementInit {\n readonly tag: string;\n readonly namespace?: IRNamespace;\n readonly isComponent?: boolean;\n readonly selfClosing?: boolean;\n readonly classes?: ClassList;\n readonly inlineStyle?: InlineStyle;\n readonly computed?: StyleMap;\n readonly attrs?: AttrMap;\n readonly children?: IRNodeId[];\n readonly parent?: IRNodeId | null;\n readonly span?: SourceSpan | null;\n readonly meta?: NodeMeta;\n}\n\nexport function createElement(id: IRNodeId, init: ElementInit): IRElement {\n return {\n id,\n kind: 'element',\n parent: init.parent ?? null,\n span: init.span ?? null,\n meta: init.meta ?? defaultMeta(),\n tag: init.tag,\n namespace: init.namespace ?? 'html',\n isComponent: init.isComponent ?? false,\n selfClosing: init.selfClosing ?? false,\n classes: init.classes ?? emptyClassList(),\n inlineStyle: init.inlineStyle ?? emptyInlineStyle(),\n computed: init.computed ?? emptyStyleMap(),\n attrs: init.attrs ?? emptyAttrMap(),\n children: init.children ?? [],\n };\n}\n\nexport function createText(\n id: IRNodeId,\n value: string,\n opts?: { collapsible?: boolean; parent?: IRNodeId | null; span?: SourceSpan | null },\n): IRText {\n return {\n id,\n kind: 'text',\n parent: opts?.parent ?? null,\n span: opts?.span ?? null,\n meta: defaultMeta(),\n value,\n collapsible: opts?.collapsible ?? true,\n };\n}\n\nexport function createExpr(\n id: IRNodeId,\n expr: ExprRef,\n opts?: { parent?: IRNodeId | null; span?: SourceSpan | null },\n): IRExpr {\n return {\n id,\n kind: 'expr',\n parent: opts?.parent ?? null,\n span: opts?.span ?? null,\n meta: defaultMeta(),\n expr,\n };\n}\n\nexport function createFragment(\n id: IRNodeId,\n opts?: { children?: IRNodeId[]; parent?: IRNodeId | null; span?: SourceSpan | null },\n): IRFragment {\n return {\n id,\n kind: 'fragment',\n parent: opts?.parent ?? null,\n span: opts?.span ?? null,\n meta: defaultMeta(),\n children: opts?.children ?? [],\n };\n}\n\nexport function createComment(\n id: IRNodeId,\n value: string,\n opts?: { parent?: IRNodeId | null; span?: SourceSpan | null },\n): IRComment {\n return {\n id,\n kind: 'comment',\n parent: opts?.parent ?? null,\n span: opts?.span ?? null,\n meta: defaultMeta(),\n value,\n };\n}\n\n/** Build an empty document whose root is a fresh fragment. */\nexport function createDocument(frontend: FrontendKind): IRDocument {\n const alloc = createIdAllocator();\n const rootId = alloc.next();\n const root = createFragment(rootId);\n const nodes = new Map<IRNodeId, IRNode>([[rootId, root]]);\n return {\n root: rootId,\n nodes,\n exprs: createExprRegistry(),\n sources: new Map(),\n backref: createBackrefTable(),\n frontend,\n alloc,\n };\n}\n\n/* ───────────────────────── tree accessors ───────────────────────── */\n\n/** Returns the child id list for container nodes, or an empty array. */\nexport function childIds(node: IRNode): readonly IRNodeId[] {\n return node.kind === 'element' || node.kind === 'fragment' ? node.children : [];\n}\n\n/** Returns the node, or undefined. */\nexport function getNode(doc: IRDocument, id: IRNodeId): IRNode | undefined {\n return doc.nodes.get(id);\n}\n\n/** Returns the node iff it is an element. */\nexport function getElement(doc: IRDocument, id: IRNodeId): IRElement | undefined {\n const n = doc.nodes.get(id);\n return n && n.kind === 'element' ? n : undefined;\n}\n\n/** Pre-order list of every element id reachable from the root. */\nexport function elementIds(doc: IRDocument): IRNodeId[] {\n const out: IRNodeId[] = [];\n const visit = (id: IRNodeId): void => {\n const n = doc.nodes.get(id);\n if (!n) return;\n if (n.kind === 'element') out.push(id);\n for (const c of childIds(n)) visit(c);\n };\n visit(doc.root);\n return out;\n}\n\n/* ───────────────────────── traversal ───────────────────────── */\n\n/**\n * Depth-first pre/post-order walk. `enter` may return `'skip'` (don't descend) or `'stop'`\n * (abort the whole walk); `exit` may return `'stop'`. The visitor receives a live {@link IRNode}\n * plus a {@link VisitContext} exposing depth and the parent node.\n */\nexport function walk(doc: IRDocument, visitor: Visitor): void {\n const roDoc = doc as unknown as VisitContext['doc'];\n let stopped = false;\n\n const visit = (id: IRNodeId, depth: number): void => {\n if (stopped) return;\n const node = doc.nodes.get(id);\n if (!node) return;\n\n const ctx: VisitContext = {\n doc: roDoc,\n depth,\n parent(): IRNode | null {\n return node.parent == null ? null : doc.nodes.get(node.parent) ?? null;\n },\n };\n\n const entered: VisitSignal = visitor.enter ? visitor.enter(node, ctx) : undefined;\n if (entered === 'stop') {\n stopped = true;\n return;\n }\n if (entered !== 'skip') {\n for (const child of childIds(node)) {\n visit(child, depth + 1);\n if (stopped) return;\n }\n }\n\n const exited: VisitSignal = visitor.exit ? visitor.exit(node, ctx) : undefined;\n if (exited === 'stop') stopped = true;\n };\n\n visit(doc.root, 0);\n}\n","/**\n * @domflax/core — applier runtime helpers (shared by the per-op handlers in `./apply`).\n *\n * Pure, dependency-free building blocks for the trusted mutator: input-preserving cloning, the\n * mutable apply state, small tree helpers, detached-spec materialization, and style merging.\n * Only depends on the `../types` contract and `../builders` runtime helpers.\n */\n\nimport type {\n ApplyContext,\n ApplyResult,\n AttrMap,\n AttrValue,\n ConditionKey,\n CssProperty,\n Diagnostic,\n DiagnosticCode,\n ElementSpec,\n IRDocument,\n IRNode,\n IRNodeId,\n NodeSpec,\n RewriteOp,\n SkippedOpGroup,\n StyleBlock,\n StyleConflictPolicy,\n StyleDecl,\n StyleMap,\n} from '../types';\n\nimport {\n createComment,\n createElement,\n createExpr,\n createFragment,\n createText,\n defaultMeta,\n} from '../builders';\n\n/* ───────────────────────── result of an apply run ───────────────────────── */\n\nexport interface ApplyOutcome {\n /** The new document (the input doc is never mutated). */\n readonly doc: IRDocument;\n readonly result: ApplyResult;\n}\n\nexport interface MutState {\n readonly doc: IRDocument;\n readonly touched: Set<IRNodeId>;\n readonly removed: Set<IRNodeId>;\n readonly created: Set<IRNodeId>;\n readonly diagnostics: Diagnostic[];\n readonly skipped: SkippedOpGroup[];\n appliedGroups: number;\n readonly ceiling: number;\n readonly ctx: ApplyContext;\n}\n\n/* ───────────────────────── cloning (keep input pure) ───────────────────────── */\n\nexport function cloneStyleMap(sm: StyleMap): StyleMap {\n const blocks = new Map<ConditionKey, StyleBlock>();\n for (const [key, block] of sm.blocks) {\n blocks.set(key, {\n condition: block.condition,\n decls: new Map<CssProperty, StyleDecl>(block.decls),\n });\n }\n return { blocks };\n}\n\nfunction cloneNode(node: IRNode): IRNode {\n const meta = { ...node.meta };\n switch (node.kind) {\n case 'element':\n return {\n ...node,\n meta,\n children: [...node.children],\n computed: cloneStyleMap(node.computed),\n };\n case 'fragment':\n return { ...node, meta, children: [...node.children] };\n default:\n return { ...node, meta };\n }\n}\n\n/** Shallow-immutable clone: input doc and its node objects are never mutated. */\nexport function cloneDocument(doc: IRDocument): IRDocument {\n const nodes = new Map<IRNodeId, IRNode>();\n for (const [id, n] of doc.nodes) nodes.set(id, cloneNode(n));\n return {\n root: doc.root,\n nodes,\n exprs: doc.exprs,\n sources: doc.sources,\n backref: doc.backref,\n frontend: doc.frontend,\n alloc: doc.alloc,\n };\n}\n\n/* ───────────────────────── small helpers ───────────────────────── */\n\nexport function diag(\n code: DiagnosticCode,\n message: string,\n extra?: Partial<Diagnostic>,\n): Diagnostic {\n return { code, severity: 'warn', message, ...extra };\n}\n\nexport function getParentChildren(doc: IRDocument, id: IRNodeId): IRNodeId[] | null {\n const node = doc.nodes.get(id);\n if (!node || node.parent == null) return null;\n const parent = doc.nodes.get(node.parent);\n if (!parent) return null;\n if (parent.kind === 'element' || parent.kind === 'fragment') return parent.children;\n return null;\n}\n\nexport function indexInParent(doc: IRDocument, id: IRNodeId): number {\n const siblings = getParentChildren(doc, id);\n return siblings ? siblings.indexOf(id) : -1;\n}\n\nexport function markTouched(state: MutState, id: IRNodeId): void {\n const n = state.doc.nodes.get(id);\n if (n) {\n n.meta.touched = true;\n state.touched.add(id);\n }\n}\n\n/**\n * Mark a node whose OWN computed style a pass just rewrote (setClassList / mergeStyle onto it /\n * fold into it). Implies {@link markTouched}, and additionally raises `meta.styleDirty` — the signal\n * reverse-emit uses to re-derive class tokens. A purely structural bystander (a neighbour's unwrap /\n * merge / move) uses {@link markTouched} instead, so it is left byte-for-byte identical.\n */\nexport function markStyleDirty(state: MutState, id: IRNodeId): void {\n const n = state.doc.nodes.get(id);\n if (n) {\n n.meta.touched = true;\n n.meta.styleDirty = true;\n state.touched.add(id);\n }\n}\n\nexport function removeSubtree(state: MutState, id: IRNodeId): void {\n const node = state.doc.nodes.get(id);\n if (!node) return;\n if (node.kind === 'element' || node.kind === 'fragment') {\n for (const child of [...node.children]) removeSubtree(state, child);\n }\n state.doc.nodes.delete(id);\n state.removed.add(id);\n}\n\nexport function precond(op: RewriteOp, nodeId: IRNodeId, message: string): Diagnostic {\n return diag('DF_OP_PRECONDITION_FAILED', message, {\n nodeId,\n pattern: op.origin.pattern,\n severity: 'error',\n });\n}\n\nexport function primaryTarget(op: RewriteOp): IRNodeId | null {\n switch (op.op) {\n case 'removeNode':\n case 'unwrap':\n case 'replaceWith':\n case 'wrap':\n case 'moveNode':\n case 'setClassList':\n case 'mergeStyle':\n return op.target;\n case 'insertBefore':\n case 'insertAfter':\n return op.anchor;\n case 'mergeSiblings':\n return op.first;\n case 'foldInheritedStyles':\n return op.from;\n }\n}\n\n/* ───────────────────────── spec materialization ───────────────────────── */\n\nfunction specToAttrs(map: ReadonlyMap<string, string | boolean> | undefined): AttrMap {\n if (!map || map.size === 0) return { entries: new Map(), spreads: [], order: [] };\n const entries = new Map<string, AttrValue>();\n const order: string[] = [];\n for (const [k, v] of map) {\n entries.set(k, { kind: 'static', value: v });\n order.push(k);\n }\n return { entries, spreads: [], order };\n}\n\n/** Materialize a detached {@link NodeSpec} into live nodes; returns the new (or reused) id. */\nexport function materialize(state: MutState, spec: NodeSpec, parent: IRNodeId | null): IRNodeId {\n const { doc } = state;\n if (spec.kind === 'ref') {\n const existing = doc.nodes.get(spec.ref);\n if (existing) existing.parent = parent;\n return spec.ref;\n }\n\n const id = doc.alloc.next();\n state.created.add(id);\n switch (spec.kind) {\n case 'element': {\n const childIds: IRNodeId[] = [];\n const el = createElement(id, {\n tag: spec.tag,\n namespace: spec.namespace,\n selfClosing: spec.selfClosing,\n attrs: specToAttrs(spec.attrs),\n parent,\n meta: { ...defaultMeta(), synthetic: true },\n });\n if (spec.classes) el.computed = cloneStyleMap(spec.classes);\n doc.nodes.set(id, el);\n for (const child of spec.children ?? []) {\n childIds.push(materialize(state, child, id));\n }\n el.children = childIds;\n return id;\n }\n case 'text': {\n const t = createText(id, spec.value, { parent });\n t.meta.synthetic = true;\n doc.nodes.set(id, t);\n return id;\n }\n case 'expr': {\n const e = createExpr(id, spec.expr, { parent });\n e.meta.synthetic = true;\n doc.nodes.set(id, e);\n return id;\n }\n case 'comment': {\n const c = createComment(id, spec.value, { parent });\n c.meta.synthetic = true;\n doc.nodes.set(id, c);\n return id;\n }\n case 'fragment': {\n const frag = createFragment(id, { parent });\n frag.meta.synthetic = true;\n doc.nodes.set(id, frag);\n const childIds: IRNodeId[] = [];\n for (const child of spec.children) childIds.push(materialize(state, child, id));\n frag.children = childIds;\n return id;\n }\n }\n}\n\nexport function elementSpecToNode(\n state: MutState,\n spec: ElementSpec,\n parent: IRNodeId | null,\n): IRNodeId {\n return materialize(state, spec, parent);\n}\n\n/* ───────────────────────── style merging ───────────────────────── */\n\nexport function isInherited(state: MutState, decl: StyleDecl): boolean {\n if (decl.inherited) return true;\n const table = state.ctx.normalizer?.inherited;\n if (table) {\n try {\n return table.isInherited(decl.property);\n } catch {\n return decl.inherited;\n }\n }\n return decl.inherited;\n}\n\nexport interface MergeReport {\n readonly map: StyleMap;\n readonly conflict: boolean;\n}\n\n/** Merge `source` decls into `target`, condition-by-condition, per the conflict policy. */\nexport function mergeStyleMaps(\n target: StyleMap,\n source: StyleMap,\n policy: StyleConflictPolicy,\n): MergeReport {\n // Mutable working copy; returned (widened) as an immutable StyleMap.\n const blocks = new Map<ConditionKey, StyleBlock>(cloneStyleMap(target).blocks);\n let conflict = false;\n\n for (const [key, srcBlock] of source.blocks) {\n const existing = blocks.get(key);\n if (!existing) {\n blocks.set(key, {\n condition: srcBlock.condition,\n decls: new Map<CssProperty, StyleDecl>(srcBlock.decls),\n });\n continue;\n }\n const decls = new Map<CssProperty, StyleDecl>(existing.decls);\n for (const [prop, srcDecl] of srcBlock.decls) {\n const had = decls.get(prop);\n if (had && had.value !== srcDecl.value) {\n conflict = true;\n if (policy === 'target-wins') continue;\n // 'abort' is handled by the caller before commit; 'source-wins' falls through.\n }\n if (policy === 'target-wins' && had) continue;\n decls.set(prop, srcDecl);\n }\n blocks.set(key, { condition: existing.condition, decls });\n }\n return { map: { blocks }, conflict };\n}\n","/**\n * @domflax/core — the per-op handlers + public apply entry points.\n *\n * {@link applyOps} validates each {@link RewriteOp} against the safety ceiling / node-local floor\n * and commits it to a clone of the document; {@link applyGroups} commits whole {@link RewriteGroup}s\n * atomically. Rejected ops are collected into {@link ApplyResult.skipped} rather than throwing.\n */\n\nimport type {\n ApplyContext,\n ApplyResult,\n ConditionKey,\n CssProperty,\n Diagnostic,\n IRDocument,\n IRNodeId,\n RewriteGroup,\n RewriteOp,\n SkippedOpGroup,\n StyleBlock,\n StyleDecl,\n} from '../types';\n\nimport { BASE_CONDITION_KEY } from '../builders';\n\nimport {\n cloneDocument,\n cloneStyleMap,\n diag,\n elementSpecToNode,\n getParentChildren,\n isInherited,\n markStyleDirty,\n markTouched,\n materialize,\n mergeStyleMaps,\n precond,\n primaryTarget,\n removeSubtree,\n type ApplyOutcome,\n type MutState,\n} from './runtime';\n\nexport type { ApplyOutcome } from './runtime';\nexport { cloneDocument } from './runtime';\n\n/* ───────────────────────── per-op handlers ───────────────────────── */\n\nfunction safetyOk(state: MutState, op: RewriteOp, targetId: IRNodeId): Diagnostic | null {\n const opSafety = op.origin.safety;\n if (opSafety > state.ceiling) {\n return diag(\n 'DF_SAFETY_CEILING_EXCEEDED',\n `op '${op.op}' safety ${opSafety} exceeds ceiling ${state.ceiling}`,\n { nodeId: targetId, pattern: op.origin.pattern, severity: 'error' },\n );\n }\n const node = state.doc.nodes.get(targetId);\n if (node && opSafety > node.meta.safetyFloor) {\n return diag(\n 'DF_SAFETY_CEILING_EXCEEDED',\n `op '${op.op}' safety ${opSafety} exceeds node ${targetId} floor ${node.meta.safetyFloor}`,\n { nodeId: targetId, pattern: op.origin.pattern, severity: 'error' },\n );\n }\n return null;\n}\n\n/** Returns a list of validation issues; empty ⇒ the op was applied. */\nfunction applyOne(state: MutState, op: RewriteOp): Diagnostic[] {\n const { doc } = state;\n\n const primary = primaryTarget(op);\n if (primary != null) {\n if (!doc.nodes.get(primary)) {\n return [\n diag('DF_OP_PRECONDITION_FAILED', `target node ${primary} not found`, {\n nodeId: primary,\n pattern: op.origin.pattern,\n severity: 'error',\n }),\n ];\n }\n const safety = safetyOk(state, op, primary);\n if (safety) return [safety];\n }\n\n switch (op.op) {\n case 'removeNode': {\n const siblings = getParentChildren(doc, op.target);\n if (siblings) {\n const i = siblings.indexOf(op.target);\n if (i >= 0) siblings.splice(i, 1);\n }\n removeSubtree(state, op.target);\n return [];\n }\n\n case 'unwrap': {\n const node = doc.nodes.get(op.target);\n if (!node || (node.kind !== 'element' && node.kind !== 'fragment')) {\n return [precond(op, op.target, 'unwrap target is not a container')];\n }\n const siblings = getParentChildren(doc, op.target);\n if (!siblings) return [precond(op, op.target, 'unwrap target has no parent')];\n const at = siblings.indexOf(op.target);\n const kids = node.children;\n for (const k of kids) {\n const kn = doc.nodes.get(k);\n if (kn) kn.parent = node.parent;\n }\n siblings.splice(at, 1, ...kids);\n doc.nodes.delete(op.target);\n state.removed.add(op.target);\n if (node.parent != null) markTouched(state, node.parent);\n return [];\n }\n\n case 'replaceWith': {\n const siblings = getParentChildren(doc, op.target);\n if (!siblings) return [precond(op, op.target, 'replaceWith target has no parent')];\n const at = siblings.indexOf(op.target);\n const parentId = doc.nodes.get(op.target)?.parent ?? null;\n const newId = materialize(state, op.replacement, parentId);\n siblings.splice(at, 1, newId);\n removeSubtree(state, op.target);\n if (parentId != null) markTouched(state, parentId);\n return [];\n }\n\n case 'wrap': {\n const siblings = getParentChildren(doc, op.target);\n if (!siblings) return [precond(op, op.target, 'wrap target has no parent')];\n const at = siblings.indexOf(op.target);\n const parentId = doc.nodes.get(op.target)?.parent ?? null;\n const wrapperId = elementSpecToNode(state, op.wrapper, parentId);\n const wrapper = doc.nodes.get(wrapperId);\n const targetNode = doc.nodes.get(op.target);\n if (wrapper && (wrapper.kind === 'element' || wrapper.kind === 'fragment')) {\n wrapper.children.push(op.target);\n }\n if (targetNode) targetNode.parent = wrapperId;\n siblings.splice(at, 1, wrapperId);\n return [];\n }\n\n case 'insertBefore':\n case 'insertAfter': {\n const siblings = getParentChildren(doc, op.anchor);\n if (!siblings) return [precond(op, op.anchor, 'insert anchor has no parent')];\n const at = siblings.indexOf(op.anchor);\n const parentId = doc.nodes.get(op.anchor)?.parent ?? null;\n const newId = materialize(state, op.node, parentId);\n siblings.splice(op.op === 'insertBefore' ? at : at + 1, 0, newId);\n if (parentId != null) markTouched(state, parentId);\n return [];\n }\n\n case 'moveNode': {\n const newParent = doc.nodes.get(op.newParent);\n if (!newParent || (newParent.kind !== 'element' && newParent.kind !== 'fragment')) {\n return [precond(op, op.newParent, 'moveNode newParent is not a container')];\n }\n const siblings = getParentChildren(doc, op.target);\n if (siblings) {\n const i = siblings.indexOf(op.target);\n if (i >= 0) siblings.splice(i, 1);\n }\n const target = doc.nodes.get(op.target);\n if (target) target.parent = op.newParent;\n const idx = Math.max(0, Math.min(op.index, newParent.children.length));\n newParent.children.splice(idx, 0, op.target);\n markTouched(state, op.newParent);\n return [];\n }\n\n case 'mergeSiblings': {\n const first = doc.nodes.get(op.first);\n const second = doc.nodes.get(op.second);\n if (!first || !second) return [precond(op, op.first, 'mergeSiblings node missing')];\n if (\n (first.kind === 'element' || first.kind === 'fragment') &&\n (second.kind === 'element' || second.kind === 'fragment')\n ) {\n for (const c of second.children) {\n const cn = doc.nodes.get(c);\n if (cn) cn.parent = op.first;\n first.children.push(c);\n }\n second.children = [];\n }\n const siblings = getParentChildren(doc, op.second);\n if (siblings) {\n const i = siblings.indexOf(op.second);\n if (i >= 0) siblings.splice(i, 1);\n }\n doc.nodes.delete(op.second);\n state.removed.add(op.second);\n markTouched(state, op.first);\n return [];\n }\n\n case 'setClassList': {\n const el = doc.nodes.get(op.target);\n if (!el || el.kind !== 'element') {\n return [precond(op, op.target, 'setClassList target is not an element')];\n }\n el.computed = cloneStyleMap(op.style);\n markStyleDirty(state, op.target);\n return [];\n }\n\n case 'mergeStyle': {\n const el = doc.nodes.get(op.target);\n if (!el || el.kind !== 'element') {\n return [precond(op, op.target, 'mergeStyle target is not an element')];\n }\n const report = mergeStyleMaps(el.computed, op.style, op.onConflict);\n if (report.conflict && op.onConflict === 'abort') {\n return [\n diag('DF_STYLE_CONFLICT_UNRESOLVED', `mergeStyle aborted on conflict at ${op.target}`, {\n nodeId: op.target,\n pattern: op.origin.pattern,\n severity: 'error',\n }),\n ];\n }\n el.computed = report.map;\n if (op.source != null) {\n const src = doc.nodes.get(op.source);\n if (src) markTouched(state, op.source);\n }\n markStyleDirty(state, op.target);\n return [];\n }\n\n case 'foldInheritedStyles':\n return applyFold(state, op);\n }\n}\n\nfunction applyFold(\n state: MutState,\n op: Extract<RewriteOp, { op: 'foldInheritedStyles' }>,\n): Diagnostic[] {\n const { doc } = state;\n const from = doc.nodes.get(op.from);\n if (!from || from.kind !== 'element') {\n return [precond(op, op.from, 'fold source is not an element')];\n }\n const issues: Diagnostic[] = [];\n const onlyProps: ReadonlySet<CssProperty> | null =\n op.properties === 'all-inherited' ? null : new Set(op.properties);\n\n const conditionKeys =\n op.conditions === 'all'\n ? [...from.computed.blocks.keys()]\n : [BASE_CONDITION_KEY];\n\n for (const intoId of op.into) {\n const into = doc.nodes.get(intoId);\n if (!into || into.kind !== 'element') {\n issues.push(precond(op, intoId, 'fold target is not an element'));\n continue;\n }\n // Mutable working copy; assigned back (widened) as an immutable StyleMap.\n const nextBlocks = new Map<ConditionKey, StyleBlock>(cloneStyleMap(into.computed).blocks);\n let folded = false;\n\n for (const key of conditionKeys) {\n const srcBlock = from.computed.blocks.get(key);\n if (!srcBlock) continue;\n const dstBlock = nextBlocks.get(key);\n const decls = dstBlock\n ? new Map<CssProperty, StyleDecl>(dstBlock.decls)\n : new Map<CssProperty, StyleDecl>();\n\n for (const [prop, decl] of srcBlock.decls) {\n if (onlyProps && !onlyProps.has(prop)) continue;\n if (!isInherited(state, decl)) continue;\n if (decl.relativeToParent) {\n issues.push(\n diag(\n 'DF_RELATIVE_UNIT_FOLD',\n `refused to fold relative-unit declaration '${decl.property}' onto ${intoId}`,\n { nodeId: intoId, pattern: op.origin.pattern, severity: 'warn' },\n ),\n );\n continue;\n }\n if (!decls.has(prop)) {\n decls.set(prop, decl);\n folded = true;\n }\n }\n nextBlocks.set(key, { condition: srcBlock.condition, decls });\n }\n\n if (folded) {\n into.computed = { blocks: nextBlocks };\n markStyleDirty(state, intoId);\n }\n }\n // Non-blocking (DF_RELATIVE_UNIT_FOLD) diagnostics are recorded but do not skip the op.\n for (const d of issues) state.diagnostics.push(d);\n return [];\n}\n\n/* ───────────────────────── public entry points ───────────────────────── */\n\n/**\n * Apply a flat list of ops to a copy of `doc`. The input document is never mutated.\n * Each op is independently validated; failing ops are skipped (collected in\n * {@link ApplyResult.skipped}) instead of throwing.\n */\nexport function applyOps(\n doc: IRDocument,\n ops: readonly RewriteOp[],\n ctx?: Partial<ApplyContext>,\n): ApplyOutcome {\n const cloned = cloneDocument(doc);\n const state: MutState = {\n doc: cloned,\n touched: new Set(),\n removed: new Set(),\n created: new Set(),\n diagnostics: [],\n skipped: [],\n appliedGroups: 0,\n ceiling: ctx?.safetyCeiling ?? 3,\n ctx: { doc: cloned, safetyCeiling: ctx?.safetyCeiling ?? 3, ...ctx } as ApplyContext,\n };\n\n for (const op of ops) {\n const issues = applyOne(state, op);\n if (issues.length > 0) {\n state.skipped.push({\n group: { pattern: op.origin.pattern, anchor: primaryTarget(op) ?? doc.root, ops: [op] },\n issues: issues.map((d) => ({ op, code: d.code, message: d.message })),\n });\n for (const d of issues) state.diagnostics.push(d);\n } else {\n state.appliedGroups += 1;\n }\n }\n\n return { doc: cloned, result: finalize(state) };\n}\n\n/**\n * Apply pre-grouped ops (each {@link RewriteGroup} is committed atomically: if ANY op in the group\n * fails validation, the whole group is skipped and none of its ops mutate the tree).\n */\nexport function applyGroups(\n doc: IRDocument,\n groups: readonly RewriteGroup[],\n ctx?: Partial<ApplyContext>,\n): ApplyOutcome {\n // Group-atomicity is realized by working on a throwaway clone per group, then committing.\n let current = cloneDocument(doc);\n const touched = new Set<IRNodeId>();\n const removed = new Set<IRNodeId>();\n const created = new Set<IRNodeId>();\n const diagnostics: Diagnostic[] = [];\n const skipped: SkippedOpGroup[] = [];\n let appliedGroups = 0;\n\n for (const group of groups) {\n const attempt = applyOps(current, group.ops, ctx);\n if (attempt.result.skipped.length > 0) {\n skipped.push({\n group,\n issues: attempt.result.skipped.flatMap((s) => s.issues),\n });\n for (const s of attempt.result.skipped) for (const i of s.issues) {\n diagnostics.push(diag(i.code, i.message, { pattern: group.pattern }));\n }\n continue; // discard the attempt — group is atomic\n }\n current = attempt.doc;\n appliedGroups += 1;\n for (const id of attempt.result.touched) touched.add(id);\n for (const id of attempt.result.removed) removed.add(id);\n for (const id of attempt.result.created) created.add(id);\n for (const d of attempt.result.diagnostics) diagnostics.push(d);\n }\n\n const result: ApplyResult = {\n touched,\n removed,\n created,\n appliedGroups,\n skipped,\n journal: [],\n diagnostics,\n };\n return { doc: current, result };\n}\n\nfunction finalize(state: MutState): ApplyResult {\n return {\n touched: state.touched,\n removed: state.removed,\n created: state.created,\n appliedGroups: state.appliedGroups,\n skipped: state.skipped,\n journal: [],\n diagnostics: state.diagnostics,\n };\n}\n","/**\n * @domflax/core — pass-manager supporting contexts (resolvers, selector index, rewrite factory,\n * match context).\n *\n * Split out of `pass-manager.ts` so the sync engine, the async verifier-gated engine, and the\n * classification module can all share the same context construction without any of those files\n * exceeding the module-size budget. Dependency-free: only the `./types` contract + `./builders`.\n */\n\nimport type {\n DeepReadonly,\n ElementLike,\n ElementSpec,\n EmitContext,\n EmitResult,\n IRDocument,\n IRElement,\n IRNode,\n IRNodeId,\n MatchContext,\n NodeLike,\n NodeSpec,\n PassPhase,\n ResolveInput,\n ResolveResult,\n RewriteFactory,\n RewriteOpDraft,\n SelectorIndex,\n SelectorUsage,\n StyleConflictPolicy,\n StyleMap,\n StyleResolver,\n} from './types';\n\nimport { elementIds, emptyStyleMap, getElement } from './builders';\n\n/* ───────────────────────── default resolvers / selector index ───────────────────────── */\n\n/** A no-op resolver: owns nothing, resolves to empty styles. Useful as an injection default. */\nexport function createNullResolver(): StyleResolver {\n const empty: ResolveResult = {\n styles: emptyStyleMap(),\n resolved: [],\n unknown: [],\n opaque: [],\n warnings: [],\n };\n const usage: SelectorUsage = {\n asSubject: false,\n asAncestor: false,\n asCompound: false,\n asSibling: false,\n asHasArgument: false,\n asStructural: false,\n droppable: true,\n };\n return {\n id: 'null',\n provider: 'null@0.0.0',\n fingerprint: 'null',\n owns(): boolean {\n return false;\n },\n resolve(_input: ResolveInput): ResolveResult {\n return empty;\n },\n emit(_styles: StyleMap, _ctx: EmitContext): EmitResult {\n return { classes: [], exact: true, warnings: [] };\n },\n selectorUsage(): SelectorUsage {\n return usage;\n },\n };\n}\n\n/** A SelectorIndex that reports zero CSS-targeting (no combinator/structural coupling). */\nexport function createNullSelectorIndex(): SelectorIndex {\n const none: ReadonlySet<IRNodeId> = new Set();\n return {\n targetedByCombinator(): boolean {\n return false;\n },\n targetedByStructuralPseudo(): boolean {\n return false;\n },\n reparentImpact(): ReadonlySet<IRNodeId> {\n return none;\n },\n };\n}\n\n/** Resolvers that can enumerate the project's COMPLEX selectors (the custom-CSS resolver) expose this. */\ninterface ComplexSelectorCapable {\n complexSelectors(): readonly string[];\n}\n\nfunction hasComplexSelectors(r: StyleResolver): r is StyleResolver & ComplexSelectorCapable {\n return typeof (r as Partial<ComplexSelectorCapable>).complexSelectors === 'function';\n}\n\n/**\n * Build a real {@link SelectorIndex} from the active resolver.\n *\n * For a resolver that reports project COMPLEX selectors — anything with a combinator (`>`/`+`/`~`/\n * descendant) or a structural pseudo, i.e. the custom-CSS resolver — every element whose static class\n * participates in such a selector is flagged so the flatten/compress guards (`targetedByCombinator` /\n * `affectsSelectorMatching`) fire and a wrapper a selector depends on is NOT flattened. An element is\n * combinator-coupled when one of its classes is used as a descendant/child ancestor, as a sibling\n * subject, or as a `:has()` argument; structural-coupled when used in `:nth-child(...)` etc.\n *\n * For a combinator-free resolver (Tailwind utilities — no `complexSelectors()`), this degrades to the\n * null index so behaviour is unchanged.\n */\nexport function buildSelectorIndex(doc: IRDocument, resolver: StyleResolver): SelectorIndex {\n if (!hasComplexSelectors(resolver) || resolver.complexSelectors().length === 0) {\n return createNullSelectorIndex();\n }\n\n const combinator = new Set<IRNodeId>();\n const structural = new Set<IRNodeId>();\n\n for (const id of elementIds(doc)) {\n const el = getElement(doc, id);\n if (!el) continue;\n for (const seg of el.classes.segments) {\n if (seg.kind !== 'static') continue;\n for (const t of seg.tokens) {\n const u = resolver.selectorUsage(t.value);\n // Combinator coupling: descendant/child ancestor, sibling subject, or `:has()` argument —\n // reparenting/removing the element would change a combinator match-set.\n if (u.asAncestor || u.asSibling || u.asHasArgument) combinator.add(id);\n if (u.asStructural) structural.add(id);\n }\n }\n }\n\n // reparentImpact(id): non-empty when removing/unwrapping `id` would change a combinator/structural\n // match-set — `id` itself is coupled (its own match), or it is the matched ancestor of a child\n // (removing it reparents that child out of the relation). Self + element children is conservative\n // and sufficient for the flatten guard.\n const impact = new Map<IRNodeId, Set<IRNodeId>>();\n for (const id of elementIds(doc)) {\n const el = getElement(doc, id);\n if (!el) continue;\n if (!combinator.has(id) && !structural.has(id)) continue;\n const set = new Set<IRNodeId>([id]);\n for (const c of el.children) {\n const cn = doc.nodes.get(c);\n if (cn && cn.kind === 'element') set.add(c);\n }\n impact.set(id, set);\n }\n\n const empty: ReadonlySet<IRNodeId> = new Set();\n return {\n targetedByCombinator: (id: IRNodeId): boolean => combinator.has(id),\n targetedByStructuralPseudo: (id: IRNodeId): boolean => structural.has(id),\n reparentImpact: (id: IRNodeId): ReadonlySet<IRNodeId> => impact.get(id) ?? empty,\n };\n}\n\n/* ───────────────────────── rewrite factory (emits origin-free drafts) ───────────────────────── */\n\n/** Every {@link NodeLike}/{@link ElementLike} carries a readonly `id`. */\nfunction idOf(n: ElementLike | NodeLike): IRNodeId {\n return (n as IRElement).id;\n}\n\n/** The pattern-kit factory: produces op DRAFTS and detached NodeSpecs without any allocation. */\nexport function createRewriteFactory(): RewriteFactory {\n return {\n unwrap(target: ElementLike): RewriteOpDraft {\n return { op: 'unwrap', target: idOf(target) };\n },\n removeNode(target: NodeLike): RewriteOpDraft {\n return { op: 'removeNode', target: idOf(target) };\n },\n replaceWith(target: NodeLike, replacement: NodeSpec): RewriteOpDraft {\n return { op: 'replaceWith', target: idOf(target), replacement };\n },\n wrap(target: NodeLike, wrapper: ElementSpec): RewriteOpDraft {\n return { op: 'wrap', target: idOf(target), wrapper };\n },\n insertBefore(anchor: NodeLike, node: NodeSpec): RewriteOpDraft {\n return { op: 'insertBefore', anchor: idOf(anchor), node };\n },\n insertAfter(anchor: NodeLike, node: NodeSpec): RewriteOpDraft {\n return { op: 'insertAfter', anchor: idOf(anchor), node };\n },\n moveNode(target: NodeLike, newParent: ElementLike, index: number): RewriteOpDraft {\n return { op: 'moveNode', target: idOf(target), newParent: idOf(newParent), index };\n },\n mergeSiblings(first: NodeLike, second: NodeLike): RewriteOpDraft {\n return { op: 'mergeSiblings', first: idOf(first), second: idOf(second) };\n },\n setClassList(target: ElementLike, style: StyleMap, preserveOpaque = true): RewriteOpDraft {\n return { op: 'setClassList', target: idOf(target), style, preserveOpaque };\n },\n mergeStyle(\n target: ElementLike,\n source: ElementLike | null,\n style: StyleMap,\n onConflict: StyleConflictPolicy = 'abort',\n ): RewriteOpDraft {\n return {\n op: 'mergeStyle',\n target: idOf(target),\n source: source ? idOf(source) : null,\n style,\n onConflict,\n };\n },\n foldInheritedStyles(\n from: ElementLike,\n into: ElementLike | readonly ElementLike[],\n opts?: { only?: readonly import('./types').CssProperty[]; conditions?: 'base' | 'all' },\n ): RewriteOpDraft {\n const list: readonly ElementLike[] = Array.isArray(into)\n ? (into as readonly ElementLike[])\n : [into as ElementLike];\n return {\n op: 'foldInheritedStyles',\n from: idOf(from),\n into: list.map((t) => idOf(t)),\n properties: opts?.only ?? 'all-inherited',\n conditions: opts?.conditions ?? 'base',\n };\n },\n element(spec: ElementSpec): NodeSpec {\n return spec;\n },\n text(value: string): NodeSpec {\n return { kind: 'text', value };\n },\n keep(node: NodeLike): NodeSpec {\n return { kind: 'ref', ref: idOf(node) };\n },\n };\n}\n\n/* ───────────────────────── match context ───────────────────────── */\n\nfunction ro<T>(v: T): DeepReadonly<T> {\n return v as DeepReadonly<T>;\n}\n\n/** Build the read-only {@link MatchContext} a pattern's `evaluate` receives for one element. */\nexport function buildMatchContext(\n doc: IRDocument,\n elementId: IRNodeId,\n resolver: StyleResolver,\n selectors: SelectorIndex,\n safety: import('./types').SafetyLevel,\n phase: PassPhase,\n iteration: number,\n): MatchContext {\n const self = getElement(doc, elementId)!;\n\n const parentEl = (): DeepReadonly<IRElement> | null => {\n if (self.parent == null) return null;\n const p = doc.nodes.get(self.parent);\n return p && p.kind === 'element' ? ro(p) : null;\n };\n\n const elementChildren = (): readonly DeepReadonly<IRElement>[] => {\n const out: DeepReadonly<IRElement>[] = [];\n for (const c of self.children) {\n const cn = doc.nodes.get(c);\n if (cn && cn.kind === 'element') out.push(ro(cn));\n }\n return out;\n };\n\n const ancestors = (): readonly DeepReadonly<IRElement>[] => {\n const out: DeepReadonly<IRElement>[] = [];\n let cur: IRNodeId | null = self.parent;\n while (cur != null) {\n const n: IRNode | undefined = doc.nodes.get(cur);\n if (!n) break;\n if (n.kind === 'element') out.push(ro(n));\n cur = n.parent;\n }\n return out;\n };\n\n const siblingAt = (delta: number): DeepReadonly<IRNode> | null => {\n if (self.parent == null) return null;\n const p = doc.nodes.get(self.parent);\n if (!p || (p.kind !== 'element' && p.kind !== 'fragment')) return null;\n const i = p.children.indexOf(elementId);\n const sib = p.children[i + delta];\n if (sib == null) return null;\n const sn = doc.nodes.get(sib);\n return sn ? ro(sn) : null;\n };\n\n const computedOf = (n: NodeLike): StyleMap => {\n const node = doc.nodes.get((n as IRNode).id);\n return node && node.kind === 'element' ? node.computed : emptyStyleMap();\n };\n\n return {\n node: ro(self),\n doc: ro(doc),\n resolver,\n selectors,\n safety,\n phase,\n iteration,\n parent: parentEl,\n elementChildren,\n onlyElementChild(): DeepReadonly<IRElement> | null {\n const els = elementChildren();\n return els.length === 1 ? els[0]! : null;\n },\n computed(): StyleMap {\n return self.computed;\n },\n computedOf,\n isOpaque(n?: ElementLike): boolean {\n const target = n ? doc.nodes.get((n as IRElement).id) : self;\n if (!target || target.kind !== 'element') return true;\n return target.classes.opaque || target.meta.hasSpreadAttrs;\n },\n ancestors,\n closest(pred): DeepReadonly<IRElement> | null {\n for (const a of ancestors()) if (pred(a)) return a;\n return null;\n },\n prevSibling(): DeepReadonly<IRNode> | null {\n return siblingAt(-1);\n },\n nextSibling(): DeepReadonly<IRNode> | null {\n return siblingAt(1);\n },\n nthChildIndex(): number {\n if (self.parent == null) return 1;\n const p = doc.nodes.get(self.parent);\n if (!p || (p.kind !== 'element' && p.kind !== 'fragment')) return 1;\n let idx = 0;\n for (const c of p.children) {\n const cn = doc.nodes.get(c);\n if (cn && cn.kind === 'element') {\n idx += 1;\n if (c === elementId) return idx;\n }\n }\n return idx;\n },\n };\n}\n","/**\n * @domflax/core — static classification of a flatten (the VERIFIER-GATED safety core).\n *\n * A flatten pattern matches on `paintsNothing` + a structural/style signature, but unwrapping a\n * wrapper can still change rendering: a wrapper with non-paint layout styles (e.g. `px-4 py-4`) drops\n * that padding when removed (it is NOT reproduced on the surviving child), and a centering wrapper\n * collapsed to `place-self:center` only stays centered when the child's NEW parent is flex/grid. The\n * existing emittability revert only checks the ADDED style is re-emittable — not that the wrapper's\n * own styles survive, nor that the parent context holds.\n *\n * {@link classifyFlattenOps} answers, for one applied flatten op-group, whether it is:\n *\n * • `'provably-safe'` — removing the wrapper changes NOTHING renderable: the wrapper\n * establishes no box/formatting/stacking context, has no non-inherited\n * own declaration that the rewrite does not reproduce on the surviving\n * child, AND the rewrite adds no parent-context-dependent self-alignment\n * (unless the new parent is statically flex/grid). Examples: passthrough\n * / empty-style / display-contents / redundant-fragment wrappers.\n * • `'needs-verification'` — anything else (drops/relies on a style, or centering→place-self).\n *\n * Pure + dependency-free: only the `./types` contract + `./builders` accessors.\n */\n\nimport { conditionKey, getElement } from './builders';\nimport type {\n CssProperty,\n IRDocument,\n IRElement,\n IRNodeId,\n RewriteOp,\n StyleBlock,\n StyleDecl,\n StyleMap,\n StyleNormalizer,\n} from './types';\n\n/** The static verdict for one flatten op-group. */\nexport type FlattenClass = 'provably-safe' | 'needs-verification';\n\n/** A classified flatten plus the structural anchors a verifier needs to render before/after. */\nexport interface FlattenClassification {\n readonly kind: FlattenClass;\n /** The unwrapped wrapper (in the BEFORE doc), or null when the group removes no element box. */\n readonly wrapperId: IRNodeId | null;\n /** The surviving child styles fold onto (the AFTER subtree root), or null. */\n readonly childId: IRNodeId | null;\n}\n\n/* ───────────────────────── display / context reasoning ───────────────────────── */\n\nconst DISPLAY = 'display' as CssProperty;\nconst POSITION = 'position' as CssProperty;\nconst TRANSFORM = 'transform' as CssProperty;\nconst ALIGN_ITEMS = 'align-items' as CssProperty;\nconst JUSTIFY_CONTENT = 'justify-content' as CssProperty;\nconst JUSTIFY_ITEMS = 'justify-items' as CssProperty;\nconst PLACE_ITEMS = 'place-items' as CssProperty;\nconst PLACE_SELF = 'place-self' as CssProperty;\n\n/** Displays that generate no independent formatting context for the wrapper's children. */\nconst CONTEXT_SAFE_DISPLAYS: ReadonlySet<string> = new Set(['block', 'contents', '']);\n/** `position` values that neither establish a containing block nor offset the element. */\nconst STATIC_POSITIONS: ReadonlySet<string> = new Set(['static', '']);\n\n/* ───────────────────────── context-compensated centering (grid-parent override) ───────────────────────── */\n\n/**\n * Displays under which a block-level wrapper carrying `align-items:center` + `justify-content:center`\n * truly centers a single child on BOTH axes (so collapsing it to `place-self:center` is lossless).\n * Restricted to the block-level `flex`/`grid` (per the CSS soundness rule) — the inline variants are\n * left `needs-verification`.\n */\nconst CENTERING_DISPLAYS: ReadonlySet<string> = new Set(['flex', 'grid']);\n/**\n * Parent displays that establish a GRID formatting context — the ONLY context in which the child's\n * `justify-self` (the horizontal half of `place-self:center`) is honored. A flex parent ignores\n * `justify-self`, and a block parent ignores both, so neither can host the flatten.\n */\nconst GRID_PARENT_DISPLAYS: ReadonlySet<string> = new Set(['grid']);\n/**\n * Item-alignment values under which a stretch-defaulted grid item FILLS its area. Only when the\n * wrapper fills its grid area does \"center inside the wrapper\" equal \"center inside the area\" (which\n * is what `place-self:center` on the child produces). Any other value (start/end/center/…) would let\n * the wrapper shrink and sit off-center, so the collapse could move the child → we preserve.\n */\nconst STRETCHY_ITEM_ALIGN: ReadonlySet<string> = new Set(['normal', 'stretch']);\n/** Parent item-alignment properties that, when non-stretch, stop the wrapper filling its grid area. */\nconst PARENT_ITEMS_ALIGN_PROPS: readonly CssProperty[] = [ALIGN_ITEMS, JUSTIFY_ITEMS, PLACE_ITEMS];\n\n/** True when a style condition is the unconditional base (no media / states / pseudo-element). */\nfunction isBaseCondition(block: StyleBlock): boolean {\n const c = block.condition;\n return c.media === '' && c.states.length === 0 && c.pseudoElement === '';\n}\n\n/** The base-condition value of `prop` in a NORMALIZED style map, or null when unset. */\nfunction baseValue(sm: StyleMap, prop: CssProperty): string | null {\n for (const block of sm.blocks.values()) {\n if (!isBaseCondition(block)) continue;\n const d = block.decls.get(prop);\n return d ? String(d.value) : null;\n }\n return null;\n}\n\n/**\n * True when unwrapping `wrapper` reparents the child under a statically-known GRID container that lets\n * the wrapper fill its area — the ONE parent context in which `place-self:center` reproduces the\n * wrapper's centering exactly. Requires (a) the parent is `display:grid`/`inline-grid` in the base\n * condition, (b) NO condition switches the parent to a non-grid display, and (c) NO condition forces a\n * non-stretch item-alignment (align-items/justify-items/place-items) that would shrink the wrapper off\n * its area. Anything else (flex/block/unknown parent, `place-items:center`, responsive `md:flex`, …)\n * → false → the flatten stays `needs-verification` (preserved).\n */\nfunction parentIsFillingGrid(before: IRDocument, wrapper: IRElement, norm: StyleNormalizer): boolean {\n if (wrapper.parent == null) return false;\n const p = before.nodes.get(wrapper.parent);\n if (!p || p.kind !== 'element') return false;\n const pc = norm.normalizeStyleMap(p.computed);\n let baseIsGrid = false;\n for (const block of pc.blocks.values()) {\n const disp = block.decls.get(DISPLAY);\n if (disp) {\n if (!GRID_PARENT_DISPLAYS.has(String(disp.value))) return false; // any non-grid display → unsafe\n if (isBaseCondition(block)) baseIsGrid = true;\n }\n for (const prop of PARENT_ITEMS_ALIGN_PROPS) {\n const d = block.decls.get(prop);\n if (d && !STRETCHY_ITEM_ALIGN.has(String(d.value))) return false; // wrapper would not fill its area\n }\n }\n return baseIsGrid;\n}\n\n/**\n * True when the wrapper carries NOTHING beyond the base-condition centering signature\n * (`display:flex|grid` + `align-items:center` + `justify-content:center`) that removal would drop.\n * Those three are compensated by the child's new `place-self:center`; `position:static`/`transform:none`\n * are inert; inherited declarations are folded onto the child by `foldInheritedStyles`; and any decl the\n * child provably reproduces is not lost. ANY other non-inherited own declaration — in any condition\n * (padding, margin, sizing, border, background, gap, a NON-base or NON-center align-items/justify-content,\n * a non-static position, a transform, …) → false → not a pure centering wrapper → preserved.\n */\nfunction wrapperHasOnlyCenteringStyle(\n wrapperComputed: StyleMap,\n childComputed: StyleMap | null,\n norm: StyleNormalizer,\n): boolean {\n for (const block of wrapperComputed.blocks.values()) {\n const base = isBaseCondition(block);\n const ck = conditionKey(block.condition);\n for (const [prop, decl] of block.decls) {\n const val = String(decl.value);\n if (prop === DISPLAY) {\n if (base && CENTERING_DISPLAYS.has(val)) continue;\n return false;\n }\n if (prop === ALIGN_ITEMS) {\n if (base && val === 'center') continue;\n return false;\n }\n if (prop === JUSTIFY_CONTENT) {\n if (base && val === 'center') continue;\n return false;\n }\n if (prop === POSITION) {\n if (STATIC_POSITIONS.has(val)) continue;\n return false;\n }\n if (prop === TRANSFORM) {\n if (val === 'none') continue;\n return false;\n }\n if (isInherited(decl, norm)) continue; // folded onto the child by foldInheritedStyles\n if (childReproduces(childComputed, ck, prop, val)) continue;\n return false; // some other own style would be dropped\n }\n }\n return true;\n}\n\n/** True when `wrapper` has exactly ONE element child and no other RENDERED content (rule 4). */\nfunction wrapperCentersSingleElement(before: IRDocument, wrapper: IRElement): boolean {\n let elements = 0;\n for (const cid of wrapper.children) {\n const n = before.nodes.get(cid);\n if (!n) continue;\n if (n.kind === 'element') {\n elements += 1;\n continue;\n }\n if (n.kind === 'comment') continue; // comments paint nothing and are not flex/grid items\n if (n.kind === 'text' && n.value.trim() === '') continue; // collapsible whitespace ⇒ no item\n return false; // real text / an `{expr}` island the wrapper's centering also positions\n }\n return elements === 1;\n}\n\n/** True when the child ALREADY carries a non-neutral self-alignment that place-self:center would override (rule 5). */\nfunction childHasSelfAlign(childBefore: StyleMap | null, norm: StyleNormalizer): boolean {\n if (!childBefore) return false;\n const sm = norm.normalizeStyleMap(childBefore);\n for (const block of sm.blocks.values()) {\n for (const prop of SELF_ALIGN_PROPS) {\n const d = block.decls.get(prop);\n if (d && !NEUTRAL_ALIGN.has(String(d.value))) return true;\n }\n }\n return false;\n}\n\n/** True when the rewrite grants the child the `place-self:center` equivalent (rule 2, second half). */\nfunction childGainsPlaceSelfCenter(childAfter: StyleMap): boolean {\n if (baseValue(childAfter, PLACE_SELF) === 'center') return true;\n return (\n baseValue(childAfter, 'align-self' as CssProperty) === 'center' &&\n baseValue(childAfter, 'justify-self' as CssProperty) === 'center'\n );\n}\n\n/**\n * The provably-sound override for the ubiquitous centering wrapper. Flattening\n *\n * <P grid><W flex/grid items-center justify-center><C/></W></P> → <P grid><C place-self:center/></P>\n *\n * is render-identical ONLY when ALL hold (each proven statically from the before-tree):\n * 1. Parent P establishes a GRID formatting context that lets the wrapper fill its area — so the\n * child's new `justify-self:center` (ignored under flex/block) is honored. ({@link parentIsFillingGrid})\n * 2. Wrapper W centers a single child on both axes (`display:flex|grid` + `align-items:center` +\n * `justify-content:center`) and the child gains the equivalent `place-self:center`.\n * 3. W has no OTHER non-inherited box style whose removal would drop or shift anything.\n * ({@link wrapperHasOnlyCenteringStyle})\n * 4. W has exactly one ELEMENT child and no other rendered content. ({@link wrapperCentersSingleElement})\n * 5. C does not already carry a conflicting `place-self`/`align-self`/`justify-self`. ({@link childHasSelfAlign})\n *\n * Any failure → false → the wrapper is preserved (the conservative default). Works identically for the\n * HTML and JSX pipelines: the parent display is read from the before-tree's resolved computed styles.\n */\nfunction isContextCompensatedCentering(\n before: IRDocument,\n wrapper: IRElement,\n wrapperComputed: StyleMap,\n childBefore: StyleMap | null,\n childAfter: StyleMap | null,\n norm: StyleNormalizer,\n): boolean {\n if (!childAfter) return false;\n // (2) wrapper centering signature (base condition) + the child actually gains place-self:center.\n if (!CENTERING_DISPLAYS.has(baseValue(wrapperComputed, DISPLAY) ?? '')) return false;\n if (baseValue(wrapperComputed, ALIGN_ITEMS) !== 'center') return false;\n if (baseValue(wrapperComputed, JUSTIFY_CONTENT) !== 'center') return false;\n const childAfterNorm = norm.normalizeStyleMap(childAfter);\n if (!childGainsPlaceSelfCenter(childAfterNorm)) return false;\n // (3) nothing else on the wrapper is dropped.\n if (!wrapperHasOnlyCenteringStyle(wrapperComputed, childAfterNorm, norm)) return false;\n // (4) exactly one element child, nothing else the wrapper positions.\n if (!wrapperCentersSingleElement(before, wrapper)) return false;\n // (5) the child has no pre-existing self-alignment place-self:center would override.\n if (childHasSelfAlign(childBefore, norm)) return false;\n // (1) the new parent is a statically-known grid that lets the wrapper fill its area.\n return parentIsFillingGrid(before, wrapper, norm);\n}\n\n/** Self-alignment properties whose effect depends on the parent being a flex/grid container. */\nconst SELF_ALIGN_PROPS: readonly CssProperty[] = [\n 'place-self' as CssProperty,\n 'align-self' as CssProperty,\n 'justify-self' as CssProperty,\n];\n/** Self-alignment values that are no-ops (so adding them assumes nothing about the parent). */\nconst NEUTRAL_ALIGN: ReadonlySet<string> = new Set(['auto', 'normal', 'auto auto', '']);\n/** Parent displays under which `place-self`/`*-self` centering actually takes effect. */\nconst FLEX_GRID_DISPLAYS: ReadonlySet<string> = new Set(['flex', 'inline-flex', 'grid', 'inline-grid']);\n\n/**\n * True when the wrapper establishes a box/formatting/stacking context that positions or sizes its\n * children — so removing its box could move/resize the surviving child. Derived from the COMPUTED\n * style (the frontend leaves the `meta.establishes*` flags unset for class-resolved styles), exactly\n * how `hasOwnVisualStyle` reasons over the computed map.\n */\nfunction establishesChildContext(sm: StyleMap): boolean {\n for (const block of sm.blocks.values()) {\n const display = block.decls.get(DISPLAY);\n if (display && !CONTEXT_SAFE_DISPLAYS.has(String(display.value))) return true;\n const position = block.decls.get(POSITION);\n if (position && !STATIC_POSITIONS.has(String(position.value))) return true;\n const transform = block.decls.get(TRANSFORM);\n if (transform && String(transform.value) !== 'none') return true;\n }\n return false;\n}\n\n/* ───────────────────────── declaration reasoning ───────────────────────── */\n\nfunction isInherited(decl: StyleDecl, norm: StyleNormalizer): boolean {\n if (decl.inherited) return true;\n try {\n return norm.inherited.isInherited(decl.property);\n } catch {\n return false;\n }\n}\n\n/** True when the child reproduces this exact declaration (same property + value) in the same condition. */\nfunction childReproduces(\n childComputed: StyleMap | null,\n conditionK: string,\n prop: CssProperty,\n value: string,\n): boolean {\n if (!childComputed) return false;\n const block = childComputed.blocks.get(conditionK as never);\n if (!block) return false;\n const d = block.decls.get(prop);\n return d != null && String(d.value) === value;\n}\n\n/**\n * True when the wrapper carries a non-inherited declaration that is NOT reproduced on the surviving\n * child — i.e. flattening would DROP a renderable style. `display`/`position`/`transform` are skipped\n * because {@link establishesChildContext} already governs them (and when it passed they are no-ops).\n */\nfunction dropsOwnStyle(\n wrapperComputed: StyleMap,\n childComputed: StyleMap | null,\n norm: StyleNormalizer,\n): boolean {\n for (const block of wrapperComputed.blocks.values()) {\n const ck = conditionKey(block.condition);\n for (const [prop, decl] of block.decls) {\n if (prop === DISPLAY || prop === POSITION || prop === TRANSFORM) continue;\n if (isInherited(decl, norm)) continue; // folded onto the child by foldInheritedStyles\n if (!childReproduces(childComputed, ck, prop, String(decl.value))) return true;\n }\n }\n return false;\n}\n\n/* ───────────────────────── parent-context reasoning ───────────────────────── */\n\n/** The element's base-condition `display` value (normalized), or '' when unset/not an element. */\nfunction displayOf(el: IRElement | undefined, norm: StyleNormalizer): string {\n if (!el) return '';\n for (const block of norm.normalizeStyleMap(el.computed).blocks.values()) {\n if (block.condition.media === '' && block.condition.states.length === 0 && block.condition.pseudoElement === '') {\n const d = block.decls.get(DISPLAY);\n if (d) return String(d.value);\n }\n }\n return '';\n}\n\n/** True when unwrapping `wrapper` reparents the child UNDER a flex/grid container in the before-tree. */\nfunction newParentIsFlexOrGrid(before: IRDocument, wrapper: IRElement, norm: StyleNormalizer): boolean {\n if (wrapper.parent == null) return false;\n const p = before.nodes.get(wrapper.parent);\n if (!p || p.kind !== 'element') return false;\n return FLEX_GRID_DISPLAYS.has(displayOf(p, norm));\n}\n\n/**\n * True when the rewrite GRANTS the child a parent-context-dependent self-alignment (place-self /\n * align-self / justify-self with a non-neutral value) that was not already on it — centering that only\n * holds if the new parent is flex/grid.\n */\nfunction addsParentContextStyle(\n childBefore: StyleMap | null,\n childAfter: StyleMap | null,\n norm: StyleNormalizer,\n): boolean {\n if (!childAfter) return false;\n const before = childBefore ? norm.normalizeStyleMap(childBefore) : null;\n const after = norm.normalizeStyleMap(childAfter);\n for (const block of after.blocks.values()) {\n const ck = conditionKey(block.condition);\n for (const prop of SELF_ALIGN_PROPS) {\n const d = block.decls.get(prop);\n if (!d || NEUTRAL_ALIGN.has(String(d.value))) continue;\n const prev = before?.blocks.get(ck as never)?.decls.get(prop);\n if (!prev || String(prev.value) !== String(d.value)) return true;\n }\n }\n return false;\n}\n\n/* ───────────────────────── op-group anchors ───────────────────────── */\n\n/** The wrapper the group unwraps (the structural removal), or null when the group removes no box. */\nfunction unwrapTargetOf(ops: readonly RewriteOp[]): IRNodeId | null {\n for (const op of ops) if (op.op === 'unwrap') return op.target;\n return null;\n}\n\n/** The surviving child styles fold onto: the mergeStyle/fold target, else the wrapper's sole element child. */\nfunction survivingChildOf(ops: readonly RewriteOp[], wrapper: IRElement, before: IRDocument): IRNodeId | null {\n for (const op of ops) if (op.op === 'mergeStyle') return op.target;\n for (const op of ops) if (op.op === 'foldInheritedStyles' && op.into.length > 0) return op.into[0]!;\n for (const c of wrapper.children) {\n const n = before.nodes.get(c);\n if (n && n.kind === 'element') return c;\n }\n return null;\n}\n\n/* ───────────────────────── the classifier ───────────────────────── */\n\n/**\n * Statically classify one applied flatten op-group. `before` is the doc as it was BEFORE the group's\n * ops; `after` is the result of applying them.\n *\n * A group that unwraps no element box (e.g. {@link redundant-fragment}, or a style-only flatten) is\n * `provably-safe` — there is no box whose removal could move/resize anything. Otherwise the three\n * criteria above decide.\n */\nexport function classifyFlattenOps(\n before: IRDocument,\n after: IRDocument,\n ops: readonly RewriteOp[],\n norm: StyleNormalizer,\n): FlattenClassification {\n const wrapperId = unwrapTargetOf(ops);\n if (wrapperId == null) return { kind: 'provably-safe', wrapperId: null, childId: null };\n\n const wrapper = before.nodes.get(wrapperId);\n // A fragment carries no box and no computed style — unwrapping it is always layout-identical.\n if (!wrapper || wrapper.kind !== 'element') {\n return { kind: 'provably-safe', wrapperId: null, childId: null };\n }\n\n // SAFETY (Layer 2, backstop): if ANY of the wrapper's own class tokens was UNRESOLVED, its true\n // style is UNKNOWN — `wrapper.computed` is only the resolved subset, so the static \"inert\" reasoning\n // below (which sees an empty/partial map) could wrongly clear it. Never treat such a wrapper as\n // provably safe to unwrap. Under the default `'provably-safe'` gate this reverts (preserves) the\n // flatten; the match-time `hasOwnVisualStyle` gate already blocks the paintsNothing patterns, so this\n // catches a positive-computed flatten (e.g. nested-flex-merge) that also carries an unknown token.\n if (wrapper.meta.hasUnresolvedClasses) {\n return { kind: 'needs-verification', wrapperId, childId: survivingChildOf(ops, wrapper, before) };\n }\n\n const childId = survivingChildOf(ops, wrapper, before);\n const wrapperComputed = norm.normalizeStyleMap(wrapper.computed);\n const childAfter = childId != null ? getElement(after, childId)?.computed ?? null : null;\n const childBefore = childId != null ? getElement(before, childId)?.computed ?? null : null;\n\n // (OVERRIDE) A flex/grid centering wrapper establishes a formatting context — so (A) below would\n // reject it — YET collapsing it to `place-self:center` on the sole child is provably layout-neutral\n // when the child's NEW parent is a statically-known grid that lets the wrapper fill its area (and the\n // wrapper carries nothing else). This is the ONE context-compensated case; verified render-identical\n // in Chromium. Everything that fails any rule falls through to the conservative criteria below.\n if (isContextCompensatedCentering(before, wrapper, wrapperComputed, childBefore, childAfter, norm)) {\n return { kind: 'provably-safe', wrapperId, childId };\n }\n\n // (A) wrapper positions/sizes its children → removing its box can move/resize them.\n if (establishesChildContext(wrapperComputed)) {\n return { kind: 'needs-verification', wrapperId, childId };\n }\n // (B) wrapper drops a non-inherited own style the child does not reproduce.\n if (dropsOwnStyle(wrapperComputed, childAfter ? norm.normalizeStyleMap(childAfter) : null, norm)) {\n return { kind: 'needs-verification', wrapperId, childId };\n }\n // (C) rewrite adds parent-context-dependent centering, but the new parent is not statically flex/grid.\n if (addsParentContextStyle(childBefore, childAfter, norm) && !newParentIsFlexOrGrid(before, wrapper, norm)) {\n return { kind: 'needs-verification', wrapperId, childId };\n }\n\n return { kind: 'provably-safe', wrapperId, childId };\n}\n","/**\n * @domflax/core — pass manager (the sync, static flatten driver).\n *\n * Runs {@link Pattern}s grouped by {@link PassPhase} in declared order, driving the `flatten` phase to\n * a fixpoint under a max-iteration budget, isolating per-node pattern errors into {@link Diagnostic}s\n * (a thrown pattern never aborts the run — it becomes `DF_PATTERN_THREW`), and applying the static\n * flatten policy ({@link ApplyContext.gate}) — under `'provably-safe'` only provably layout-neutral\n * flattens commit, so the transform never changes rendering and never launches a browser.\n *\n * The supporting contexts (resolvers, selector index, rewrite factory, match context) live in\n * `./pass-context`; the static flatten classifier in `./flatten-safety`. Dependency-free: only the\n * `./types` contract + sibling runtime helpers.\n */\n\nimport type {\n ApplyContext,\n Diagnostic,\n FixpointConfig,\n HaltReason,\n IRDocument,\n IRNodeId,\n Pass,\n PassManager,\n PassPhase,\n Pattern,\n PhaseRunResult,\n RewriteFactory,\n RewriteOp,\n RewriteOpDraft,\n StyleMap,\n StyleNormalizer,\n StyleResolver,\n SyntheticSink,\n EmitContext,\n} from './types';\n\nimport { childIds, elementIds, getElement } from './builders';\nimport { applyOps } from './ops';\nimport { buildMatchContext, createRewriteFactory } from './pass-context';\nimport { classifyFlattenOps } from './flatten-safety';\n\n// Re-export the supporting contexts so `@domflax/core` consumers keep importing them from here / the\n// barrel exactly as before this module was split.\nexport {\n buildMatchContext,\n buildSelectorIndex,\n createNullResolver,\n createNullSelectorIndex,\n createRewriteFactory,\n} from './pass-context';\n\n/* ───────────────────────── defaults ───────────────────────── */\n\nexport const DEFAULT_FIXPOINT: FixpointConfig = {\n maxIterations: 16,\n phases: { flatten: 16, compress: 8, extract: 4 },\n onBudgetExhausted: 'warn',\n detectOscillation: true,\n};\n\nexport const PHASE_ORDER: readonly PassPhase[] = ['flatten', 'compress', 'extract'];\n\n/* ───────────────────────── op stamping + phase grouping ───────────────────────── */\n\nexport function stampOrigin(draft: RewriteOpDraft, pattern: Pattern): RewriteOp {\n return {\n ...draft,\n origin: { pattern: pattern.name, category: pattern.category, safety: pattern.safety },\n } as RewriteOp;\n}\n\nexport function patternsForPhase(passes: readonly Pass[], phase: PassPhase): Pattern[] {\n const out: Pattern[] = [];\n for (const pass of passes) {\n if (pass.phase !== phase) continue;\n for (const p of pass.patterns) out.push(p);\n }\n out.sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0));\n return out;\n}\n\nexport interface RunState {\n doc: IRDocument;\n}\n\n/* ───────────────────────── flatten residual-skip (never drop an unreproducible style) ───────────────────────── */\n\n/** A throwaway {@link SyntheticSink} for the emit exactness probe (registrations are discarded). */\nfunction probeSink(): SyntheticSink {\n return {\n register(s): string {\n return s.className;\n },\n drain(): readonly never[] {\n return [];\n },\n };\n}\n\n/** Nodes a group writes STYLE onto (the survivors a flatten transfers declarations to). */\nfunction styleWriteTargets(ops: readonly RewriteOp[]): IRNodeId[] {\n const ids: IRNodeId[] = [];\n for (const op of ops) {\n if (op.op === 'mergeStyle' || op.op === 'setClassList') ids.push(op.target);\n else if (op.op === 'foldInheritedStyles') ids.push(...op.into);\n }\n return ids;\n}\n\n/** True iff the resolver can EXACTLY reverse-emit `sm` (no residual). An empty map is trivially exact. */\nfunction emitIsExact(resolver: StyleResolver, normalizer: StyleNormalizer, sm: StyleMap): boolean {\n if (sm.blocks.size === 0) return true;\n try {\n const ctx: EmitContext = { normalizer, sink: probeSink() };\n const r = resolver.emit(sm, ctx);\n return r.exact && r.residual == null;\n } catch {\n return true; // a throwing resolver must never block a flatten\n }\n}\n\n/**\n * T5 — flatten must never DROP a style it can't reproduce. After a flatten transfers declarations onto\n * a surviving (rewritable) element, if the resolver can no longer EXACTLY reverse-emit that element's\n * computed style — and it could before — the flatten would silently lose the residual declarations\n * during reverse-emit, so the whole flatten is reverted (the wrapper is kept). Pre-existing residue\n * (already non-exact before the flatten) is not blamed on the flatten and does not trigger a revert.\n */\nexport function flattenWouldDropStyle(\n before: IRDocument,\n after: IRDocument,\n ops: readonly RewriteOp[],\n resolver: StyleResolver,\n normalizer: StyleNormalizer,\n): boolean {\n for (const id of styleWriteTargets(ops)) {\n const newEl = getElement(after, id);\n if (!newEl) continue; // target was itself removed — its style lives on the survivor we also check\n // Opaque / dynamic class lists are kept verbatim by reverse-emit, so no style is dropped there.\n if (newEl.classes.opaque || newEl.classes.hasDynamic) continue;\n if (emitIsExact(resolver, normalizer, newEl.computed)) continue;\n const oldEl = getElement(before, id);\n const wasExact = !oldEl || emitIsExact(resolver, normalizer, oldEl.computed);\n if (wasExact) return true; // the flatten introduced an unreproducible style → revert\n }\n return false;\n}\n\n/* ───────────────────────── flatten gate decision (shared sync core) ───────────────────────── */\n\nexport type FlattenVerdict = 'commit' | 'revert';\n\n/**\n * Decide what to do with a freshly-applied flatten op-group, given the gate. Returns:\n * • `'commit'` — keep the outcome (the historical path for `'all'`, and provably-safe flattens).\n * • `'revert'` — discard + bar the node (residual-drop, or a needs-verification flatten under the\n * `'provably-safe'` gate).\n *\n * `before`/`after` are the docs immediately around the group's application.\n */\nexport function flattenVerdict(\n before: IRDocument,\n after: IRDocument,\n ops: readonly RewriteOp[],\n ctx: ApplyContext,\n): FlattenVerdict {\n // T5 (independent of the gate): a flatten must never drop a style the resolver can't re-emit.\n if (flattenWouldDropStyle(before, after, ops, ctx.resolver, ctx.normalizer)) return 'revert';\n\n const gate = ctx.gate ?? 'all';\n if (gate === 'all') return 'commit';\n\n const cls = classifyFlattenOps(before, after, ops, ctx.normalizer);\n return cls.kind === 'provably-safe' ? 'commit' : 'revert';\n}\n\n/* ───────────────────────── per-element pattern evaluation (shared) ───────────────────────── */\n\n/**\n * Evaluate every pattern against `elId` until one produces ops; returns the stamped op list (and its\n * pattern), or null when no pattern matched. Pattern throws become `DF_PATTERN_THREW` diagnostics.\n */\nexport function evaluateElement(\n doc: IRDocument,\n elId: IRNodeId,\n patterns: readonly Pattern[],\n ctx: ApplyContext,\n factory: RewriteFactory,\n phase: PassPhase,\n iteration: number,\n diagnostics: Diagnostic[],\n): { ops: RewriteOp[]; pattern: Pattern } | null {\n for (const pattern of patterns) {\n if (pattern.safety > ctx.safetyCeiling) continue;\n let drafts: readonly RewriteOpDraft[] = [];\n try {\n const mctx = buildMatchContext(doc, elId, ctx.resolver, ctx.selectors, ctx.safetyCeiling, phase, iteration);\n const result = pattern.evaluate(mctx, factory);\n if (!result) continue;\n drafts = result.ops;\n if (result.diagnostics) for (const d of result.diagnostics) diagnostics.push(d);\n } catch (err) {\n diagnostics.push({\n code: 'DF_PATTERN_THREW',\n severity: 'error',\n message: `pattern '${pattern.name}' threw: ${String((err as Error)?.message ?? err)}`,\n nodeId: elId,\n pattern: pattern.name,\n phase,\n iteration,\n cause: err,\n });\n continue;\n }\n if (drafts.length === 0) continue;\n return { ops: drafts.map((d) => stampOrigin(d, pattern)), pattern };\n }\n return null;\n}\n\n/** Emit the diagnostic recorded when a flatten is reverted by the gate / residual guard. */\nexport function revertDiagnostic(\n pattern: Pattern,\n elId: IRNodeId,\n phase: PassPhase,\n iteration: number,\n resolverId: string,\n): Diagnostic {\n return {\n code: 'DF_VERIFY_REVERTED',\n severity: 'warn',\n message:\n `flatten '${pattern.name}' reverted on node ${elId}: it would change rendering (drops a style, ` +\n `establishes layout context, or assumes a parent context) and was not proven safe by resolver ` +\n `'${resolverId}'`,\n nodeId: elId,\n pattern: pattern.name,\n phase,\n iteration,\n };\n}\n\n/* ───────────────────────── one sweep (sync) ───────────────────────── */\n\n/**\n * One sweep of a phase: evaluate every pattern against every live element, collect op drafts, stamp\n * origin, apply, then commit/revert per {@link flattenVerdict}. Returns the number of ops applied\n * (0 ⇒ fixpoint for this phase). Under the `'provably-safe'` gate, any flatten that is not provably\n * safe is reverted — the transform is fully static and never changes rendering.\n */\nfunction runSweep(\n state: RunState,\n patterns: readonly Pattern[],\n ctx: ApplyContext,\n factory: RewriteFactory,\n phase: PassPhase,\n iteration: number,\n touched: Set<IRNodeId>,\n diagnostics: Diagnostic[],\n flattenBarred: Set<IRNodeId>,\n): number {\n let appliedOps = 0;\n\n for (const elId of elementIds(state.doc)) {\n const el = getElement(state.doc, elId);\n if (!el) continue; // removed earlier in this sweep\n if (phase === 'flatten' && flattenBarred.has(elId)) continue;\n\n const evaluated = evaluateElement(state.doc, elId, patterns, ctx, factory, phase, iteration, diagnostics);\n if (!evaluated) continue;\n const { ops, pattern } = evaluated;\n\n const outcome = applyOps(state.doc, ops, ctx);\n for (const d of outcome.result.diagnostics) diagnostics.push(d);\n if (outcome.result.appliedGroups === 0) continue;\n\n if (phase === 'flatten') {\n const verdict = flattenVerdict(state.doc, outcome.doc, ops, ctx);\n if (verdict !== 'commit') {\n // Discard the outcome (keep the wrapper) AND bar this node from any further flatten this run.\n diagnostics.push(revertDiagnostic(pattern, elId, phase, iteration, ctx.resolver.id));\n flattenBarred.add(elId);\n continue;\n }\n }\n\n state.doc = outcome.doc;\n appliedOps += outcome.result.appliedGroups;\n for (const id of outcome.result.touched) touched.add(id);\n for (const id of outcome.result.created) touched.add(id);\n }\n return appliedOps;\n}\n\n/* ───────────────────────── oscillation fingerprint ───────────────────────── */\n\n/** Cheap structural fingerprint of the document for oscillation detection. */\nexport function docFingerprint(doc: IRDocument): string {\n const parts: string[] = [];\n const visit = (id: IRNodeId): void => {\n const n = doc.nodes.get(id);\n if (!n) return;\n parts.push(`${id}:${n.kind}`);\n for (const c of childIds(n)) visit(c);\n };\n visit(doc.root);\n return parts.join('|');\n}\n\n/* ───────────────────────── the fixpoint driver (sync) ───────────────────────── */\n\n/** A single phase's terminal result, built from the loop's accounting. */\nexport interface PhaseLoopState {\n iterations: number;\n converged: boolean;\n haltReason: HaltReason;\n readonly touched: Set<IRNodeId>;\n readonly diagnostics: Diagnostic[];\n readonly seen: Set<string>;\n}\n\n/** Record the budget-exhausted diagnostic + finalize a phase result. Shared by sync + async drivers. */\nexport function finalizePhase(\n phase: PassPhase,\n s: PhaseLoopState,\n budget: number,\n onBudgetExhausted: 'warn' | 'error',\n): PhaseRunResult {\n if (!s.converged && s.haltReason !== 'oscillation') {\n s.haltReason = 'budget';\n s.diagnostics.push({\n code: 'DF_FIXPOINT_BUDGET',\n severity: onBudgetExhausted === 'error' ? 'error' : 'warn',\n message: `phase '${phase}' exhausted ${budget}-iteration budget`,\n phase,\n iteration: s.iterations,\n });\n }\n return {\n phase,\n iterations: s.iterations,\n converged: s.converged,\n haltReason: s.haltReason,\n touched: s.touched,\n diagnostics: s.diagnostics,\n };\n}\n\n/**\n * Runs `passes` over `doc` to a per-phase fixpoint (synchronous). This is the concrete entry the\n * pipeline calls. Under the `'provably-safe'` gate, flattens that are not provably layout-neutral are\n * reverted — the transform is fully static and never changes rendering.\n */\nexport function runPasses(\n doc: IRDocument,\n passes: readonly Pass[],\n ctx: ApplyContext,\n config?: FixpointConfig,\n): { readonly doc: IRDocument; readonly results: readonly PhaseRunResult[] } {\n const cfg: FixpointConfig = { ...DEFAULT_FIXPOINT, ...config };\n const factory = createRewriteFactory();\n const state: RunState = { doc };\n const results: PhaseRunResult[] = [];\n // Nodes barred from flattening after a revert — persists across sweeps/phases.\n const flattenBarred = new Set<IRNodeId>();\n\n for (const phase of PHASE_ORDER) {\n const patterns = patternsForPhase(passes, phase);\n const budget = cfg.phases[phase] ?? cfg.maxIterations;\n const s: PhaseLoopState = {\n iterations: 0,\n converged: false,\n haltReason: 'converged',\n touched: new Set(),\n diagnostics: [],\n seen: new Set(),\n };\n\n if (patterns.length === 0) {\n s.converged = true;\n results.push(finalizePhase(phase, s, budget, cfg.onBudgetExhausted));\n continue;\n }\n\n while (s.iterations < budget) {\n s.iterations += 1;\n const applied = runSweep(\n state,\n patterns,\n ctx,\n factory,\n phase,\n s.iterations,\n s.touched,\n s.diagnostics,\n flattenBarred,\n );\n\n if (applied === 0) {\n s.converged = true;\n break;\n }\n\n if (cfg.detectOscillation) {\n const fp = docFingerprint(state.doc);\n if (s.seen.has(fp)) {\n s.haltReason = 'oscillation';\n s.diagnostics.push({\n code: 'DF_FIXPOINT_OSCILLATION',\n severity: 'warn',\n message: `phase '${phase}' oscillated; halting`,\n phase,\n iteration: s.iterations,\n });\n break;\n }\n s.seen.add(fp);\n }\n }\n\n results.push(finalizePhase(phase, s, budget, cfg.onBudgetExhausted));\n }\n\n return { doc: state.doc, results };\n}\n\n/** A {@link PassManager} that runs the given passes (carried on the manager instance). */\nexport function createPassManager(passes: readonly Pass[]): PassManager {\n return {\n run(doc: IRDocument, ctx: ApplyContext, config?: FixpointConfig): readonly PhaseRunResult[] {\n return runPasses(doc, passes, ctx, config).results;\n },\n };\n}\n","/**\n * @domflax/core — the pure, single-file pipeline.\n *\n * Wires injected interfaces together: {@link Frontend} → resolve → {@link PassManager} →\n * {@link Backend}. Core itself stays dependency-free; the resolver, frontend, and backend are all\n * supplied by the caller, so no heavy third-party libs ever reach this package.\n */\n\nimport type {\n ApplyContext,\n Backend,\n BackendContext,\n CodegenResult,\n Diagnostic,\n EditPlan,\n Frontend,\n FrontendParseContext,\n IRDocument,\n IRElement,\n PassPhase,\n Pipeline,\n PipelineInput,\n PipelineOutput,\n PipelineStats,\n SourceSpan,\n StyleMap,\n SyntheticClass,\n SyntheticSink,\n} from './types';\n\nimport { elementIds, getElement } from './builders';\nimport { createNullSelectorIndex, runPasses } from './pass-manager';\n\n/* ───────────────────────── synthetic sink ───────────────────────── */\n\n/** A minimal in-memory {@link SyntheticSink}: dedupes by className, drains in insertion order. */\nexport function createSyntheticSink(): SyntheticSink {\n const map = new Map<string, SyntheticClass>();\n return {\n register(s: SyntheticClass): string {\n if (!map.has(s.className)) map.set(s.className, s);\n return s.className;\n },\n drain(): readonly SyntheticClass[] {\n return [...map.values()];\n },\n };\n}\n\n/* ───────────────────────── resolve step ───────────────────────── */\n\nfunction staticClassTokens(el: IRElement): string[] {\n const out: string[] = [];\n for (const seg of el.classes.segments) {\n if (seg.kind === 'static') for (const t of seg.tokens) out.push(t.value);\n }\n return out;\n}\n\n/**\n * Populate each element's `computed` StyleMap from its author classes via the injected resolver.\n * Opaque/spread elements and elements without static classes are left untouched. Resolver throws\n * are isolated into diagnostics (a stub resolver may legitimately be NotImplemented).\n */\nfunction resolveStyles(\n doc: IRDocument,\n input: PipelineInput,\n diagnostics: Diagnostic[],\n): void {\n const { resolver, normalizer } = input;\n for (const id of elementIds(doc)) {\n const el = getElement(doc, id);\n if (!el || el.classes.opaque) continue;\n const tokens = staticClassTokens(el);\n if (tokens.length === 0) continue;\n try {\n const result = resolver.resolve({\n classes: tokens,\n element: {\n tagName: el.tag,\n namespace: el.namespace === 'svg' ? 'svg' : 'html',\n },\n });\n let styles: StyleMap = result.styles;\n try {\n styles = normalizer.normalizeStyleMap(styles);\n } catch {\n /* normalizer is optional/stubbed — keep raw styles */\n }\n el.computed = styles;\n for (const w of result.warnings) {\n diagnostics.push({\n code: 'DF_STYLE_CONFLICT_UNRESOLVED',\n severity: w.severity,\n message: w.message,\n nodeId: id,\n });\n }\n } catch (err) {\n diagnostics.push({\n code: 'DF_OP_PRECONDITION_FAILED',\n severity: 'debug',\n message: `resolve skipped for <${el.tag}>: ${String((err as Error)?.message ?? err)}`,\n nodeId: id,\n cause: err,\n });\n }\n }\n}\n\n/* ───────────────────────── the pipeline ───────────────────────── */\n\nconst ZERO_ITERATIONS: Readonly<Record<PassPhase, number>> = {\n flatten: 0,\n compress: 0,\n extract: 0,\n};\n\nclass DefaultPipeline implements Pipeline {\n run(input: PipelineInput): PipelineOutput {\n const startedAt = now();\n const diagnostics: Diagnostic[] = [];\n const report = (d: Diagnostic): void => {\n diagnostics.push(d);\n input.reporter?.report(d);\n };\n\n // 1. PARSE ────────────────────────────────────────────────────────────\n const parseCtx: FrontendParseContext = {\n id: input.id,\n kind: input.kind,\n resolver: input.resolver,\n normalizer: input.normalizer,\n config: { preserveComments: input.config?.preserveComments ?? true },\n onDiagnostic: report,\n };\n if (input.babelAst !== undefined) parseCtx.babelAst = input.babelAst;\n\n const parsed = input.frontend.parse(input.code, parseCtx);\n for (const d of parsed.diagnostics) report(d);\n const doc = parsed.doc;\n const nodesIn = doc.nodes.size;\n\n // 2. RESOLVE ──────────────────────────────────────────────────────────\n resolveStyles(doc, input, diagnostics);\n\n // 3. PASSES (fixpoint per phase) ──────────────────────────────────────\n const ctx: ApplyContext = {\n doc,\n safetyCeiling: input.config?.safety ?? 2,\n normalizer: input.normalizer,\n selectors: createNullSelectorIndex(),\n resolver: input.resolver,\n };\n const { doc: optimized, results } = runPasses(doc, input.passes, ctx, fixpointFrom(input));\n\n let opsApplied = 0;\n const iterations: Record<PassPhase, number> = { ...ZERO_ITERATIONS };\n for (const r of results) {\n iterations[r.phase] = r.iterations;\n for (const d of r.diagnostics) {\n diagnostics.push(d);\n input.reporter?.report(d);\n }\n opsApplied += r.touched.size;\n }\n\n // 4. PRINT ────────────────────────────────────────────────────────────\n const editPlan: EditPlan = {\n moduleId: input.id,\n ops: [],\n provenance: new Map(),\n };\n const backendCtx: BackendContext = {\n normalizer: input.normalizer,\n resolver: input.resolver,\n sink: createSyntheticSink(),\n eol: eolOf(optimized),\n onDiagnostic: report,\n };\n const printed: CodegenResult = input.backend.print(optimized, editPlan, backendCtx);\n for (const d of printed.diagnostics) {\n diagnostics.push(d);\n input.reporter?.report(d);\n }\n\n // 5. ASSEMBLE OUTPUT ──────────────────────────────────────────────────\n const stats: PipelineStats = {\n nodesIn,\n nodesOut: optimized.nodes.size,\n opsApplied,\n iterations,\n durationMs: now() - startedAt,\n };\n const touched: readonly SourceSpan[] = printed.edits.map((e) => e.span);\n\n return {\n code: printed.code,\n map: printed.map,\n changed: printed.code !== input.code,\n touched,\n diagnostics,\n stats,\n doc: optimized,\n editPlan,\n };\n }\n}\n\nfunction fixpointFrom(input: PipelineInput): import('./types').FixpointConfig | undefined {\n const fp = input.config?.fixpoint;\n if (!fp) return undefined;\n return {\n maxIterations: fp.maxIterations ?? 16,\n phases: fp.phases ?? {},\n onBudgetExhausted: fp.onBudgetExhausted ?? 'warn',\n detectOscillation: fp.detectOscillation ?? true,\n };\n}\n\nfunction eolOf(doc: IRDocument): '\\n' | '\\r\\n' {\n for (const src of doc.sources.values()) return src.eol;\n return '\\n';\n}\n\n// `performance` is a host global (node20 / browser) not covered by the ES2023 lib;\n// declared minimally so the runtime feature-detection below stays type-safe.\ndeclare const performance: { now(): number } | undefined;\n\nfunction now(): number {\n return typeof performance !== 'undefined' && typeof performance.now === 'function'\n ? performance.now()\n : Date.now();\n}\n\n/** Build the pure single-file {@link Pipeline}. */\nexport function createPipeline(): Pipeline {\n return new DefaultPipeline();\n}\n","/**\r\n * @domflax/core — the shared reverse-emit step (computed → className).\r\n *\r\n * The backend re-prints `className` from each element's {@link ClassList}, but the pass manager\r\n * records optimized styles on `computed`. This module folds those optimized computed styles back\r\n * into the element's static class tokens, and is the SINGLE source of truth shared by every\r\n * orchestrator (the `domflax` meta package, `@domflax/cli`, and the pattern auto-test harness) so\r\n * their pipelines cannot diverge.\r\n *\r\n * ## Only STYLE-DIRTY elements are re-emitted (never inflate a bystander)\r\n *\r\n * Reverse-emit runs ONLY on elements a pass actually rewrote the computed style of — `meta.styleDirty`\r\n * (a `setClassList`, a `mergeStyle` onto it, or an inherited fold into it). An element that was merely\r\n * `touched` as a STRUCTURAL BYSTANDER — a child was flattened/unwrapped, a sibling merged/moved, a\r\n * node inserted next to it — never has its own computed changed, so its `class` attribute is left\r\n * BYTE-FOR-BYTE IDENTICAL. This is what stops a real custom-CSS site from INFLATING: an unchanged\r\n * `<div class=\"product-art\">` can no longer gain a redundant `.bg-cream-deep` just because an inert\r\n * child next to it was flattened.\r\n *\r\n * ## REPLACE, not append — with retained-class coverage SUBTRACTED\r\n *\r\n * For every style-dirty, rewritable (non-opaque, non-dynamic) element we ask the resolver for the\r\n * MINIMAL class set reproducing the element's computed style, then REPLACE the element's droppable\r\n * tokens with it — rather than appending. Replacing is what lets a compress pass actually shorten\r\n * output: `px-4 py-4` collapses to `p-4`, equal `w/h` to `size-*`, the four insets to `inset-0`, and\r\n * fully-overridden duplicates simply disappear.\r\n *\r\n * Crucially, before choosing what to emit we SUBTRACT the style already supplied by the element's\r\n * RETAINED (kept, non-droppable) classes: we emit only for the RESIDUAL declarations those classes do\r\n * not already reproduce. So reverse-emit can never materialize a utility for a property a semantic\r\n * class the element keeps already sets (the `.product-art` background is never re-added as\r\n * `.bg-cream-deep`). Output therefore never grows with a class whose contribution is already covered.\r\n *\r\n * ## Droppability gate (never lose a load-bearing class)\r\n *\r\n * A token is only removed when `resolver.selectorUsage(token).droppable` is true — i.e. it is a\r\n * plain, resolver-owned utility whose entire contribution is reproducible from `computed`. Tokens\r\n * that are unknown to the resolver, opaque (combinator/at-rule utilities whose effect never folds\r\n * onto the element's own box), variant-bound, or referenced by a custom-CSS selector are NOT\r\n * droppable and are preserved verbatim. As a safety net, if the residual `emit` produces nothing at\r\n * all we leave the element's tokens untouched (a resolver that failed to load must never erase\r\n * classes).\r\n */\r\n\r\nimport { elementIds, getElement } from './builders';\r\nimport { createSyntheticSink } from './pipeline';\r\nimport type {\r\n ClassList,\r\n ClassSegment,\r\n ClassToken,\r\n ConditionKey,\r\n CssProperty,\r\n EmitContext,\r\n IRDocument,\r\n SafetyLevel,\r\n StyleBlock,\r\n StyleDecl,\r\n StyleMap,\r\n StyleNormalizer,\r\n StyleResolver,\r\n} from './types';\r\n\r\n/** All static class tokens of a {@link ClassList}, in source order. */\r\nfunction staticTokensOf(cl: ClassList): string[] {\r\n const out: string[] = [];\r\n for (const seg of cl.segments) {\r\n if (seg.kind === 'static') for (const t of seg.tokens) out.push(t.value);\r\n }\r\n return out;\r\n}\r\n\r\n/** A rewritable static {@link ClassList} over `tokens`, preserving the previous list's spans. */\r\nfunction staticClassList(prev: ClassList, tokens: readonly string[]): ClassList {\r\n const classTokens: ClassToken[] = tokens.map((value) => ({ value }));\r\n const seg: ClassSegment = { kind: 'static', tokens: classTokens };\r\n return {\r\n form: 'string-literal',\r\n segments: [seg],\r\n valueSpan: prev.valueSpan,\r\n attrSpan: prev.attrSpan,\r\n hasDynamic: false,\r\n opaque: false,\r\n rewritable: true,\r\n };\r\n}\r\n\r\n/** Two token lists are equal iff same length and same tokens in the same order. */\r\nfunction sameTokens(a: readonly string[], b: readonly string[]): boolean {\r\n if (a.length !== b.length) return false;\r\n for (let i = 0; i < a.length; i += 1) if (a[i] !== b[i]) return false;\r\n return true;\r\n}\r\n\r\n/**\r\n * Return the RESIDUAL of `computed` after removing every declaration the element's retained classes\r\n * already reproduce EXACTLY (same value + `!important`, in the same style condition). What's left is\r\n * the set of declarations the emitted classes must actually cover — so reverse-emit never re-adds a\r\n * utility for a property a kept class already supplies. A declaration whose retained-class value\r\n * DIFFERS from the computed one (i.e. the class was overridden) is kept in the residual: the final\r\n * value still has to be emitted by something.\r\n */\r\nfunction residualStyle(computed: StyleMap, covered: StyleMap, norm: StyleNormalizer): StyleMap {\r\n const cov = norm.normalizeStyleMap(covered);\r\n const blocks = new Map<ConditionKey, StyleBlock>();\r\n for (const [key, block] of norm.normalizeStyleMap(computed).blocks) {\r\n const covBlock = cov.blocks.get(key);\r\n const decls = new Map<CssProperty, StyleDecl>();\r\n for (const [prop, decl] of block.decls) {\r\n const covDecl = covBlock?.decls.get(prop);\r\n if (covDecl && covDecl.value === decl.value && covDecl.important === decl.important) continue;\r\n decls.set(prop, decl);\r\n }\r\n if (decls.size > 0) blocks.set(key, { condition: block.condition, decls });\r\n }\r\n return { blocks };\r\n}\r\n\r\n/** The rendered `class=\"…\"` byte length of a token list (tokens joined by single spaces). */\r\nfunction joinedLength(tokens: readonly string[]): number {\r\n if (tokens.length === 0) return 0;\r\n let len = tokens.length - 1; // joining spaces\r\n for (const t of tokens) len += t.length;\r\n return len;\r\n}\r\n\r\n/** SafetyLevel a `compress/*` rewrite carried — an opaque (floor-0) element is off-limits to it. */\r\nconst COMPRESS_FLOOR: SafetyLevel = 1;\r\n\r\n/**\r\n * Fold each rewritable element's computed style back into the MINIMAL static class-token set — the\r\n * general compress engine (see module docs + {@link import('./compress-engine')}). Mutates `doc`.\r\n *\r\n * TWO kinds of element are processed, and their guarantees differ:\r\n *\r\n * • STYLE-DIRTY — a pass rewrote this element's own computed style (a flatten fold / merge). Its\r\n * computed CHANGED, so its classes MUST be re-derived to represent the new style (which may\r\n * legitimately need MORE tokens than before). Handled exactly as it always was.\r\n *\r\n * • COMPRESS-ONLY — no pass touched it; we run the exact-cover engine purely to SHORTEN its class\r\n * string (`px-4 py-4 → p-4`, drop a redundant class, pick a custom class that covers the same\r\n * style, …). This is a pure class-string rewrite that must NEVER change the render or GROW the\r\n * output, so it carries two extra hard backstops below: the rewritten set must re-resolve to the\r\n * element's exact computed style, and it must not be longer than the original. A structural\r\n * bystander with no compression opportunity therefore keeps its `class` attribute byte-for-byte.\r\n */\r\nexport function syncClassesFromComputed(\r\n doc: IRDocument,\r\n resolver: StyleResolver,\r\n norm: StyleNormalizer,\r\n): void {\r\n const sink = createSyntheticSink();\r\n // A token is safe to drop/replace only when the resolver OWNS it (an unknown / JS-hook / typo class\r\n // is preserved verbatim) AND its whole contribution is a plain, reproducible subject utility. Owning\r\n // is checked explicitly so a custom-CSS resolver that has no usage record for an unknown token (its\r\n // conservative default is \"droppable\") can never erase it.\r\n const isDroppable = (t: string): boolean =>\r\n resolver.owns(t) && resolver.selectorUsage(t).droppable;\r\n\r\n for (const id of elementIds(doc)) {\r\n const el = getElement(doc, id);\r\n if (!el) continue;\r\n if (el.classes.opaque || el.classes.hasDynamic) continue;\r\n\r\n const compressOnly = !el.meta.styleDirty;\r\n // COMPRESS-ONLY mirrors the compress patterns' applier gate: an opaque (floor-0) element — an HTML\r\n // `id`/`on*=`/`<script>` node, a synthetic wrapper — is never rewritten. STYLE-DIRTY elements were\r\n // already rewritten by an op the applier authorized, so their floor is irrelevant here.\r\n if (compressOnly && el.meta.safetyFloor < COMPRESS_FLOOR) continue;\r\n\r\n const tokens = staticTokensOf(el.classes);\r\n if (tokens.length === 0) continue;\r\n\r\n // Tokens that are ALWAYS retained (unknown / opaque / variant / selector-bound). Their style is\r\n // subtracted from the computed map so we never re-emit a class for a property they already cover.\r\n const retained = tokens.filter((t) => !isDroppable(t));\r\n // A pure-compress element with NOTHING droppable can never shorten — leave it byte-for-byte.\r\n if (compressOnly && retained.length === tokens.length) continue;\r\n\r\n const covered = retained.length > 0 ? resolver.resolve({ classes: retained }).styles : null;\r\n const target = covered ? residualStyle(el.computed, covered, norm) : el.computed;\r\n\r\n // Minimal class set reproducing the residual (computed MINUS retained-class coverage).\r\n const ctx: EmitContext = { normalizer: norm, sink };\r\n const emitted = resolver.emit(target, ctx).classes;\r\n // A resolver that reverse-synthesized nothing must never erase the element's classes.\r\n if (emitted.length === 0) continue;\r\n\r\n const emittedSet = new Set(emitted);\r\n const next: string[] = [];\r\n const seen = new Set<string>();\r\n\r\n // 1. Keep each existing token that is either NOT droppable (unknown / opaque / variant /\r\n // selector-bound) or still part of the emitted minimal set — preserving source order.\r\n for (const t of tokens) {\r\n if (seen.has(t)) continue;\r\n const keep = emittedSet.has(t) || !isDroppable(t);\r\n if (keep) {\r\n next.push(t);\r\n seen.add(t);\r\n }\r\n }\r\n // 2. Append any newly-emitted classes not already present, in emit order.\r\n for (const c of emitted) {\r\n if (seen.has(c)) continue;\r\n next.push(c);\r\n seen.add(c);\r\n }\r\n\r\n if (sameTokens(next, tokens)) continue; // no churn when nothing actually changed\r\n\r\n if (compressOnly) {\r\n // Hard correctness backstop for a pure compress: the rewritten token set must reproduce the\r\n // element's EXACT computed style (never change a pixel) and must NOT be longer than the original\r\n // (never inflate). Either failing ⇒ keep the original classes untouched.\r\n if (!norm.equals(resolver.resolve({ classes: next }).styles, el.computed)) continue;\r\n if (joinedLength(next) > joinedLength(tokens)) continue;\r\n }\r\n\r\n el.classes = staticClassList(el.classes, next);\r\n }\r\n}\r\n","/**\r\n * @domflax/core — the general COMPRESS ENGINE: a minimal-string exact-cover solver.\r\n *\r\n * ## What it replaces\r\n *\r\n * The hand-written compress patterns (padding/margin/inset/size/gap/place/border/overflow/…-shorthand\r\n * and dedupe-classes) each recognised ONE shorthand shape and folded it. This module subsumes them\r\n * ALL with a SINGLE, provider-uniform algorithm: given an element's target computed style, find the\r\n * class set that reproduces it EXACTLY with the SHORTEST total `class=\"…\"` string, searching the whole\r\n * vocabulary (every Tailwind utility AND the project's custom-CSS classes at once).\r\n *\r\n * ## The algorithm (per element, per style-condition — all folded into one solve)\r\n *\r\n * Given a normalized target StyleMap `U`:\r\n * 1. UNIVERSE = the set of `(conditionKey, property, value, important)` tuples in `U`\r\n * (a `tupleKey` per {@link tupleKey}).\r\n * 2. CANDIDATES = the vocabulary classes whose FULL normalized-longhand declaration set is a SUBSET\r\n * of `U` (never introduces a declaration `U` does not already contain). The caller feeds the\r\n * vocabulary; the element's own droppable tokens are part of it, guaranteeing feasibility and the\r\n * \"never worse than the original\" property.\r\n * 3. COST(class) = token length + 1 (the token plus its joining space) — so minimizing total cost\r\n * minimizes the rendered `class=\"…\"` byte length exactly.\r\n * 4. MIN-COST EXACT COVER via bitmask DP over `U`'s tuples: `dp[coveredMask]` = least cost reaching\r\n * that coverage; each transition adds one candidate's mask. Because every candidate AGREES with\r\n * `U` on every tuple it sets, ANY full cover reproduces `U` at the tuple level.\r\n * 5. `|U|` is BOUNDED ({@link DEFAULT_MAX_UNIVERSE}); a larger condition-block returns `null` so the\r\n * caller falls back to its greedy emit for that element.\r\n *\r\n * The **correctness backstop** (re-resolve the chosen set and assert it equals `U` exactly) lives in\r\n * each resolver's `emit` — it owns the forward `resolve`, and running the check there keeps this core\r\n * helper pure and provider-agnostic. A chosen set that fails the backstop is discarded and the greedy\r\n * emit is used instead, so a set that does not reproduce `U` is NEVER emitted.\r\n */\r\n\r\nimport type { StyleMap, StyleNormalizer } from './types';\r\n\r\n/** Field separator for {@link tupleKey} — a control char that never appears in CSS text. */\r\nconst SEP = '\u0001';\r\n\r\n/**\r\n * The canonical key for one normalized declaration under one style condition: the atomic unit both the\r\n * target universe and every vocabulary class are expressed in. Equal keys ⇔ the SAME declaration.\r\n */\r\nexport function tupleKey(\r\n condition: string,\r\n property: string,\r\n value: string,\r\n important: boolean,\r\n): string {\r\n return `${condition}${SEP}${property}${SEP}${value}${SEP}${important ? '1' : '0'}`;\r\n}\r\n\r\n/**\r\n * Flatten a StyleMap into its set of {@link tupleKey}s (normalizing first). This is how BOTH the target\r\n * universe and each vocabulary class's declarations are lowered, so a class's tuples can be tested for\r\n * subset-membership in the universe by plain string equality.\r\n */\r\nexport function styleMapTuples(map: StyleMap, norm: StyleNormalizer): string[] {\r\n const out: string[] = [];\r\n const normalized = norm.normalizeStyleMap(map);\r\n for (const [ck, block] of normalized.blocks) {\r\n for (const [prop, decl] of block.decls) {\r\n out.push(tupleKey(String(ck), String(prop), String(decl.value), decl.important));\r\n }\r\n }\r\n return out;\r\n}\r\n\r\n/** One vocabulary entry: a class token and the {@link tupleKey}s its full declaration set produces. */\r\nexport interface CoverClass {\r\n readonly token: string;\r\n readonly tuples: readonly string[];\r\n}\r\n\r\nexport interface MinCoverOptions {\r\n /** Upper bound on `|U|`; above it the DP is skipped (`null`) so the caller uses its greedy emit. */\r\n readonly maxUniverse?: number;\r\n}\r\n\r\n/**\r\n * The largest universe the bitmask DP will solve. 20 tuples ⇒ a `2^20` (~1M) DP table, comfortably\r\n * fast and bounded in memory; a heavier element (rare) falls back to the resolver's greedy emit.\r\n */\r\nexport const DEFAULT_MAX_UNIVERSE = 20;\r\n\r\n/**\r\n * Solve the minimal-string exact cover of `universe` using `vocabulary`.\r\n *\r\n * Returns the chosen class tokens (sorted, de-duplicated) whose union reproduces `universe` EXACTLY at\r\n * least total string cost, or `null` when there is no exact cover OR the universe exceeds the bound (in\r\n * both cases the caller falls back to its greedy emit). An empty universe yields `[]`.\r\n *\r\n * Pure and provider-agnostic: the caller performs the re-resolve correctness backstop.\r\n */\r\nexport function minStringCover(\r\n universe: readonly string[],\r\n vocabulary: Iterable<CoverClass>,\r\n options: MinCoverOptions = {},\r\n): readonly string[] | null {\r\n const uniq = [...new Set(universe)];\r\n if (uniq.length === 0) return [];\r\n const n = uniq.length;\r\n const max = options.maxUniverse ?? DEFAULT_MAX_UNIVERSE;\r\n if (n > max) return null;\r\n\r\n const bitOf = new Map<string, number>();\r\n uniq.forEach((t, i) => bitOf.set(t, i));\r\n\r\n interface Cand {\r\n readonly token: string;\r\n readonly mask: number;\r\n readonly cost: number;\r\n }\r\n // A candidate is any vocabulary class ALL of whose tuples lie in the universe (a subset fit). Two\r\n // classes with the same coverage mask are collapsed to the cheaper (shorter, then lexicographically\r\n // smaller) one — an equal-mask class can never help beyond the cheapest representative.\r\n const byMask = new Map<number, Cand>();\r\n for (const entry of vocabulary) {\r\n if (entry.tuples.length === 0) continue;\r\n let mask = 0;\r\n let ok = true;\r\n for (const t of entry.tuples) {\r\n const b = bitOf.get(t);\r\n if (b === undefined) {\r\n ok = false;\r\n break;\r\n }\r\n mask |= 1 << b;\r\n }\r\n if (!ok || mask === 0) continue;\r\n const cost = entry.token.length + 1;\r\n const prev = byMask.get(mask);\r\n if (!prev || cost < prev.cost || (cost === prev.cost && entry.token < prev.token)) {\r\n byMask.set(mask, { token: entry.token, mask, cost });\r\n }\r\n }\r\n const cands = [...byMask.values()];\r\n if (cands.length === 0) return null;\r\n\r\n const full = (1 << n) - 1;\r\n\r\n // For each universe bit, the candidates that cover it — the DP only ever expands the lowest still-\r\n // uncovered bit, which bounds the branching without missing any optimum.\r\n const byBit: number[][] = Array.from({ length: n }, () => []);\r\n cands.forEach((c, ci) => {\r\n for (let b = 0; b < n; b += 1) if (c.mask & (1 << b)) byBit[b]!.push(ci);\r\n });\r\n\r\n const size = full + 1;\r\n const dp = new Float64Array(size).fill(Infinity);\r\n const fromCand = new Int32Array(size).fill(-1);\r\n const fromMask = new Int32Array(size).fill(-1);\r\n dp[0] = 0;\r\n\r\n for (let mask = 0; mask < full; mask += 1) {\r\n const cur = dp[mask]!;\r\n if (!Number.isFinite(cur)) continue;\r\n // Lowest uncovered bit — every optimal cover must include a candidate covering it.\r\n let b = 0;\r\n while (b < n && mask & (1 << b)) b += 1;\r\n for (const ci of byBit[b]!) {\r\n const c = cands[ci]!;\r\n const nm = mask | c.mask;\r\n const cost = cur + c.cost;\r\n if (cost < dp[nm]!) {\r\n dp[nm] = cost;\r\n fromCand[nm] = ci;\r\n fromMask[nm] = mask;\r\n }\r\n }\r\n }\r\n\r\n if (!Number.isFinite(dp[full]!)) return null;\r\n\r\n const chosen: string[] = [];\r\n let m = full;\r\n while (m !== 0) {\r\n const ci = fromCand[m]!;\r\n if (ci < 0) return null;\r\n chosen.push(cands[ci]!.token);\r\n m = fromMask[m]!;\r\n }\r\n return [...new Set(chosen)].sort();\r\n}\r\n","/**\r\n * @domflax/pattern-kit — the shared StyleMap normalizer.\r\n *\r\n * A single, syntactic-only {@link StyleNormalizer} implementation that core, the patterns, and the\r\n * verifier all reuse so they agree, byte-for-byte, on what two style declarations \"mean\". It NEVER\r\n * resolves initial/inherited/computed defaults (that is the verifier's job) — it only:\r\n *\r\n * • canonicalizes colors (`transparent` ⇒ `rgba(0, 0, 0, 0)`, hex lower-cased + 3→6 expanded,\r\n * `rgb()/rgba()/hsl()/hsla()` argument spacing normalized),\r\n * • canonicalizes units (whitespace collapsed, zero-lengths `0px`/`0%`/… ⇒ `0`),\r\n * • expands a fixed set of box shorthands to longhands (`padding`/`margin`/`inset`/`border-width`\r\n * into their four sides, `gap` into `row-gap`/`column-gap`),\r\n * • orders declarations by property for stable comparison.\r\n *\r\n * Dependency-free: only `@domflax/core` (types + the StyleMap builder helpers).\r\n */\r\n\r\nimport type {\r\n CssProperty,\r\n CssValue,\r\n ConditionKey,\r\n InheritedPropertyTable,\r\n StyleBlock,\r\n StyleDecl,\r\n StyleMap,\r\n StyleNormalizer,\r\n} from '@domflax/core';\r\n\r\nimport { conditionKey, emptyStyleMap } from '@domflax/core';\r\n\r\n/* ───────────────────────── inherited-property table ───────────────────────── */\r\n\r\n/**\r\n * Canonical, versioned set of inherited CSS longhands. Any author custom property (`--*`) is\r\n * also treated as inherited via the `isInherited` predicate.\r\n */\r\nconst INHERITED_PROPERTIES: readonly string[] = [\r\n 'azimuth',\r\n 'border-collapse',\r\n 'border-spacing',\r\n 'caption-side',\r\n 'color',\r\n 'cursor',\r\n 'direction',\r\n 'empty-cells',\r\n 'font-family',\r\n 'font-feature-settings',\r\n 'font-kerning',\r\n 'font-size',\r\n 'font-size-adjust',\r\n 'font-stretch',\r\n 'font-style',\r\n 'font-variant',\r\n 'font-variant-caps',\r\n 'font-variant-numeric',\r\n 'font-weight',\r\n 'hyphens',\r\n 'letter-spacing',\r\n 'line-height',\r\n 'list-style-image',\r\n 'list-style-position',\r\n 'list-style-type',\r\n 'orphans',\r\n 'overflow-wrap',\r\n 'quotes',\r\n 'tab-size',\r\n 'text-align',\r\n 'text-align-last',\r\n 'text-decoration-color',\r\n 'text-indent',\r\n 'text-justify',\r\n 'text-rendering',\r\n 'text-shadow',\r\n 'text-transform',\r\n 'text-underline-position',\r\n 'visibility',\r\n 'white-space',\r\n 'widows',\r\n 'word-break',\r\n 'word-spacing',\r\n 'writing-mode',\r\n '-webkit-font-smoothing',\r\n];\r\n\r\nfunction createInheritedTable(): InheritedPropertyTable {\r\n const properties = new Set<CssProperty>(INHERITED_PROPERTIES as unknown as CssProperty[]);\r\n return {\r\n version: 'domflax-inherited@1',\r\n properties,\r\n isInherited(property: CssProperty): boolean {\r\n // Author custom properties (`--*`) inherit by definition.\r\n return String(property).startsWith('--') || properties.has(property);\r\n },\r\n };\r\n}\r\n\r\n/* ───────────────────────── value canonicalization ───────────────────────── */\r\n\r\nconst ZERO_LENGTH_RE =\r\n /\\b0(?:px|em|rem|ex|ch|vh|vw|vmin|vmax|vi|vb|pt|pc|cm|mm|in|q|lh|rlh|fr|deg|rad|turn|s|ms|%)\\b/g;\r\n\r\nconst FUNC_ARGS_RE = /\\b(rgba?|hsla?|hwb|lab|lch|oklab|oklch)\\(([^()]*)\\)/gi;\r\n\r\nconst RELATIVE_UNIT_RE = /(?:\\d*\\.?\\d+)(?:em|ex|ch|lh)\\b|%/i;\r\n\r\n/**\r\n * Pure, syntactic value canonicalization. Idempotent: `canon(canon(v)) === canon(v)`.\r\n */\r\nfunction canonValue(raw: string): string {\r\n let v = raw.trim().replace(/\\s+/g, ' ');\r\n\r\n // Lower-case hex colors (#abc / #aabbcc / #aabbccff).\r\n v = v.replace(/#([0-9a-fA-F]{3,8})\\b/g, (_m, hex: string) => '#' + hex.toLowerCase());\r\n\r\n // Expand 3-digit hex (#abc → #aabbcc) — only when exactly 3 hex digits.\r\n v = v.replace(\r\n /#([0-9a-f])([0-9a-f])([0-9a-f])(?![0-9a-f])/g,\r\n (_m, r: string, g: string, b: string) => `#${r}${r}${g}${g}${b}${b}`,\r\n );\r\n\r\n // Canonical fully-transparent color.\r\n v = v.replace(/\\btransparent\\b/gi, 'rgba(0, 0, 0, 0)');\r\n v = v.replace(/#00000000\\b/g, 'rgba(0, 0, 0, 0)');\r\n\r\n // Collapse zero lengths/angles/times to a bare `0`.\r\n v = v.replace(ZERO_LENGTH_RE, '0');\r\n\r\n // Normalize the argument spacing of color/space functions: single space after each comma.\r\n v = v.replace(FUNC_ARGS_RE, (_m, fn: string, args: string) => {\r\n const parts = args\r\n .split(',')\r\n .map((s) => s.trim())\r\n .filter((s) => s.length > 0);\r\n return `${fn.toLowerCase()}(${parts.join(', ')})`;\r\n });\r\n\r\n return v;\r\n}\r\n\r\n/** True when the (canonicalized) value uses a parent-relative unit (em/ex/ch/lh/%). */\r\nfunction isRelativeValue(value: string): boolean {\r\n return RELATIVE_UNIT_RE.test(value);\r\n}\r\n\r\n/* ───────────────────────── shorthand expansion ───────────────────────── */\r\n\r\n/** Box-model shorthands whose 1–4 value form expands to four explicit sides. */\r\nconst BOX_SIDES: Readonly<Record<string, readonly [string, string, string, string]>> = {\r\n padding: ['padding-top', 'padding-right', 'padding-bottom', 'padding-left'],\r\n margin: ['margin-top', 'margin-right', 'margin-bottom', 'margin-left'],\r\n inset: ['top', 'right', 'bottom', 'left'],\r\n 'scroll-margin': [\r\n 'scroll-margin-top',\r\n 'scroll-margin-right',\r\n 'scroll-margin-bottom',\r\n 'scroll-margin-left',\r\n ],\r\n 'scroll-padding': [\r\n 'scroll-padding-top',\r\n 'scroll-padding-right',\r\n 'scroll-padding-bottom',\r\n 'scroll-padding-left',\r\n ],\r\n 'border-width': [\r\n 'border-top-width',\r\n 'border-right-width',\r\n 'border-bottom-width',\r\n 'border-left-width',\r\n ],\r\n 'border-style': [\r\n 'border-top-style',\r\n 'border-right-style',\r\n 'border-bottom-style',\r\n 'border-left-style',\r\n ],\r\n 'border-color': [\r\n 'border-top-color',\r\n 'border-right-color',\r\n 'border-bottom-color',\r\n 'border-left-color',\r\n ],\r\n // `border-radius` 1–4 value form maps to the four CORNERS (TL, TR, BR, BL) — the same positional\r\n // pattern boxFourSides implements. Only the slash-free form is expanded (see expandShorthand).\r\n 'border-radius': [\r\n 'border-top-left-radius',\r\n 'border-top-right-radius',\r\n 'border-bottom-right-radius',\r\n 'border-bottom-left-radius',\r\n ],\r\n};\r\n\r\n/** Two-axis shorthands whose 1–2 value form expands to an explicit [x/block-start, y/inline-…] pair. */\r\nconst AXIS_PAIRS: Readonly<Record<string, readonly [string, string]>> = {\r\n overflow: ['overflow-x', 'overflow-y'],\r\n 'overscroll-behavior': ['overscroll-behavior-x', 'overscroll-behavior-y'],\r\n 'place-items': ['align-items', 'justify-items'],\r\n 'place-content': ['align-content', 'justify-content'],\r\n 'place-self': ['align-self', 'justify-self'],\r\n};\r\n\r\n/**\r\n * LOGICAL box shorthands (Tailwind v4 emits these for `px-*`/`py-*`/`mx-*`/`inset-x-*`, …). Their\r\n * SINGLE-value form is direction-INDEPENDENT — `padding-inline: X` sets left AND right to the same `X`\r\n * regardless of writing mode — so it is canonicalized to the physical side pair, letting the compress\r\n * engine reconcile v4's `px-4 py-4` with the physical `p-4` (which expands via {@link BOX_SIDES}).\r\n * A TWO-value logical form (`A B`) is direction-DEPENDENT (start/end ≠ left/right under RTL) and is\r\n * left verbatim — Tailwind never generates it from a single utility, so no compression is lost.\r\n */\r\nconst LOGICAL_PAIRS: Readonly<Record<string, readonly [string, string]>> = {\r\n 'padding-inline': ['padding-left', 'padding-right'],\r\n 'padding-block': ['padding-top', 'padding-bottom'],\r\n 'margin-inline': ['margin-left', 'margin-right'],\r\n 'margin-block': ['margin-top', 'margin-bottom'],\r\n 'inset-inline': ['left', 'right'],\r\n 'inset-block': ['top', 'bottom'],\r\n 'scroll-padding-inline': ['scroll-padding-left', 'scroll-padding-right'],\r\n 'scroll-padding-block': ['scroll-padding-top', 'scroll-padding-bottom'],\r\n 'scroll-margin-inline': ['scroll-margin-left', 'scroll-margin-right'],\r\n 'scroll-margin-block': ['scroll-margin-top', 'scroll-margin-bottom'],\r\n};\r\n\r\n/** Split on top-level whitespace, keeping `fn(a, b)` groups intact. */\r\nfunction splitTopLevel(value: string): string[] {\r\n const out: string[] = [];\r\n let depth = 0;\r\n let cur = '';\r\n for (const ch of value) {\r\n if (ch === '(') depth += 1;\r\n else if (ch === ')') depth = Math.max(0, depth - 1);\r\n if (depth === 0 && /\\s/.test(ch)) {\r\n if (cur.length > 0) {\r\n out.push(cur);\r\n cur = '';\r\n }\r\n continue;\r\n }\r\n cur += ch;\r\n }\r\n if (cur.length > 0) out.push(cur);\r\n return out;\r\n}\r\n\r\n/** Map a 1–4 value box shorthand onto its [top, right, bottom, left] sides. */\r\nfunction boxFourSides(values: readonly string[]): [string, string, string, string] {\r\n const [a, b, c, d] = values;\r\n switch (values.length) {\r\n case 1:\r\n return [a!, a!, a!, a!];\r\n case 2:\r\n return [a!, b!, a!, b!];\r\n case 3:\r\n return [a!, b!, c!, b!];\r\n default:\r\n return [a!, b!, c!, d!];\r\n }\r\n}\r\n\r\n/** Expand one declaration into longhand `[property, value]` pairs (single pair if not shorthand). */\r\nfunction expandShorthand(prop: string, value: string): Array<[string, string]> {\r\n // `border-radius` with a `/` carries distinct horizontal/vertical radii per corner — a shape our\r\n // per-corner single-value longhands cannot represent — so it is left as the shorthand verbatim.\r\n if (prop === 'border-radius' && value.includes('/')) return [[prop, value]];\r\n\r\n const box = BOX_SIDES[prop];\r\n if (box) {\r\n const parts = splitTopLevel(value);\r\n if (parts.length >= 1 && parts.length <= 4) {\r\n const sides = boxFourSides(parts);\r\n return box.map((p, i) => [p, sides[i]!] as [string, string]);\r\n }\r\n return [[prop, value]];\r\n }\r\n\r\n const axis = AXIS_PAIRS[prop];\r\n if (axis) {\r\n const parts = splitTopLevel(value);\r\n if (parts.length === 1) return [[axis[0], parts[0]!], [axis[1], parts[0]!]];\r\n if (parts.length === 2) return [[axis[0], parts[0]!], [axis[1], parts[1]!]];\r\n return [[prop, value]];\r\n }\r\n\r\n const logical = LOGICAL_PAIRS[prop];\r\n if (logical) {\r\n const parts = splitTopLevel(value);\r\n // Only the direction-independent single-value form maps to physical sides (see LOGICAL_PAIRS).\r\n if (parts.length === 1) return [[logical[0], parts[0]!], [logical[1], parts[0]!]];\r\n return [[prop, value]];\r\n }\r\n\r\n if (prop === 'gap' || prop === 'grid-gap') {\r\n const parts = splitTopLevel(value);\r\n if (parts.length === 1) {\r\n return [\r\n ['row-gap', parts[0]!],\r\n ['column-gap', parts[0]!],\r\n ];\r\n }\r\n if (parts.length === 2) {\r\n return [\r\n ['row-gap', parts[0]!],\r\n ['column-gap', parts[1]!],\r\n ];\r\n }\r\n return [[prop, value]];\r\n }\r\n\r\n return [[prop, value]];\r\n}\r\n\r\n/* ───────────────────────── the normalizer ───────────────────────── */\r\n\r\nfunction makeDecl(\r\n table: InheritedPropertyTable,\r\n prop: string,\r\n rawValue: string,\r\n important: boolean,\r\n): StyleDecl {\r\n const property = prop.trim().toLowerCase() as CssProperty;\r\n const value = canonValue(rawValue) as CssValue;\r\n return {\r\n property,\r\n value,\r\n important,\r\n relativeToParent: isRelativeValue(value),\r\n inherited: table.isInherited(property),\r\n };\r\n}\r\n\r\nexport function createNormalizer(): StyleNormalizer {\r\n const inherited = createInheritedTable();\r\n\r\n const normalizeDeclaration = (\r\n prop: string,\r\n value: string,\r\n important: boolean,\r\n ): readonly StyleDecl[] => {\r\n const p = prop.trim().toLowerCase();\r\n const expanded = expandShorthand(p, value.trim());\r\n return expanded.map(([lp, lv]) => makeDecl(inherited, lp, lv, important));\r\n };\r\n\r\n const normalizeValue = (prop: CssProperty, raw: string): CssValue => {\r\n void prop;\r\n return canonValue(raw) as CssValue;\r\n };\r\n\r\n const normalizeStyleMap = (sm: StyleMap): StyleMap => {\r\n const blocks = new Map<ConditionKey, StyleBlock>();\r\n for (const block of sm.blocks.values()) {\r\n const decls = new Map<CssProperty, StyleDecl>();\r\n // Re-canonicalize every value and re-key (the decls are already longhand).\r\n for (const decl of block.decls.values()) {\r\n const next: StyleDecl = {\r\n ...decl,\r\n value: canonValue(String(decl.value)) as CssValue,\r\n relativeToParent: isRelativeValue(String(decl.value)),\r\n inherited: inherited.isInherited(decl.property),\r\n };\r\n decls.set(next.property, next);\r\n }\r\n // Property-sorted for deterministic iteration/serialization.\r\n const sorted = new Map<CssProperty, StyleDecl>(\r\n [...decls.entries()].sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)),\r\n );\r\n const key = conditionKey(block.condition);\r\n blocks.set(key, { condition: block.condition, decls: sorted });\r\n }\r\n return { blocks };\r\n };\r\n\r\n const equals = (a: StyleMap, b: StyleMap): boolean => {\r\n const na = normalizeStyleMap(a);\r\n const nb = normalizeStyleMap(b);\r\n if (na.blocks.size !== nb.blocks.size) return false;\r\n for (const [key, blockA] of na.blocks) {\r\n const blockB = nb.blocks.get(key);\r\n if (!blockB) return false;\r\n if (blockA.decls.size !== blockB.decls.size) return false;\r\n for (const [prop, declA] of blockA.decls) {\r\n const declB = blockB.decls.get(prop);\r\n if (!declB) return false;\r\n if (declA.value !== declB.value || declA.important !== declB.important) return false;\r\n }\r\n }\r\n return true;\r\n };\r\n\r\n return {\r\n version: 'domflax-normalizer@1',\r\n normalizeDeclaration,\r\n normalizeValue,\r\n normalizeStyleMap,\r\n equals,\r\n inherited,\r\n };\r\n}\r\n\r\n/** The shared, process-wide normalizer instance reused by core / patterns / verify. */\r\nexport const normalizer: StyleNormalizer = createNormalizer();\r\n\r\n/* ───────────────────────── superset helper (used by `computed()` matcher) ───────────────────────── */\r\n\r\n/**\r\n * True when `full` contains every declaration of `partial` with an equal normalized value\r\n * (a per-condition, per-declaration superset test). Both maps are normalized first so the\r\n * comparison is meaning-based, not string-based. Empty `partial` ⇒ always `true`.\r\n */\r\nexport function isStyleSuperset(\r\n full: StyleMap,\r\n partial: StyleMap,\r\n norm: StyleNormalizer = normalizer,\r\n): boolean {\r\n const nf = norm.normalizeStyleMap(full);\r\n const np = norm.normalizeStyleMap(partial);\r\n for (const [key, want] of np.blocks) {\r\n const have = nf.blocks.get(key) ?? nf.blocks.get(conditionKey(want.condition));\r\n if (!have) return false;\r\n for (const [prop, decl] of want.decls) {\r\n const got = have.decls.get(prop);\r\n if (!got || got.value !== decl.value) return false;\r\n }\r\n }\r\n return true;\r\n}\r\n\r\n/** Re-exported for callers that want to (de)construct keys without importing core directly. */\r\nexport { emptyStyleMap };\r\n","/**\r\n * @domflax/pattern-kit — composable matcher vocabulary.\r\n *\r\n * A {@link Matcher} is a PURE predicate over a node + its {@link MatchContext}. Matchers never\r\n * mutate; they only read the (DeepReadonly) IR and the precomputed targeting/selector facts the\r\n * context exposes. Authors compose them with {@link and}/{@link or}/{@link not} and feed the\r\n * result into a pattern's `evaluate`.\r\n *\r\n * Style-aware matchers (`computed`, `hasOwnVisualStyle`) reason over the NORMALIZED StyleMap via\r\n * the shared normalizer in `./normalize`, so they query meaning, not raw CSS strings.\r\n */\r\n\r\nimport type {\r\n DeepReadonly,\r\n ElementLike,\r\n IRElement,\r\n IRNode,\r\n IRNodeId,\r\n MatchContext,\r\n NodeLike,\r\n StyleMap,\r\n} from '@domflax/core';\r\n\r\nimport { isStyleSuperset, normalizer } from './normalize';\r\n\r\n/** A pure predicate: does `node` satisfy this condition in the given match context? */\r\nexport type Matcher = (node: NodeLike, ctx: MatchContext) => boolean;\r\n\r\n/* ───────────────────────── internal helpers ───────────────────────── */\r\n\r\nfunction asElement(node: NodeLike): DeepReadonly<IRElement> | null {\r\n const n = node as DeepReadonly<IRNode>;\r\n return n.kind === 'element' ? (n as DeepReadonly<IRElement>) : null;\r\n}\r\n\r\nfunction elementChildrenOf(\r\n el: DeepReadonly<IRElement>,\r\n ctx: MatchContext,\r\n): DeepReadonly<IRElement>[] {\r\n const out: DeepReadonly<IRElement>[] = [];\r\n for (const childId of el.children) {\r\n const child = ctx.doc.nodes.get(childId);\r\n if (child && child.kind === 'element') out.push(child as DeepReadonly<IRElement>);\r\n }\r\n return out;\r\n}\r\n\r\n/* ───────────────────────── boolean combinators ───────────────────────── */\r\n\r\n/** Logical AND. Empty list ⇒ always matches. Short-circuits on the first failure. */\r\nexport function and(...matchers: readonly Matcher[]): Matcher {\r\n return (node, ctx) => matchers.every((m) => m(node, ctx));\r\n}\r\n\r\n/** Logical OR. Empty list ⇒ never matches. Short-circuits on the first success. */\r\nexport function or(...matchers: readonly Matcher[]): Matcher {\r\n return (node, ctx) => matchers.some((m) => m(node, ctx));\r\n}\r\n\r\n/** Logical NOT. */\r\nexport function not(matcher: Matcher): Matcher {\r\n return (node, ctx) => !matcher(node, ctx);\r\n}\r\n\r\n/* ───────────────────────── structural matchers ───────────────────────── */\r\n\r\n/** Matches any element; with `tag`, only elements whose (case-insensitive) tag equals it. */\r\nexport function isElement(tag?: string): Matcher {\r\n const want = tag?.toLowerCase();\r\n return (node) => {\r\n const el = asElement(node);\r\n if (!el) return false;\r\n return want === undefined || el.tag.toLowerCase() === want;\r\n };\r\n}\r\n\r\n/** Matches an element with exactly one ELEMENT child (text/expr/comment children ignored). */\r\nexport const hasSingleElementChild: Matcher = (node, ctx) => {\r\n const el = asElement(node);\r\n if (!el) return false;\r\n return elementChildrenOf(el, ctx).length === 1;\r\n};\r\n\r\n/* ───────────────────────── style matchers ───────────────────────── */\r\n\r\n/**\r\n * Matches when the node's computed StyleMap is a SUPERSET of `partial` — i.e. every declaration\r\n * in `partial` is present in `node.computed` with an equal normalized value. Comparison is\r\n * meaning-based (both sides normalized first). Empty `partial` always matches.\r\n */\r\nexport function computed(partial: StyleMap): Matcher {\r\n return (node, ctx) => {\r\n const el = asElement(node);\r\n if (!el) return false;\r\n const full = ctx.computedOf(el as unknown as NodeLike) ?? (el.computed as StyleMap);\r\n return isStyleSuperset(full as StyleMap, partial, normalizer);\r\n };\r\n}\r\n\r\n/** Visual (paint-establishing) properties that count as \"own visual style\", beyond pure layout. */\r\nconst VISUAL_PROPERTIES: ReadonlySet<string> = new Set<string>([\r\n 'background',\r\n 'background-color',\r\n 'background-image',\r\n 'border-top-width',\r\n 'border-right-width',\r\n 'border-bottom-width',\r\n 'border-left-width',\r\n 'border-top-style',\r\n 'border-right-style',\r\n 'border-bottom-style',\r\n 'border-left-style',\r\n 'border-top-color',\r\n 'border-right-color',\r\n 'border-bottom-color',\r\n 'border-left-color',\r\n // `border-radius` is expanded to its four corner longhands by the shared normalizer, so the\r\n // paint-establishing check must match those (a rounded wrapper still clips its background).\r\n 'border-top-left-radius',\r\n 'border-top-right-radius',\r\n 'border-bottom-right-radius',\r\n 'border-bottom-left-radius',\r\n 'box-shadow',\r\n 'outline',\r\n 'outline-width',\r\n 'outline-style',\r\n 'outline-color',\r\n 'text-shadow',\r\n 'filter',\r\n 'backdrop-filter',\r\n 'mix-blend-mode',\r\n 'opacity',\r\n]);\r\n\r\n/** Values that mean \"no paint\" — a visual property set to one of these does NOT count. */\r\nconst EMPTY_VISUAL_VALUES: ReadonlySet<string> = new Set<string>([\r\n 'none',\r\n '0',\r\n 'normal',\r\n 'transparent',\r\n 'rgba(0, 0, 0, 0)',\r\n 'initial',\r\n 'unset',\r\n 'auto',\r\n]);\r\n\r\n/**\r\n * Matches when the element paints something of its own: a meaningful background, border, shadow,\r\n * outline, filter, etc. across ANY style condition. Honours the frontend-set `meta.hasOwnVisualStyle`\r\n * fast-path, then falls back to scanning the normalized computed StyleMap.\r\n */\r\nexport const hasOwnVisualStyle: Matcher = (node, ctx) => {\r\n const el = asElement(node);\r\n if (!el) return false;\r\n if (el.meta.hasOwnVisualStyle) return true;\r\n // SAFETY (Layer 2): an element with an UNRESOLVED class has an UNKNOWN true style — we cannot prove\r\n // it paints nothing, so it must NOT satisfy `paintsNothing` (`not(hasOwnVisualStyle)`). Reporting\r\n // \"has own visual style\" here makes every flatten pattern gated on paintsNothing decline to match,\r\n // so the element is preserved. This is the primary flatten fail-safe (the flatten-safety classifier\r\n // is the backstop). Compress is unaffected — its guards never consult hasOwnVisualStyle.\r\n if (el.meta.hasUnresolvedClasses) return true;\r\n\r\n const computedMap = ctx.computedOf(el as unknown as NodeLike) ?? (el.computed as StyleMap);\r\n const norm = normalizer.normalizeStyleMap(computedMap as StyleMap);\r\n for (const block of norm.blocks.values()) {\r\n for (const decl of block.decls.values()) {\r\n if (!VISUAL_PROPERTIES.has(String(decl.property))) continue;\r\n if (!EMPTY_VISUAL_VALUES.has(String(decl.value))) return true;\r\n }\r\n }\r\n return false;\r\n};\r\n\r\n/* ───────────────────────── opacity-barrier / meta matchers ───────────────────────── */\r\n\r\n/** Element carries a `ref` (hard opacity barrier). */\r\nexport const hasRef: Matcher = (node) => asElement(node)?.meta.hasRef ?? false;\r\n\r\n/** Element has event handlers (onClick, …). */\r\nexport const hasEventHandlers: Matcher = (node) => asElement(node)?.meta.hasEventHandlers ?? false;\r\n\r\n/** Element has dynamic children (mapped/conditional islands). */\r\nexport const hasDynamicChildren: Matcher = (node) =>\r\n asElement(node)?.meta.hasDynamicChildren ?? false;\r\n\r\n/** Element's class list contains a dynamic segment (template/expr) → not freely rewritable. */\r\nexport const hasDynamicClasses: Matcher = (node) => asElement(node)?.classes.hasDynamic ?? false;\r\n\r\n/**\r\n * Element's class list is wholly dynamic / spread-derived (`classes.opaque`, or spread attrs) — its\r\n * concrete tokens can't be seen or statically rewritten, so a class-rewriting (compress) pattern\r\n * must decline. Delegates to the context's authoritative {@link MatchContext.isOpaque}.\r\n */\r\nexport const opaque: Matcher = (node, ctx) => {\r\n const el = asElement(node);\r\n if (!el) return false;\r\n return ctx.isOpaque(el as unknown as ElementLike);\r\n};\r\n\r\n/**\r\n * Element is the subject of a combinator selector (`>`/`+`/`~`). Honours the frontend-set meta\r\n * flag and the precomputed {@link SelectorIndex} in the context.\r\n */\r\nexport const targetedByCombinator: Matcher = (node, ctx) => {\r\n const el = asElement(node);\r\n if (!el) return false;\r\n if (el.meta.targetedByCombinator) return true;\r\n // `el.id` is a branded number; DeepReadonly widens the brand, so re-narrow for the index call.\r\n return ctx.selectors.targetedByCombinator(el.id as unknown as IRNodeId);\r\n};\r\n","/**\n * @domflax/pattern-kit — `validatePattern` (INTERNAL).\n *\n * A small, eager validator + identity wrapper that turns a lowered {@link Pattern} spec into a\n * frozen, contract-checked Pattern. Catching shape errors here (bad category/phase, missing\n * `evaluate`, out-of-range safety) keeps the pass-manager's hot loop free of defensive checks and\n * gives authors an immediate, actionable error at module-load time.\n *\n * This is the PRIVATE lower-level core: it is consumed only by the declarative\n * {@link import('./pattern').definePattern} authoring surface (which compiles a high-level config\n * down to a {@link Pattern} and then runs it through this validator). It is intentionally NOT part\n * of the public package surface — authors use `definePattern` instead.\n */\n\nimport type { PassPhase, Pattern, SafetyLevel } from '@domflax/core';\n\nconst PHASES: ReadonlySet<PassPhase> = new Set<PassPhase>(['flatten', 'compress', 'extract']);\nconst SAFETY_LEVELS: ReadonlySet<SafetyLevel> = new Set<SafetyLevel>([0, 1, 2, 3]);\n\nfunction fail(name: string, why: string): never {\n throw new Error(`definePattern(${name || '<anonymous>'}): ${why}`);\n}\n\n/**\n * Validate and freeze a {@link Pattern}. Throws on any contract violation; otherwise returns the\n * (shallow-frozen) spec unchanged so it can be registered into a {@link Pass}. INTERNAL — see the\n * module header; authors call the declarative {@link import('./pattern').definePattern}.\n */\nexport function validatePattern(spec: Pattern): Pattern {\n if (spec == null || typeof spec !== 'object') {\n throw new Error('definePattern: spec must be an object');\n }\n\n const name = spec.name;\n if (typeof name !== 'string' || name.length === 0) {\n fail(String(name), 'name must be a non-empty string');\n }\n\n if (typeof spec.category !== 'string' || !spec.category.includes('/')) {\n fail(name, `category must be a \"<phase>/<slug>\" string (got ${JSON.stringify(spec.category)})`);\n }\n\n const phase = spec.category.split('/', 1)[0] as PassPhase;\n if (!PHASES.has(phase)) {\n fail(name, `category phase must be one of flatten|compress|extract (got \"${phase}\")`);\n }\n\n if (!SAFETY_LEVELS.has(spec.safety)) {\n fail(name, `safety must be 0|1|2|3 (got ${JSON.stringify(spec.safety)})`);\n }\n\n if (typeof spec.evaluate !== 'function') {\n fail(name, 'evaluate must be a function');\n }\n\n if (spec.priority !== undefined && !Number.isFinite(spec.priority)) {\n fail(name, 'priority must be a finite number when provided');\n }\n\n return Object.freeze({ ...spec });\n}\n","/**\n * @domflax/pattern-kit — `definePattern()`: THE declarative pattern-authoring surface.\n *\n * `definePattern(config)` is the single public way to author a rewrite pattern: definition AND its\n * tests are co-located in one call. It compiles down to the private lower-level\n * {@link import('./define').validatePattern}/{@link Pattern} contract (it never replaces the\n * engine). Authors describe the match as a plain DATA object and the rewrite as a named RECIPE; this\n * module maps each key to the existing matcher combinators and op-draft factories, auto-applies the\n * phase-appropriate safety guards (the full opacity-barrier + selector set for `flatten/*`; the\n * narrower class-rewrite-safety set for `compress/*`) so authors never hand-write them, and threads\n * `doc`/`test` through. Two escape hatches — a `match` predicate and a `rewrite` function — keep\n * exotic patterns (e.g. ones anchored on a parent fragment) expressible.\n *\n * The co-located {@link PatternTest} (`provider`/`cssFiles`/`cases`/`noMatch`/`custom`) is carried on\n * the compiled {@link AuthoredPattern} as `.test`, where the generic harness (`./testing`) reads it:\n * each `case` asserts `before → after`, each `noMatch` asserts the input is left unchanged, and the\n * optional `custom` hook runs arbitrary assertions against the built transform.\n *\n * `style` blocks in the declarative match (and in `childGains`/`mergeStyle` recipes) are PLAIN\n * objects (camelCase or kebab keys) auto-normalized into a superset StyleMap via the shared\n * normalizer — authors never import the normalizer or hand-build a StyleMap.\n *\n * `pattern` remains exported as a DEPRECATED alias of `definePattern` for backward compatibility.\n */\n\nimport type {\n Captures,\n ConditionKey,\n CssProperty,\n DeepReadonly,\n IRElement,\n IRNode,\n IRNodeId,\n MatchContext,\n MatchResult,\n NodeLike,\n NodeMeta,\n PassCategory,\n PassPhase,\n Pattern,\n PatternDoc,\n PreconditionSketch,\n RewriteFactory,\n RewriteOpDraft,\n SafetyLevel,\n StyleBlock,\n StyleDecl,\n StyleMap,\n StyleOrigin,\n StyleConflictPolicy,\n} from '@domflax/core';\nimport { BASE_CONDITION, conditionKey } from '@domflax/core';\n\nimport {\n and,\n computed,\n hasDynamicChildren,\n hasDynamicClasses,\n hasEventHandlers,\n hasOwnVisualStyle,\n hasRef,\n hasSingleElementChild,\n isElement,\n not,\n opaque,\n targetedByCombinator,\n type Matcher,\n} from './combinators';\nimport { validatePattern } from './define';\nimport { normalizer } from './normalize';\n\n/* ───────────────────────── public config shapes ───────────────────────── */\n\n/** A plain CSS style object: camelCase or kebab-case keys, string or number values. */\nexport type PlainStyle = Readonly<Record<string, string | number>>;\n\n/**\n * Declarative match as DATA. Every key maps to one of the existing matcher combinators; an empty\n * object matches any element. Use the `match` FUNCTION escape hatch for anything not expressible\n * here (relational/ancestor/sibling shapes, parent-anchored patterns, …).\n */\nexport interface DeclarativeMatch {\n /** Restrict to a tag (case-insensitive). Omit to match any element. */\n readonly tag?: string;\n /** Computed style the node must be a SUPERSET of (plain object, auto-normalized). */\n readonly style?: PlainStyle;\n /** Require exactly one ELEMENT child. */\n readonly onlyChild?: 'element';\n /** Require the element to paint nothing of its own (no own visual style). */\n readonly paintsNothing?: boolean;\n /** Extra, hand-written predicate AND-ed into the declarative match. */\n readonly where?: Matcher | readonly Matcher[];\n}\n\n/** Escape hatch: a raw match predicate (no auto-guards are added). */\nexport type MatchFn = (node: NodeLike, ctx: MatchContext) => boolean;\n\n/**\n * Flatten recipe: fold inherited styles onto the sole element child (default on), optionally merge\n * `childGains` onto it, then unwrap the node (id-preserving). Mirrors the flatten exemplars.\n */\nexport interface FlattenIntoRecipe {\n readonly flattenInto: 'child';\n /** Plain style merged onto the surviving child (source-wins) before unwrap. */\n readonly childGains?: PlainStyle;\n /** Fold inheritable declarations onto the child first. Default `true`. */\n readonly foldInherited?: boolean;\n}\n\n/** Compress recipe: rebuild the element's class StyleMap; return `null` to decline. */\nexport interface RewriteClassesRecipe {\n readonly rewriteClasses: (computed: StyleMap, ctx: MatchContext) => StyleMap | null;\n /** Keep opaque/selector-bound tokens verbatim. Default `true`. */\n readonly preserveOpaque?: boolean;\n}\n\n/** Compress recipe: drop fully-overridden class tokens (provenance is pruned automatically). */\nexport interface DropClassesRecipe {\n readonly dropClasses: (computed: StyleMap, ctx: MatchContext) => Iterable<string>;\n /** Keep opaque/selector-bound tokens verbatim. Default `true`. */\n readonly preserveOpaque?: boolean;\n}\n\n/** Merge a literal plain style onto the matched element. */\nexport interface MergeStyleRecipe {\n readonly mergeStyle: PlainStyle;\n readonly onConflict?: StyleConflictPolicy;\n}\n\nexport type RewriteRecipe =\n | FlattenIntoRecipe\n | RewriteClassesRecipe\n | DropClassesRecipe\n | MergeStyleRecipe;\n\n/** Escape hatch: a raw rewrite that returns op drafts (or `null`/`[]` for no-op). */\nexport type RewriteFn = (\n ctx: MatchContext,\n rw: RewriteFactory,\n) => readonly RewriteOpDraft[] | null;\n\n/** A single positive before→after assertion run through the pattern's built transform. */\nexport interface PatternTestCase {\n readonly name?: string;\n readonly before: string;\n readonly after: string;\n}\n\n/** Helpers handed to a {@link PatternTest.custom} hook (the built transform + expectation sugar). */\nexport interface TestHelpers {\n /** Run the pattern's transform on `code` (default filename `'X.tsx'`). */\n readonly transform: (code: string, filename?: string) => string;\n /** Assert `before` transforms to `after` (whitespace-normalized). */\n readonly expectTransforms: (before: string, after: string) => void;\n /** Assert `code` is left unchanged (whitespace-normalized). */\n readonly expectUnchanged: (code: string) => void;\n}\n\n/**\n * Co-located test spec for a pattern. The generic harness (`./testing`) builds a transform for the\n * declared `provider` (default `'tailwind'`; `'custom'` resolves the listed `cssFiles`), then runs\n * every `case` (`before → after`), every `noMatch` (left unchanged), and the optional `custom` hook.\n */\nexport interface PatternTest {\n /** Which style provider the harness builds the transform from. Default `'tailwind'`. */\n readonly provider?: 'tailwind' | 'custom';\n /** For `provider: 'custom'` — the project stylesheet paths backing the CSS resolver. */\n readonly cssFiles?: readonly string[];\n /** Positive before→after assertions. */\n readonly cases?: readonly PatternTestCase[];\n /** Inputs the pattern must leave UNCHANGED (barriers, non-matching shapes, safety reverts). */\n readonly noMatch?: readonly string[];\n /** Arbitrary extra assertions against the built transform. */\n readonly custom?: (h: TestHelpers) => void;\n}\n\nexport interface PatternConfig {\n readonly name: string;\n readonly category: PassCategory;\n readonly safety: SafetyLevel;\n readonly priority?: number;\n readonly precondition?: PreconditionSketch;\n readonly doc?: PatternDoc;\n /** Co-located tests consumed by the generic harness (`./testing`). */\n readonly test?: PatternTest;\n /** Declarative match DATA, or a raw predicate escape hatch. Defaults to \"any element\". */\n readonly match?: DeclarativeMatch | MatchFn;\n /** A named rewrite recipe, or a raw op-draft factory escape hatch. */\n readonly rewrite: RewriteRecipe | RewriteFn;\n}\n\n/** A {@link Pattern} that also carries its co-located {@link PatternTest} for the test harness. */\nexport interface AuthoredPattern<C extends Captures = Captures> extends Pattern {\n readonly test?: PatternTest;\n evaluate(ctx: MatchContext, rw: RewriteFactory): MatchResult<C> | null;\n}\n\n/* ───────────────────────── plain-style → StyleMap ───────────────────────── */\n\nfunction camelToKebab(key: string): string {\n if (key.startsWith('--')) return key; // custom property — leave verbatim\n return key.replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`);\n}\n\n/** Build a single-(base-)condition StyleMap from a plain style object via the shared normalizer. */\nfunction plainToStyleMap(style: PlainStyle): StyleMap {\n const decls = new Map<CssProperty, StyleDecl>();\n for (const [rawKey, rawValue] of Object.entries(style)) {\n const prop = camelToKebab(rawKey);\n for (const decl of normalizer.normalizeDeclaration(prop, String(rawValue), false)) {\n decls.set(decl.property, decl);\n }\n }\n const block: StyleBlock = { condition: BASE_CONDITION, decls };\n return { blocks: new Map<ConditionKey, StyleBlock>([[conditionKey(BASE_CONDITION), block]]) };\n}\n\n/* ───────────────────────── local meta / selector matchers ───────────────────────── */\n\nfunction asElement(node: NodeLike): DeepReadonly<IRElement> | null {\n const n = node as DeepReadonly<IRNode>;\n return n.kind === 'element' ? (n as DeepReadonly<IRElement>) : null;\n}\n\nfunction metaFlag(flag: keyof NodeMeta): Matcher {\n return (node) => Boolean(asElement(node)?.meta[flag]);\n}\n\n/** Element renders raw/`dangerouslySetInnerHTML` markup — a hard opacity barrier. */\nconst hasRawHtml: Matcher = metaFlag('hasDangerousHtml');\n\n/**\n * Unwrapping/removing this node would change the combinator / structural-pseudo match-set of itself,\n * its child, or a former sibling. Empty `reparentImpact` ⇒ structurally safe to hoist.\n */\nconst affectsSelectorMatching: Matcher = (node, ctx) => {\n const el = asElement(node);\n if (!el) return false;\n return ctx.selectors.reparentImpact(el.id as unknown as IRNodeId).size > 0;\n};\n\n/**\n * The opacity-barrier + selector-safety guards every `flatten/*` pattern must carry. Auto-applied to\n * the declarative match so authors never hand-write them (the flatten exemplars spell them out).\n *\n * Flatten UNWRAPS the element (moving its children into a new parent and dropping its box), so every\n * opacity barrier matters: a ref, event handler, dynamic child, or raw HTML on the wrapper — or any\n * selector the reparent would disturb — makes the flatten unsafe.\n */\nconst FLATTEN_GUARDS: Matcher = and(\n not(hasRef),\n not(hasEventHandlers),\n not(hasDynamicChildren),\n not(hasRawHtml),\n not(targetedByCombinator),\n not(affectsSelectorMatching),\n);\n\n/**\n * The guards every `compress/*` pattern must carry. Compress ONLY ever rewrites the element's OWN\n * class tokens (e.g. `px-4 py-4 → p-4`) — it never touches the element's structure, children, or\n * identity. A dynamic `{expr}` child, a ref, an event handler, or `dangerouslySetInnerHTML` is\n * therefore wholly unaffected by a class-only change, so — unlike flatten — those opacity barriers\n * must NOT gate compress. Compress is gated ONLY on what actually makes a class rewrite unsafe:\n * • a className we can't statically rewrite — a dynamic segment ({@link hasDynamicClasses}) or a\n * wholly dynamic / spread-derived list ({@link opaque}); and\n * • the selector-safety guard — a class a CSS combinator selector structurally depends on\n * ({@link targetedByCombinator}) must not be dropped or rewritten.\n */\nconst COMPRESS_GUARDS: Matcher = and(\n not(hasDynamicClasses),\n not(opaque),\n not(targetedByCombinator),\n);\n\n/* ───────────────────────── match compilation ───────────────────────── */\n\n/** The auto-applied guard set for a pattern's phase (compress vs flatten get different barriers). */\nfunction autoGuardsFor(category: PassCategory): Matcher | null {\n switch (category.split('/', 1)[0] as PassPhase) {\n case 'flatten':\n return FLATTEN_GUARDS;\n case 'compress':\n return COMPRESS_GUARDS;\n default:\n return null;\n }\n}\n\nfunction compileDeclarativeMatch(m: DeclarativeMatch): Matcher {\n const parts: Matcher[] = [isElement(m.tag)];\n if (m.style) parts.push(computed(plainToStyleMap(m.style)));\n if (m.onlyChild === 'element') parts.push(hasSingleElementChild);\n if (m.paintsNothing) parts.push(not(hasOwnVisualStyle));\n if (m.where) {\n const extra = Array.isArray(m.where) ? (m.where as readonly Matcher[]) : [m.where as Matcher];\n for (const w of extra) parts.push(w);\n }\n return and(...parts);\n}\n\nfunction compileMatch(\n match: DeclarativeMatch | MatchFn | undefined,\n category: PassCategory,\n): MatchFn {\n // Escape hatch: a raw predicate takes full control (no auto-guards).\n if (typeof match === 'function') return match;\n\n const declarative = compileDeclarativeMatch(match ?? {});\n const guards = autoGuardsFor(category);\n const guarded = guards ? and(declarative, guards) : declarative;\n return (node, ctx) => guarded(node, ctx);\n}\n\n/* ───────────────────────── rewrite compilation ───────────────────────── */\n\n/** Clone `sm`, pruning every `shadowed` provenance entry that references a dropped class token. */\nfunction pruneShadowed(sm: StyleMap, drop: ReadonlySet<string>): StyleMap {\n const blocks = new Map<ConditionKey, StyleBlock>();\n for (const [key, block] of sm.blocks) {\n const decls = new Map<CssProperty, StyleDecl>();\n for (const [prop, decl] of block.decls) {\n const filtered = (decl.shadowed ?? []).filter(\n (o) => !(o.kind === 'class' && drop.has(o.className)),\n );\n const rest: StyleDecl = { ...decl };\n delete (rest as { shadowed?: readonly StyleOrigin[] }).shadowed;\n const next: StyleDecl = filtered.length > 0 ? { ...rest, shadowed: filtered } : rest;\n decls.set(prop, next);\n }\n blocks.set(key, { condition: block.condition, decls });\n }\n return { blocks };\n}\n\nfunction compileFlattenInto(recipe: FlattenIntoRecipe): RewriteFn {\n const childGains = recipe.childGains ? plainToStyleMap(recipe.childGains) : null;\n const fold = recipe.foldInherited !== false;\n return (ctx, rw) => {\n const wrapper = ctx.node;\n const child = ctx.onlyElementChild();\n if (!child) return null;\n const ops: RewriteOpDraft[] = [];\n if (fold) ops.push(rw.foldInheritedStyles(wrapper, child, { conditions: 'all' }));\n if (childGains) ops.push(rw.mergeStyle(child, null, childGains, 'source-wins'));\n ops.push(rw.unwrap(wrapper));\n return ops;\n };\n}\n\nfunction compileRewrite(rewrite: RewriteRecipe | RewriteFn): RewriteFn {\n if (typeof rewrite === 'function') return rewrite;\n\n if ('flattenInto' in rewrite) return compileFlattenInto(rewrite);\n\n if ('rewriteClasses' in rewrite) {\n const preserveOpaque = rewrite.preserveOpaque ?? true;\n return (ctx, rw) => {\n const next = rewrite.rewriteClasses(ctx.computed(), ctx);\n if (!next) return null;\n return [rw.setClassList(ctx.node, next, preserveOpaque)];\n };\n }\n\n if ('dropClasses' in rewrite) {\n const preserveOpaque = rewrite.preserveOpaque ?? true;\n return (ctx, rw) => {\n const drop = new Set<string>(rewrite.dropClasses(ctx.computed(), ctx));\n if (drop.size === 0) return null;\n return [rw.setClassList(ctx.node, pruneShadowed(ctx.computed(), drop), preserveOpaque)];\n };\n }\n\n // MergeStyleRecipe\n const style = plainToStyleMap(rewrite.mergeStyle);\n const onConflict = rewrite.onConflict ?? 'abort';\n return (ctx, rw) => [rw.mergeStyle(ctx.node, null, style, onConflict)];\n}\n\n/* ───────────────────────── the public factory ───────────────────────── */\n\n/**\n * THE declarative pattern-authoring function. Compile a {@link PatternConfig} (definition + co-located\n * {@link PatternTest}) into a validated {@link AuthoredPattern}: a normal {@link Pattern} (registerable\n * into any {@link import('@domflax/core').Pass}) that also exposes its `test` for the generic harness.\n */\nexport function definePattern(config: PatternConfig): AuthoredPattern {\n const matchFn = compileMatch(config.match, config.category);\n const rewriteFn = compileRewrite(config.rewrite);\n\n const spec: AuthoredPattern = {\n name: config.name,\n category: config.category,\n safety: config.safety,\n priority: config.priority,\n precondition: config.precondition,\n doc: config.doc,\n test: config.test,\n evaluate(ctx: MatchContext, rw: RewriteFactory): MatchResult | null {\n if (!matchFn(ctx.node as unknown as NodeLike, ctx)) return null;\n const ops = rewriteFn(ctx, rw);\n if (!ops || ops.length === 0) return null;\n return { ops };\n },\n };\n\n // `validatePattern` validates + freezes; the spread preserves `test` at runtime.\n return validatePattern(spec) as AuthoredPattern;\n}\n\n/**\n * @deprecated Use {@link definePattern}. Retained as a thin alias for backward compatibility.\n */\nexport const pattern = definePattern;\n","/**\n * @domflax/patterns — flatten pattern: `flex-center-wrapper`.\n *\n * Collapses the ubiquitous \"centering wrapper\" idiom\n *\n * <div style=\"display:flex; align-items:center; justify-content:center\"><Child/></div>\n *\n * into its sole child, pushing the centering intent down onto the child as `place-self: center`.\n * The wrapper only exists to center one element; once `place-self:center` lives on the child the\n * wrapper is pure structural noise and can go.\n *\n * Authored with the declarative {@link definePattern} API: the match is the flex-centering\n * computed-style signature on a single-element-child `<div>` that paints nothing of its own; the\n * recipe folds inheritable styles onto the child, grants it `place-self:center`, then unwraps the\n * wrapper (id-preserving). The opacity-barrier + selector-safety guards are applied automatically by\n * the `definePattern` factory for every `flatten/*` pattern.\n */\n\nimport { definePattern } from '@domflax/pattern-kit';\n\n/**\n * Flatten a flex-centering `<div>` wrapper into its sole element child, granting the child\n * `place-self:center`.\n */\nexport const flexCenterWrapper = definePattern({\n name: 'flex-center-wrapper',\n category: 'flatten/flex/flex-center-wrapper',\n safety: 2,\n doc: {\n title: 'Flatten flex-centering wrapper',\n summary:\n 'A div that only centers a single child (display:flex; align-items:center; ' +\n 'justify-content:center) is removed; the child gains place-self:center.',\n before: '<div style=\"display:flex;align-items:center;justify-content:center\"><Child/></div>',\n after: '<Child style=\"place-self:center\"/>',\n safetyRationale:\n 'Wrapper paints nothing, carries no ref/handlers/dynamic children, and is not a combinator ' +\n 'subject; inheritable styles are folded onto the child before removal.',\n },\n match: {\n tag: 'div',\n style: { display: 'flex', alignItems: 'center', justifyContent: 'center' },\n onlyChild: 'element',\n paintsNothing: true,\n },\n rewrite: {\n flattenInto: 'child',\n childGains: { placeSelf: 'center' },\n },\n // Collapsing a flex-centering wrapper to `place-self:center` on the child is render-identical ONLY\n // when the child's NEW parent is a statically-known GRID that lets the wrapper fill its area (there\n // `place-self`'s align-self AND justify-self both take effect). Under that ONE context the flatten is\n // classified `provably-safe` and commits; under a flex/block/unknown parent — or when the wrapper\n // drops any own style — it stays `needs-verification` and the conservative production gate PRESERVES\n // it. Op-level correctness (purity, id-preserving unwrap, opacity-barrier safety) is additionally\n // asserted by the invariant suite over every pattern.\n test: {\n cases: [\n {\n name: 'grid parent → flattened (child gains place-self-center)',\n before:\n '<div className=\"grid\">' +\n '<div className=\"flex items-center justify-center\"><span className=\"bg-red-200\">x</span></div>' +\n '</div>',\n after: '<div className=\"grid\"><span className=\"bg-red-200 place-self-center\">x</span></div>',\n },\n ],\n noMatch: [\n // Non-grid (flex) parent (document root): `justify-self` is ignored in flex → not provably safe.\n '<div className=\"flex justify-center items-center\"><div className=\"bg-red-200\">Hello</div></div>',\n // Grid parent, but the wrapper drops padding when removed → not layout-neutral (rule 3).\n '<div className=\"grid\">' +\n '<div className=\"p-4 flex items-center justify-center\"><span className=\"bg-red-200\">x</span></div>' +\n '</div>',\n // Grid parent forcing place-items-center: the wrapper would not fill its area → fill guard skips.\n '<div className=\"grid place-items-center\">' +\n '<div className=\"flex items-center justify-center\"><span className=\"bg-red-200\">x</span></div>' +\n '</div>',\n // onClick is a hard opacity barrier → the wrapper is load-bearing regardless of the gate.\n '<div className=\"flex justify-center items-center\" onClick={handleClick}>' +\n '<div className=\"bg-red-200\">Hello</div>' +\n '</div>',\n ],\n },\n});\n","/**\n * @domflax/patterns — flatten pattern: `redundant-fragment`.\n *\n * Collapses a fragment that wraps exactly one child\n *\n * <><Child/></> → <Child/>\n *\n * A fragment renders no box of its own, so a fragment whose sole purpose is to wrap a single node\n * is pure structural noise: splicing the child up into the fragment's slot is invisible in both\n * the rendered DOM and the project's CSS cascade.\n *\n * Anchoring: the pass manager only visits ELEMENT nodes (see core's `elementIds`), never fragments,\n * so this pattern is anchored on the fragment's sole *element* child and removes the PARENT fragment.\n * Because the match is PARENT-anchored (and reads a fragment's `meta`, which the element-only\n * combinator vocabulary cannot inspect), it uses the declarative API's two escape hatches: a raw\n * `match` predicate and a raw `rewrite` op-draft factory.\n */\n\nimport type {\n DeepReadonly,\n ElementLike,\n IRNode,\n IRNodeId,\n MatchContext,\n NodeLike,\n RewriteFactory,\n RewriteOpDraft,\n} from '@domflax/core';\n\nimport { definePattern } from '@domflax/pattern-kit';\n\n/* ───────────────────────── match predicate (escape hatch) ───────────────────────── */\n\n/**\n * Matches an element whose PARENT is a redundant, unwrappable fragment: a non-root fragment with\n * exactly one child (this element), free of every opacity barrier and CSS-targeting coupling.\n */\nfunction parentIsRedundantFragment(node: NodeLike, ctx: MatchContext): boolean {\n const el = node as DeepReadonly<IRNode>;\n if (el.kind !== 'element') return false;\n\n const parentId = el.parent;\n if (parentId == null) return false;\n\n const parent = ctx.doc.nodes.get(parentId);\n if (!parent || parent.kind !== 'fragment') return false;\n\n // Never unwrap the document root (it must always be a fragment — IRDocument invariant).\n if (parent.parent == null) return false;\n\n // Exactly one child (counting EVERY kind) ⇒ the anchor element is the fragment's sole child.\n if (parent.children.length !== 1) return false;\n\n // Hard opacity barriers on the fragment: keyed `<Fragment key>`, ref/handlers/dynamic children/\n // dangerous HTML/spread/component identity. Any of these means the fragment is load-bearing.\n const m = parent.meta;\n if (\n m.hasKey ||\n m.hasRef ||\n m.hasEventHandlers ||\n m.hasDynamicChildren ||\n m.hasDangerousHtml ||\n m.hasSpreadAttrs ||\n m.isComponent\n ) {\n return false;\n }\n\n // CSS-selector safety: the fragment (or its reparented child) must not move any combinator /\n // structural-pseudo match-set. Honour both the frontend-set meta flags and the SelectorIndex.\n if (m.targetedByCombinator || m.targetedByStructuralPseudo) return false;\n const fid = parentId as unknown as IRNodeId;\n if (ctx.selectors.targetedByCombinator(fid) || ctx.selectors.targetedByStructuralPseudo(fid)) {\n return false;\n }\n if (ctx.selectors.reparentImpact(fid).size > 0) return false;\n\n return true;\n}\n\n/* ───────────────────────── the pattern ───────────────────────── */\n\n/**\n * Flatten a fragment that wraps exactly one child into that child.\n *\n * Safety level 1 (`safe`): a purely structural, style-free, selector-transparent cleanup.\n */\nexport const redundantFragment = definePattern({\n name: 'redundant-fragment',\n category: 'flatten/fragment/redundant-fragment',\n safety: 1,\n doc: {\n title: 'Flatten redundant single-child fragment',\n summary:\n 'A fragment whose only child is a single node is removed; the child is spliced up into the ' +\n \"fragment's slot, preserving its IRNodeId, siblings, attributes and the CSS cascade.\",\n before: '<><Child/></>',\n after: '<Child/>',\n safetyRationale:\n 'A fragment paints nothing and renders no box; with exactly one child its removal changes ' +\n 'no sibling/structural-pseudo match-set. Keyed fragments and fragments carrying ' +\n 'ref/handlers/dynamic-children/raw-html/spread are excluded as opacity barriers.',\n },\n match: parentIsRedundantFragment,\n rewrite: (ctx: MatchContext, rw: RewriteFactory): readonly RewriteOpDraft[] | null => {\n const parentId = ctx.node.parent;\n if (parentId == null) return null;\n const fragment = ctx.doc.nodes.get(parentId);\n if (!fragment || fragment.kind !== 'fragment') return null;\n // Splice the sole child up into the fragment's slot, deleting ONLY the fragment node.\n return [rw.unwrap(fragment as unknown as ElementLike)];\n },\n test: {\n cases: [\n {\n // A fragment renders no box, so unwrapping a single-child fragment is always layout-identical\n // → a provably-safe flatten: the child is spliced up into the fragment's slot.\n before: '<><span className=\"bg-red-200\">Hi</span></>',\n after: '<span className=\"bg-red-200\">Hi</span>',\n },\n ],\n noMatch: [\n // Two children ⇒ not a single-child fragment, so the fragment is load-bearing and stays.\n '<><span className=\"bg-red-200\">A</span><span className=\"bg-green-200\">B</span></>',\n ],\n },\n});\n","/**\n * @domflax/patterns — flatten pattern: `grid-center-wrapper`.\n *\n * Collapses the grid flavour of the \"centering wrapper\" idiom\n *\n * <div style=\"display:grid; align-items:center; justify-content:center\"><Child/></div>\n *\n * into its sole child, pushing the centering intent down onto the child as `place-self:center`. This is\n * the grid analogue of `flex-center-wrapper`: the wrapper only exists to center one element, and once\n * `place-self:center` lives on the child the wrapper is pure structural noise.\n *\n * Authored with the declarative {@link definePattern} API: the match is the grid-centering computed-style\n * signature on a single-element-child `<div>` that paints nothing of its own; the recipe folds\n * inheritable styles onto the child, grants it `place-self:center`, then unwraps the wrapper. The\n * opacity-barrier + selector-safety guards are auto-applied for every `flatten/*` pattern.\n *\n * Genuinely additive under the conservative gate: unlike a plain passthrough (which the gate REVERTS on\n * a grid wrapper because grid establishes a formatting context), the compensating `place-self:center`\n * makes the flatten `provably-safe` — but ONLY when the child's NEW parent is a statically-known grid\n * that lets the wrapper fill its area (the ONE context where the child's `justify-self` is honored).\n */\n\nimport { definePattern } from '@domflax/pattern-kit';\n\n/**\n * Flatten a grid-centering `<div>` wrapper into its sole element child, granting the child\n * `place-self:center`.\n */\nexport const gridCenterWrapper = definePattern({\n name: 'grid-center-wrapper',\n category: 'flatten/grid/grid-center-wrapper',\n safety: 2,\n doc: {\n title: 'Flatten grid-centering wrapper',\n summary:\n 'A div that only centers a single child (display:grid; align-items:center; ' +\n 'justify-content:center) is removed; the child gains place-self:center.',\n before: '<div style=\"display:grid;align-items:center;justify-content:center\"><Child/></div>',\n after: '<Child style=\"place-self:center\"/>',\n safetyRationale:\n 'Wrapper paints nothing, carries no ref/handlers/dynamic children, and is not a combinator ' +\n 'subject; inheritable styles are folded onto the child before removal. The place-self:center ' +\n 'collapse is committed by the gate only under a statically-known filling grid parent.',\n },\n match: {\n tag: 'div',\n style: { display: 'grid', alignItems: 'center', justifyContent: 'center' },\n onlyChild: 'element',\n paintsNothing: true,\n },\n rewrite: {\n flattenInto: 'child',\n childGains: { placeSelf: 'center' },\n },\n // Like `flex-center-wrapper`, collapsing to `place-self:center` is render-identical ONLY when the\n // child's NEW parent is a statically-known GRID that lets the wrapper fill its area (there both halves\n // of place-self take effect). Under that ONE context the flatten is `provably-safe` and commits; under\n // a flex/block/unknown parent — or when the wrapper drops any own style — it stays `needs-verification`\n // and the conservative production gate PRESERVES it. Op-level correctness is asserted by the invariant suite.\n test: {\n cases: [\n {\n name: 'grid parent → flattened (child gains place-self-center)',\n before:\n '<div className=\"grid\">' +\n '<div className=\"grid items-center justify-center\"><span className=\"bg-red-200\">x</span></div>' +\n '</div>',\n after: '<div className=\"grid\"><span className=\"bg-red-200 place-self-center\">x</span></div>',\n },\n ],\n noMatch: [\n // Non-grid (document-root) parent: justify-self is ignored outside a grid → not provably safe.\n '<div className=\"grid justify-center items-center\"><div className=\"bg-red-200\">Hello</div></div>',\n // Grid parent, but the wrapper drops padding when removed → not layout-neutral, preserved.\n '<div className=\"grid\">' +\n '<div className=\"p-4 grid items-center justify-center\"><span className=\"bg-red-200\">x</span></div>' +\n '</div>',\n // onClick is a hard opacity barrier → the wrapper is load-bearing regardless of the gate.\n '<div className=\"grid justify-center items-center\" onClick={handleClick}>' +\n '<div className=\"bg-red-200\">Hello</div>' +\n '</div>',\n ],\n },\n});\n","/**\n * @domflax/patterns — flatten pattern: `display-contents-wrapper`.\n *\n * Collapses a wrapper that has explicitly opted OUT of generating a box:\n *\n * <div style=\"display:contents\"><Child/></div> → <Child/>\n *\n * `display:contents` makes an element generate NO box of its own — its children render exactly as if\n * they were direct children of the element's parent. A `display:contents` wrapper with a single\n * element child is therefore already a layout passthrough: it contributes nothing to flow, paint\n * (a contents box paints nothing), formatting, stacking, or containing-block resolution. Removing it\n * and hoisting the child produces a tree that is layout-identical — the wrapper's only remaining\n * effect was inheritance, which is preserved by folding inheritable declarations onto the child first.\n *\n * This is the safest possible wrapper-elimination: the box being removed provably did not exist.\n * The opacity-barrier + selector-safety guards (ref/handlers/dynamic-children/raw-html/combinator/\n * reparent-impact) are auto-applied for every `flatten/*` pattern; the `where` predicates add the\n * passthrough-specific requirements (no own attrs / dynamic-or-spread classes, no `var()` coupling,\n * not a component, not a structural-pseudo subject).\n *\n * (Chosen as the safe variant of the size-hoisting \"full-size passthrough\" idea: hoisting an explicit\n * `width/height:100%` onto a child is only sound when the child is block-level and unsized, which is\n * not knowable from the wrapper alone — whereas a `display:contents` box is a passthrough by definition.)\n */\n\nimport type {\n DeepReadonly,\n IRElement,\n IRNode,\n IRNodeId,\n NodeLike,\n NodeMeta,\n} from '@domflax/core';\n\nimport { definePattern, hasDynamicClasses, not, type Matcher } from '@domflax/pattern-kit';\n\n/* ───────────────────────── local meta/attr/selector matchers ───────────────────────── */\n\nfunction asEl(node: NodeLike): DeepReadonly<IRElement> | null {\n const n = node as DeepReadonly<IRNode>;\n return n.kind === 'element' ? (n as DeepReadonly<IRElement>) : null;\n}\n\nfunction metaOf(node: NodeLike): DeepReadonly<NodeMeta> | null {\n return asEl(node)?.meta ?? null;\n}\n\n/**\n * Element exposes custom properties to a descendant — removing its box could sever a `var()` coupling,\n * so it is NOT a free passthrough. (A `display:contents` box establishes no formatting/stacking/box\n * context and is no containing block, so those flags need not be checked.)\n */\nconst declaresCustomProperties: Matcher = (node) => metaOf(node)?.declaresCustomProperties ?? false;\n\n/** Hard opacity barriers beyond the auto-applied set: spread attrs, component identity. */\nconst hasSpreadAttrs: Matcher = (node) => metaOf(node)?.hasSpreadAttrs ?? false;\nconst isComponentNode: Matcher = (node) => metaOf(node)?.isComponent ?? false;\n\n/** Element carries own attributes (id / data-* / …) beyond its class list — possible selector/JS hook. */\nconst hasOwnAttrs: Matcher = (node) => {\n const el = asEl(node);\n if (!el) return false;\n return el.attrs.entries.size > 0 || el.attrs.spreads.length > 0;\n};\n\n/**\n * Element is the subject of a structural pseudo (`:first/:last/:only/:nth-*`). Honours the meta flag\n * and the precomputed {@link SelectorIndex}.\n */\nconst targetedByStructuralPseudo: Matcher = (node, ctx) => {\n const el = asEl(node);\n if (!el) return false;\n if (el.meta.targetedByStructuralPseudo) return true;\n return ctx.selectors.targetedByStructuralPseudo(el.id as unknown as IRNodeId);\n};\n\n/* ───────────────────────── the pattern ───────────────────────── */\n\n/**\n * Flatten a `display:contents` wrapper (a box that generates no box) into its sole element child,\n * folding any inheritable styles down first so inherited values survive the removal.\n */\nexport const displayContentsWrapper = definePattern({\n name: 'display-contents-wrapper',\n category: 'flatten/wrapper/display-contents-wrapper',\n safety: 2,\n doc: {\n title: 'Flatten display:contents wrapper',\n summary:\n 'A div with display:contents (which generates no box) wrapping a single element child, with ' +\n 'no own visual style, no attributes beyond an inert class, and no opacity barriers, is removed; ' +\n 'its sole child is hoisted in its place.',\n before: '<div style=\"display:contents\"><Child/></div>',\n after: '<Child/>',\n safetyRationale:\n 'A display:contents element generates no box at all, so its children already render as direct ' +\n \"children of its parent; removing it is layout-identical. It paints nothing, establishes no \" +\n 'formatting/stacking/box context, is no containing block, carries no ' +\n 'ref/handlers/dynamic-children/html/spread/component identity, owns no targetable attrs / ' +\n 'custom-property coupling, and is not a combinator/structural-pseudo subject; inheritable ' +\n 'styles are folded onto the child before removal.',\n },\n match: {\n tag: 'div',\n style: { display: 'contents' },\n onlyChild: 'element',\n paintsNothing: true,\n where: [\n not(declaresCustomProperties),\n not(hasOwnAttrs),\n not(hasDynamicClasses),\n not(hasSpreadAttrs),\n not(isComponentNode),\n not(targetedByStructuralPseudo),\n ],\n },\n rewrite: { flattenInto: 'child' },\n test: {\n cases: [\n {\n // `display:contents` generates no box, so removing it is provably layout-identical → the\n // wrapper is flattened even under the conservative gate; the child is hoisted.\n before: '<div className=\"contents\"><a className=\"text-blue-500\">Link</a></div>',\n after: '<a className=\"text-blue-500\">Link</a>',\n },\n ],\n noMatch: [\n // A ref pins the wrapper's element identity (a hard opacity barrier) → not a passthrough.\n '<div className=\"contents\" ref={rootRef}><a className=\"text-blue-500\">Link</a></div>',\n ],\n },\n});\n","/**\n * @domflax/patterns — flatten pattern: `empty-style-div`.\n *\n * Collapses the most common piece of structural noise of all: a `<div>` whose ONLY role is to wrap\n * a single child while contributing nothing to layout or paint —\n *\n * <div><Child/></div> (no styles at all)\n * <div style=\"display:block\"><Child/></div> (the default; still a no-op box)\n *\n * Such a div is layout-neutral: it is a plain block box with no own visual style, establishes no\n * box / formatting / stacking context, is not a containing block, and declares no custom properties\n * a descendant might read. Its box is therefore indistinguishable from \"not being there\", so it can\n * be unwrapped into its sole child.\n *\n * Authored with the declarative {@link definePattern} API. The opacity-barrier + selector-safety\n * guards (ref/handlers/dynamic-children/raw-html/combinator/reparent-impact) are applied\n * automatically for every `flatten/*` pattern; the `where` predicates below add the LAYOUT-neutrality\n * requirements specific to this pattern (no non-block display, no box/formatting/stacking context, no\n * containing block, no custom-property coupling, no structural-pseudo targeting).\n */\n\nimport type {\n CssProperty,\n DeepReadonly,\n IRElement,\n IRNode,\n IRNodeId,\n NodeLike,\n NodeMeta,\n StyleMap,\n} from '@domflax/core';\n\nimport { definePattern, not, type Matcher } from '@domflax/pattern-kit';\n\n/* ───────────────────────── local matcher helpers ───────────────────────── */\n\n/** Narrow a NodeLike to a (readonly) element, or null. */\nfunction asEl(node: NodeLike): DeepReadonly<IRElement> | null {\n const n = node as DeepReadonly<IRNode>;\n return n.kind === 'element' ? (n as DeepReadonly<IRElement>) : null;\n}\n\n/** A boolean `meta` flag, lifted into a {@link Matcher}. Mirrors how core's combinators read meta. */\nfunction metaFlag(flag: keyof NodeMeta): Matcher {\n return (node) => Boolean(asEl(node)?.meta[flag]);\n}\n\n/** Wrapper establishes an intrinsic/explicit box (sizing) — NOT layout-neutral. */\nconst establishesBox = metaFlag('establishesBox');\n/** Wrapper establishes a formatting context (flex/grid/flow-root/…) — NOT layout-neutral. */\nconst establishesFormattingContext = metaFlag('establishesFormattingContext');\n/** Wrapper establishes a stacking context (transform/opacity<1/z-index/…) — NOT layout-neutral. */\nconst establishesStackingContext = metaFlag('establishesStackingContext');\n/** Wrapper is the containing block for abs/fixed descendants — removing it would reposition them. */\nconst isContainingBlock = metaFlag('isContainingBlock');\n/** Wrapper sets `--*` custom properties a descendant reads (author-var coupling). */\nconst declaresCustomProperties = metaFlag('declaresCustomProperties');\n\n/**\n * Wrapper is a structural-pseudo target (:first/:last/:only/:nth-child/-of-type). Honours the\n * frontend-set meta flag and the precomputed {@link SelectorIndex}. Unwrapping such a node would\n * change a selector's match-set.\n */\nconst targetedByStructuralPseudo: Matcher = (node, ctx) => {\n const el = asEl(node);\n if (!el) return false;\n if (el.meta.targetedByStructuralPseudo) return true;\n return ctx.selectors.targetedByStructuralPseudo(el.id as unknown as IRNodeId);\n};\n\nconst DISPLAY = 'display' as CssProperty;\n\n/**\n * True when the wrapper sets `display` to anything other than the block default in ANY condition.\n * An `inline`/`inline-block`/`flex`/`grid`/`contents`/`none` div is NOT layout-neutral — its box (or\n * lack of one) participates in layout differently from its surviving child.\n */\nconst hasNonBlockDisplay: Matcher = (node, ctx) => {\n const el = asEl(node);\n if (!el) return false;\n const sm: StyleMap = ctx.computedOf(el as unknown as NodeLike) ?? (el.computed as StyleMap);\n for (const block of sm.blocks.values()) {\n const decl = block.decls.get(DISPLAY);\n if (decl && String(decl.value) !== 'block') return true;\n }\n return false;\n};\n\n/* ───────────────────────── the pattern ───────────────────────── */\n\n/**\n * Flatten a layout-neutral, style-free `<div>` wrapper into its sole element child.\n */\nexport const emptyStyleDiv = definePattern({\n name: 'empty-style-div',\n category: 'flatten/wrapper/empty-style-div',\n safety: 1,\n doc: {\n title: 'Flatten empty-style div wrapper',\n summary:\n 'A layout-neutral div (display:block default, no box/visual styles) that wraps a single ' +\n 'child is removed; the child is hoisted into its place.',\n before: '<div><Child/></div>',\n after: '<Child/>',\n safetyRationale:\n 'Wrapper is a plain block box that paints nothing, establishes no box/formatting/stacking ' +\n 'context, is no containing block, has no custom-property coupling, carries no ' +\n 'ref/handlers/dynamic children/raw HTML, and is neither a combinator subject nor a ' +\n 'structural-pseudo target; inheritable styles are folded onto the child before removal.',\n },\n match: {\n tag: 'div',\n onlyChild: 'element',\n paintsNothing: true,\n where: [\n not(hasNonBlockDisplay),\n not(establishesBox),\n not(establishesFormattingContext),\n not(establishesStackingContext),\n not(isContainingBlock),\n not(declaresCustomProperties),\n not(targetedByStructuralPseudo),\n ],\n },\n rewrite: { flattenInto: 'child' },\n test: {\n cases: [\n {\n // A layout-neutral, style-free block div is a provably-safe flatten → removed, child hoisted.\n before: '<div><span className=\"bg-red-200\">Hi</span></div>',\n after: '<span className=\"bg-red-200\">Hi</span>',\n },\n ],\n noMatch: [\n // The wrapper paints its own background (own visual style) → not layout-neutral, kept.\n '<div className=\"bg-blue-500\"><span className=\"bg-red-200\">Hi</span></div>',\n ],\n },\n});\n","/**\n * @domflax/patterns — flatten pattern: `inherited-only-wrapper`.\n *\n * Collapses a paint-free wrapper whose ONLY own declarations are INHERITED properties\n * (`text-align`, `color`, `font-*`, `line-height`, `letter-spacing`, `white-space`, …):\n *\n * <div style=\"text-align:center\"><Child/></div> → <Child style=\"text-align:center\"/>\n *\n * An inherited property on a wrapper reaches its descendants purely through inheritance, so folding it\n * onto the sole child and removing the box is render-identical — the child (and everything below it)\n * still sees the same inherited value. The wrapper carries nothing NON-inherited (no padding, margin,\n * sizing, border, background, layout), so its box contributes nothing to flow or paint.\n *\n * Distinct from `passthrough-wrapper` in INTENT: it recognizes the common \"styling wrapper\" idiom —\n * a box that exists only to set an inherited text/font property on a subtree — and pushes that intent\n * down onto the child. `foldInheritedStyles` (auto-applied by the flatten recipe) performs the fold;\n * the `where` predicate restricts the match to wrappers whose entire own style is inheritable.\n */\n\nimport type { DeepReadonly, IRElement, IRNode } from '@domflax/core';\n\nimport { definePattern, normalizer, not, type Matcher } from '@domflax/pattern-kit';\n\n/**\n * The wrapper is an inert host element — a `<div>` (block) or `<span>` (inline) — whose user-agent\n * default display/box is layout-neutral. Removing such a box is provably safe; removing a UA-significant\n * element instead (`<li>`/`<p>`/`<td>`/…, whose default display or margins are NOT captured in the\n * class-derived computed style) or a component is NOT, so those are excluded. This mirrors the tag guard\n * every other safe wrapper pattern (passthrough/empty-style-div/redundant-inline) relies on.\n */\nconst INERT_HOST_TAGS: ReadonlySet<string> = new Set(['div', 'span']);\nconst isInertHostTag: Matcher = (node) => {\n const n = node as DeepReadonly<IRNode>;\n if (n.kind !== 'element') return false;\n return INERT_HOST_TAGS.has(String((n as DeepReadonly<IRElement>).tag).toLowerCase());\n};\n\n/** Component identity is a hard opacity barrier — never fold-and-remove a component wrapper. */\nconst isComponentNode: Matcher = (node) => {\n const n = node as DeepReadonly<IRNode>;\n return n.kind === 'element' ? (n as DeepReadonly<IRElement>).meta.isComponent : false;\n};\n\n/**\n * The wrapper carries at least one own declaration and EVERY own declaration is an inherited property\n * — so the whole wrapper style survives the box removal by being folded onto the child.\n */\nconst hasOnlyInheritedStyle: Matcher = (node, ctx) => {\n const sm = normalizer.normalizeStyleMap(ctx.computed());\n let sawAny = false;\n for (const block of sm.blocks.values()) {\n for (const decl of block.decls.values()) {\n sawAny = true;\n const inherited = decl.inherited || normalizer.inherited.isInherited(decl.property);\n if (!inherited) return false;\n }\n }\n return sawAny;\n};\n\n/**\n * Flatten a wrapper whose only own style is inherited into its sole element child (folding the\n * inherited declarations down first so the subtree keeps the same inherited values).\n */\nexport const inheritedOnlyWrapper = definePattern({\n name: 'inherited-only-wrapper',\n category: 'flatten/wrapper/inherited-only-wrapper',\n safety: 2,\n doc: {\n title: 'Flatten inherited-only styling wrapper',\n summary:\n 'A paint-free wrapper whose only own declarations are inherited properties (text-align, color, ' +\n 'font-*, …) is removed; its inherited style is folded onto the sole child, which keeps the ' +\n 'same inherited values for the whole subtree.',\n before: '<div style=\"text-align:center\"><Child/></div>',\n after: '<Child style=\"text-align:center\"/>',\n safetyRationale:\n 'Inherited properties reach descendants purely through inheritance, so folding them onto the ' +\n 'child and removing the box is render-identical. The wrapper carries nothing non-inherited, ' +\n 'establishes no box/formatting/stacking context, and is guarded by the auto-applied ' +\n 'opacity-barrier + selector-safety set.',\n },\n match: {\n onlyChild: 'element',\n paintsNothing: true,\n where: [isInertHostTag, not(isComponentNode), hasOnlyInheritedStyle],\n },\n rewrite: { flattenInto: 'child' },\n test: {\n cases: [\n {\n // `text-align:center` is inherited → folded onto the child; the paint-free wrapper is removed.\n before: '<div className=\"text-center\"><p className=\"bg-red-200\">x</p></div>',\n after: '<p className=\"bg-red-200 text-center\">x</p>',\n },\n ],\n noMatch: [\n // `p-4` is a NON-inherited padding: removing the box would drop it, so the flatten-safety gate\n // reverts the unwrap and the wrapper is left unchanged.\n '<div className=\"p-4\"><p className=\"bg-red-200\">x</p></div>',\n // A `<p>` wrapper is NOT an inert host box: its UA default display/margins are not captured in the\n // class-derived computed style, so removing it is not provably layout-neutral → left unchanged.\n '<p className=\"text-center\"><span className=\"bg-red-200\">x</span></p>',\n ],\n },\n});\n","/**\n * @domflax/patterns — flatten pattern: `passthrough-wrapper`.\n *\n * Collapses a purely-structural wrapper that exists for no reason at all:\n *\n * <div><Child/></div>\n *\n * The wrapper paints nothing, establishes no box / formatting / stacking context, carries no\n * attributes beyond an (optional) inert class, holds exactly one element child, and is free of every\n * opacity barrier (ref / event-handlers / dynamic children / dangerous html / spread / component).\n * Such a `<div>` is pure DOM noise: removing it and hoisting the child is invisible to both paint\n * and layout.\n *\n * Authored with the declarative {@link definePattern} API. The opacity-barrier + selector-safety\n * guards (ref/handlers/dynamic-children/raw-html/combinator/reparent-impact) are applied\n * automatically for every `flatten/*` pattern; the `where` predicates add the passthrough-specific\n * requirements (no box/formatting/stacking context, no own attrs, no dynamic/spread classes, not a\n * component, not a structural-pseudo subject).\n */\n\nimport type {\n DeepReadonly,\n IRElement,\n IRNode,\n IRNodeId,\n NodeLike,\n NodeMeta,\n} from '@domflax/core';\n\nimport { definePattern, hasDynamicClasses, not, type Matcher } from '@domflax/pattern-kit';\n\n/* ───────────────────────── local meta/attr/selector matchers ───────────────────────── */\n\nfunction metaOf(node: NodeLike): DeepReadonly<NodeMeta> | null {\n const n = node as DeepReadonly<IRNode>;\n return n.kind === 'element' ? (n as DeepReadonly<IRElement>).meta : null;\n}\n\nfunction elementOf(node: NodeLike): DeepReadonly<IRElement> | null {\n const n = node as DeepReadonly<IRNode>;\n return n.kind === 'element' ? (n as DeepReadonly<IRElement>) : null;\n}\n\n/**\n * Element establishes some box / formatting / stacking context, is a containing block, or exposes\n * custom properties to a descendant — any of which means removing its box could shift layout or\n * break a `var()` coupling, so it is NOT a passthrough.\n */\nconst establishesContext: Matcher = (node) => {\n const m = metaOf(node);\n if (!m) return false;\n return (\n m.establishesBox ||\n m.establishesFormattingContext ||\n m.establishesStackingContext ||\n m.isContainingBlock ||\n m.declaresCustomProperties\n );\n};\n\n/** Hard opacity barriers beyond the auto-applied set: spread attrs, component identity. */\nconst hasSpreadAttrs: Matcher = (node) => metaOf(node)?.hasSpreadAttrs ?? false;\nconst isComponentNode: Matcher = (node) => metaOf(node)?.isComponent ?? false;\n\n/** Element carries own attributes (id / data-* / …) beyond its class list — possible selector/JS hook. */\nconst hasOwnAttrs: Matcher = (node) => {\n const el = elementOf(node);\n if (!el) return false;\n return el.attrs.entries.size > 0 || el.attrs.spreads.length > 0;\n};\n\n/**\n * Element is the subject of a structural pseudo (`:first/:last/:only/:nth-*`). Honours the meta flag\n * and the precomputed {@link SelectorIndex}.\n */\nconst targetedByStructuralPseudo: Matcher = (node, ctx) => {\n const el = elementOf(node);\n if (!el) return false;\n if (el.meta.targetedByStructuralPseudo) return true;\n return ctx.selectors.targetedByStructuralPseudo(el.id as unknown as IRNodeId);\n};\n\n/* ───────────────────────── the pattern ───────────────────────── */\n\n/**\n * Flatten a do-nothing `<div>` wrapper into its sole element child, folding any inheritable styles\n * down first so inherited values survive the box removal.\n */\nexport const passthroughWrapper = definePattern({\n name: 'passthrough-wrapper',\n category: 'flatten/wrapper/passthrough-wrapper',\n safety: 2,\n doc: {\n title: 'Flatten passthrough wrapper',\n summary:\n 'A div with no own visual/box style, no attributes beyond an inert class, exactly one ' +\n 'element child, and no opacity barriers is removed; its sole child is hoisted in its place.',\n before: '<div><Child/></div>',\n after: '<Child/>',\n safetyRationale:\n 'Wrapper paints nothing and establishes no layout/paint/var context, carries no ' +\n 'ref/handlers/dynamic-children/html/spread/component identity, owns no targetable attrs, ' +\n 'and is not a combinator/structural-pseudo subject (reparenting changes no match-set); ' +\n 'inheritable styles are folded onto the child before removal.',\n },\n match: {\n tag: 'div',\n onlyChild: 'element',\n paintsNothing: true,\n where: [\n not(establishesContext),\n not(hasOwnAttrs),\n not(hasDynamicClasses),\n not(hasSpreadAttrs),\n not(isComponentNode),\n not(targetedByStructuralPseudo),\n ],\n },\n rewrite: { flattenInto: 'child' },\n test: {\n cases: [\n {\n // A plain, style-free wrapper paints nothing and establishes no context → a provably-safe\n // flatten under the conservative gate: the wrapper is removed and its sole child hoisted.\n before: '<div><a className=\"bg-red-200\">Link</a></div>',\n after: '<a className=\"bg-red-200\">Link</a>',\n },\n ],\n noMatch: [\n // A ref pins the wrapper's element identity (a hard opacity barrier) → not a passthrough.\n '<div ref={rootRef}><a className=\"bg-red-200\">Link</a></div>',\n // A `display:flex` wrapper establishes a formatting context, so removing its box is NOT\n // provably layout-neutral → the conservative gate leaves it in place.\n '<div className=\"flex\"><a className=\"bg-red-200\">Link</a></div>',\n ],\n },\n});\n","/**\n * @domflax/patterns — flatten pattern: `redundant-inline-wrapper`.\n *\n * Collapses a purely-structural INLINE wrapper:\n *\n * <span><Child/></span> (display:inline, no own style)\n *\n * An inline `<span>` that paints nothing, establishes no box / formatting / stacking context, carries\n * no attributes beyond an (optional) inert class, declares no custom properties, and holds exactly one\n * element child is pure inline noise. An empty inline box merely wraps its child's box; removing it and\n * hoisting the child leaves both paint and layout untouched (the surviving child folds the inheritable\n * declarations the span carried).\n *\n * This is the inline sibling of `passthrough-wrapper` (which targets `<div>`): the same opacity-barrier\n * + selector-safety guards are auto-applied by the `pattern()` factory for every `flatten/*` pattern;\n * the `where` predicates add the inline-passthrough requirements (display must be the inline default,\n * no box/formatting/stacking context or var coupling, no own attrs / dynamic-or-spread classes, not a\n * component, not a structural-pseudo subject).\n */\n\nimport type {\n CssProperty,\n DeepReadonly,\n IRElement,\n IRNode,\n IRNodeId,\n NodeLike,\n NodeMeta,\n StyleMap,\n} from '@domflax/core';\n\nimport { definePattern, hasDynamicClasses, not, type Matcher } from '@domflax/pattern-kit';\n\n/* ───────────────────────── local meta/attr/selector matchers ───────────────────────── */\n\nfunction asEl(node: NodeLike): DeepReadonly<IRElement> | null {\n const n = node as DeepReadonly<IRNode>;\n return n.kind === 'element' ? (n as DeepReadonly<IRElement>) : null;\n}\n\nfunction metaOf(node: NodeLike): DeepReadonly<NodeMeta> | null {\n return asEl(node)?.meta ?? null;\n}\n\n/**\n * Element establishes some box / formatting / stacking context, is a containing block, or exposes\n * custom properties to a descendant — removing its box could shift layout or sever a `var()` coupling,\n * so it is NOT an inline passthrough.\n */\nconst establishesContext: Matcher = (node) => {\n const m = metaOf(node);\n if (!m) return false;\n return (\n m.establishesBox ||\n m.establishesFormattingContext ||\n m.establishesStackingContext ||\n m.isContainingBlock ||\n m.declaresCustomProperties\n );\n};\n\n/** Hard opacity barriers beyond the auto-applied set: spread attrs, component identity. */\nconst hasSpreadAttrs: Matcher = (node) => metaOf(node)?.hasSpreadAttrs ?? false;\nconst isComponentNode: Matcher = (node) => metaOf(node)?.isComponent ?? false;\n\n/** Element carries own attributes (id / data-* / …) beyond its class list — possible selector/JS hook. */\nconst hasOwnAttrs: Matcher = (node) => {\n const el = asEl(node);\n if (!el) return false;\n return el.attrs.entries.size > 0 || el.attrs.spreads.length > 0;\n};\n\n/**\n * Element is the subject of a structural pseudo (`:first/:last/:only/:nth-*`). Honours the meta flag\n * and the precomputed {@link SelectorIndex}.\n */\nconst targetedByStructuralPseudo: Matcher = (node, ctx) => {\n const el = asEl(node);\n if (!el) return false;\n if (el.meta.targetedByStructuralPseudo) return true;\n return ctx.selectors.targetedByStructuralPseudo(el.id as unknown as IRNodeId);\n};\n\nconst DISPLAY = 'display' as CssProperty;\n\n/**\n * Element sets `display` to anything other than the inline default in ANY condition. An\n * inline-block / block / flex / grid / contents span is NOT an inline passthrough — its box (or lack\n * of one) participates in layout differently from a bare inline box.\n */\nconst hasNonInlineDisplay: Matcher = (node, ctx) => {\n const el = asEl(node);\n if (!el) return false;\n const sm: StyleMap = ctx.computedOf(el as unknown as NodeLike) ?? (el.computed as StyleMap);\n for (const block of sm.blocks.values()) {\n const decl = block.decls.get(DISPLAY);\n if (decl && String(decl.value) !== 'inline') return true;\n }\n return false;\n};\n\n/* ───────────────────────── the pattern ───────────────────────── */\n\n/**\n * Flatten a do-nothing inline `<span>` wrapper into its sole element child, folding any inheritable\n * styles down first so inherited values survive the box removal.\n */\nexport const redundantInlineWrapper = definePattern({\n name: 'redundant-inline-wrapper',\n category: 'flatten/wrapper/redundant-inline-wrapper',\n safety: 2,\n doc: {\n title: 'Flatten redundant inline wrapper',\n summary:\n 'An inline span with no own visual/box style, no attributes beyond an inert class, exactly ' +\n 'one element child, and no opacity barriers is removed; its sole child is hoisted in its place.',\n before: '<span><Child/></span>',\n after: '<Child/>',\n safetyRationale:\n 'An empty inline box paints nothing and establishes no layout/paint/var context; with the ' +\n 'inline default display and a single element child its removal changes no paint and no flow. ' +\n 'The span carries no ref/handlers/dynamic-children/html/spread/component identity, owns no ' +\n 'targetable attrs, and is not a combinator/structural-pseudo subject; inheritable styles are ' +\n 'folded onto the child before removal.',\n },\n match: {\n tag: 'span',\n onlyChild: 'element',\n paintsNothing: true,\n where: [\n not(hasNonInlineDisplay),\n not(establishesContext),\n not(hasOwnAttrs),\n not(hasDynamicClasses),\n not(hasSpreadAttrs),\n not(isComponentNode),\n not(targetedByStructuralPseudo),\n ],\n },\n rewrite: { flattenInto: 'child' },\n test: {\n cases: [\n {\n // An empty inline span paints nothing and establishes no context → a provably-safe flatten:\n // the span is removed and its sole child hoisted in place.\n before: '<span><a className=\"text-blue-500\">Link</a></span>',\n after: '<a className=\"text-blue-500\">Link</a>',\n },\n ],\n noMatch: [\n // A ref pins the span's element identity (a hard opacity barrier) → not a passthrough.\n '<span ref={spanRef}><a className=\"text-blue-500\">Link</a></span>',\n // The span paints its own background (own visual style) → kept.\n '<span className=\"bg-green-200\"><a className=\"text-blue-500\">Link</a></span>',\n // Non-inline display (inline-block) participates in layout differently → kept.\n '<span className=\"inline-block\"><a className=\"text-blue-500\">Link</a></span>',\n ],\n },\n});\n","/**\n * AUTO-GENERATED by `scripts/gen-registry.mjs` — DO NOT EDIT BY HAND.\n *\n * Regenerate with `npm run generate` (also runs automatically before build/typecheck/test).\n * Patterns are discovered by the recursive `*.pattern.ts` file convention (organized into DOMAIN\n * folders under `src/library/`); the array below is sorted flatten-before-compress.\n */\n\nimport type { Pattern } from '@domflax/core';\n\nimport { flexCenterWrapper } from './library/flex/flex-center-wrapper.pattern';\nimport { redundantFragment } from './library/fragment/redundant-fragment.pattern';\nimport { gridCenterWrapper } from './library/grid/grid-center-wrapper.pattern';\nimport { displayContentsWrapper } from './library/wrapper/display-contents-wrapper.pattern';\nimport { emptyStyleDiv } from './library/wrapper/empty-style-div.pattern';\nimport { inheritedOnlyWrapper } from './library/wrapper/inherited-only-wrapper.pattern';\nimport { passthroughWrapper } from './library/wrapper/passthrough-wrapper.pattern';\nimport { redundantInlineWrapper } from './library/wrapper/redundant-inline-wrapper.pattern';\n\nexport {\n flexCenterWrapper,\n redundantFragment,\n gridCenterWrapper,\n displayContentsWrapper,\n emptyStyleDiv,\n inheritedOnlyWrapper,\n passthroughWrapper,\n redundantInlineWrapper,\n};\n\n/** Every built-in pattern, in registration order (flatten patterns before compress). */\nexport const builtinPatterns: readonly Pattern[] = [\n flexCenterWrapper,\n redundantFragment,\n gridCenterWrapper,\n displayContentsWrapper,\n emptyStyleDiv,\n inheritedOnlyWrapper,\n passthroughWrapper,\n redundantInlineWrapper,\n];\n\nexport default builtinPatterns;\n","/**\n * @domflax/resolver-tailwind — tiny dependency-free hash for cache-busting fingerprints.\n */\n\n/** Tiny, dependency-free FNV-1a string hash (hex). Used to derive the cache-busting fingerprint. */\nexport function fnv1a(input: string): string {\n let h = 0x811c9dc5;\n for (let i = 0; i < input.length; i += 1) {\n h ^= input.charCodeAt(i);\n h = Math.imul(h, 0x01000193);\n }\n return (h >>> 0).toString(16).padStart(8, '0');\n}\n","/**\n * @domflax/resolver-tailwind — emit-side shorthand expansion + residual synthesis.\n */\n\nimport type {\n CssProperty,\n EmitContext,\n StyleBlock,\n StyleDecl,\n StyleMap,\n SyntheticClass,\n} from '@domflax/core';\nimport { BASE_CONDITION, conditionKey } from '@domflax/core';\nimport { normalizer } from '@domflax/pattern-kit';\n\nimport { fnv1a } from './fingerprint';\n\n/**\n * Expand a single computed declaration into the canonical LONGHAND `[property, value]` pairs the\n * reverse index is keyed on. The shared normalizer already expands the physical box shorthands\n * (`padding`/`margin`/`inset`/`border-*`); we additionally expand the few logical shorthands the\n * compress passes synthesize that the normalizer leaves intact (`size`, `inset-block`,\n * `inset-inline`). Values are re-canonicalized via the normalizer so they match the index exactly.\n */\nexport function expandForEmit(\n norm: { normalizeDeclaration: typeof normalizer.normalizeDeclaration },\n prop: string,\n value: string,\n important: boolean,\n): Array<readonly [CssProperty, string]> {\n const pairsFor = (p: string, v: string): Array<readonly [CssProperty, string]> =>\n norm.normalizeDeclaration(p, v, important).map((d) => [d.property, String(d.value)] as const);\n\n if (prop === 'size') {\n return [...pairsFor('width', value), ...pairsFor('height', value)];\n }\n if (prop === 'inset-block' || prop === 'inset-inline') {\n const parts = value.split(/\\s+/).filter((s) => s.length > 0);\n const a = parts[0] ?? value;\n const b = parts[1] ?? a;\n const sides = prop === 'inset-block' ? (['top', 'bottom'] as const) : (['left', 'right'] as const);\n return [...pairsFor(sides[0], a), ...pairsFor(sides[1], b)];\n }\n return pairsFor(prop, value);\n}\n\n/** Build a residual {@link SyntheticClass} for declarations no utility covered; `null` on failure. */\nexport function synthesizeResidual(\n remaining: ReadonlyMap<CssProperty, string>,\n ctx: EmitContext,\n): SyntheticClass | undefined {\n if (remaining.size === 0) return undefined;\n const norm = ctx.normalizer ?? normalizer;\n const decls = new Map<CssProperty, StyleDecl>();\n for (const [prop, value] of remaining) {\n for (const decl of norm.normalizeDeclaration(String(prop), value, false)) {\n decls.set(decl.property, decl);\n }\n }\n const block: StyleBlock = { condition: BASE_CONDITION, decls };\n const styleMap: StyleMap = { blocks: new Map([[conditionKey(BASE_CONDITION), block]]) };\n const css = [...remaining].map(([p, v]) => `${p}:${v}`).join(';');\n const className = `df-${fnv1a(css)}`;\n const synthetic: SyntheticClass = { className, decls: styleMap, css: `.${className}{${css}}` };\n try {\n ctx.sink.register(synthetic);\n } catch {\n /* a sink that rejects registration must not break emit */\n }\n return synthetic;\n}\n","/**\n * @domflax/resolver-tailwind — engine loading (synchronous v3 internals).\n *\n * The forward/reverse engine lives in tailwindcss' CommonJS internals. We load them through\n * `createRequire` (rather than `import`) so the exact same code path works whether this module is\n * bundled to ESM or CJS, and so the untyped internal subpaths don't need ambient declarations.\n *\n * CRITICAL (bundling): tailwindcss must be resolved from the CONSUMER'S project, NOT from the file\n * this module happens to live in. When `domflax` inlines this resolver into its own bundle\n * (`noExternal: [/^@domflax\\//]`), a require based on the bundle's location (`__filename`) would\n * look for `tailwindcss` next to `domflax/dist`, where it does not exist — so the engine silently\n * failed to load and `emit`'s reverse index came up empty. Instead we root the require in the user's\n * project (an explicit project root, then `process.cwd()`), exactly how prettier-plugin-tailwindcss\n * and the Tailwind IntelliSense engine locate a project's Tailwind. The bundle/source location is\n * kept only as a last-resort fallback (covers the non-bundled / in-repo dev case). The first base\n * from which `tailwindcss/package.json` resolves wins.\n */\n\nimport { createRequire } from 'node:module';\nimport * as path from 'node:path';\n\nimport type { TailwindResolverConfig } from './config';\nimport { loadV4Engine } from './engine-v4';\nimport type { TwContext, TwEngine, TwNode } from './types';\n\n/**\n * This module's own location, used as a last-resort require base. esbuild substitutes a real\n * `__filename` in a CJS bundle; in an ESM bundle `__filename` is undefined and we fall back to\n * `import.meta.url` (a `file://` URL, which `createRequire` accepts).\n */\nfunction moduleBase(): string {\n return typeof __filename === 'string' ? __filename : import.meta.url;\n}\n\n/**\n * Build a `require` rooted in the consumer's project so engine resolution is independent of where\n * this (possibly bundled) module physically lives. Returns `null` if `tailwindcss` resolves from no\n * candidate base.\n */\nfunction projectRequire(projectRoot?: string): NodeRequire | null {\n const bases: string[] = [];\n // A real file name is irrelevant — `createRequire` only uses the containing directory for\n // resolution; the file need not exist.\n if (projectRoot) bases.push(path.join(projectRoot, '__domflax__.js'));\n bases.push(path.join(process.cwd(), '__domflax__.js'));\n bases.push(moduleBase());\n for (const base of bases) {\n try {\n const candidate = createRequire(base);\n candidate.resolve('tailwindcss/package.json');\n return candidate;\n } catch {\n /* try the next base */\n }\n }\n return null;\n}\n\n/**\n * The FIRST major whose engine internals the v3 CODE PATH cannot drive. v4+ is handled by a separate\n * adapter ({@link loadV4Engine}); only when THAT adapter also fails do we treat the major as\n * unsupported and fall back to the safe \"everything UNKNOWN ⇒ files unchanged\" behavior.\n */\nexport const FIRST_UNSUPPORTED_MAJOR = 4;\n\n/** The outcome of trying to load the project's Tailwind engine. */\nexport interface LoadedEngine {\n /** The synchronous forward/reverse engine, or `null` when it could not be built. */\n readonly engine: TwEngine | null;\n /** The resolved `tailwindcss` version, or `null` when the package could not be located at all. */\n readonly version: string | null;\n /**\n * SAFETY (Layer 1): set to the detected MAJOR when the project's `tailwindcss` is a version this\n * resolver cannot drive (>= {@link FIRST_UNSUPPORTED_MAJOR}, e.g. v4's rewritten engine). In that\n * case `engine` is `null` and — rather than silently resolving every class to empty and then\n * mis-optimizing — the resolver reports every token as UNKNOWN so files are left UNCHANGED, and\n * surfaces a one-time diagnostic. `null` for a supported/driveable (or absent) Tailwind.\n */\n readonly unsupportedMajor: number | null;\n}\n\n/** Parse the leading integer major from a semver-ish version string, or `null`. */\nfunction majorOf(version: string): number | null {\n const m = /^\\s*(\\d+)/.exec(version);\n return m ? Number(m[1]) : null;\n}\n\n/**\n * Load a synchronous Tailwind engine for the given resolved config. Detects the project's\n * `tailwindcss` version FIRST: a MAJOR this resolver cannot drive (v4+) fails LOUDLY via\n * {@link LoadedEngine.unsupportedMajor} (engine `null`) instead of silently returning empty\n * resolutions. Any other initialization failure returns a `null` engine with no version.\n */\nexport function loadEngine(options: TailwindResolverConfig): LoadedEngine {\n const req = projectRequire(options.projectRoot);\n if (!req) return { engine: null, version: null, unsupportedMajor: null };\n\n // Read the version BEFORE touching the (v3-shaped) internals: v4 ships a different engine at\n // `dist/lib.js` and has no `lib/lib/*.js` CJS internals, so probing them would only throw — we want\n // to positively identify v4 and refuse to drive it, not fall through to a generic failure.\n let version: string | null = null;\n try {\n version = (req('tailwindcss/package.json') as { version: string }).version;\n } catch {\n return { engine: null, version: null, unsupportedMajor: null };\n }\n const major = majorOf(version);\n if (major !== null && major >= FIRST_UNSUPPORTED_MAJOR) {\n // v4+: drive the project's REAL design system through the v4 adapter (a synchronous snapshot of\n // its async API). Success ⇒ a normal, fully-resolving engine. Failure ⇒ fall back to the fail-safe\n // (`unsupportedMajor` set ⇒ every class UNKNOWN ⇒ files left unchanged), never a wrong resolution.\n const projectRoot = options.projectRoot ?? process.cwd();\n let v4: TwEngine | null = null;\n try {\n v4 = loadV4Engine(projectRoot, version);\n } catch {\n v4 = null;\n }\n if (v4) return { engine: v4, version, unsupportedMajor: null };\n return { engine: null, version, unsupportedMajor: major };\n }\n\n try {\n const resolveConfig = req('tailwindcss/resolveConfig.js') as (c: unknown) => unknown;\n const { createContext } = req('tailwindcss/lib/lib/setupContextUtils.js') as {\n createContext: (config: unknown) => TwContext;\n };\n const { generateRules } = req('tailwindcss/lib/lib/generateRules.js') as {\n generateRules: (candidates: Set<string>, context: TwContext) => Array<[number, TwNode]>;\n };\n\n let userConfig: unknown = options.config ?? { content: [{ raw: '' }] };\n if (options.configPath !== undefined) {\n const loadConfig = req('tailwindcss/loadConfig.js') as (p: string) => unknown;\n userConfig = loadConfig(options.configPath);\n }\n const resolved = resolveConfig(userConfig);\n const context = createContext(resolved);\n\n return {\n engine: {\n version,\n context,\n generate(candidates: readonly string[]): TwNode[] {\n const rules = generateRules(new Set(candidates), context);\n return rules.map(([, node]) => node);\n },\n },\n version,\n unsupportedMajor: null,\n };\n } catch {\n return { engine: null, version, unsupportedMajor: null };\n }\n}\n","/**\n * @domflax/resolver-tailwind — Tailwind v4 engine adapter.\n *\n * Builds a {@link TwEngine} (the SAME interface the v3 path exposes) backed by a synchronous snapshot\n * of the project's real v4 design system (see {@link runV4Bridge}). Because it satisfies `TwEngine`\n * exactly — `version`, `context.getClassList()`, `generate(candidates)` — the resolver, extractor,\n * emitter and serializer all work UNCHANGED; the only v4-specific step is parsing each utility's CSS\n * ({@link parseUtilityCss}), which yields the identical flat {@link TwNode} shape v3 produces.\n *\n * SAFETY: if the snapshot cannot be built (no `@tailwindcss/node`, load error, timeout, …) this\n * returns `null` and the caller falls back to the fail-safe (every class UNKNOWN ⇒ files unchanged).\n */\n\nimport { readdirSync, readFileSync, statSync } from 'node:fs';\nimport * as path from 'node:path';\n\nimport { runV4Bridge } from './v4-bridge';\nimport type { V4CssEntry } from './v4-bridge';\nimport type { TwEngine, TwNode } from './types';\nimport { parseUtilityCss } from './v4-css';\n\n/** Directories worth scanning for the Tailwind CSS entry; anything else is skipped. */\nconst SEARCH_DIRS = ['', 'src', 'app', 'styles', 'src/styles', 'src/app', 'app/styles', 'assets/css', 'css'];\nconst SKIP_DIRS = new Set(['node_modules', '.git', 'dist', 'build', 'out', '.next', 'coverage']);\nconst ENTRY_RE = /@import\\s+[\"']tailwindcss[\"']|@tailwind\\b|@theme\\b/;\n\n/** Shallowly scan one directory (non-recursive) for a `.css` file that looks like the TW entry. */\nfunction scanDir(dir: string): V4CssEntry | null {\n let names: string[];\n try {\n names = readdirSync(dir);\n } catch {\n return null;\n }\n for (const name of names) {\n if (!name.toLowerCase().endsWith('.css')) continue;\n const file = path.join(dir, name);\n try {\n if (!statSync(file).isFile()) continue;\n const css = readFileSync(file, 'utf8');\n if (ENTRY_RE.test(css)) return { css, base: path.dirname(file) };\n } catch {\n /* unreadable file — skip */\n }\n }\n return null;\n}\n\n/**\n * Assemble the ordered CSS-entry candidates the bridge should try: the project's real Tailwind entry\n * (found by a bounded scan of a few conventional directories) first, then a minimal\n * `@import \"tailwindcss\";` default so a design system can still be loaded when no entry is found.\n */\nexport function findCssEntries(projectRoot: string): V4CssEntry[] {\n const out: V4CssEntry[] = [];\n const seen = new Set<string>();\n for (const rel of SEARCH_DIRS) {\n const dir = path.resolve(projectRoot, rel);\n if (seen.has(dir) || [...SKIP_DIRS].some((s) => dir.includes(`${path.sep}${s}`))) continue;\n seen.add(dir);\n const hit = scanDir(dir);\n if (hit) {\n out.push(hit);\n break; // first plausible entry wins (conventional dirs are ordered shallow → deep)\n }\n }\n out.push({ css: '@import \"tailwindcss\";', base: projectRoot });\n return out;\n}\n\n/**\n * Adapt a class→CSS snapshot into a {@link TwEngine}. Per-class CSS is parsed lazily (and cached) into\n * the flat {@link TwNode} shape shared with v3, so `generate([...])` is a lookup + parse.\n */\nfunction makeV4Engine(entries: ReadonlyArray<readonly [string, string]>, version: string): TwEngine {\n const cssByClass = new Map<string, string>(entries.map(([name, css]) => [name, css] as const));\n const nodeCache = new Map<string, TwNode[]>();\n\n const nodesFor = (token: string): TwNode[] => {\n let cached = nodeCache.get(token);\n if (!cached) {\n const css = cssByClass.get(token);\n cached = css ? parseUtilityCss(css) : [];\n nodeCache.set(token, cached);\n }\n return cached;\n };\n\n return {\n version,\n context: {\n // The resolver keeps only string entries; we hand it the concrete class names directly.\n getClassList: () => [...cssByClass.keys()],\n },\n generate(candidates: readonly string[]): TwNode[] {\n const out: TwNode[] = [];\n for (const c of candidates) for (const n of nodesFor(c)) out.push(n);\n return out;\n },\n };\n}\n\n/**\n * Try to build a v4-backed {@link TwEngine} for the project. Returns `null` (⇒ fail-safe) when the\n * design-system snapshot cannot be produced. `version` is the already-detected `tailwindcss` version.\n */\nexport function loadV4Engine(projectRoot: string, version: string): TwEngine | null {\n const snapshot = runV4Bridge({ projectRoot, entries: findCssEntries(projectRoot) });\n if (!snapshot) return null;\n return makeV4Engine(snapshot.entries, version);\n}\n","/**\n * @domflax/resolver-tailwind — SYNCHRONOUS bridge to Tailwind v4's async design-system API.\n *\n * The {@link StyleResolver} contract is fully synchronous, but every v4 programmatic entry point\n * (`__unstable__loadDesignSystem`, `compile`) returns a Promise and there is no synchronous\n * design-system constructor. Rather than a blocking-on-promise hack in-process, we run the async load\n * ONCE, at resolver construction, inside a short-lived child `node` process via `execFileSync` (which\n * is synchronous by nature). The child loads the project's real design system, enumerates its full\n * class list, and returns each utility's CSS (`candidatesToCss`) as `[className, css]` pairs. The\n * parent then drives everything synchronously off that snapshot — forward resolution is a map lookup +\n * {@link parseUtilityCss}, and the reverse index is built from the same pairs.\n *\n * SAFETY: the child is fully guarded and its result is treated as advisory — ANY failure (missing\n * `@tailwindcss/node`, load error, timeout, non-JSON output) makes {@link runV4Bridge} return `null`,\n * and the caller then falls back to the fail-safe (every class UNKNOWN ⇒ files left unchanged).\n */\n\nimport { execFileSync } from 'node:child_process';\nimport { mkdtempSync, rmSync, writeFileSync } from 'node:fs';\nimport { tmpdir } from 'node:os';\nimport * as path from 'node:path';\n\n/** A single CSS entry the child should try to load the design system from. */\nexport interface V4CssEntry {\n readonly css: string;\n readonly base: string;\n}\n\nexport interface V4BridgePayload {\n readonly projectRoot: string;\n /** Candidate CSS entries, tried in order until one loads (the last is a minimal default). */\n readonly entries: readonly V4CssEntry[];\n}\n\nexport interface V4BridgeResult {\n /** `[className, cssText]` for every utility whose `candidatesToCss` produced CSS. */\n readonly entries: ReadonlyArray<readonly [string, string]>;\n}\n\n/**\n * The child script, kept as a source STRING (not an imported module) so it survives domflax's bundle\n * and resolves the project's Tailwind independently of where the bundle physically lives. Written to a\n * temp `.mjs` at runtime and executed with `node <script> <payload.json>`; it prints a JSON result.\n */\nconst CHILD_SOURCE = String.raw`\nimport { createRequire } from 'node:module';\nimport { pathToFileURL } from 'node:url';\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\n\nfunction out(obj) { process.stdout.write(JSON.stringify(obj)); process.exit(0); }\n\nlet payload;\ntry { payload = JSON.parse(fs.readFileSync(process.argv[2], 'utf8')); }\ncatch { out({ ok: false }); }\n\nconst projectRoot = payload.projectRoot;\nconst entries = payload.entries || [];\nconst req = createRequire(path.join(projectRoot, '__domflax_tw4__.js'));\n\nasync function importFrom(id) {\n const resolved = req.resolve(id);\n return import(pathToFileURL(resolved).href);\n}\n\n// Primary loader: @tailwindcss/node (the companion every v4 build tool installs). It resolves\n// '@import \"tailwindcss\"' and @theme against the project on disk.\nasync function loadViaNode() {\n let mod;\n try { mod = await importFrom('@tailwindcss/node'); } catch { return null; }\n if (!mod || typeof mod.__unstable__loadDesignSystem !== 'function') return null;\n for (const e of entries) {\n try { return await mod.__unstable__loadDesignSystem(e.css, { base: e.base }); } catch {}\n }\n return null;\n}\n\n// Secondary loader: bare 'tailwindcss' with a filesystem stylesheet resolver (best-effort).\nasync function loadViaCore() {\n let tw;\n try { tw = await importFrom('tailwindcss'); } catch { return null; }\n if (!tw || typeof tw.__unstable__loadDesignSystem !== 'function') return null;\n const loadStylesheet = async (id, base) => {\n const r = createRequire(path.join(base, '__domflax_tw4__.js'));\n let p;\n const tries = id === 'tailwindcss' ? ['tailwindcss/index.css', 'tailwindcss'] : [id, id + '/index.css'];\n for (const t of tries) { try { p = r.resolve(t); break; } catch {} }\n if (!p) p = path.resolve(base, id);\n return { path: p, base: path.dirname(p), content: fs.readFileSync(p, 'utf8') };\n };\n const loadModule = async (id, base) => {\n const r = createRequire(path.join(base, '__domflax_tw4__.js'));\n const p = r.resolve(id);\n return { path: p, base: path.dirname(p), module: (await import(pathToFileURL(p).href)).default };\n };\n for (const e of entries) {\n try { return await tw.__unstable__loadDesignSystem(e.css, { base: e.base, loadStylesheet, loadModule }); } catch {}\n }\n return null;\n}\n\nconst ds = (await loadViaNode()) || (await loadViaCore());\nif (!ds) out({ ok: false });\n\nlet names = [];\ntry {\n names = ds.getClassList().map((e) => (Array.isArray(e) ? e[0] : e)).filter((n) => typeof n === 'string');\n} catch { out({ ok: false }); }\n\nlet css = [];\ntry { css = ds.candidatesToCss(names); } catch { out({ ok: false }); }\n\nconst result = [];\nfor (let i = 0; i < names.length; i += 1) {\n const c = css[i];\n if (typeof c === 'string' && c.length > 0) result.push([names[i], c]);\n}\nout({ ok: true, entries: result });\n`;\n\n/**\n * Run the v4 bridge synchronously. Returns the class→CSS snapshot, or `null` on ANY failure (the\n * caller then uses the fail-safe path). Never throws.\n */\nexport function runV4Bridge(payload: V4BridgePayload): V4BridgeResult | null {\n let dir: string | null = null;\n try {\n dir = mkdtempSync(path.join(tmpdir(), 'domflax-tw4-'));\n const scriptPath = path.join(dir, 'bridge.mjs');\n const payloadPath = path.join(dir, 'payload.json');\n writeFileSync(scriptPath, CHILD_SOURCE, 'utf8');\n writeFileSync(payloadPath, JSON.stringify(payload), 'utf8');\n\n const stdout = execFileSync(process.execPath, [scriptPath, payloadPath], {\n cwd: payload.projectRoot,\n encoding: 'utf8',\n timeout: 90_000,\n maxBuffer: 256 * 1024 * 1024,\n stdio: ['ignore', 'pipe', 'ignore'],\n });\n\n const parsed = JSON.parse(stdout) as { ok?: boolean; entries?: Array<[string, string]> };\n if (!parsed.ok || !Array.isArray(parsed.entries) || parsed.entries.length === 0) return null;\n const entries = parsed.entries.filter(\n (e): e is [string, string] =>\n Array.isArray(e) && typeof e[0] === 'string' && typeof e[1] === 'string',\n );\n return entries.length > 0 ? { entries } : null;\n } catch {\n return null;\n } finally {\n if (dir) {\n try {\n rmSync(dir, { recursive: true, force: true });\n } catch {\n /* best-effort temp cleanup */\n }\n }\n }\n}\n","/**\n * @domflax/resolver-tailwind — parse + FLATTEN Tailwind v4 `candidatesToCss` output into the same\n * flat, v3-shaped {@link TwNode} array the rest of the resolver (extract / emit / serialize) already\n * consumes. This is the ONE v4-specific adapter; everything downstream stays version-agnostic.\n *\n * ## Why a bespoke parser (no postcss)\n *\n * v4's `candidatesToCss(tokens)` returns per-token CSS in the modern NESTED authoring form, e.g.\n *\n * .px-4 { padding-inline: calc(var(--spacing) * 4); }\n * .container { width: 100%; @media (width >= 40rem) { max-width: 40rem; } }\n * .divide-y { :where(& > :not(:last-child)) { border-top-width: …; } }\n * .hover\\:x { &:hover { @media (hover: hover) { … } } }\n *\n * The v3 engine, by contrast, emits FLAT postcss rules (`@media { .md\\:x { … } }`, and combinator\n * utilities as top-level complex-selector rules). `extract.ts` is written against that flat shape and\n * — crucially for SAFETY — classifies a combinator/`&`-nested selector as {@link OpaqueToken} so the\n * element is preserved, never treated as inert. So instead of re-teaching `extract` about nesting, we\n * FLATTEN here: resolve `&` against the parent selector, hoist `@media` into wrapping at-rules, and\n * emit exactly the flat structure v3 produces. A combinator like `divide-y` then flattens to a\n * `:where(.divide-y > …)` rule → `extract` marks it opaque → the element is kept. Bundling postcss\n * into domflax's dist is explicitly avoided (project convention), and a tiny, fail-safe parser we own\n * is unit-testable end to end.\n *\n * ## Fail-safe\n *\n * Any parse/flatten error yields `[]` (⇒ the token is reported UNKNOWN ⇒ the element is preserved).\n * We never invent declarations from malformed input.\n */\n\nimport type { TwGeneratedDecl, TwGeneratedRule, TwNode } from './types';\n\n/* ───────────────────────── raw parse tree ───────────────────────── */\n\ninterface RawDecl {\n readonly type: 'decl';\n readonly prop: string;\n readonly value: string;\n readonly important: boolean;\n}\ninterface RawRule {\n readonly type: 'rule';\n readonly selector: string;\n readonly nodes: RawNode[];\n}\ninterface RawAtRule {\n readonly type: 'atrule';\n readonly name: string;\n readonly params: string;\n readonly nodes: RawNode[];\n}\ntype RawNode = RawDecl | RawRule | RawAtRule;\n\n/** Strip `/* … *​/` comments (v4 prepends a license banner to some output). */\nfunction stripComments(src: string): string {\n return src.replace(/\\/\\*[\\s\\S]*?\\*\\//g, '');\n}\n\n/** Turn a `prop: value` buffer into a declaration, or `null` for empties / at-statements. */\nfunction toDecl(buffer: string): RawDecl | null {\n const buf = buffer.trim();\n if (buf.length === 0 || buf[0] === '@') return null; // `@import …;` etc. carry no element box style\n const colon = buf.indexOf(':');\n if (colon <= 0) return null;\n const prop = buf.slice(0, colon).trim();\n let value = buf.slice(colon + 1).trim();\n if (prop.length === 0 || value.length === 0) return null;\n let important = false;\n const bang = /!\\s*important\\s*$/i.exec(value);\n if (bang) {\n important = true;\n value = value.slice(0, bang.index).trim();\n }\n return { type: 'decl', prop, value, important };\n}\n\n/** Split a `@name params` prelude into its parts. */\nfunction splitAtRule(prelude: string): { name: string; params: string } {\n const m = /^@([A-Za-z-]+)\\s*([\\s\\S]*)$/.exec(prelude);\n if (!m) return { name: prelude.slice(1).trim(), params: '' };\n return { name: m[1]!.toLowerCase(), params: m[2]!.trim() };\n}\n\n/**\n * Recursive-descent block parser. Declaration values in Tailwind output never contain `{`/`}`/`;`\n * (function args use parentheses), so a plain brace/semicolon scanner is sufficient and robust.\n */\nfunction parseBlock(src: string, start: number): { nodes: RawNode[]; next: number } {\n const nodes: RawNode[] = [];\n let buf = '';\n let i = start;\n while (i < src.length) {\n const c = src[i]!;\n if (c === '{') {\n const prelude = buf.trim();\n buf = '';\n const inner = parseBlock(src, i + 1);\n i = inner.next;\n if (prelude.startsWith('@')) {\n const { name, params } = splitAtRule(prelude);\n nodes.push({ type: 'atrule', name, params, nodes: inner.nodes });\n } else if (prelude.length > 0) {\n nodes.push({ type: 'rule', selector: prelude, nodes: inner.nodes });\n }\n } else if (c === '}') {\n const d = toDecl(buf);\n if (d) nodes.push(d);\n return { nodes, next: i + 1 };\n } else if (c === ';') {\n const d = toDecl(buf);\n if (d) nodes.push(d);\n buf = '';\n i += 1;\n } else {\n buf += c;\n i += 1;\n }\n }\n const tail = toDecl(buf);\n if (tail) nodes.push(tail);\n return { nodes, next: i };\n}\n\n/* ───────────────────────── nesting flatten ───────────────────────── */\n\ninterface AtFrame {\n readonly name: string;\n readonly params: string;\n}\ninterface Leaf {\n readonly selector: string;\n readonly at: readonly AtFrame[];\n readonly decls: readonly RawDecl[];\n}\n\n/** Resolve a nested selector against its parent per CSS Nesting (`&` = parent; else descendant). */\nfunction resolveNesting(child: string, parent: string): string {\n const c = child.trim();\n if (parent.length === 0) return c;\n if (c.includes('&')) return c.split('&').join(parent);\n return `${parent} ${c}`;\n}\n\n/** At-rules that never contribute to the element's own box and carry no nested element styles. */\nconst DROP_ATRULES = new Set(['property', 'keyframes', 'font-face', 'charset', 'import']);\n\n/** Recursively hoist a nested tree into flat {@link Leaf}s (selector + at-rule stack + own decls). */\nfunction flattenNodes(nodes: readonly RawNode[], selector: string, at: readonly AtFrame[], out: Leaf[]): void {\n const own: RawDecl[] = [];\n for (const n of nodes) if (n.type === 'decl') own.push(n);\n if (own.length > 0 && selector.length > 0) out.push({ selector, at: [...at], decls: own });\n\n for (const n of nodes) {\n if (n.type === 'rule') {\n flattenNodes(n.nodes, resolveNesting(n.selector, selector), at, out);\n } else if (n.type === 'atrule') {\n if (n.name === 'media') {\n flattenNodes(n.nodes, selector, [...at, { name: 'media', params: n.params }], out);\n } else if (n.name === 'layer') {\n flattenNodes(n.nodes, selector, at, out); // @layer only affects cascade order → transparent\n } else if (!DROP_ATRULES.has(n.name)) {\n // @supports / @container / unknown → keep the wrapper so `extract` treats it as opaque.\n flattenNodes(n.nodes, selector, [...at, { name: n.name, params: n.params }], out);\n }\n }\n }\n}\n\n/** Build a flat {@link TwNode} (at-rule-wrapped rule) from one hoisted leaf. */\nfunction leafToNode(leaf: Leaf): TwNode {\n const declNodes: TwGeneratedDecl[] = leaf.decls.map((d) => ({\n type: 'decl',\n prop: d.prop,\n value: d.value,\n important: d.important,\n }));\n let node: TwNode = { type: 'rule', selector: leaf.selector, nodes: declNodes } satisfies TwGeneratedRule;\n for (let i = leaf.at.length - 1; i >= 0; i -= 1) {\n node = { type: 'atrule', name: leaf.at[i]!.name, params: leaf.at[i]!.params, nodes: [node] };\n }\n return node;\n}\n\n/**\n * Parse one v4 `candidatesToCss` string and return the FLAT {@link TwNode}s (identical in shape to\n * what the v3 engine yields). Returns `[]` on any failure — the fail-safe that keeps the token\n * UNKNOWN so its element is preserved.\n */\nexport function parseUtilityCss(css: string): TwNode[] {\n try {\n const { nodes } = parseBlock(stripComments(css), 0);\n const leaves: Leaf[] = [];\n flattenNodes(nodes, '', [], leaves);\n return leaves.map(leafToNode);\n } catch {\n return [];\n }\n}\n","/**\n * @domflax/resolver-tailwind — selector / condition parsing.\n */\n\nimport type { StyleCondition } from '@domflax/core';\n\n/** Pseudo-elements that Tailwind may emit with a legacy single colon. */\nconst LEGACY_PSEUDO_ELEMENTS = new Set([\n ':before',\n ':after',\n ':first-line',\n ':first-letter',\n]);\n\nexport type ParsedSelector =\n | { readonly kind: 'simple'; readonly states: readonly string[]; readonly pseudoElement: string }\n | { readonly kind: 'complex' };\n\n/**\n * Parse a generated selector into a {@link StyleCondition} fragment. Accepts ONLY a single class\n * selector optionally followed by pseudo-class / pseudo-element parts (`.x`, `.x:hover`,\n * `.x::before`, `.x:focus:hover`). Anything with a combinator, a second compound class, an attribute\n * selector, or a selector list is `complex` (⇒ opaque) because its declarations do not apply to the\n * element's own box.\n */\nexport function parseSelector(selector: string): ParsedSelector {\n const sel = selector.trim();\n if (sel.length === 0 || sel[0] !== '.') return { kind: 'complex' };\n\n // Consume the class identifier, honoring CSS backslash escapes (`\\:`, `\\/`, `\\[`, …).\n let i = 1;\n for (; i < sel.length; i += 1) {\n const c = sel[i]!;\n if (c === '\\\\') {\n i += 1; // skip the escaped char\n continue;\n }\n if (c === ':' || c === '.' || c === '[' || c === ' ' || c === '>' || c === '+' || c === '~' || c === ',') {\n break;\n }\n }\n\n const remainder = sel.slice(i);\n if (remainder.length === 0) {\n return { kind: 'simple', states: [], pseudoElement: '' };\n }\n // The remainder must be EXCLUSIVELY pseudo parts — no combinator / compound / attribute follows.\n if (!/^(?:::?[-a-z]+(?:\\([^()]*\\))?)+$/i.test(remainder)) {\n return { kind: 'complex' };\n }\n\n const parts = remainder.match(/::?[-a-z]+(?:\\([^()]*\\))?/gi) ?? [];\n const states: string[] = [];\n let pseudoElement = '';\n for (const part of parts) {\n if (part.startsWith('::') || LEGACY_PSEUDO_ELEMENTS.has(part)) {\n pseudoElement = part.startsWith('::') ? part : `:${part}`;\n } else {\n states.push(part);\n }\n }\n return { kind: 'simple', states, pseudoElement };\n}\n\nexport function makeCondition(media: string, states: readonly string[], pseudoElement: string): StyleCondition {\n return {\n media,\n states: [...new Set(states)].sort(),\n pseudoElement,\n };\n}\n\n/** Recover a class name from a simple `.escaped-class` selector, or `null` if it isn't simple. */\nexport function unescapeClass(selector: string): string | null {\n const sel = selector.trim();\n if (sel[0] !== '.') return null;\n let out = '';\n for (let i = 1; i < sel.length; i += 1) {\n const c = sel[i]!;\n if (c === '\\\\') {\n i += 1;\n if (i < sel.length) out += sel[i];\n continue;\n }\n if (c === ':' || c === '.' || c === '[' || c === ' ' || c === '>' || c === '+' || c === '~' || c === ',') {\n return null; // not a bare single-class selector\n }\n out += c;\n }\n return out.length > 0 ? out : null;\n}\n","/**\n * @domflax/resolver-tailwind — rule extraction (engine nodes → usable blocks).\n */\n\nimport type { OpaqueToken, StyleCondition } from '@domflax/core';\n\nimport { makeCondition, parseSelector } from './selector';\nimport type { TwGeneratedAtRule, TwGeneratedDecl, TwGeneratedRule, TwNode } from './types';\n\nexport interface ExtractedBlock {\n readonly condition: StyleCondition;\n readonly decls: ReadonlyArray<readonly [string, string, boolean]>;\n}\n\nexport interface ExtractedToken {\n /** Usable (BASE + supported-variant) blocks. */\n readonly blocks: readonly ExtractedBlock[];\n /** True if the engine emitted at least one rule for the token (even an opaque one). */\n readonly produced: boolean;\n /** Set when the token only resolves via combinator / unsupported at-rule selectors. */\n readonly opaque?: OpaqueToken;\n}\n\n/** Collect every leaf `rule` node together with the `@media` stack that wraps it. */\nfunction collectRules(\n node: TwNode,\n mediaStack: readonly string[],\n inUnsupportedAtRule: boolean,\n out: Array<{ rule: TwGeneratedRule; media: readonly string[]; unsupported: boolean }>,\n): void {\n if (node.type === 'rule') {\n out.push({ rule: node as TwGeneratedRule, media: mediaStack, unsupported: inUnsupportedAtRule });\n return;\n }\n if (node.type === 'atrule') {\n const at = node as TwGeneratedAtRule;\n const children = at.nodes ?? [];\n if (at.name === 'media') {\n const nextStack = at.params ? [...mediaStack, at.params] : mediaStack;\n for (const child of children) collectRules(child, nextStack, inUnsupportedAtRule, out);\n } else {\n // @supports / @container / etc. — recurse but flag as unsupported (⇒ opaque).\n for (const child of children) collectRules(child, mediaStack, true, out);\n }\n }\n}\n\n/** Extract usable blocks + opacity info for a single candidate token from its generated nodes. */\nexport function extractToken(token: string, nodes: readonly TwNode[]): ExtractedToken {\n if (nodes.length === 0) return { blocks: [], produced: false };\n\n const leaves: Array<{ rule: TwGeneratedRule; media: readonly string[]; unsupported: boolean }> = [];\n for (const node of nodes) collectRules(node, [], false, leaves);\n\n const blocks: ExtractedBlock[] = [];\n let sawComplex = false;\n\n for (const { rule, media, unsupported } of leaves) {\n const parsed = parseSelector(rule.selector);\n if (parsed.kind === 'complex' || unsupported) {\n sawComplex = true;\n continue;\n }\n const decls: Array<readonly [string, string, boolean]> = [];\n for (const child of rule.nodes ?? []) {\n if (child.type !== 'decl') continue; // skip @defaults markers, comments, nested rules\n const d = child as TwGeneratedDecl;\n if (typeof d.value !== 'string') continue;\n decls.push([d.prop, d.value, d.important === true]);\n }\n if (decls.length === 0) continue;\n const mediaQuery = media.join(' and ');\n blocks.push({ condition: makeCondition(mediaQuery, parsed.states, parsed.pseudoElement), decls });\n }\n\n const opaque: OpaqueToken | undefined =\n sawComplex && blocks.length === 0\n ? { token, reason: 'combinator-variant', detail: 'utility targets descendants/siblings, not its own box' }\n : undefined;\n\n return { blocks, produced: true, opaque };\n}\n","/**\n * @domflax/resolver-tailwind — CSS serialization for `cssFor`.\n */\n\nimport type { TwGeneratedAtRule, TwGeneratedDecl, TwGeneratedRule, TwNode } from './types';\n\n/** Serialize one engine-emitted node (rule / atrule / decl) into plain CSS text. */\nexport function serializeCssNode(node: TwNode): string {\n if (node.type === 'decl') {\n const d = node as TwGeneratedDecl;\n if (typeof d.value !== 'string') return '';\n return `${d.prop}:${d.value}${d.important === true ? ' !important' : ''}`;\n }\n if (node.type === 'rule') {\n const r = node as TwGeneratedRule;\n const body = (r.nodes ?? [])\n .map((c) => serializeCssNode(c))\n .filter((s) => s.length > 0)\n .join(';');\n return `${r.selector}{${body}}`;\n }\n if (node.type === 'atrule') {\n const a = node as TwGeneratedAtRule;\n const body = (a.nodes ?? [])\n .map((c) => serializeCssNode(c))\n .filter((s) => s.length > 0)\n .join('');\n return `@${a.name} ${a.params}{${body}}`;\n }\n return '';\n}\n","/**\n * @domflax/resolver-tailwind — StyleMap assembly + provenance helpers.\n */\n\nimport type {\n CssProperty,\n StyleBlock,\n StyleCondition,\n StyleDecl,\n StyleMap,\n StyleOrigin,\n} from '@domflax/core';\nimport { conditionKey, emptyStyleMap } from '@domflax/core';\nimport { normalizer } from '@domflax/pattern-kit';\n\nexport function buildStyleMap(\n blockMaps: Map<string, { condition: StyleCondition; decls: Map<CssProperty, StyleDecl> }>,\n): StyleMap {\n if (blockMaps.size === 0) return emptyStyleMap();\n const blocks = new Map<ReturnType<typeof conditionKey>, StyleBlock>();\n for (const { condition, decls } of blockMaps.values()) {\n if (decls.size === 0) continue;\n blocks.set(conditionKey(condition), { condition, decls });\n }\n if (blocks.size === 0) return emptyStyleMap();\n return normalizer.normalizeStyleMap({ blocks });\n}\n\n/**\n * The shadow chain a newly-winning declaration inherits when it overrides `prev` on the same\n * property: everything `prev` already shadowed, plus `prev`'s own origin (now shadowed too). Deduped\n * by class name and restricted to class origins (the only kind `dedupe-classes` acts on).\n */\nexport function shadowedBy(prev: StyleDecl): readonly StyleOrigin[] | undefined {\n const out: StyleOrigin[] = [];\n const seen = new Set<string>();\n const add = (o: StyleOrigin | undefined): void => {\n if (!o || o.kind !== 'class' || seen.has(o.className)) return;\n seen.add(o.className);\n out.push(o);\n };\n for (const o of prev.shadowed ?? []) add(o);\n add(prev.origin);\n return out.length > 0 ? out : undefined;\n}\n","/**\n * @domflax/resolver-tailwind — conservative {@link SelectorUsage} constants.\n */\n\nimport type { SelectorUsage } from '@domflax/core';\n\n/**\n * A conservative, never-droppable {@link SelectorUsage}. Until a real project selector graph exists\n * we must assume a class could be referenced in any unsafe position, so nothing is safe to rewrite.\n */\nexport const OPAQUE_USAGE: SelectorUsage = {\n asSubject: true,\n asAncestor: true,\n asCompound: true,\n asSibling: true,\n asHasArgument: true,\n asStructural: true,\n droppable: false,\n};\n\n/**\n * A plain-subject {@link SelectorUsage}: the class is a resolver-owned, base-only utility whose\n * whole effect is reproducible from `computed`, so it is safe to drop/replace during reverse-emit.\n */\nexport const DROPPABLE_USAGE: SelectorUsage = {\n asSubject: true,\n asAncestor: false,\n asCompound: false,\n asSibling: false,\n asHasArgument: false,\n asStructural: false,\n droppable: true,\n};\n","/**\r\n * @domflax/resolver-tailwind — the {@link StyleResolver} implementation + public factory.\r\n */\r\n\r\nimport type {\r\n CoverClass,\r\n CssProperty,\r\n EmitContext,\r\n EmitResult,\r\n OpaqueToken,\r\n ResolveInput,\r\n ResolveResult,\r\n SelectorUsage,\r\n StyleCondition,\r\n StyleDecl,\r\n StyleMap,\r\n StyleOrigin,\r\n StyleResolver,\r\n} from '@domflax/core';\r\nimport { BASE_CONDITION, conditionKey, minStringCover, styleMapTuples, tupleKey } from '@domflax/core';\r\nimport { normalizer } from '@domflax/pattern-kit';\r\n\r\nimport type { TailwindResolverConfig } from './config';\r\nimport { expandForEmit, synthesizeResidual } from './emit';\r\nimport { loadEngine } from './engine';\r\nimport type { ExtractedToken } from './extract';\r\nimport { extractToken } from './extract';\r\nimport { fnv1a } from './fingerprint';\r\nimport { parseSelector, unescapeClass } from './selector';\r\nimport { serializeCssNode } from './serialize';\r\nimport { buildStyleMap, shadowedBy } from './stylemap';\r\nimport type { TwEngine, TwGeneratedDecl, TwGeneratedRule } from './types';\r\nimport { DROPPABLE_USAGE, OPAQUE_USAGE } from './usage';\r\n\r\n/**\r\n * Providers already warned about an unsupported Tailwind major, so the diagnostic is emitted ONCE per\r\n * distinct provider/version even when many resolvers (per-file caches, multiple runs) are constructed.\r\n */\r\nconst warnedUnsupported = new Set<string>();\r\n\r\nclass TailwindResolver implements StyleResolver {\r\n readonly id = 'tailwind';\r\n readonly provider: string;\r\n readonly fingerprint: string;\r\n /**\r\n * SAFETY (Layer 1): the detected Tailwind MAJOR when the project's version is one this resolver\r\n * cannot drive (v4+), else `null`. When set, {@link resolve} reports every token as unknown, so\r\n * downstream files are left unchanged (never mis-optimized). Exposed for diagnostics/tests.\r\n */\r\n readonly unsupportedMajor: number | null;\r\n\r\n readonly #engine: TwEngine | null;\r\n /** Per-token extraction cache (engine output is pure for a fixed config). */\r\n readonly #tokenCache = new Map<string, ExtractedToken>();\r\n /** Per-class-set forward-resolution cache. */\r\n readonly #resolveCache = new Map<string, ResolveResult>();\r\n /** Lazily built reverse index for the greedy {@link emit} fallback. */\r\n #reverseIndex: ReadonlyArray<readonly [string, ReadonlyMap<CssProperty, string>]> | null = null;\r\n /** Lazily built cover vocabulary (base-condition tuple sets) for the exact-cover engine. */\r\n #coverVocab: readonly CoverClass[] | null = null;\r\n\r\n constructor(config: TailwindResolverConfig = {}) {\r\n const loaded = loadEngine(config);\r\n this.#engine = loaded.engine;\r\n this.unsupportedMajor = loaded.unsupportedMajor;\r\n this.provider =\r\n config.provider ??\r\n (loaded.version ? `tailwindcss@${loaded.version}` : 'tailwindcss');\r\n const seed = JSON.stringify(config.config ?? {}) + (config.configPath ?? '');\r\n this.fingerprint = config.fingerprint ?? `${this.provider}/${fnv1a(seed)}`;\r\n\r\n // SAFETY (Layer 1): fail LOUDLY (once) when a v4+ project's real design system could NOT be\r\n // loaded (the v4 adapter fell through — e.g. `@tailwindcss/node` is missing). Every class then\r\n // resolves to `unknown` (below), so the per-element fail-safe leaves files unchanged instead of\r\n // unsafely flattening. A v4 project whose design system DID load has `unsupportedMajor === null`\r\n // and resolves normally — no warning.\r\n if (this.unsupportedMajor !== null && !warnedUnsupported.has(this.provider)) {\r\n warnedUnsupported.add(this.provider);\r\n // eslint-disable-next-line no-console\r\n console.warn(\r\n `domflax: detected Tailwind v${this.unsupportedMajor} (${this.provider}) but could not load its ` +\r\n `design system (is @tailwindcss/node installed?); classes cannot be resolved, so files are ` +\r\n `left unchanged to avoid unsafe edits.`,\r\n );\r\n }\r\n }\r\n\r\n /** Engine-backed, cached single-token extraction. */\r\n #extract(token: string): ExtractedToken {\r\n const cached = this.#tokenCache.get(token);\r\n if (cached) return cached;\r\n let result: ExtractedToken;\r\n if (!this.#engine) {\r\n result = { blocks: [], produced: false };\r\n } else {\r\n try {\r\n result = extractToken(token, this.#engine.generate([token]));\r\n } catch {\r\n result = { blocks: [], produced: false };\r\n }\r\n }\r\n this.#tokenCache.set(token, result);\r\n return result;\r\n }\r\n\r\n owns(token: string): boolean {\r\n if (token.length === 0) return false;\r\n return this.#extract(token).produced;\r\n }\r\n\r\n resolve(input: ResolveInput): ResolveResult {\r\n const key = JSON.stringify(input.classes);\r\n const cached = this.#resolveCache.get(key);\r\n if (cached) return cached;\r\n\r\n // condition-key → { condition, longhand decls }. Iterating classes in source order means later\r\n // utilities overwrite earlier ones on the same property (equal-specificity cascade).\r\n const blockMaps = new Map<\r\n string,\r\n { condition: StyleCondition; decls: Map<CssProperty, StyleDecl> }\r\n >();\r\n const resolved: string[] = [];\r\n const unknown: string[] = [];\r\n const opaque: OpaqueToken[] = [];\r\n\r\n input.classes.forEach((token, tokenIndex) => {\r\n const extracted = this.#extract(token);\r\n if (!extracted.produced) {\r\n unknown.push(token);\r\n return;\r\n }\r\n if (extracted.opaque) opaque.push(extracted.opaque);\r\n if (extracted.blocks.length === 0) return; // produced only opaque rules\r\n\r\n const origin: StyleOrigin = { kind: 'class', tokenIndex, className: token };\r\n let contributed = false;\r\n for (const block of extracted.blocks) {\r\n const ck = conditionKey(block.condition);\r\n let bucket = blockMaps.get(ck);\r\n if (!bucket) {\r\n bucket = { condition: block.condition, decls: new Map() };\r\n blockMaps.set(ck, bucket);\r\n }\r\n for (const [prop, value, important] of block.decls) {\r\n for (const decl of normalizer.normalizeDeclaration(prop, value, important)) {\r\n // Record provenance: a LATER token on the same property shadows the earlier one. The\r\n // overridden origin (plus anything it already shadowed) is carried in `shadowed`, which\r\n // is exactly what the `dedupe-classes` pattern reads to find fully-overridden tokens.\r\n // This only enriches decl metadata — the resolved VALUES are unchanged.\r\n const prev = bucket.decls.get(decl.property);\r\n const shadowed = prev ? shadowedBy(prev) : undefined;\r\n bucket.decls.set(decl.property, shadowed ? { ...decl, origin, shadowed } : { ...decl, origin });\r\n contributed = true;\r\n }\r\n }\r\n }\r\n if (contributed) resolved.push(token);\r\n });\r\n\r\n const result: ResolveResult = {\r\n styles: buildStyleMap(blockMaps),\r\n resolved,\r\n unknown,\r\n opaque,\r\n warnings: [],\r\n };\r\n this.#resolveCache.set(key, result);\r\n return result;\r\n }\r\n\r\n /**\r\n * Lazily build the reverse index from the engine's own enumerable class list. Each indexable\r\n * utility maps to its NORMALIZED BASE longhand declarations (property → canonical value). Utilities\r\n * with variant conditions, combinator selectors, or no BASE declarations are skipped. Sorted by\r\n * declaration count (desc) so greedier (shorthand-like) utilities are tried first.\r\n */\r\n #buildReverseIndex(): ReadonlyArray<readonly [string, ReadonlyMap<CssProperty, string>]> {\r\n if (this.#reverseIndex) return this.#reverseIndex;\r\n const index: Array<readonly [string, Map<CssProperty, string>]> = [];\r\n if (this.#engine) {\r\n try {\r\n const classes = this.#engine.context\r\n .getClassList()\r\n .filter((c): c is string => typeof c === 'string');\r\n const nodes = this.#engine.generate(classes);\r\n // Re-extract per class would be costly; instead group decls by their (single) class selector.\r\n for (const node of nodes) {\r\n if (node.type !== 'rule') continue; // skip @media / @keyframes wrappers (⇒ variants only)\r\n const rule = node as TwGeneratedRule;\r\n const parsed = parseSelector(rule.selector);\r\n if (parsed.kind !== 'simple' || parsed.states.length > 0 || parsed.pseudoElement !== '') {\r\n continue; // BASE-only\r\n }\r\n const className = unescapeClass(rule.selector);\r\n if (className === null) continue;\r\n const decls = new Map<CssProperty, string>();\r\n for (const child of rule.nodes ?? []) {\r\n if (child.type !== 'decl') continue;\r\n const d = child as TwGeneratedDecl;\r\n if (typeof d.value !== 'string') continue;\r\n for (const decl of normalizer.normalizeDeclaration(d.prop, d.value, d.important === true)) {\r\n decls.set(decl.property, String(decl.value));\r\n }\r\n }\r\n if (decls.size > 0) index.push([className, decls]);\r\n }\r\n } catch {\r\n /* leave index empty on failure — emit degrades to a no-op */\r\n }\r\n }\r\n index.sort((a, b) => b[1].size - a[1].size || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));\r\n this.#reverseIndex = index;\r\n return index;\r\n }\r\n\r\n /**\r\n * The cover vocabulary: every base-condition, plain-subject utility mapped to the {@link tupleKey}s\r\n * of its full normalized-longhand declaration set. Built once from a SINGLE engine `generate` over\r\n * the enumerable class list (grouped by selector), so it is the same cost as {@link #buildReverseIndex}.\r\n * This is what the provider-uniform exact-cover engine searches; the element's own droppable tokens\r\n * are members of it, guaranteeing feasibility. Variant / combinator / pseudo utilities are excluded\r\n * (their effect is not the element's own base box), so a target carrying such conditions simply finds\r\n * no cover and falls back to the greedy emit.\r\n */\r\n #buildCoverVocab(): readonly CoverClass[] {\r\n if (this.#coverVocab) return this.#coverVocab;\r\n const baseCk = String(conditionKey(BASE_CONDITION));\r\n const out: CoverClass[] = [];\r\n if (this.#engine) {\r\n try {\r\n const classes = this.#engine.context\r\n .getClassList()\r\n .filter((c): c is string => typeof c === 'string');\r\n const nodes = this.#engine.generate(classes);\r\n for (const node of nodes) {\r\n if (node.type !== 'rule') continue;\r\n const rule = node as TwGeneratedRule;\r\n const parsed = parseSelector(rule.selector);\r\n if (parsed.kind !== 'simple' || parsed.states.length > 0 || parsed.pseudoElement !== '') {\r\n continue; // BASE-only, own-box utilities only\r\n }\r\n const className = unescapeClass(rule.selector);\r\n if (className === null) continue;\r\n const tuples: string[] = [];\r\n const seen = new Set<string>();\r\n for (const child of rule.nodes ?? []) {\r\n if (child.type !== 'decl') continue;\r\n const d = child as TwGeneratedDecl;\r\n if (typeof d.value !== 'string') continue;\r\n for (const decl of normalizer.normalizeDeclaration(d.prop, d.value, d.important === true)) {\r\n const k = tupleKey(baseCk, String(decl.property), String(decl.value), decl.important);\r\n if (!seen.has(k)) {\r\n seen.add(k);\r\n tuples.push(k);\r\n }\r\n }\r\n }\r\n if (tuples.length > 0) out.push({ token: className, tuples });\r\n }\r\n } catch {\r\n /* leave vocab empty on failure — cover degrades to the greedy fallback */\r\n }\r\n }\r\n this.#coverVocab = out;\r\n return out;\r\n }\r\n\r\n /**\r\n * Try the minimal-string exact-cover engine over the WHOLE utility vocabulary. On success the chosen\r\n * set is verified by the mandatory CORRECTNESS BACKSTOP — re-resolve it and assert it reproduces the\r\n * target's tuples EXACTLY — before it is returned; any mismatch (or no cover / oversize universe)\r\n * yields `null` so {@link emit} uses its greedy fallback. Never returns a set that misrepresents `U`.\r\n */\r\n #tryCover(normalized: StyleMap, norm: EmitContext['normalizer']): EmitResult | null {\r\n const universe = styleMapTuples(normalized, norm);\r\n if (universe.length === 0) return { classes: [], exact: true, warnings: [] };\r\n const chosen = minStringCover(universe, this.#buildCoverVocab());\r\n if (!chosen || chosen.length === 0) return null;\r\n const reTuples = new Set(styleMapTuples(this.resolve({ classes: chosen }).styles, norm));\r\n if (reTuples.size !== universe.length) return null;\r\n for (const t of universe) if (!reTuples.has(t)) return null;\r\n return { classes: chosen, exact: true, warnings: [] };\r\n }\r\n\r\n emit(styles: StyleMap, ctx: EmitContext): EmitResult {\r\n const norm = ctx.normalizer ?? normalizer;\r\n const normalized = norm.normalizeStyleMap(styles);\r\n\r\n // Primary path: the provider-uniform minimal-string exact cover over the full vocabulary.\r\n const cover = this.#tryCover(normalized, norm);\r\n if (cover) return cover;\r\n\r\n const base = normalized.blocks.get(conditionKey(BASE_CONDITION));\r\n if (!base || base.decls.size === 0) return { classes: [], exact: true, warnings: [] };\r\n\r\n // Only the BASE block is reverse-synthesized (see module LIMITATION). Any non-base condition\r\n // present in the target means we cannot be exact.\r\n const hasNonBase = normalized.blocks.size > 1;\r\n\r\n // The target longhand map. The IR's compress passes hand us SHORTHAND properties (`padding`,\r\n // `margin`, `inset`, `inset-block`, `inset-inline`, `size`); we expand them to the same longhand\r\n // basis the reverse index is keyed on, so a single shorthand utility (`p-4`, `size-4`, `inset-0`)\r\n // can cover them.\r\n const target = new Map<CssProperty, string>();\r\n for (const [prop, decl] of base.decls) {\r\n for (const [lp, lv] of expandForEmit(norm, String(prop), String(decl.value), decl.important)) {\r\n target.set(lp, lv);\r\n }\r\n }\r\n\r\n // Keep only utilities every one of whose declarations matches the target (an exact-fit subset);\r\n // emitting a utility that sets an unwanted property/value would change the computed style.\r\n const candidates: Array<readonly [string, ReadonlyMap<CssProperty, string>]> = [];\r\n for (const entry of this.#buildReverseIndex()) {\r\n const [, declMap] = entry;\r\n if (declMap.size === 0 || declMap.size > target.size) continue;\r\n let fits = true;\r\n for (const [prop, value] of declMap) {\r\n if (target.get(prop) !== value) {\r\n fits = false;\r\n break;\r\n }\r\n }\r\n if (fits) candidates.push(entry);\r\n }\r\n\r\n // Greedy set-cover: repeatedly take the candidate covering the MOST still-needed declarations,\r\n // so a shorthand (`p-4`, 4 decls) beats `px-4`+`py-4`. Ties break toward the tighter decl-set\r\n // then lexicographically, for deterministic output.\r\n const remaining = new Map(target);\r\n const classes: string[] = [];\r\n while (remaining.size > 0) {\r\n let best: readonly [string, ReadonlyMap<CssProperty, string>] | null = null;\r\n let bestCover = 0;\r\n for (const entry of candidates) {\r\n const [token, declMap] = entry;\r\n let cover = 0;\r\n for (const prop of declMap.keys()) if (remaining.has(prop)) cover += 1;\r\n if (cover === 0) continue;\r\n const better =\r\n best === null ||\r\n cover > bestCover ||\r\n (cover === bestCover && declMap.size < best[1].size) ||\r\n (cover === bestCover && declMap.size === best[1].size && token < best[0]);\r\n if (better) {\r\n best = entry;\r\n bestCover = cover;\r\n }\r\n }\r\n if (!best) break; // nothing covers any still-needed declaration → residual\r\n classes.push(best[0]);\r\n for (const prop of best[1].keys()) remaining.delete(prop);\r\n }\r\n\r\n const exact = remaining.size === 0 && !hasNonBase;\r\n if (remaining.size === 0) return { classes, exact, warnings: [] };\r\n\r\n // Surface what no utility could cover as a residual synthetic (never thrown, never invented).\r\n const residual = synthesizeResidual(remaining, ctx);\r\n return residual\r\n ? { classes, residual, exact, warnings: [] }\r\n : { classes, exact, warnings: [] };\r\n }\r\n\r\n /**\r\n * Generate a CSS stylesheet that defines `classes`, so a verifier can render a subtree with the\r\n * real Tailwind styling applied. Backed by the same engine `resolve` uses (`generate(candidates)`),\r\n * serialized to plain CSS. Returns `''` when the engine is unavailable or generates nothing.\r\n */\r\n cssFor(classes: readonly string[]): string {\r\n if (!this.#engine) return '';\r\n const tokens = [...new Set(classes)].filter((c) => c.length > 0);\r\n if (tokens.length === 0) return '';\r\n try {\r\n return this.#engine\r\n .generate(tokens)\r\n .map((n) => serializeCssNode(n))\r\n .filter((s) => s.length > 0)\r\n .join('\\n');\r\n } catch {\r\n return '';\r\n }\r\n }\r\n\r\n selectorUsage(token: string): SelectorUsage {\r\n // No project selector graph yet, so we cannot know how a CUSTOM (non-Tailwind) class is\r\n // referenced — treat it as load-bearing (preserved verbatim). A resolver-OWNED utility, by\r\n // contrast, is safe to drop/replace iff its whole effect is reproducible from `computed`: it\r\n // must be a plain (non-opaque) utility contributing ONLY base-condition declarations. Opaque\r\n // (combinator/at-rule) and variant-bound utilities are kept, because `emit` cannot rebuild them.\r\n const ex = this.#extract(token);\r\n if (!ex.produced || ex.opaque) return OPAQUE_USAGE;\r\n const baseOnly =\r\n ex.blocks.length > 0 &&\r\n ex.blocks.every((b) => conditionKey(b.condition) === conditionKey(BASE_CONDITION));\r\n if (!baseOnly) return OPAQUE_USAGE;\r\n return DROPPABLE_USAGE;\r\n }\r\n}\r\n\r\n/** Factory: build a Tailwind-backed {@link StyleResolver}. */\r\nexport function createTailwindResolver(config?: TailwindResolverConfig): StyleResolver {\r\n return new TailwindResolver(config);\r\n}\r\n","/* ────────────────────────────────────────────────────────────────────────── *\n * Resolver identity + selector classification constants\n * ────────────────────────────────────────────────────────────────────────── */\n\n/** Stable resolver id surfaced on {@link StyleResolver.id}. */\nexport const CSS_RESOLVER_ID = 'css';\n\n/** Provider tag surfaced on {@link StyleResolver.provider}. */\nexport const CSS_RESOLVER_PROVIDER = 'custom-css';\n\n/** Version stamp for the index/cascade machinery; bump when its semantics change (cache-busting). */\nexport const ENGINE_VERSION = 'css-index@1';\n\n/** Structural pseudo-classes — their presence makes a class structurally targeted (review-1 blocker). */\nexport const STRUCTURAL_PSEUDOS: ReadonlySet<string> = new Set([\n ':nth-child',\n ':nth-last-child',\n ':first-child',\n ':last-child',\n ':only-child',\n ':nth-of-type',\n ':nth-last-of-type',\n ':first-of-type',\n ':last-of-type',\n ':only-of-type',\n]);\n\n/** Functional pseudos whose argument is itself a selector list — opaque to forward resolution. */\nexport const FUNCTIONAL_PSEUDOS: ReadonlySet<string> = new Set([\n ':not',\n ':is',\n ':where',\n ':has',\n ':matches',\n]);\n\n/** Legacy single-colon pseudo-ELEMENTS that the parser may not flag via `isPseudoElement`. */\nexport const LEGACY_PSEUDO_ELEMENTS: ReadonlySet<string> = new Set([\n ':before',\n ':after',\n ':first-line',\n ':first-letter',\n]);\n","import { createRequire } from 'node:module';\nimport * as path from 'node:path';\nimport type { Root as PostcssRoot } from 'postcss';\nimport type selectorParser from 'postcss-selector-parser';\n\n/* ────────────────────────────────────────────────────────────────────────── *\n * Lazy engine loading (postcss + postcss-selector-parser)\n * ────────────────────────────────────────────────────────────────────────── *\n *\n * postcss and postcss-selector-parser are OPTIONAL peers of the published `domflax` package: a\n * Tailwind-only user need not install them. They must therefore be loaded LAZILY (only when this\n * resolver is actually constructed) and from the CONSUMER'S project — never via a static top-level\n * `import`, which would (a) crash on module load for a postcss-less install and (b), once this\n * resolver is inlined into domflax's bundle, resolve relative to `domflax/dist` instead of the\n * user's project. We root the require in `process.cwd()` (or an explicit project root), exactly as\n * the Tailwind resolver does, with the bundle/source location as a last-resort fallback.\n */\n\n/** This module's own location — esbuild fills `__filename` in CJS; ESM falls back to `import.meta.url`. */\nexport function moduleBase(): string {\n return typeof __filename === 'string' ? __filename : import.meta.url;\n}\n\n/** The single postcss entry point this resolver calls at runtime. */\nexport type PostcssParseApi = (css: string, opts?: { from?: string }) => PostcssRoot;\n\n/** The subset of the postcss-selector-parser API this resolver calls at runtime (guards preserve narrowing). */\nexport interface SelectorParserApi {\n (): { astSync(selector: string): selectorParser.Root };\n isClassName(n: selectorParser.Node): n is selectorParser.ClassName;\n isTag(n: selectorParser.Node): n is selectorParser.Tag;\n isIdentifier(n: selectorParser.Node): n is selectorParser.Identifier;\n isAttribute(n: selectorParser.Node): n is selectorParser.Attribute;\n isUniversal(n: selectorParser.Node): n is selectorParser.Universal;\n isNesting(n: selectorParser.Node): n is selectorParser.Nesting;\n isPseudo(n: selectorParser.Node): n is selectorParser.Pseudo;\n isPseudoClass(n: selectorParser.Node): n is selectorParser.Pseudo;\n isPseudoElement(n: selectorParser.Node): n is selectorParser.Pseudo;\n isCombinator(n: selectorParser.Node): n is selectorParser.Combinator;\n}\n\nexport interface PostcssEngine {\n readonly parse: PostcssParseApi;\n readonly selectorParser: SelectorParserApi;\n}\n\n/** Resolve postcss + postcss-selector-parser from the consumer's project; `null` if unavailable. */\nexport function loadPostcssEngine(projectRoot?: string): PostcssEngine | null {\n const bases: string[] = [];\n if (projectRoot) bases.push(path.join(projectRoot, '__domflax__.js'));\n bases.push(path.join(process.cwd(), '__domflax__.js'));\n bases.push(moduleBase());\n for (const base of bases) {\n try {\n const req = createRequire(base);\n req.resolve('postcss');\n req.resolve('postcss-selector-parser');\n const postcss = req('postcss') as { parse: PostcssParseApi };\n const raw = req('postcss-selector-parser') as SelectorParserApi & { default?: SelectorParserApi };\n // postcss-selector-parser is CJS with a default export under interop; accept both shapes.\n const selector = raw.default ?? raw;\n return { parse: postcss.parse, selectorParser: selector };\n } catch {\n /* try the next base */\n }\n }\n return null;\n}\n\n/* ────────────────────────────────────────────────────────────────────────── *\n * Lazily-loaded postcss engine (module singleton)\n * ────────────────────────────────────────────────────────────────────────── */\n\n/** Runtime postcss `parse`, populated on first resolver construction. */\nexport let pc: PostcssParseApi | null = null;\n/** Runtime postcss-selector-parser, populated on first resolver construction. */\nexport let sp: SelectorParserApi | null = null;\n\n/** Ensure the postcss engine is loaded; throws a clear error if the optional peers are absent. */\nexport function ensurePostcss(projectRoot?: string): void {\n if (pc && sp) return;\n const engine = loadPostcssEngine(projectRoot);\n if (!engine) {\n throw new Error(\n '@domflax/resolver-css requires \"postcss\" and \"postcss-selector-parser\" to be installed in ' +\n 'your project (they are optional peer dependencies of domflax, loaded only when the custom-CSS ' +\n 'provider is used). Install them with: npm install postcss postcss-selector-parser',\n );\n }\n pc = engine.parse;\n sp = engine.selectorParser;\n}\n","import type { AtRule, Rule } from 'postcss';\nimport type { RawDecl } from './types';\n\n/* ────────────────────────────────────────────────────────────────────────── *\n * postcss helpers\n * ────────────────────────────────────────────────────────────────────────── */\n\ninterface MediaContext {\n readonly media: string;\n /** True when the rule lives under an at-rule that is not a style context (keyframes/font-face). */\n readonly skip: boolean;\n}\n\n/** Walk a rule's at-rule ancestry, collecting `@media` params and detecting non-style contexts. */\nexport function mediaContext(rule: Rule): MediaContext {\n const parts: string[] = [];\n let skip = false;\n let parent = rule.parent;\n while (parent && parent.type === 'atrule') {\n const at = parent as AtRule;\n const name = at.name.toLowerCase();\n if (name === 'media') parts.unshift(at.params.trim().replace(/\\s+/g, ' '));\n else if (name === 'keyframes' || name.endsWith('keyframes') || name === 'font-face') skip = true;\n parent = parent.parent;\n }\n return { media: parts.join(' and '), skip };\n}\n\n/** A rule's direct declarations, in source order, as raw `[prop, value, important]` triples. */\nexport function collectDecls(rule: Rule): RawDecl[] {\n const out: RawDecl[] = [];\n for (const node of rule.nodes) {\n if (node.type === 'decl') out.push([node.prop, node.value, node.important === true]);\n }\n return out;\n}\n","import { readFileSync } from 'node:fs';\nimport { ENGINE_VERSION } from './constants';\nimport type { CssFile } from './types';\n\n/* ────────────────────────────────────────────────────────────────────────── *\n * Misc helpers\n * ────────────────────────────────────────────────────────────────────────── */\n\n/** Cheap, allocation-free CSS-identifier check used by {@link CustomCSSResolver.owns}. */\nexport function isPlainClassToken(token: string): boolean {\n return token.length > 0 && !/[\\s.#>+~:[\\]()]/.test(token);\n}\n\n/** Read a CSS file from disk; surfaces unreadable paths as a clear input error. */\nexport function readCssPath(path: string): CssFile {\n try {\n return { id: path, css: readFileSync(path, 'utf8') };\n } catch (cause) {\n throw new Error(`resolver-css: cannot read CSS file \"${path}\"`, { cause });\n }\n}\n\n/**\n * Derive a deterministic fingerprint from the provider tag, engine version, and each file's id +\n * length. Cheap and good enough to bust downstream caches when the source CSS set changes.\n */\nexport function deriveFingerprint(provider: string, files: readonly CssFile[]): string {\n const parts = files.map((f) => `${f.id}:${f.css.length}`).sort();\n return `${provider}/${ENGINE_VERSION}::${parts.join('|')}`;\n}\n","import type selectorParser from 'postcss-selector-parser';\nimport { LEGACY_PSEUDO_ELEMENTS } from './constants';\nimport { sp } from './engine';\n\n/* ────────────────────────────────────────────────────────────────────────── *\n * Selector helpers\n * ────────────────────────────────────────────────────────────────────────── */\n\nexport interface Compound {\n /** The combinator immediately to this compound's LEFT (`null` for the first compound). */\n readonly leftCombinator: string | null;\n readonly nodes: readonly selectorParser.Node[];\n}\n\n/** Split a selector's flat node list into compounds delimited by combinator nodes. */\nexport function splitCompounds(selector: selectorParser.Selector): Compound[] {\n const compounds: Compound[] = [];\n let current: selectorParser.Node[] = [];\n let leftCombinator: string | null = null;\n for (const node of selector.nodes) {\n if (sp!.isCombinator(node)) {\n compounds.push({ leftCombinator, nodes: current });\n current = [];\n leftCombinator = combinatorValue(node);\n } else {\n current.push(node);\n }\n }\n compounds.push({ leftCombinator, nodes: current });\n return compounds;\n}\n\n/** A combinator's normalized value — descendant combinators are a single space. */\nfunction combinatorValue(node: selectorParser.Combinator): string {\n const v = node.value;\n return v.trim() === '' ? ' ' : v.trim();\n}\n\n/** The pseudo's lower-cased name including its leading colon(s), without any argument. */\nexport function pseudoName(node: selectorParser.Pseudo): string {\n return node.value.toLowerCase();\n}\n\nexport function isPseudoElement(node: selectorParser.Pseudo): boolean {\n return sp!.isPseudoElement(node) || LEGACY_PSEUDO_ELEMENTS.has(pseudoName(node));\n}\n\n/** Canonicalize a pseudo-element to the modern double-colon form (e.g. `:before` → `::before`). */\nexport function normalizePseudoElement(node: selectorParser.Pseudo): string {\n const name = pseudoName(node);\n return name.startsWith('::') ? name : `::${name.replace(/^:/, '')}`;\n}\n","import type {\r\n ConditionKey,\r\n CoverClass,\r\n CssProperty,\r\n EmitContext,\r\n EmitResult,\r\n ResolveInput,\r\n ResolveResult,\r\n SelectorUsage,\r\n StyleBlock,\r\n StyleCondition,\r\n StyleDecl,\r\n StyleMap,\r\n StyleOrigin,\r\n StyleResolver,\r\n} from '@domflax/core';\r\nimport { conditionKey, emptyStyleMap, minStringCover, styleMapTuples } from '@domflax/core';\r\nimport { normalizer } from '@domflax/pattern-kit';\r\nimport type selectorParser from 'postcss-selector-parser';\r\nimport {\r\n CSS_RESOLVER_ID,\r\n CSS_RESOLVER_PROVIDER,\r\n FUNCTIONAL_PSEUDOS,\r\n STRUCTURAL_PSEUDOS,\r\n} from './constants';\r\nimport { ensurePostcss, pc, sp } from './engine';\r\nimport { collectDecls, mediaContext } from './postcss-helpers';\r\nimport { deriveFingerprint, isPlainClassToken, readCssPath } from './misc-helpers';\r\nimport {\r\n isPseudoElement,\r\n normalizePseudoElement,\r\n pseudoName,\r\n splitCompounds,\r\n} from './selector-helpers';\r\nimport type {\r\n CssFile,\r\n CssResolverOptions,\r\n MutableUsage,\r\n RawDecl,\r\n ReverseEntry,\r\n RuleEntry,\r\n} from './types';\r\n\r\n/* ────────────────────────────────────────────────────────────────────────── *\r\n * CustomCSSResolver\r\n * ────────────────────────────────────────────────────────────────────────── */\r\n\r\n/**\r\n * Resolves plain CSS classes against a fixed set of project stylesheets parsed with postcss.\r\n */\r\nexport class CustomCSSResolver implements StyleResolver {\r\n public readonly id: string = CSS_RESOLVER_ID;\r\n public readonly provider: string = CSS_RESOLVER_PROVIDER;\r\n public readonly fingerprint: string;\r\n\r\n readonly #files: readonly CssFile[];\r\n /** Forward map: class token → simple-`.class` rule contributions (source order). */\r\n readonly #classIndex = new Map<string, RuleEntry[]>();\r\n /** Selector-participation facts per class token. */\r\n readonly #usage = new Map<string, MutableUsage>();\r\n /** Every class referenced anywhere in the stylesheets (forward-resolvable or not). */\r\n readonly #known = new Set<string>();\r\n /** Distinct COMPLEX selectors (combinator or structural pseudo), sorted. */\r\n readonly #complex: readonly string[];\r\n\r\n #reverse: readonly ReverseEntry[] | null = null;\r\n /** Lazily built cover vocabulary (full condition-keyed tuple sets) for the exact-cover engine. */\r\n #coverVocab: readonly CoverClass[] | null = null;\r\n\r\n public constructor(cssFiles: readonly CssFile[] = [], options: CssResolverOptions = {}) {\r\n ensurePostcss(options.projectRoot);\r\n const fromDisk = (options.files ?? []).map(readCssPath);\r\n this.#files = [...cssFiles, ...fromDisk];\r\n this.fingerprint = options.fingerprint ?? deriveFingerprint(this.provider, this.#files);\r\n\r\n const complex = new Set<string>();\r\n let order = 0;\r\n for (const file of this.#files) {\r\n order = this.#indexFile(file, order, complex);\r\n }\r\n this.#complex = [...complex].sort();\r\n }\r\n\r\n /** The stylesheets this resolver was constructed with (raw sources + any read from disk). */\r\n public get files(): readonly CssFile[] {\r\n return this.#files;\r\n }\r\n\r\n /** Owns any plain class token referenced by one of {@link files}. */\r\n public owns(token: string): boolean {\r\n return isPlainClassToken(token) && this.#known.has(token);\r\n }\r\n\r\n public resolve(input: ResolveInput): ResolveResult {\r\n const styles = this.#resolveTokens(input.classes, input.classes);\r\n const resolved: string[] = [];\r\n const unknown: string[] = [];\r\n for (const token of input.classes) {\r\n if (this.#classIndex.has(token)) resolved.push(token);\r\n else unknown.push(token);\r\n }\r\n return { styles, resolved, unknown, opaque: [], warnings: [] };\r\n }\r\n\r\n public emit(styles: StyleMap, ctx: EmitContext): EmitResult {\r\n const norm = ctx.normalizer ?? normalizer;\r\n const normalized = norm.normalizeStyleMap(styles);\r\n\r\n // Primary path: the provider-uniform minimal-string exact cover over the whole class vocabulary —\r\n // this is what lets custom CSS finally compress (pick the shortest class set, or the single\r\n // semantic class, that reproduces the target; drop a class another class fully covers). The\r\n // element's own droppable tokens are members of the vocabulary, so a cover always exists when the\r\n // target is reproducible. The chosen set is verified by the mandatory re-resolve backstop below.\r\n const universe = styleMapTuples(normalized, norm);\r\n if (universe.length === 0) return { classes: [], exact: true, warnings: [] };\r\n const chosen = minStringCover(universe, this.#buildCoverVocab());\r\n if (chosen && chosen.length > 0) {\r\n const reTuples = new Set(styleMapTuples(this.resolve({ classes: chosen }).styles, norm));\r\n let ok = reTuples.size === universe.length;\r\n if (ok) for (const t of universe) if (!reTuples.has(t)) { ok = false; break; }\r\n if (ok) return { classes: chosen, exact: true, warnings: [] };\r\n }\r\n\r\n // Fallback: the original greedy set-cover (also surfaces uncovered decls via `exact:false`).\r\n const remaining = new Map<string, string>();\r\n for (const [ck, block] of normalized.blocks) {\r\n for (const [prop, decl] of block.decls) {\r\n remaining.set(`${ck} ${prop}`, String(decl.value));\r\n }\r\n }\r\n if (remaining.size === 0) return { classes: [], exact: true, warnings: [] };\r\n\r\n const classes: string[] = [];\r\n // Greedy set-cover: larger classes first so the emitted set stays minimal.\r\n for (const { token, keyed } of this.#reverseIndex()) {\r\n let matches = true;\r\n for (const [key, value] of keyed) {\r\n if (remaining.get(key) !== value) {\r\n matches = false;\r\n break;\r\n }\r\n }\r\n if (!matches) continue;\r\n classes.push(token);\r\n for (const key of keyed.keys()) remaining.delete(key);\r\n if (remaining.size === 0) break;\r\n }\r\n\r\n // Unmatched declarations are left as-is (no synthetic residual) — surfaced via `exact:false`.\r\n return { classes, exact: remaining.size === 0, warnings: [] };\r\n }\r\n\r\n /**\r\n * Return a CSS stylesheet defining the given class tokens, so a verifier can render a subtree with\r\n * the project's real styling applied. The source stylesheets ARE the definition, so we hand back\r\n * their concatenation verbatim (every relevant rule — including combinator/structural selectors —\r\n * is preserved). `classes` is accepted for interface parity but the full source is always returned.\r\n */\r\n public cssFor(_classes: readonly string[]): string {\r\n return this.#files.map((f) => f.css).join('\\n');\r\n }\r\n\r\n public selectorUsage(token: string): SelectorUsage {\r\n const u = this.#usage.get(token);\r\n if (!u) {\r\n return {\r\n asSubject: false,\r\n asAncestor: false,\r\n asCompound: false,\r\n asSibling: false,\r\n asHasArgument: false,\r\n asStructural: false,\r\n droppable: true,\r\n };\r\n }\r\n return {\r\n asSubject: u.asSubject,\r\n asAncestor: u.asAncestor,\r\n asCompound: u.asCompound,\r\n asSibling: u.asSibling,\r\n asHasArgument: u.asHasArgument,\r\n asStructural: u.asStructural,\r\n // Safe to drop/rename only when every reference is the lone subject of a bare `.x {}`.\r\n droppable: u.referenced && !u.loadBearing,\r\n };\r\n }\r\n\r\n /**\r\n * The distinct COMPLEX selectors found across all stylesheets — anything containing a combinator\r\n * (descendant / `>` / `+` / `~`) or a structural pseudo (`:nth-child`, `:first-child`, …). Feeds\r\n * domflax's CSS-selector-safety guard.\r\n */\r\n public complexSelectors(): readonly string[] {\r\n return this.#complex;\r\n }\r\n\r\n /* ─────────────────────────── internals ─────────────────────────── */\r\n\r\n /** Parse one stylesheet and fold its rules into the indexes. Returns the advanced order counter. */\r\n #indexFile(file: CssFile, startOrder: number, complex: Set<string>): number {\r\n let order = startOrder;\r\n let root;\r\n try {\r\n root = pc!(file.css, { from: file.id });\r\n } catch {\r\n // Malformed CSS contributes nothing (never throws — only clear input errors do).\r\n return order;\r\n }\r\n\r\n root.walkRules((rule) => {\r\n const media = mediaContext(rule);\r\n if (media.skip) return; // inside @keyframes / @font-face etc. — not class rules\r\n const decls = collectDecls(rule);\r\n\r\n let ast;\r\n try {\r\n ast = sp!().astSync(rule.selector);\r\n } catch {\r\n return;\r\n }\r\n\r\n for (const sel of ast.nodes) {\r\n const thisOrder = order;\r\n this.#analyzeSelector(sel as selectorParser.Selector, media.media, decls, thisOrder, complex);\r\n }\r\n order += 1;\r\n });\r\n\r\n return order;\r\n }\r\n\r\n /** Analyze one comma-segment selector: forward indexing, usage facts, complex detection. */\r\n #analyzeSelector(\r\n selector: selectorParser.Selector,\r\n media: string,\r\n decls: readonly RawDecl[],\r\n order: number,\r\n complex: Set<string>,\r\n ): void {\r\n const compounds = splitCompounds(selector);\r\n let hasCombinator = false;\r\n let hasStructural = false;\r\n\r\n compounds.forEach((compound, index) => {\r\n const isSubject = index === compounds.length - 1;\r\n const rightCombinator = index < compounds.length - 1 ? compounds[index + 1]!.leftCombinator : null;\r\n if (rightCombinator) hasCombinator = true;\r\n\r\n const classes = compound.nodes.filter((n) => sp!.isClassName(n));\r\n const otherSimple = compound.nodes.some(\r\n (n) =>\r\n sp!.isTag(n) ||\r\n sp!.isIdentifier(n) ||\r\n sp!.isAttribute(n) ||\r\n sp!.isUniversal(n) ||\r\n sp!.isNesting(n),\r\n );\r\n const pseudos = compound.nodes.filter((n) => sp!.isPseudo(n));\r\n const structuralPseudo = pseudos.some((p) => STRUCTURAL_PSEUDOS.has(pseudoName(p)));\r\n const functionalPseudo = pseudos.some((p) => FUNCTIONAL_PSEUDOS.has(pseudoName(p)));\r\n const statePseudos = pseudos.filter(\r\n (p) =>\r\n sp!.isPseudoClass(p) &&\r\n !STRUCTURAL_PSEUDOS.has(pseudoName(p)) &&\r\n !FUNCTIONAL_PSEUDOS.has(pseudoName(p)),\r\n );\r\n const elementPseudos = pseudos.filter((p) => isPseudoElement(p));\r\n const qualified = classes.length > 1 || otherSimple || functionalPseudo || statePseudos.length > 0;\r\n\r\n if (structuralPseudo) hasStructural = true;\r\n\r\n for (const cls of classes) {\r\n const token = cls.value;\r\n this.#known.add(token);\r\n const u = this.#getUsage(token);\r\n u.referenced = true;\r\n if (isSubject) u.asSubject = true;\r\n if (rightCombinator === ' ' || rightCombinator === '>') u.asAncestor = true;\r\n if (rightCombinator === '+' || rightCombinator === '~') u.asSibling = true;\r\n if (qualified) u.asCompound = true;\r\n if (structuralPseudo) u.asStructural = true;\r\n if (rightCombinator !== null || qualified || structuralPseudo || elementPseudos.length > 0) {\r\n u.loadBearing = true;\r\n }\r\n\r\n // Forward indexing: a single bare `.class` compound, optionally qualified by state\r\n // pseudo-classes and/or a pseudo-element, with NO other simple selector and NO\r\n // structural/functional pseudo and NO combinator on this compound's right edge.\r\n const forwardEligible =\r\n compounds.length === 1 &&\r\n classes.length === 1 &&\r\n !otherSimple &&\r\n !structuralPseudo &&\r\n !functionalPseudo &&\r\n elementPseudos.length <= 1;\r\n if (forwardEligible && decls.length > 0) {\r\n const condition: StyleCondition = {\r\n media,\r\n states: statePseudos.map(pseudoName).sort(),\r\n pseudoElement: elementPseudos.length === 1 ? normalizePseudoElement(elementPseudos[0]!) : '',\r\n };\r\n this.#addRuleEntry(token, { order, token, condition, decls });\r\n }\r\n }\r\n\r\n // Classes nested inside selector-argument pseudos (:has/:is/:where/:not) are references too.\r\n for (const p of pseudos) {\r\n const isHas = pseudoName(p) === ':has';\r\n p.walkClasses((inner) => {\r\n const token = inner.value;\r\n this.#known.add(token);\r\n const u = this.#getUsage(token);\r\n u.referenced = true;\r\n u.loadBearing = true;\r\n if (isHas) u.asHasArgument = true;\r\n });\r\n }\r\n });\r\n\r\n if (hasCombinator || hasStructural) {\r\n complex.add(selector.toString().trim());\r\n }\r\n }\r\n\r\n #addRuleEntry(token: string, entry: RuleEntry): void {\r\n const list = this.#classIndex.get(token);\r\n if (list) list.push(entry);\r\n else this.#classIndex.set(token, [entry]);\r\n }\r\n\r\n #getUsage(token: string): MutableUsage {\r\n let u = this.#usage.get(token);\r\n if (!u) {\r\n u = {\r\n referenced: false,\r\n asSubject: false,\r\n asAncestor: false,\r\n asCompound: false,\r\n asSibling: false,\r\n asHasArgument: false,\r\n asStructural: false,\r\n loadBearing: false,\r\n };\r\n this.#usage.set(token, u);\r\n }\r\n return u;\r\n }\r\n\r\n /**\r\n * Resolve a set of tokens into a normalized condition-keyed StyleMap. `tokenList` is the original\r\n * class list (for per-declaration `tokenIndex` provenance); `request` is the set being resolved.\r\n */\r\n #resolveTokens(request: readonly string[], tokenList: readonly string[]): StyleMap {\r\n const entries: RuleEntry[] = [];\r\n for (const token of new Set(request)) {\r\n const list = this.#classIndex.get(token);\r\n if (list) entries.push(...list);\r\n }\r\n if (entries.length === 0) return emptyStyleMap();\r\n\r\n // Equal-specificity single-class rules cascade by source order — later wins.\r\n entries.sort((a, b) => a.order - b.order);\r\n\r\n const acc = new Map<ConditionKey, { condition: StyleCondition; decls: Map<CssProperty, StyleDecl> }>();\r\n for (const entry of entries) {\r\n const key = conditionKey(entry.condition);\r\n let block = acc.get(key);\r\n if (!block) {\r\n block = { condition: entry.condition, decls: new Map() };\r\n acc.set(key, block);\r\n }\r\n const tokenIndex = tokenList.indexOf(entry.token);\r\n const origin: StyleOrigin = { kind: 'class', tokenIndex, className: entry.token };\r\n for (const [prop, value, important] of entry.decls) {\r\n for (const decl of normalizer.normalizeDeclaration(prop, value, important)) {\r\n block.decls.set(decl.property, { ...decl, origin });\r\n }\r\n }\r\n }\r\n\r\n const rawBlocks = new Map<ConditionKey, StyleBlock>();\r\n for (const [key, block] of acc) {\r\n if (block.decls.size === 0) continue;\r\n rawBlocks.set(key, { condition: block.condition, decls: block.decls });\r\n }\r\n if (rawBlocks.size === 0) return emptyStyleMap();\r\n return normalizer.normalizeStyleMap({ blocks: rawBlocks });\r\n }\r\n\r\n /**\r\n * Build (once) the cover vocabulary for the exact-cover engine: every forward-resolvable class\r\n * mapped to the {@link styleMapTuples} of its full (condition-keyed, `!important`-aware) declaration\r\n * set. Unlike {@link #reverseIndex} this carries ALL style conditions and the important flag, so the\r\n * engine can pick a custom class covering hover/media declarations too.\r\n */\r\n #buildCoverVocab(): readonly CoverClass[] {\r\n if (this.#coverVocab) return this.#coverVocab;\r\n const out: CoverClass[] = [];\r\n for (const token of this.#classIndex.keys()) {\r\n const tuples = styleMapTuples(this.#resolveTokens([token], [token]), normalizer);\r\n if (tuples.length > 0) out.push({ token, tuples });\r\n }\r\n this.#coverVocab = out;\r\n return out;\r\n }\r\n\r\n /** Build (once) the reverse index used by the greedy {@link emit} fallback. */\r\n #reverseIndex(): readonly ReverseEntry[] {\r\n if (this.#reverse) return this.#reverse;\r\n const out: ReverseEntry[] = [];\r\n for (const token of this.#classIndex.keys()) {\r\n const styles = this.#resolveTokens([token], [token]);\r\n const keyed = new Map<string, string>();\r\n for (const [ck, block] of styles.blocks) {\r\n for (const [prop, decl] of block.decls) keyed.set(`${ck} ${prop}`, String(decl.value));\r\n }\r\n if (keyed.size > 0) out.push({ token, keyed });\r\n }\r\n // Larger declaration sets first → greedy minimal cover in `emit`.\r\n out.sort((a, b) => b.keyed.size - a.keyed.size);\r\n this.#reverse = out;\r\n return out;\r\n }\r\n}\r\n\r\n/* ────────────────────────────────────────────────────────────────────────── *\r\n * Factory\r\n * ────────────────────────────────────────────────────────────────────────── */\r\n\r\n/**\r\n * Construct a {@link CustomCSSResolver} from raw CSS sources and/or file paths.\r\n *\r\n * @param cssFiles raw stylesheets (`{ id, css }`) — pass `[]` when loading only from disk.\r\n * @param options optional disk paths (`files`) and/or an explicit `fingerprint`.\r\n */\r\nexport function createCssResolver(\r\n cssFiles: readonly CssFile[] = [],\r\n options?: CssResolverOptions,\r\n): StyleResolver {\r\n return new CustomCSSResolver(cssFiles, options);\r\n}\r\n","/**\n * domflax — public meta package.\n *\n * Re-exports the entire `@domflax/core` public API (types + reference runtime) and the built-in\n * `@domflax/patterns` library, then layers thin, framework-agnostic build adapters on top\n * (`vite()` / `webpack()`) plus a programmatic `createDomflax()` factory.\n *\n * Each adapter runs the SAME single-file engine as {@link createDomflax} (JSX/TSX + HTML frontends +\n * lazy Tailwind/CSS resolver → core pass manager → reverse-emit → surgical backend). The adapters are\n * structurally typed against their bundlers — they never hard-depend on `vite` or `webpack`.\n *\n * `.jsx`/`.tsx` route to `@domflax/frontend-jsx` (Babel); `.html`/`.htm` route to\n * `@domflax/frontend-html` (parse5). Both emit via SURGICAL span edits over the original source.\n */\n\nimport { createPipeline } from '@domflax/core';\nimport type {\n EncodedSourceMap,\n Pattern,\n Pipeline,\n SafetyLevel,\n StyleResolver,\n} from '@domflax/core';\nimport { builtinPatterns } from '@domflax/patterns';\nimport { createTailwindResolver } from '@domflax/resolver-tailwind';\nimport { createCssResolver } from '@domflax/resolver-css';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nimport { htmlKindOf, jsxKindOf, runHtmlPipeline, runJsxPipeline } from './pipeline-run';\nimport {\n addStats,\n emptyTotals,\n printCompilationSummary,\n renderSummary,\n resetTotals,\n zeroStats,\n type FileStatDelta,\n type Totals,\n} from './summary';\n\n// ── Re-export the public surface ──────────────────────────────────────────────────────────────\nexport * from '@domflax/core';\nexport * from '@domflax/patterns';\n\n/* ────────────────────────────────────────────────────────────────────────── *\n * Options\n * ────────────────────────────────────────────────────────────────────────── */\n\n/** How class names resolve to computed styles. */\nexport type DomflaxProvider = 'auto' | 'tailwind' | 'custom';\n\n/** Public adapter/factory options (mirrors the documented `domflax({...})` surface). */\nexport interface DomflaxOptions {\n /** Resolution strategy. Defaults to `'auto'`. */\n readonly provider?: DomflaxProvider;\n /** Stylesheets to parse when `provider` is `'custom'`. */\n readonly cssFiles?: readonly string[];\n /** Preview changes without rewriting source. */\n readonly dryRun?: boolean;\n /** Optimization aggressiveness handed to the pass manager (0 lint … 3 aggressive). */\n readonly safety?: SafetyLevel;\n /** File globs/extensions the adapters should consider. Defaults to jsx/tsx/html. */\n readonly include?: readonly string[];\n}\n\n/** Fully-resolved options with defaults applied. */\nexport interface ResolvedDomflaxOptions {\n readonly provider: DomflaxProvider;\n readonly cssFiles: readonly string[];\n readonly dryRun: boolean;\n readonly safety: SafetyLevel;\n readonly include: readonly string[];\n}\n\nconst DEFAULT_INCLUDE: readonly string[] = ['.jsx', '.tsx', '.html', '.htm'];\n\nfunction resolveOptions(options: DomflaxOptions): ResolvedDomflaxOptions {\n return {\n provider: options.provider ?? 'auto',\n cssFiles: options.cssFiles ?? [],\n dryRun: options.dryRun ?? false,\n safety: options.safety ?? 2,\n include: options.include ?? DEFAULT_INCLUDE,\n };\n}\n\n/** True when `id` is a file domflax knows how to transform. */\nfunction isSupported(id: string, include: readonly string[]): boolean {\n // Strip query suffixes bundlers append (e.g. `App.tsx?used`).\n const clean = id.split('?', 1)[0] ?? id;\n return include.some((ext) => clean.endsWith(ext));\n}\n\n/* ────────────────────────────────────────────────────────────────────────── *\n * Programmatic instance\n * ────────────────────────────────────────────────────────────────────────── */\n\n/** Result of a single-file transform. `map` is null until codegen lands. */\nexport interface DomflaxTransformResult {\n readonly code: string;\n readonly map: EncodedSourceMap | null;\n /**\n * Per-file optimization delta (nodes removed / classes saved / bytes saved). Zeroed for\n * unsupported or unchanged files. Consumed by the build adapters to accumulate the build-end\n * {@link renderSummary summary}.\n */\n readonly stats: FileStatDelta;\n}\n\n/**\n * A configured domflax engine. Holds the wired core {@link Pipeline}, the passthrough\n * {@link StyleResolver}, and the built-in {@link Pattern} set, and exposes a single-file\n * `transform`.\n */\nexport interface Domflax {\n readonly options: ResolvedDomflaxOptions;\n readonly pipeline: Pipeline;\n readonly resolver: StyleResolver;\n readonly patterns: readonly Pattern[];\n /**\n * Transform one file (SYNCHRONOUS, fully static, never launches a browser). For `.jsx`/`.tsx` this\n * runs the full pipeline (parse → resolve → flatten[provably-safe only] → reverse-emit → print);\n * every other (or unsupported) file is returned unchanged. Only provably layout-neutral flattens are\n * applied — domflax never changes rendering.\n */\n transform(code: string, id: string): DomflaxTransformResult;\n}\n\n/**\n * Build a configured domflax engine.\n *\n * Wires a real single-file pipeline: the JSX/TSX frontend + a Tailwind resolver feed the core pass\n * manager (running {@link builtinPatterns}), whose output is reverse-emitted back to class tokens\n * and re-printed by the JSX backend. Non-jsx/tsx files pass through unchanged.\n */\n/**\n * Build the {@link StyleResolver} for the chosen provider. The heavy engine each resolver wraps\n * (Tailwind v3 / postcss) is loaded LAZILY — at the moment this factory runs — and resolved from the\n * CONSUMER'S project, NOT from domflax's (possibly bundled) location. Both engines are OPTIONAL peer\n * dependencies of the published `domflax`: a Tailwind-only user never triggers a postcss load, and a\n * custom-CSS-only user never triggers a Tailwind load, because only the selected branch constructs.\n */\nfunction createResolver(resolved: ResolvedDomflaxOptions): StyleResolver {\n if (resolved.provider === 'custom') {\n return createCssResolver([], { files: resolved.cssFiles });\n }\n // 'auto' and 'tailwind' both resolve against the project's Tailwind engine.\n return createTailwindResolver();\n}\n\nexport function createDomflax(options: DomflaxOptions = {}): Domflax {\n const resolved = resolveOptions(options);\n const pipeline = createPipeline();\n const patterns = builtinPatterns;\n\n // Construct the resolver lazily so neither optional engine (Tailwind / postcss) is loaded until a\n // file is actually transformed (and only the engine for the selected provider is ever loaded).\n let cachedResolver: StyleResolver | null = null;\n const getResolver = (): StyleResolver => (cachedResolver ??= createResolver(resolved));\n\n return {\n options: resolved,\n pipeline,\n get resolver(): StyleResolver {\n return getResolver();\n },\n patterns,\n transform(code: string, id: string): DomflaxTransformResult {\n if (!isSupported(id, resolved.include)) return { code, map: null, stats: zeroStats() };\n const kind = jsxKindOf(id);\n if (kind !== null) {\n const out = runJsxPipeline(code, id, kind, getResolver(), patterns, resolved.safety);\n return { code: out.code, map: null, stats: out.stats };\n }\n // `.html`/`.htm` route to the parse5 HTML frontend/backend (surgical span edits).\n if (htmlKindOf(id) !== null) {\n const out = runHtmlPipeline(code, id, getResolver(), patterns, resolved.safety);\n return { code: out.code, map: null, stats: out.stats };\n }\n return { code, map: null, stats: zeroStats() };\n },\n };\n}\n\n/* ────────────────────────────────────────────────────────────────────────── *\n * Build adapters (framework-agnostic, structurally-typed shapes)\n * ────────────────────────────────────────────────────────────────────────── */\n\n/**\n * Minimal Vite-plugin shape. Declared locally so this adapter does NOT depend on `vite`'s types\n * (an optional, type-only peer). Structurally compatible with Vite's `Plugin` for the hooks domflax\n * uses: `enforce: 'pre'` runs domflax before Vite's JSX→`createElement` transform, and `transform`\n * is Vite's per-file source hook. Returning `null` is Vite's \"no change\" signal.\n */\nexport interface DomflaxVitePlugin {\n readonly name: string;\n readonly enforce: 'pre';\n /** Vite's per-file source hook. Fully synchronous and browser-free. */\n transform(code: string, id: string): DomflaxTransformResult | null;\n /** Vite build-start hook — resets the per-build summary accumulator (watch/serve safe). */\n buildStart(): void;\n /** Vite build-end hook — prints the aggregate {@link renderSummary} once (if anything changed). */\n buildEnd(): void;\n /** Vite close-bundle hook — prints the summary as a backstop if `buildEnd` did not fire. */\n closeBundle(): void;\n}\n\n/**\n * Vite adapter. Returns a real Vite `Plugin` (`enforce: 'pre'`) whose `transform` runs the domflax\n * engine on `.jsx`/`.tsx` modules — strips any bundler query suffix (e.g. `App.tsx?used`) before\n * matching, returns `{ code, map }` when the source changed, and `null` (Vite's unchanged signal)\n * for unchanged sources and for any non-jsx/tsx module.\n *\n * @example\n * ```js\n * // vite.config.js\n * import domflax from 'domflax';\n * export default { plugins: [domflax.vite({ provider: 'tailwind' })] };\n * ```\n */\nexport function vite(options: DomflaxOptions = {}): DomflaxVitePlugin {\n const engine = createDomflax(options);\n\n // Aggregate across every `transform` call in this plugin instance. `buildStart` resets it so\n // watch/serve rebuilds each get their own summary; a `printed` latch guards the double-fire of\n // `buildEnd` + `closeBundle`.\n const totals: Totals = emptyTotals();\n let printed = false;\n\n const printSummary = (): void => {\n if (printed) return;\n printed = true;\n if (totals.files > 0) process.stdout.write(renderSummary(totals));\n };\n\n return {\n name: 'domflax',\n enforce: 'pre',\n buildStart(): void {\n resetTotals(totals);\n printed = false;\n },\n transform(code: string, id: string): DomflaxTransformResult | null {\n if (!isSupported(id, engine.options.include)) return null;\n const out = engine.transform(code, id);\n const changed = out.code !== code;\n addStats(totals, out.stats, changed);\n // Signal \"no change\" to Vite when the source round-tripped unchanged.\n return changed ? out : null;\n },\n buildEnd(): void {\n printSummary();\n },\n closeBundle(): void {\n printSummary();\n },\n };\n}\n\n/* ── webpack / Next.js ──────────────────────────────────────────────────────────────────────── */\n\n/** A `module.rule` `use` entry: an absolute loader path plus the options forwarded to it. */\ninterface DomflaxRuleUse {\n readonly loader: string;\n readonly options: DomflaxOptions;\n}\n\n/** The slice of a webpack `module.rule` domflax appends. */\ninterface DomflaxModuleRule {\n readonly test: RegExp;\n readonly enforce: 'pre';\n readonly exclude: RegExp;\n readonly use: readonly DomflaxRuleUse[];\n}\n\n/** Anything carrying a `module.rules` array — both a webpack `Compiler.options` and Next's bare config. */\ninterface DomflaxWebpackModuleHost {\n module?: { rules?: unknown[] };\n /** webpack's plugin list (present on both a real `Compiler.options` and Next's bare config). */\n plugins?: unknown[];\n}\n\n/** A tappable webpack hook (only the `tap` arm domflax uses). */\ninterface DomflaxWebpackHook {\n tap(name: string, fn: (arg: unknown) => void): void;\n}\n\n/**\n * Minimal webpack-compiler shape. Declared locally so this adapter does NOT depend on `webpack`'s\n * types. domflax only needs to push a rule onto the host's `module.rules`.\n *\n * `apply` accepts BOTH shapes: a real webpack `Compiler` (rules live under `compiler.options.module`)\n * AND the bare `config` object Next.js hands you from `webpack(config)` (rules live directly under\n * `config.module`). It duck-types `compiler.options ?? compiler` to find the right host.\n */\nexport interface DomflaxWebpackCompiler extends DomflaxWebpackModuleHost {\n options?: DomflaxWebpackModuleHost;\n /** Present only on a REAL webpack `Compiler` (not on Next's bare config). Used for the summary. */\n hooks?: { done?: DomflaxWebpackHook };\n}\n\n/**\n * Minimal webpack-plugin shape. `apply(compiler)` is the webpack plugin entry point.\n */\nexport interface DomflaxWebpackPlugin {\n readonly name: string;\n apply(compiler: DomflaxWebpackCompiler): void;\n}\n\n/** `.jsx`/`.tsx` modules only (combinator-free with the JSX frontend; `.js`/`.ts` are skipped). */\nconst WEBPACK_JSX_TEST = /\\.[jt]sx$/;\n\n/**\n * Absolute path to the bundled webpack loader (`./webpack-loader`). Resolved lazily against THIS\n * module's location so it works whether `domflax` is loaded as ESM (`dist/index.js`) or CJS\n * (`dist/index.cjs`) — both sit beside `dist/webpack-loader.cjs`. webpack requires loaders via\n * CommonJS, so we always point at the `.cjs` output.\n */\nfunction webpackLoaderPath(): string {\n const here = dirname(fileURLToPath(import.meta.url));\n return join(here, 'webpack-loader.cjs');\n}\n\n/**\n * webpack adapter (also the Next.js path). Returns a plugin whose `apply(compiler)` injects a\n * pre-enforced `module.rule` that invokes the domflax {@link ./webpack-loader loader} on every\n * `.jsx`/`.tsx` module. The loader runs the SAME lazy engine as {@link createDomflax} (no eager\n * Tailwind/postcss load).\n *\n * Next.js wiring (`next.config.js`) — Next exposes the underlying webpack config via `webpack(config)`:\n * ```js\n * // next.config.js\n * const domflax = require('domflax');\n * module.exports = {\n * webpack(config) {\n * domflax.webpack({ provider: 'tailwind' }).apply(config);\n * return config;\n * },\n * };\n * ```\n * `apply(compiler)` is intentionally duck-typed on `compiler.options.module.rules`, so it accepts\n * both a real webpack `Compiler` and the bare `config` object Next.js hands you.\n *\n * Caveat: this targets the webpack builder only. **Turbopack is not yet supported** — it does not\n * accept arbitrary webpack loaders, so the `next.config.js` wiring above is a no-op under\n * `next dev --turbopack`. Run domflax through the webpack builder until Turbopack exposes a loader API.\n */\n/**\n * Tap a REAL webpack `Compiler`'s `done` hook to print the build-end summary. The per-file stats were\n * stashed on the `compilation` by the loader (separate bundle) under a shared `Symbol.for` key; here\n * we read + print them once. No-op if `compiler` has no `done` hook (e.g. a bare config or a stub).\n */\nfunction tapWebpackSummary(compiler: DomflaxWebpackCompiler): void {\n const done = compiler.hooks?.done;\n if (typeof done?.tap !== 'function') return;\n done.tap('domflax', (stats: unknown) => {\n // `done` receives a `Stats` whose `.compilation` is the object the loader wrote to; some stubs\n // pass the compilation directly.\n const compilation = (stats as { compilation?: unknown } | null)?.compilation ?? stats;\n printCompilationSummary(compilation);\n });\n}\n\n/**\n * Wire the summary printer. On a real `Compiler` we tap `done` directly. On Next's bare config (no\n * `hooks`) we push a child plugin onto `config.plugins`; webpack later calls its `apply(compiler)`\n * with the real `Compiler`, at which point we tap `done`.\n */\nfunction installWebpackSummary(compiler: DomflaxWebpackCompiler, host: DomflaxWebpackModuleHost): void {\n if (typeof compiler.hooks?.done?.tap === 'function') {\n tapWebpackSummary(compiler);\n return;\n }\n const plugins = (host.plugins ??= []);\n if (Array.isArray(plugins)) {\n plugins.push({ apply: (real: DomflaxWebpackCompiler) => tapWebpackSummary(real) });\n }\n}\n\nexport function webpack(options: DomflaxOptions = {}): DomflaxWebpackPlugin {\n // Validate options eagerly (parity with the other adapters); the resolver stays lazy.\n createDomflax(options);\n return {\n name: 'domflax',\n apply(compiler: DomflaxWebpackCompiler): void {\n // Real webpack passes a `Compiler` (rules under `.options.module`); Next's `webpack(config)`\n // passes the bare config (rules under `.module`). Duck-type to the right host.\n const host: DomflaxWebpackModuleHost = compiler.options ?? compiler;\n const mod = (host.module ??= {});\n const rules = (mod.rules ??= []);\n const rule: DomflaxModuleRule = {\n test: WEBPACK_JSX_TEST,\n enforce: 'pre',\n exclude: /node_modules/,\n use: [{ loader: webpackLoaderPath(), options }],\n };\n rules.push(rule);\n // Print the aggregate summary at build end (loader ↔ plugin bridge over the compilation).\n installWebpackSummary(compiler, host);\n },\n };\n}\n\n/**\n * The default-export namespace. Exposes the build adapters and the programmatic factory as an OBJECT\n * so the documented `import domflax from 'domflax'; domflax.vite()` / `domflax.webpack()` works (and a\n * CommonJS `const domflax = require('domflax'); domflax.vite()` too). The named exports\n * (`createDomflax`, `vite`, `webpack`, …) remain available for direct import.\n */\nexport interface DomflaxDefault {\n createDomflax(options?: DomflaxOptions): Domflax;\n vite(options?: DomflaxOptions): DomflaxVitePlugin;\n webpack(options?: DomflaxOptions): DomflaxWebpackPlugin;\n}\n\n/** Default export: an object exposing `vite`, `webpack`, and the programmatic `createDomflax`. */\nconst domflax: DomflaxDefault = { createDomflax, vite, webpack };\nexport default domflax;\n","/**\n * @domflax/frontend-html — IR → HTML backend (SURGICAL, verbatim-preserving).\n *\n * The pass manager mutates the IR tree that was lowered from a complete HTML document. The backend\n * emits the SAME document back with ONLY the diffs the passes produced, applied as span edits over the\n * ORIGINAL source via `magic-string`. It NEVER re-serializes the parse5 tree — doing so would normalize\n * quoting/whitespace/attribute order across the whole file. Every untouched byte (doctype, `<head>`,\n * comments, scripts, whitespace, attribute ordering) stays byte-for-byte identical.\n *\n * • CLASS CHANGE — for a surviving element whose static class list differs from its source text,\n * overwrite just the `class` attribute VALUE span (quotes included) with the new tokens.\n * • UNWRAP (flatten) — when a wrapper element was removed but a descendant survived, delete ONLY the\n * wrapper's open- and close-tag spans; the children (their entire subtrees) survive verbatim.\n * • FULL REMOVAL — when a node was removed with no surviving descendant, delete its whole span.\n */\n\nimport MagicString from 'magic-string';\n\nimport type {\n Backref,\n ClassList,\n IRDocument,\n IRElement,\n IRNode,\n IRNodeId,\n SourceFile,\n SourceSpan,\n} from '@domflax/core';\n\n/* ───────────────────────── shared helpers ───────────────────────── */\n\n/** All static class tokens of a {@link ClassList}, in source order. */\nfunction staticTokensOf(classes: ClassList): string[] {\n const out: string[] = [];\n for (const seg of classes.segments) {\n if (seg.kind === 'static') for (const t of seg.tokens) out.push(t.value);\n }\n return out;\n}\n\n/** Two token lists are equal iff same length and same tokens in the same order. */\nfunction sameTokens(a: readonly string[], b: readonly string[]): boolean {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i += 1) if (a[i] !== b[i]) return false;\n return true;\n}\n\n/** Pick the single retained source file this document was parsed from (if any). */\nfunction primarySource(doc: IRDocument): SourceFile | null {\n for (const sf of doc.sources.values()) {\n if (typeof sf.text === 'string' && sf.text.length > 0) return sf;\n }\n return null;\n}\n\n/** Collect every node reachable from the root of the (mutated) tree. */\nfunction collectKept(doc: IRDocument): IRNode[] {\n const out: IRNode[] = [];\n const seen = new Set<IRNodeId>();\n const visit = (id: IRNodeId): void => {\n if (seen.has(id)) return;\n seen.add(id);\n const n = doc.nodes.get(id);\n if (!n) return;\n out.push(n);\n if (n.kind === 'element' || n.kind === 'fragment') for (const c of n.children) visit(c);\n };\n visit(doc.root);\n return out;\n}\n\n/** Span `a` strictly contains span `b` (same file, b nested inside, not identical). */\nfunction strictlyContains(a: SourceSpan, b: SourceSpan): boolean {\n if (a.file !== b.file) return false;\n if (a.start <= b.start && b.end <= a.end) return !(a.start === b.start && a.end === b.end);\n return false;\n}\n\n/** All ids the backref table knows about (every originally-parsed element with a source location). */\nfunction backrefIds(doc: IRDocument): IRNodeId[] {\n const out: IRNodeId[] = [];\n const max = doc.alloc.peek as unknown as number;\n for (let i = 1; i < max; i += 1) {\n const id = i as IRNodeId;\n if (doc.backref.get(id)) out.push(id);\n }\n return out;\n}\n\n/* ───────────────────────── class-value rewrite ───────────────────────── */\n\n/** The tokens currently written in the class value span (quotes/whitespace stripped). */\nfunction currentTokens(sf: SourceFile, valueSpan: SourceSpan): string[] {\n const raw = sf.text.slice(valueSpan.start, valueSpan.end).trim();\n const unquoted = raw.replace(/^['\"]/, '').replace(/['\"]$/, '');\n return unquoted.split(/\\s+/).filter((t) => t.length > 0);\n}\n\n/** Apply the class-list diff for one surviving element. Returns true if a byte edit was made. */\nfunction editClasses(ms: MagicString, doc: IRDocument, sf: SourceFile, el: IRElement): boolean {\n const classes = el.classes;\n if (classes.hasDynamic || classes.opaque) return false; // never rewrite an opaque/dynamic list\n\n const tokens = staticTokensOf(classes);\n const valueSpan = classes.valueSpan;\n\n if (valueSpan && valueSpan.file === sf.id) {\n if (sameTokens(currentTokens(sf, valueSpan), tokens)) return false; // unchanged → leave verbatim\n const current = sf.text.slice(valueSpan.start, valueSpan.end).trim();\n const quote = current.startsWith(\"'\") ? \"'\" : '\"';\n ms.overwrite(valueSpan.start, valueSpan.end, `${quote}${tokens.join(' ')}${quote}`);\n return true;\n }\n\n // No class attribute originally, but the passes added classes ⇒ insert one on the opening tag.\n if (tokens.length === 0) return false;\n const openTag = doc.backref.get(el.id)?.openTagSpan;\n if (!openTag || openTag.file !== sf.id) return false;\n ms.appendLeft(openTag.start + 1 + el.tag.length, ` class=\"${tokens.join(' ')}\"`);\n return true;\n}\n\n/* ───────────────────────── surgical codegen ───────────────────────── */\n\ninterface RemovedRegion {\n readonly backref: Backref;\n /** A surviving node nested inside this region ⇒ this was an UNWRAP (keep inner, drop tags). */\n readonly unwrapped: boolean;\n}\n\n/** Surgical whole-document codegen. Returns null when the document has no retained source. */\nfunction surgicalPrint(doc: IRDocument): string | null {\n const sf = primarySource(doc);\n if (!sf) return null;\n\n const ms = new MagicString(sf.text);\n\n const kept = collectKept(doc);\n const keptSpans: SourceSpan[] = [];\n for (const n of kept) if (n.span && n.span.file === sf.id) keptSpans.push(n.span);\n\n // 1) Structural removals — an id in the backref table but absent from the live node map was removed\n // by the passes. Classify as UNWRAP (a surviving node nests inside) or FULL removal.\n const removed: RemovedRegion[] = [];\n for (const id of backrefIds(doc)) {\n if (doc.nodes.has(id)) continue;\n const back = doc.backref.get(id);\n if (!back || back.span.file !== sf.id) continue;\n const unwrapped = keptSpans.some((k) => strictlyContains(back.span, k));\n removed.push({ backref: back, unwrapped });\n }\n\n // Skip any removed region nested inside a FULL-removal region (already deleted by the ancestor), so\n // every delete stays disjoint (magic-string requires it).\n const fullRemovals = removed.filter((r) => !r.unwrapped).map((r) => r.backref.span);\n for (const r of removed) {\n const s = r.backref.span;\n if (fullRemovals.some((f) => f !== s && strictlyContains(f, s))) continue;\n\n if (r.unwrapped) {\n const open = r.backref.openTagSpan;\n const close = r.backref.closeTagSpan;\n if (open && open.file === sf.id && open.end > open.start) ms.remove(open.start, open.end);\n if (close && close.file === sf.id && close.end > close.start) ms.remove(close.start, close.end);\n } else {\n ms.remove(s.start, s.end);\n }\n }\n\n // 2) Class-list diffs on every surviving element.\n for (const n of kept) if (n.kind === 'element') editClasses(ms, doc, sf, n);\n\n return ms.toString();\n}\n\n/** Emit the (possibly edited) document. Falls back to the empty string only for a source-less doc. */\nexport function doPrint(doc: IRDocument): string {\n return surgicalPrint(doc) ?? '';\n}\n","/**\n * @domflax/frontend-html — the parse5 HTML → IR parse pass.\n *\n * Parses HTML with parse5 (WHATWG-compliant tree construction) and lowers its tree into the\n * `@domflax/core` IR: every element → {@link IRElement} (tag + non-class attributes, with the `class`\n * attribute resolved through `ctx.resolver`/`ctx.normalizer` into `computed` so downstream patterns\n * match on resolved style), text → {@link IRText}, comments → {@link IRComment}. Doctype and\n * auto-inserted (`<html>`/`<head>`/`<body>`) wrappers are preserved verbatim: doctype is not\n * represented, synthetic wrappers become opaque (never edited).\n *\n * Precise SOURCE SPANS from parse5 location info (element span, open-/close-tag spans, and the `class`\n * VALUE span) are recorded in the {@link MutableBackrefTable} so the backend edits surgically instead\n * of re-serializing (which would reformat the whole document).\n *\n * OPACITY (never flatten/rewrite), enforced via `meta.safetyFloor = 0` (blocks every op above lint):\n * • elements with an `id`, any inline `on*=` handler, or `contenteditable` (element only);\n * • `<script>`/`<style>`/`<template>`/`<svg>`/`<pre>`/`<textarea>` subtrees (not descended into);\n * • synthetic (auto-inserted) elements carrying no source location.\n *\n * parse5 is LAZILY required (via `createRequire`, since {@link Frontend.parse} is synchronous) INSIDE\n * `doParse`, so the JSX-only path never loads it.\n */\n\nimport { createRequire } from 'node:module';\n\nimport type {\n AttrMap,\n AttrValue,\n ClassList,\n ClassSegment,\n Diagnostic,\n FrontendParseContext,\n IRDocument,\n IRElement,\n IRFragment,\n IRNodeId,\n MutableBackrefTable,\n NodeMeta,\n ParseResult,\n SourceFile,\n StyleMap,\n} from '@domflax/core';\nimport {\n createComment,\n createDocument,\n createElement,\n createText,\n defaultMeta,\n emptyClassList,\n emptyStyleMap,\n} from '@domflax/core';\n\nimport type { P5Attr, P5Location, P5Node, Parse5Module } from './walk';\nimport {\n FILE_ID,\n attrsLocOf,\n classValueSpan,\n elementIsOpaque,\n hasEventHandler,\n isOpaqueSubtreeTag,\n span,\n} from './walk';\n\n/* ───────────────────────── lazy parse5 ───────────────────────── */\n\nlet cachedParse5: Parse5Module | null = null;\n\n/**\n * Load parse5 lazily via `createRequire` (NOT a top-level import): {@link Frontend.parse} is\n * synchronous, so a dynamic `import()` is unavailable, and the JSX-only path must never pull parse5\n * into memory. Rooted at THIS module so it resolves the parse5 the frontend depends on.\n */\nfunction loadParse5(): Parse5Module {\n if (cachedParse5) return cachedParse5;\n const req = createRequire(import.meta.url);\n cachedParse5 = req('parse5') as Parse5Module;\n return cachedParse5;\n}\n\n/* ───────────────────────── parse pass ───────────────────────── */\n\nexport function doParse(code: string, ctx: FrontendParseContext): ParseResult {\n const diagnostics: Diagnostic[] = [];\n const doc: IRDocument = createDocument('html');\n const backref = doc.backref as MutableBackrefTable;\n\n const parse5 = loadParse5();\n const document = parse5.parse(code, { sourceCodeLocationInfo: true });\n\n const eol: '\\n' | '\\r\\n' = code.includes('\\r\\n') ? '\\r\\n' : '\\n';\n const sourceFile: SourceFile = {\n id: FILE_ID,\n path: ctx.id,\n text: code,\n frontend: 'html',\n eol,\n indentUnit: ' ',\n native: document,\n };\n doc.sources.set(FILE_ID, sourceFile);\n\n /* ----- class resolution (static classes → computed style) ----- */\n\n const resolveComputed = (\n tokens: readonly string[],\n tag: string,\n nodeId: IRNodeId,\n meta: NodeMeta,\n ): StyleMap => {\n if (tokens.length === 0) return emptyStyleMap();\n const res = ctx.resolver.resolve({ classes: tokens, element: { tagName: tag, namespace: 'html' } });\n // SAFETY (Layer 2): any unresolved token → the element's true style is UNKNOWN → mark it opaque\n // for flatten (never unwrap it as inert). Resolved-to-no-paint elements keep hasUnresolvedClasses\n // false and stay flatten-eligible.\n if (res.unknown.length > 0) meta.hasUnresolvedClasses = true;\n for (const w of res.warnings) {\n diagnostics.push({\n code: 'DF_STYLE_CONFLICT_UNRESOLVED',\n severity: w.severity,\n message: w.message,\n nodeId,\n });\n }\n return ctx.normalizer.normalizeStyleMap(res.styles);\n };\n\n const splitTokens = (raw: string): string[] => raw.split(/\\s+/).filter((t) => t.length > 0);\n\n /* ----- child lowering ----- */\n\n const appendChild = (node: P5Node, parentId: IRNodeId, out: IRNodeId[]): void => {\n const name = node.nodeName;\n if (name === '#text') {\n const value = node.value ?? '';\n const id = doc.alloc.next();\n const loc = node.sourceCodeLocation ?? null;\n doc.nodes.set(\n id,\n createText(id, value, {\n parent: parentId,\n span: loc ? span(loc.startOffset, loc.endOffset) : null,\n collapsible: /^\\s*$/.test(value),\n }),\n );\n out.push(id);\n return;\n }\n if (name === '#comment') {\n const id = doc.alloc.next();\n const loc = node.sourceCodeLocation ?? null;\n doc.nodes.set(\n id,\n createComment(id, node.data ?? '', {\n parent: parentId,\n span: loc ? span(loc.startOffset, loc.endOffset) : null,\n }),\n );\n out.push(id);\n return;\n }\n if (name === '#documentType') return; // doctype stays verbatim in source (never represented)\n if (name.startsWith('#')) {\n // #document / #document-fragment — a container with no element identity: hoist its children.\n for (const c of node.childNodes ?? []) appendChild(c, parentId, out);\n return;\n }\n out.push(buildElement(node, parentId));\n };\n\n /* ----- element lowering ----- */\n\n const buildElement = (node: P5Node, parentId: IRNodeId): IRNodeId => {\n const id = doc.alloc.next();\n const tag = (node.tagName ?? node.nodeName).toLowerCase();\n const loc: P5Location | null = node.sourceCodeLocation ?? null;\n const attrsArr: readonly P5Attr[] = node.attrs ?? [];\n\n const opaqueSubtree = isOpaqueSubtreeTag(tag);\n const synthetic = loc == null; // auto-inserted <html>/<head>/<body>\n const opaque = opaqueSubtree || synthetic || elementIsOpaque(attrsArr);\n\n const meta: NodeMeta = defaultMeta();\n meta.hasEventHandlers = hasEventHandler(attrsArr);\n // Opaque nodes get floor 0 (any op above lint is refused by the applier); optimizable nodes get\n // floor 3 (fully open — the pattern predicates + flatten classifier are the real gate).\n meta.safetyFloor = opaque ? 0 : 3;\n\n // Split attributes: `class` → ClassList; everything else → AttrMap entries (so flatten's\n // `hasOwnAttrs` guard sees id/data-*/… and refuses to unwrap the element).\n let classes: ClassList = emptyClassList();\n let classTokens: string[] = [];\n const entries = new Map<string, AttrValue>();\n const order: string[] = [];\n\n for (const a of attrsArr) {\n if (a.name.toLowerCase() === 'class') {\n classTokens = splitTokens(a.value);\n const valueSpan = classValueSpan(loc, code);\n const clAttr = attrsLocOf(loc)?.['class'];\n const seg: ClassSegment = {\n kind: 'static',\n span: valueSpan ?? undefined,\n tokens: classTokens.map((value) => ({ value })),\n };\n classes = {\n form: 'string-literal',\n segments: [seg],\n valueSpan,\n attrSpan: clAttr ? span(clAttr.startOffset, clAttr.endOffset) : undefined,\n hasDynamic: false,\n opaque: false,\n rewritable: valueSpan != null,\n };\n continue;\n }\n const v = a.value;\n entries.set(a.name, { kind: 'static', value: v === '' ? true : v });\n order.push(a.name);\n }\n\n const attrs: AttrMap = { entries, spreads: [], order };\n const computed = resolveComputed(classTokens, tag, id, meta);\n\n // Children — opaque-subtree elements are NOT descended into; their inner bytes survive verbatim.\n const children: IRNodeId[] = [];\n if (!opaqueSubtree) {\n for (const c of node.childNodes ?? []) appendChild(c, id, children);\n }\n\n const el: IRElement = createElement(id, {\n tag,\n namespace: 'html',\n isComponent: false,\n selfClosing: loc ? loc.endTag == null : false,\n classes,\n computed,\n attrs,\n children,\n parent: parentId,\n span: loc ? span(loc.startOffset, loc.endOffset) : null,\n meta,\n });\n doc.nodes.set(id, el);\n\n // Backref (surgical-edit anchors) — only for elements with a real source location. Synthetic\n // wrappers get none, so the backend never tries to move/remove their bytes.\n if (loc) {\n backref.set(id, {\n nodeId: id,\n span: span(loc.startOffset, loc.endOffset),\n openTagSpan: loc.startTag ? span(loc.startTag.startOffset, loc.startTag.endOffset) : null,\n closeTagSpan: loc.endTag ? span(loc.endTag.startOffset, loc.endTag.endOffset) : null,\n innerSpan: null,\n selfClosing: loc.endTag == null,\n });\n }\n return id;\n };\n\n /* ----- attach top-level nodes under the root fragment ----- */\n\n const rootFrag = doc.nodes.get(doc.root) as IRFragment;\n appendChild(document, doc.root, rootFrag.children);\n\n return { doc, diagnostics };\n}\n","/**\n * @domflax/frontend-html — pure parse5 interop, constants, and opacity/span helpers.\n *\n * Stateless building blocks shared by the HTML parse pass: the minimal parse5 node/location shapes\n * this frontend reads (parse5 ships its own types, but the frontend requires it LAZILY as `unknown`,\n * so it re-declares only the slice it touches), the fixed constants, the opacity classification\n * predicates (which elements/subtrees must never be flattened or rewritten), and the source-span\n * helpers that turn parse5 location info into {@link SourceSpan}s for surgical codegen.\n *\n * No closure state, no document mutation, no third-party imports — only the `@domflax/core` type\n * contract.\n */\n\nimport type { FileKind, SourceFileId, SourceSpan } from '@domflax/core';\n\n/** Languages this frontend claims. HTML only; JSX/TSX is owned by a sibling frontend. */\nexport const HTML_LANGS: readonly FileKind[] = ['html'];\n\n/** The single registered source file id (one parse == one document). */\nexport const FILE_ID = 1 as SourceFileId;\n\n/* ───────────────────────── parse5 minimal shapes (lazy-required as unknown) ───────────────────────── */\n\n/** A `{ startOffset, endOffset }` byte range parse5 records for a node/tag/attribute. */\nexport interface P5Range {\n readonly startOffset: number;\n readonly endOffset: number;\n}\n\n/** parse5 element start-tag location (parse5 v7 nests per-attribute ranges under `startTag.attrs`). */\nexport interface P5TagLoc extends P5Range {\n readonly attrs?: Readonly<Record<string, P5Range>>;\n}\n\n/** parse5 element source-code location. `attrs` may live at the top level (v6) or under `startTag` (v7). */\nexport interface P5Location extends P5Range {\n readonly startTag?: P5TagLoc | null;\n readonly endTag?: P5Range | null;\n readonly attrs?: Readonly<Record<string, P5Range>>;\n}\n\nexport interface P5Attr {\n readonly name: string;\n readonly value: string;\n}\n\nexport interface P5Node {\n readonly nodeName: string;\n readonly tagName?: string;\n readonly value?: string; // #text\n readonly data?: string; // #comment\n readonly attrs?: readonly P5Attr[];\n readonly childNodes?: readonly P5Node[];\n readonly sourceCodeLocation?: P5Location | null;\n}\n\n/** The tiny slice of the parse5 module surface the frontend calls. */\nexport interface Parse5Module {\n parse(html: string, opts: { readonly sourceCodeLocationInfo: boolean }): P5Node;\n}\n\n/* ───────────────────────── HTML detection ───────────────────────── */\n\n/** Lightweight heuristic: does this source id / code look like HTML we can own? */\nexport function looksLikeHtml(id: string, code: string): boolean {\n if (/\\.html?$/i.test(id)) return true;\n const head = code.slice(0, 256).trimStart().toLowerCase();\n return head.startsWith('<!doctype html') || head.startsWith('<html') || head.startsWith('<');\n}\n\n/* ───────────────────────── opacity classification ───────────────────────── */\n\n/**\n * Tags whose ENTIRE subtree is opaque — never descended into, flattened, or rewritten. Raw-text /\n * embedded-content / whitespace-significant elements whose inner bytes must survive verbatim:\n * `<script>`/`<style>` (raw text + JS/CSS), `<template>` (inert content), `<svg>` (foreign markup),\n * `<pre>`/`<textarea>` (whitespace-significant).\n */\nexport const OPAQUE_SUBTREE_TAGS: ReadonlySet<string> = new Set([\n 'script',\n 'style',\n 'template',\n 'svg',\n 'pre',\n 'textarea',\n]);\n\nexport function isOpaqueSubtreeTag(tag: string): boolean {\n return OPAQUE_SUBTREE_TAGS.has(tag);\n}\n\n/**\n * Element-level opacity: an `id` (JS may `querySelector`/anchor-link it), any inline `on*=` event\n * handler, or `contenteditable` pins the element's identity/behaviour — it must never be flattened or\n * rewritten (its subtree may still be optimized).\n */\nexport function elementIsOpaque(attrs: readonly P5Attr[]): boolean {\n for (const a of attrs) {\n const n = a.name.toLowerCase();\n if (n === 'id' || n === 'contenteditable') return true;\n if (n.startsWith('on')) return true;\n }\n return false;\n}\n\n/** True when the element carries any inline `on*=` event handler. */\nexport function hasEventHandler(attrs: readonly P5Attr[]): boolean {\n for (const a of attrs) if (/^on/i.test(a.name)) return true;\n return false;\n}\n\n/* ───────────────────────── source-span helpers ───────────────────────── */\n\n/** A {@link SourceSpan} over `[start, end)` in the single source file. */\nexport function span(start: number, end: number): SourceSpan {\n return { file: FILE_ID, start, end };\n}\n\n/** The per-attribute location map, tolerating both the v6 (top-level) and v7 (`startTag`) layouts. */\nexport function attrsLocOf(loc: P5Location | null | undefined): Readonly<Record<string, P5Range>> | undefined {\n if (!loc) return undefined;\n return loc.startTag?.attrs ?? loc.attrs;\n}\n\n/**\n * The VALUE span (quotes included) of the `class` attribute — the splice target the backend overwrites\n * to rewrite the class list in place. Derived from the whole-attribute range (`class=\"…\"`) by skipping\n * past the name and `=`; returns null when there is no class attribute or it has no value.\n */\nexport function classValueSpan(loc: P5Location | null | undefined, source: string): SourceSpan | null {\n const attrsLoc = attrsLocOf(loc);\n const cl = attrsLoc?.['class'];\n if (!cl) return null;\n const text = source.slice(cl.startOffset, cl.endOffset);\n const eq = text.indexOf('=');\n if (eq === -1) return null; // bare `class` with no value\n let i = eq + 1;\n while (i < text.length && /\\s/.test(text[i]!)) i += 1;\n if (i >= text.length) return null;\n return span(cl.startOffset + i, cl.endOffset);\n}\n","/**\n * @domflax/frontend-html — parse5 HTML <-> IR frontend + backend.\n *\n * A {@link Frontend} that parses HTML into an {@link IRDocument} (parse5 tree → IR, resolving each\n * element's `class` attribute onto `computed`), and a matching {@link Backend} that prints the edited\n * document back to HTML with SURGICAL, span-based edits over the original source (never re-serializing\n * the parse5 tree). Untouched bytes — doctype, comments, whitespace, scripts, attribute order — stay\n * byte-for-byte identical.\n *\n * parse5 is a real dependency but is LAZILY required inside `parse()` (see `./parse`), so the JSX-only\n * path never loads it. The parse walk + opacity/span helpers live in `./walk` + `./parse`; the reverse\n * codegen in `./backend`. This module is the public assembly point.\n */\n\nimport type {\n Backend,\n BackendContext,\n CodegenResult,\n EditPlan,\n Frontend,\n FrontendParseContext,\n IRDocument,\n ParseResult,\n} from '@domflax/core';\n\nimport { doPrint } from './backend';\nimport { doParse } from './parse';\nimport { HTML_LANGS, looksLikeHtml } from './walk';\n\nexport { HTML_LANGS, looksLikeHtml } from './walk';\n\n/** HTML frontend: parse5 HTML → IR (with source spans for surgical codegen). */\nexport const htmlFrontend: Frontend = {\n name: 'html',\n langs: HTML_LANGS,\n canParse(id: string, code: string): boolean {\n return looksLikeHtml(id, code);\n },\n parse(code: string, ctx: FrontendParseContext): ParseResult {\n return doParse(code, ctx);\n },\n};\n\n/** Factory mirror — returns a fresh handle to the (stateless) HTML frontend. */\nexport function createHtmlFrontend(): Frontend {\n return htmlFrontend;\n}\n\n/** HTML backend: IR → HTML via span-based surgical edits over the retained verbatim source. */\nexport const htmlBackend: Backend = {\n name: 'html',\n langs: HTML_LANGS,\n print(doc: IRDocument, _plan: EditPlan, _ctx: BackendContext): CodegenResult {\n return { code: doPrint(doc), map: null, edits: [], diagnostics: [] };\n },\n};\n\n/** Factory mirror — returns a fresh handle to the (stateless) HTML backend. */\nexport function createHtmlBackend(): Backend {\n return htmlBackend;\n}\n\nexport default htmlFrontend;\n","/**\n * @domflax/frontend-jsx — AST interop, constants, and pure classification helpers.\n *\n * Stateless building blocks shared by the JSX parse pass: the `@babel/traverse`\n * default-export normalization, the frontend's fixed constants, and the pure\n * name/classification/JSX-discovery helpers (no closure state, no document mutation).\n */\n\nimport babelTraverse from '@babel/traverse';\nimport type {\n JSXAttribute,\n JSXElement,\n JSXFragment,\n JSXIdentifier,\n JSXMemberExpression,\n JSXNamespacedName,\n Node as BabelNode,\n} from '@babel/types';\n\nimport type { ClassListForm, ExprKind, FileKind, SourceFileId } from '@domflax/core';\n\n/* ───────────────────────── @babel/traverse interop ───────────────────────── */\n\n// `@babel/traverse` is published as CJS (`module.exports = traverse; exports.default = traverse`).\n// Under an ESM default import the value may be the function OR `{ default: fn }` depending on the\n// interop layer (Node ESM vs. esbuild vs. tsup), so normalize defensively.\nexport const traverse = (\n typeof babelTraverse === 'function'\n ? babelTraverse\n : (babelTraverse as unknown as { default: typeof babelTraverse }).default\n) as typeof babelTraverse;\n\n/** Languages this frontend claims. JSX/TSX only; HTML is owned by a sibling frontend. */\nexport const JSX_LANGS: readonly FileKind[] = ['jsx', 'tsx'];\n\n/** The single registered source file id (one parse == one module). */\nexport const FILE_ID = 1 as SourceFileId;\n\n/** Marker payload stored for every interned expression so the backend can re-print it. */\nexport interface ExprPayload {\n readonly text: string;\n readonly spread: boolean;\n}\n\n/* ───────────────────────── name + classification helpers ───────────────────────── */\n\nexport type JSXName = JSXIdentifier | JSXMemberExpression | JSXNamespacedName;\n\nexport function jsxName(node: JSXName): string {\n switch (node.type) {\n case 'JSXIdentifier':\n return node.name;\n case 'JSXMemberExpression':\n return `${jsxName(node.object)}.${node.property.name}`;\n case 'JSXNamespacedName':\n return `${node.namespace.name}:${node.name.name}`;\n }\n}\n\n/** Component vs. intrinsic: capitalized identifier or member expression ⇒ component. */\nexport function isComponentName(node: JSXName): boolean {\n if (node.type === 'JSXMemberExpression') return true;\n if (node.type === 'JSXNamespacedName') return false;\n return /^[A-Z]/.test(node.name);\n}\n\nexport function attrName(name: JSXAttribute['name']): string {\n return name.type === 'JSXNamespacedName'\n ? `${name.namespace.name}:${name.name.name}`\n : name.name;\n}\n\nexport function exprKind(node: BabelNode): ExprKind {\n switch (node.type) {\n case 'CallExpression':\n case 'OptionalCallExpression':\n return 'call';\n case 'MemberExpression':\n case 'OptionalMemberExpression':\n return 'member';\n case 'ConditionalExpression':\n case 'LogicalExpression':\n return 'conditional';\n case 'TemplateLiteral':\n case 'TaggedTemplateExpression':\n return 'template';\n case 'Identifier':\n return 'identifier';\n case 'SpreadElement':\n return 'spread';\n default:\n return 'other';\n }\n}\n\n/** Map a dynamic className expression to the closest {@link ClassListForm}. */\nexport function classFormOf(node: BabelNode): ClassListForm {\n switch (node.type) {\n case 'TemplateLiteral':\n case 'TaggedTemplateExpression':\n return 'template-literal';\n case 'CallExpression':\n case 'OptionalCallExpression':\n return 'call';\n case 'ConditionalExpression':\n case 'LogicalExpression':\n return 'conditional';\n case 'MemberExpression':\n case 'OptionalMemberExpression':\n case 'Identifier':\n return 'member';\n default:\n return 'call';\n }\n}\n\n/**\n * Find the OUTERMOST JSXElement/JSXFragment nodes that a dynamic expression renders, so the frontend\n * can lower JSX nested inside `{…}` holes — `.map`/`.filter`/`.forEach((x) => <jsx/>)` callbacks,\n * `&&`/`||` logical expressions, ternaries, and parenthesized/cast wrappers — into REAL IR element\n * nodes. The dynamic scaffolding around them (the call itself, the conditions, `{expr}` holes) stays\n * opaque; only the renderable JSX is surfaced so the pass manager descends into and optimizes it.\n *\n * Only the outermost JSX is collected: `buildElement`/`buildFragment` recurse into the\n * descendants themselves, so we must NOT descend past a JSX boundary here (that would double-register\n * inner elements).\n */\nexport function findNestedJsxRoots(root: BabelNode): (JSXElement | JSXFragment)[] {\n const out: (JSXElement | JSXFragment)[] = [];\n const seen = new Set<BabelNode>();\n\n const visit = (n: BabelNode | null | undefined): void => {\n if (!n || seen.has(n)) return;\n seen.add(n);\n switch (n.type) {\n case 'JSXElement':\n case 'JSXFragment':\n out.push(n); // outermost renderable JSX — buildElement/buildFragment recurse from here\n return;\n case 'ParenthesizedExpression':\n case 'TSNonNullExpression':\n case 'TSAsExpression':\n case 'TSSatisfiesExpression':\n case 'TSTypeAssertion':\n visit(n.expression);\n return;\n case 'LogicalExpression':\n visit(n.left);\n visit(n.right);\n return;\n case 'ConditionalExpression':\n visit(n.consequent);\n visit(n.alternate);\n return;\n case 'SequenceExpression':\n for (const e of n.expressions) visit(e);\n return;\n case 'CallExpression':\n case 'OptionalCallExpression':\n // `.map`/`.filter`/`.forEach(cb)` etc. — descend into the call arguments (the callbacks),\n // never the callee (that is the `items.map` member access, which renders nothing).\n for (const a of n.arguments) visit(a as BabelNode);\n return;\n case 'ArrowFunctionExpression':\n case 'FunctionExpression':\n visit(n.body);\n return;\n case 'BlockStatement':\n for (const s of n.body) visit(s);\n return;\n case 'ReturnStatement':\n visit(n.argument);\n return;\n case 'IfStatement':\n visit(n.consequent);\n visit(n.alternate);\n return;\n case 'ArrayExpression':\n for (const el of n.elements) visit(el as BabelNode);\n return;\n default:\n return;\n }\n };\n\n visit(root);\n return out;\n}\n\nexport function looksLikeJsx(id: string, code: string): boolean {\n if (/\\.[jt]sx$/i.test(id)) return true;\n return /<\\/?[A-Za-z][\\w.-]*|<>/.test(code);\n}\n","/**\n * @domflax/frontend-jsx — the JSX/TSX → IR parse pass.\n *\n * Walks a Babel AST (`@babel/parser` → `@babel/traverse`) and lowers JSXElement /\n * JSXFragment / JSXText / JSXExpressionContainer / JSXSpreadChild nodes into the\n * `@domflax/core` IR. ALL dynamic JavaScript stays out of the structural IR: every\n * expression container, spread, and dynamic className/child is interned into the\n * document's {@link ExprRegistry} as an opaque {@link ExprRef} (with its verbatim source\n * slice as payload), and only its source span survives in the tree.\n *\n * Static `class`/`className` literals are split into {@link ClassToken}s on a static\n * {@link ClassSegment}; a non-string-literal className becomes a single dynamic segment\n * (opaque, never optimized). Static classes are resolved through the supplied\n * {@link StyleResolver} + {@link StyleNormalizer} into `element.computed` so downstream\n * patterns can match on resolved style.\n *\n * NodeMeta opacity barriers populated here: hasRef (`ref=`), hasEventHandlers (`on*=`),\n * hasKey (`key=`), hasSpreadAttrs (`{...x}`), hasDangerousHtml\n * (`dangerouslySetInnerHTML=`), hasDynamicChildren (any expression / spread child),\n * isComponent (capitalized / member tag). \"hasDynamicClasses\" is carried on the\n * {@link ClassList} itself (`hasDynamic` / `opaque`), not on NodeMeta.\n */\n\nimport { parse as babelParse } from '@babel/parser';\nimport type { NodePath } from '@babel/traverse';\nimport type {\n Expression,\n JSXAttribute,\n JSXElement,\n JSXEmptyExpression,\n JSXFragment,\n JSXOpeningElement,\n Node as BabelNode,\n} from '@babel/types';\n\nimport type {\n AttrMap,\n AttrValue,\n ClassList,\n ClassSegment,\n ClassToken,\n Diagnostic,\n ExprRef,\n FrontendParseContext,\n IRDocument,\n IRElement,\n IRFragment,\n IRNamespace,\n IRNodeId,\n MutableBackrefTable,\n NodeMeta,\n ParseResult,\n SourceFile,\n SourceSpan,\n StyleMap,\n} from '@domflax/core';\nimport {\n createDocument,\n createElement,\n createExpr,\n createFragment,\n createText,\n defaultMeta,\n emptyClassList,\n emptyStyleMap,\n} from '@domflax/core';\n\nimport type { ExprPayload } from './frontend-ast';\nimport {\n FILE_ID,\n attrName,\n classFormOf,\n exprKind,\n findNestedJsxRoots,\n isComponentName,\n jsxName,\n traverse,\n} from './frontend-ast';\n\nexport function doParse(code: string, ctx: FrontendParseContext): ParseResult {\n const diagnostics: Diagnostic[] = [];\n const doc: IRDocument = createDocument('jsx');\n const backref = doc.backref as MutableBackrefTable;\n\n const ast = babelParse(code, {\n sourceType: 'module',\n plugins: ['jsx', 'typescript'],\n });\n\n const eol: '\\n' | '\\r\\n' = code.includes('\\r\\n') ? '\\r\\n' : '\\n';\n const sourceFile: SourceFile = {\n id: FILE_ID,\n path: ctx.id,\n text: code,\n frontend: 'jsx',\n eol,\n indentUnit: ' ',\n native: ast,\n };\n doc.sources.set(FILE_ID, sourceFile);\n\n /* ----- span helpers (close over `code`) ----- */\n\n const spanOf = (node: BabelNode): SourceSpan | null => {\n if (node.start == null || node.end == null) return null;\n const span: SourceSpan = {\n file: FILE_ID,\n start: node.start,\n end: node.end,\n startLoc: node.loc\n ? { line: node.loc.start.line, column: node.loc.start.column }\n : undefined,\n endLoc: node.loc ? { line: node.loc.end.line, column: node.loc.end.column } : undefined,\n };\n return span;\n };\n\n const sliceOf = (node: BabelNode): string =>\n node.start == null || node.end == null ? '' : code.slice(node.start, node.end);\n\n /** Intern an expression as an opaque ExprRef, recording its verbatim source slice. */\n const internExpr = (node: Expression | JSXEmptyExpression, spread: boolean): ExprRef => {\n const payload: ExprPayload = { text: sliceOf(node), spread };\n return doc.exprs.intern({\n span: spanOf(node) ?? { file: FILE_ID, start: 0, end: 0 },\n kind: exprKind(node),\n payload,\n });\n };\n\n /* ----- class list ----- */\n\n const splitTokens = (raw: string): ClassToken[] =>\n raw\n .split(/\\s+/)\n .filter((t) => t.length > 0)\n .map((value) => ({ value }) as ClassToken);\n\n const buildClassList = (attr: JSXAttribute): ClassList => {\n const attrSpan = spanOf(attr) ?? undefined;\n const v = attr.value;\n\n const staticList = (tokens: ClassToken[], valueSpan: SourceSpan | null): ClassList => {\n const seg: ClassSegment = { kind: 'static', span: valueSpan ?? undefined, tokens };\n return {\n form: 'string-literal',\n segments: [seg],\n valueSpan,\n attrSpan,\n hasDynamic: false,\n opaque: false,\n rewritable: true,\n };\n };\n\n if (v == null) return staticList([], null);\n\n if (v.type === 'StringLiteral') {\n return staticList(splitTokens(v.value), spanOf(v));\n }\n\n if (v.type === 'JSXExpressionContainer') {\n const expr = v.expression;\n // `className={\"a b\"}` is still a static string literal.\n if (expr.type === 'StringLiteral') {\n return staticList(splitTokens(expr.value), spanOf(expr));\n }\n if (expr.type === 'JSXEmptyExpression') return staticList([], null);\n const ref = internExpr(expr, false);\n const valueSpan = spanOf(expr);\n const seg: ClassSegment = { kind: 'dynamic', span: valueSpan ?? undefined, expr: ref };\n return {\n form: classFormOf(expr),\n segments: [seg],\n valueSpan,\n attrSpan,\n hasDynamic: true,\n opaque: true,\n rewritable: false,\n };\n }\n\n return emptyClassList();\n };\n\n const staticTokensOf = (classes: ClassList): string[] => {\n const out: string[] = [];\n for (const seg of classes.segments) {\n if (seg.kind === 'static') for (const t of seg.tokens) out.push(t.value);\n }\n return out;\n };\n\n /* ----- attribute value ----- */\n\n const buildAttrValue = (attr: JSXAttribute): AttrValue => {\n const v = attr.value;\n if (v == null) return { kind: 'static', value: true, span: spanOf(attr) ?? undefined };\n if (v.type === 'StringLiteral') {\n return { kind: 'static', value: v.value, span: spanOf(v) ?? undefined };\n }\n if (v.type === 'JSXExpressionContainer') {\n if (v.expression.type === 'JSXEmptyExpression') {\n return { kind: 'static', value: true, span: spanOf(v) ?? undefined };\n }\n return { kind: 'dynamic', expr: internExpr(v.expression, false), span: spanOf(v) ?? undefined };\n }\n // JSXElement / JSXFragment used as an attribute value → opaque expression.\n return { kind: 'dynamic', expr: internExpr(v as Expression, false), span: spanOf(v) ?? undefined };\n };\n\n /* ----- node builders ----- */\n\n const buildNestedRoot = (jsx: JSXElement | JSXFragment, parentId: IRNodeId): IRNodeId =>\n jsx.type === 'JSXFragment' ? buildFragment(jsx, parentId) : buildElement(jsx, parentId);\n\n /** Lower a single JSX child, appending the resulting IR node id(s) onto `out`. */\n const appendChild = (\n node: JSXElement['children'][number],\n parentId: IRNodeId,\n out: IRNodeId[],\n ): void => {\n switch (node.type) {\n case 'JSXText': {\n const id = doc.alloc.next();\n doc.nodes.set(\n id,\n createText(id, node.value, {\n parent: parentId,\n span: spanOf(node),\n collapsible: /^\\s*$/.test(node.value),\n }),\n );\n out.push(id);\n return;\n }\n case 'JSXExpressionContainer': {\n const expr = node.expression;\n if (expr.type === 'JSXEmptyExpression') return; // `{/* comment */}`\n // A container whose WHOLE expression is a JSX node (`{<X/>}`) renders that node directly —\n // lower it as a real element so passes can optimize it (no opaque wrapper needed).\n if (expr.type === 'JSXElement' || expr.type === 'JSXFragment') {\n out.push(buildNestedRoot(expr, parentId));\n return;\n }\n // Otherwise the expression itself stays OPAQUE — the `.map`/condition/`{expr}` hole is\n // interned and preserved verbatim by the backend …\n const id = doc.alloc.next();\n const ref = internExpr(expr, false);\n doc.nodes.set(id, createExpr(id, ref, { parent: parentId, span: spanOf(node) }));\n out.push(id);\n // … but any JSX nested INSIDE it (map/filter callbacks, `&&`/`||`, ternary, parens) is\n // lowered to real element nodes (with their true source spans) so the pass manager descends\n // into and optimizes them too.\n for (const jsx of findNestedJsxRoots(expr)) out.push(buildNestedRoot(jsx, parentId));\n return;\n }\n case 'JSXSpreadChild': {\n const id = doc.alloc.next();\n const ref = internExpr(node.expression, true);\n doc.nodes.set(id, createExpr(id, ref, { parent: parentId, span: spanOf(node) }));\n out.push(id);\n for (const jsx of findNestedJsxRoots(node.expression)) {\n out.push(buildNestedRoot(jsx, parentId));\n }\n return;\n }\n case 'JSXElement':\n out.push(buildElement(node, parentId));\n return;\n case 'JSXFragment':\n out.push(buildFragment(node, parentId));\n return;\n default:\n return;\n }\n };\n\n const buildFragment = (node: JSXFragment, parentId: IRNodeId): IRNodeId => {\n const id = doc.alloc.next();\n const children: IRNodeId[] = [];\n for (const c of node.children) appendChild(c, id, children);\n doc.nodes.set(id, createFragment(id, { children, parent: parentId, span: spanOf(node) }));\n backref.set(id, {\n nodeId: id,\n span: spanOf(node) ?? { file: FILE_ID, start: 0, end: 0 },\n openTagSpan: spanOf(node.openingFragment),\n closeTagSpan: spanOf(node.closingFragment),\n innerSpan: null,\n selfClosing: false,\n });\n return id;\n };\n\n const buildElement = (node: JSXElement, parentId: IRNodeId): IRNodeId => {\n const id = doc.alloc.next();\n const opening: JSXOpeningElement = node.openingElement;\n const tag = jsxName(opening.name);\n const component = isComponentName(opening.name);\n\n const meta: NodeMeta = defaultMeta();\n meta.isComponent = component;\n\n let classes: ClassList = emptyClassList();\n const entries = new Map<string, AttrValue>();\n const order: string[] = [];\n const spreads: ExprRef[] = [];\n\n for (const attr of opening.attributes) {\n if (attr.type === 'JSXSpreadAttribute') {\n spreads.push(internExpr(attr.argument, true));\n meta.hasSpreadAttrs = true;\n continue;\n }\n const name = attrName(attr.name);\n if (name === 'className' || name === 'class') {\n classes = buildClassList(attr);\n continue;\n }\n if (name === 'ref') meta.hasRef = true;\n else if (name === 'key') meta.hasKey = true;\n else if (name === 'dangerouslySetInnerHTML') meta.hasDangerousHtml = true;\n else if (/^on[A-Z]/.test(name)) meta.hasEventHandlers = true;\n entries.set(name, buildAttrValue(attr));\n order.push(name);\n }\n\n const attrs: AttrMap = { entries, spreads, order };\n\n const children: IRNodeId[] = [];\n for (const c of node.children) appendChild(c, id, children);\n for (const cid of children) {\n const cn = doc.nodes.get(cid);\n if (cn && cn.kind === 'expr') {\n meta.hasDynamicChildren = true;\n break;\n }\n }\n\n // Resolve static classes (+ tag) into computed style via the injected resolver/normalizer.\n let computed: StyleMap = emptyStyleMap();\n if (!classes.hasDynamic) {\n const tokens = staticTokensOf(classes);\n if (tokens.length > 0) {\n const res = ctx.resolver.resolve({\n classes: tokens,\n element: { tagName: tag, namespace: component ? undefined : 'html' },\n });\n computed = ctx.normalizer.normalizeStyleMap(res.styles);\n // SAFETY (Layer 2): a token the resolver could not resolve leaves the element's true style\n // UNKNOWN → mark it opaque for flatten (never unwrap it as inert). Distinct from a token that\n // resolved to no paint (which keeps the element flatten-eligible).\n if (res.unknown.length > 0) meta.hasUnresolvedClasses = true;\n for (const w of res.warnings) {\n diagnostics.push({\n code: 'DF_STYLE_CONFLICT_UNRESOLVED',\n severity: w.severity,\n message: w.message,\n nodeId: id,\n });\n }\n }\n }\n\n const namespace: IRNamespace = component ? 'component' : 'html';\n const el: IRElement = createElement(id, {\n tag,\n namespace,\n isComponent: component,\n selfClosing: opening.selfClosing,\n classes,\n computed,\n attrs,\n children,\n parent: parentId,\n span: spanOf(node),\n meta,\n });\n doc.nodes.set(id, el);\n\n const inner =\n children.length > 0\n ? spanOf(node.children[0]! as BabelNode) && spanOf(node.children.at(-1)! as BabelNode)\n ? {\n file: FILE_ID,\n start: spanOf(node.children[0]! as BabelNode)!.start,\n end: spanOf(node.children.at(-1)! as BabelNode)!.end,\n }\n : null\n : null;\n backref.set(id, {\n nodeId: id,\n span: spanOf(node) ?? { file: FILE_ID, start: 0, end: 0 },\n openTagSpan: spanOf(opening),\n closeTagSpan: node.closingElement ? spanOf(node.closingElement) : null,\n innerSpan: inner,\n selfClosing: opening.selfClosing,\n });\n return id;\n };\n\n /* ----- collect the outermost JSX islands and attach them to the root fragment ----- */\n\n const roots: (JSXElement | JSXFragment)[] = [];\n traverse(ast, {\n JSXElement(path: NodePath<JSXElement>) {\n roots.push(path.node);\n path.skip();\n },\n JSXFragment(path: NodePath<JSXFragment>) {\n roots.push(path.node);\n path.skip();\n },\n });\n\n const rootFrag = doc.nodes.get(doc.root) as IRFragment;\n for (const r of roots) {\n const id = r.type === 'JSXFragment' ? buildFragment(r, doc.root) : buildElement(r, doc.root);\n rootFrag.children.push(id);\n }\n\n return { doc, diagnostics };\n}\n","/**\n * @domflax/frontend-jsx — Babel JSX/TSX → IR frontend.\n *\n * Walks a Babel AST (`@babel/parser` → `@babel/traverse`) and lowers JSXElement /\n * JSXFragment / JSXText / JSXExpressionContainer / JSXSpreadChild nodes into the\n * `@domflax/core` IR. ALL dynamic JavaScript stays out of the structural IR: every\n * expression container, spread, and dynamic className/child is interned into the\n * document's {@link ExprRegistry} as an opaque {@link ExprRef} (with its verbatim source\n * slice as payload), and only its source span survives in the tree.\n *\n * Static `class`/`className` literals are split into {@link ClassToken}s on a static\n * {@link ClassSegment}; a non-string-literal className becomes a single dynamic segment\n * (opaque, never optimized). Static classes are resolved through the supplied\n * {@link StyleResolver} + {@link StyleNormalizer} into `element.computed` so downstream\n * patterns can match on resolved style.\n *\n * NodeMeta opacity barriers populated here: hasRef (`ref=`), hasEventHandlers (`on*=`),\n * hasKey (`key=`), hasSpreadAttrs (`{...x}`), hasDangerousHtml\n * (`dangerouslySetInnerHTML=`), hasDynamicChildren (any expression / spread child),\n * isComponent (capitalized / member tag). \"hasDynamicClasses\" is carried on the\n * {@link ClassList} itself (`hasDynamic` / `opaque`), not on NodeMeta.\n *\n * The pure AST/classification helpers live in `./frontend-ast`; the parse pass itself\n * lives in `./frontend-parse`. This module is the public assembly point.\n */\n\nimport type { Frontend, FrontendParseContext, ParseResult } from '@domflax/core';\n\nimport { JSX_LANGS, looksLikeJsx } from './frontend-ast';\nimport { doParse } from './frontend-parse';\n\nexport const jsxFrontend: Frontend = {\n name: 'babel-jsx',\n langs: JSX_LANGS,\n canParse(id: string, code: string): boolean {\n return looksLikeJsx(id, code);\n },\n parse(code: string, ctx: FrontendParseContext): ParseResult {\n return doParse(code, ctx);\n },\n};\n\n/** Factory mirror — returns a fresh handle to the (stateless) JSX frontend. */\nexport function createJsxFrontend(): Frontend {\n return jsxFrontend;\n}\n","/**\n * @domflax/frontend-jsx — IR → JSX/TSX backend (SURGICAL, full-module round-trip).\n *\n * The pass manager mutates a tree of JSX *islands* that were lowered from a complete module\n * (imports, `export default function`, hooks, `return (…)`, `{expr}` holes, comments, …). The\n * backend's job is to emit a COMPLETE, valid module — not just the JSX subtree. It does this by\n * starting from the element's ORIGINAL verbatim source (retained on {@link SourceFile.text}) and\n * applying ONLY the diffs the passes produced, via `magic-string`:\n *\n * • CLASS CHANGE — for every surviving element whose static class list differs from its source\n * text, overwrite just the `class`/`className` attribute VALUE span (quotes included) with the\n * new tokens. If the element gained classes but had no class attribute, insert one on the\n * opening tag.\n * • UNWRAP (flatten) — when a wrapper element/fragment was removed but its children survived,\n * delete ONLY the wrapper's open- and close-tag spans; the children (and their entire subtrees,\n * including dynamic `{expr}` holes and `key=`) are preserved verbatim.\n * • FULL REMOVAL — when a node was removed with no surviving descendant, delete its whole span.\n *\n * Every other byte — imports, exports, function declarations, returns, hooks, `{expr}` holes,\n * whitespace, comments, attribute ordering — is left exactly as authored. Output is\n * `magicString.toString()`: a complete module.\n *\n * Fallback: a document with no retained source (e.g. a hand-synthesized IR) cannot be spliced, so\n * it falls back to a clean structural re-print ({@link rePrint}).\n */\n\nimport MagicString from 'magic-string';\n\nimport type {\n AttrValue,\n Backend,\n BackendContext,\n Backref,\n ClassList,\n CodegenResult,\n EditPlan,\n ExprRef,\n FileKind,\n IRDocument,\n IRElement,\n IRNode,\n IRNodeId,\n SourceFile,\n SourceSpan,\n} from '@domflax/core';\n\nconst JSX_LANGS: readonly FileKind[] = ['jsx', 'tsx'];\n\ninterface ExprPayload {\n readonly text: string;\n readonly spread: boolean;\n}\n\n/* ───────────────────────── shared expr/class helpers ───────────────────────── */\n\n/** Recover an interned expression's source text (payload first, span-slice fallback). */\nfunction exprText(doc: IRDocument, ref: ExprRef): ExprPayload {\n const rec = doc.exprs.get(ref);\n const payload = rec?.payload as Partial<ExprPayload> | undefined;\n if (payload && typeof payload.text === 'string') {\n return { text: payload.text, spread: payload.spread === true };\n }\n if (rec) {\n const sf = doc.sources.get(rec.span.file);\n if (sf) return { text: sf.text.slice(rec.span.start, rec.span.end), spread: false };\n }\n return { text: '', spread: false };\n}\n\n/** All static class tokens of a {@link ClassList}, in order. */\nfunction staticTokensOf(classes: ClassList): string[] {\n const out: string[] = [];\n for (const seg of classes.segments) {\n if (seg.kind === 'static') for (const t of seg.tokens) out.push(t.value);\n }\n return out;\n}\n\n/* ───────────────────────── surgical (magic-string) codegen ───────────────────────── */\n\n/** Pick the single retained source file this document was parsed from (if any). */\nfunction primarySource(doc: IRDocument): SourceFile | null {\n for (const sf of doc.sources.values()) {\n if (typeof sf.text === 'string' && sf.text.length > 0) return sf;\n }\n return null;\n}\n\n/** Collect every node reachable from the root of the (mutated) tree. */\nfunction collectKept(doc: IRDocument): IRNode[] {\n const out: IRNode[] = [];\n const seen = new Set<IRNodeId>();\n const visit = (id: IRNodeId): void => {\n if (seen.has(id)) return;\n seen.add(id);\n const n = doc.nodes.get(id);\n if (!n) return;\n out.push(n);\n if (n.kind === 'element' || n.kind === 'fragment') for (const c of n.children) visit(c);\n };\n visit(doc.root);\n return out;\n}\n\n/** Span `a` strictly contains span `b` (same file, b nested inside, not identical). */\nfunction strictlyContains(a: SourceSpan, b: SourceSpan): boolean {\n if (a.file !== b.file) return false;\n if (a.start <= b.start && b.end <= a.end) return !(a.start === b.start && a.end === b.end);\n return false;\n}\n\ninterface RemovedRegion {\n readonly backref: Backref;\n /** A surviving node nested inside this region ⇒ this was an UNWRAP (keep inner, drop tags). */\n readonly unwrapped: boolean;\n}\n\n/**\n * Apply the class-list diff for a single surviving element. Returns true if an edit was made.\n */\nfunction editClasses(ms: MagicString, doc: IRDocument, sf: SourceFile, el: IRElement): boolean {\n const classes = el.classes;\n // Wholly dynamic / opaque class lists are never rewritten by the passes — leave verbatim.\n if (classes.hasDynamic || classes.opaque) return false;\n\n const tokens = staticTokensOf(classes);\n const valueSpan = classes.valueSpan;\n\n if (valueSpan && valueSpan.file === sf.id) {\n const current = sf.text.slice(valueSpan.start, valueSpan.end);\n // Preserve the original quote style; default to double quotes when we can't detect one.\n const quote = current.startsWith(\"'\") ? \"'\" : '\"';\n const next = `${quote}${tokens.join(' ')}${quote}`;\n if (current !== next) {\n ms.overwrite(valueSpan.start, valueSpan.end, next);\n return true;\n }\n return false;\n }\n\n // No class attribute originally, but the passes added classes ⇒ insert one on the opening tag.\n if (tokens.length === 0) return false;\n if (el.isComponent) return false; // never synthesize className onto an opaque component\n const back = doc.backref.get(el.id);\n const openTag = back?.openTagSpan;\n if (!openTag || openTag.file !== sf.id) return false;\n // Insert immediately after the tag name: `<tag‸ …`.\n const insertAt = openTag.start + 1 + el.tag.length;\n ms.appendLeft(insertAt, ` className=\"${tokens.join(' ')}\"`);\n return true;\n}\n\n/**\n * Extract a `key=…` attribute (verbatim, e.g. `key={f.id}` or `key=\"row\"`) from an opening-tag's\n * source text, or null when the tag carries no key. Brace/quote-aware so `key={f.id}` with nested\n * braces is captured whole. Requires whitespace before `key` so `data-key=` / `aria-keyshortcuts=`\n * never false-match.\n */\nfunction extractKeyAttr(openTag: string): string | null {\n const m = /(^|\\s)key\\s*=\\s*/.exec(openTag);\n if (!m) return null;\n const keyStart = m.index + m[1].length;\n let i = m.index + m[0].length;\n const ch = openTag[i];\n if (ch === '{') {\n let depth = 0;\n for (; i < openTag.length; i += 1) {\n const c = openTag[i];\n if (c === '{') depth += 1;\n else if (c === '}') {\n depth -= 1;\n if (depth === 0) {\n i += 1;\n break;\n }\n }\n }\n } else if (ch === '\"' || ch === \"'\") {\n const q = ch;\n i += 1;\n for (; i < openTag.length; i += 1) {\n if (openTag[i] === q) {\n i += 1;\n break;\n }\n }\n } else {\n for (; i < openTag.length; i += 1) {\n if (/[\\s>/]/.test(openTag[i]!)) break;\n }\n }\n return openTag.slice(keyStart, i);\n}\n\n/**\n * KEY SAFETY: when an UNWRAPPED wrapper carried a React `key`, that key must not vanish with the\n * deleted tags. If the wrapper had exactly one surviving (maximal) element child and that child has\n * no key of its own, transfer the wrapper's `key=…` verbatim onto the survivor's opening tag.\n * Conservative: anything ambiguous (no surviving element child, multiple survivors, child already\n * keyed) is left untouched (the flatten pattern is expected to have refused such a case).\n */\nfunction transferKeyOnUnwrap(\n ms: MagicString,\n doc: IRDocument,\n sf: SourceFile,\n region: Backref,\n kept: readonly IRNode[],\n): void {\n const open = region.openTagSpan;\n if (!open || open.file !== sf.id) return;\n const keyAttr = extractKeyAttr(sf.text.slice(open.start, open.end));\n if (!keyAttr) return;\n\n const inside: IRElement[] = [];\n for (const n of kept) {\n if (n.kind !== 'element' || !n.span || n.span.file !== sf.id) continue;\n if (strictlyContains(region.span, n.span)) inside.push(n);\n }\n // Keep only the topmost survivors (not nested inside another survivor of this region).\n const maximal = inside.filter(\n (n) => !inside.some((o) => o !== n && o.span && n.span && strictlyContains(o.span, n.span)),\n );\n if (maximal.length !== 1) return;\n\n const child = maximal[0]!;\n const childOpen = doc.backref.get(child.id)?.openTagSpan;\n if (!childOpen || childOpen.file !== sf.id) return;\n if (extractKeyAttr(sf.text.slice(childOpen.start, childOpen.end))) return; // already keyed\n\n // Insert immediately after the child's tag name: `<tag‸ …`.\n ms.appendLeft(childOpen.start + 1 + child.tag.length, ` ${keyAttr}`);\n}\n\n/** Surgical full-module codegen. Returns null when the document has no retained source. */\nfunction surgicalPrint(doc: IRDocument): string | null {\n const sf = primarySource(doc);\n if (!sf) return null;\n\n const ms = new MagicString(sf.text);\n\n const kept = collectKept(doc);\n const keptSpans: SourceSpan[] = [];\n for (const n of kept) if (n.span && n.span.file === sf.id) keptSpans.push(n.span);\n\n // 1) Structural removals. A node present in the backref table but absent from the live node map\n // was removed by the passes. Classify each as an UNWRAP (a surviving node nests inside it) or\n // a FULL removal (nothing survived inside).\n const removed: RemovedRegion[] = [];\n for (const id of backrefIds(doc)) {\n if (doc.nodes.has(id)) continue; // still live\n const back = doc.backref.get(id);\n if (!back || back.span.file !== sf.id) continue;\n const unwrapped = keptSpans.some((k) => strictlyContains(back.span, k));\n removed.push({ backref: back, unwrapped });\n }\n\n // Skip any removed region nested inside a FULL-removal region (its bytes are already deleted by\n // the ancestor) — this keeps every delete disjoint, which magic-string requires.\n const fullRemovals = removed.filter((r) => !r.unwrapped).map((r) => r.backref.span);\n for (const r of removed) {\n const span = r.backref.span;\n const coveredByFull = fullRemovals.some((f) => f !== span && strictlyContains(f, span));\n if (coveredByFull) continue;\n\n if (r.unwrapped) {\n // KEY SAFETY: salvage a `key=…` off the wrapper onto its surviving child before deleting tags.\n transferKeyOnUnwrap(ms, doc, sf, r.backref, kept);\n // Delete only the wrapper's tags; keep its (surviving) inner content verbatim.\n const open = r.backref.openTagSpan;\n const close = r.backref.closeTagSpan;\n if (open && open.file === sf.id && open.end > open.start) ms.remove(open.start, open.end);\n if (close && close.file === sf.id && close.end > close.start) {\n ms.remove(close.start, close.end);\n }\n } else {\n ms.remove(span.start, span.end);\n }\n }\n\n // 2) Class-list diffs on every surviving element.\n for (const n of kept) {\n if (n.kind === 'element') editClasses(ms, doc, sf, n);\n }\n\n return ms.toString();\n}\n\n/** All ids the backref table knows about (every originally-parsed element / fragment). */\nfunction backrefIds(doc: IRDocument): IRNodeId[] {\n // The backref table is shared verbatim from parse time; collect ids by scanning original spans we\n // recorded for live + removed nodes. We don't have a public iterator, so reconstruct the universe\n // from the live nodes plus their (now-removed) original ancestry isn't possible directly — instead\n // ask the table for each id we can reach. The table exposes `get`; the set of candidate ids is the\n // contiguous allocation range [1, alloc.peek). Scanning that range is O(n) and dependency-free.\n const out: IRNodeId[] = [];\n const max = doc.alloc.peek as unknown as number;\n for (let i = 1; i < max; i += 1) {\n const id = i as IRNodeId;\n if (doc.backref.get(id)) out.push(id);\n }\n return out;\n}\n\n/* ───────────────────────── structural re-print (fallback) ───────────────────────── */\n\n/** Re-build the `className=…` attribute (or null when the element has no class list). */\nfunction classText(doc: IRDocument, classes: ClassList): string | null {\n if (classes.form === 'absent' || classes.segments.length === 0) return null;\n\n const dynamic = classes.segments.find((s) => s.kind === 'dynamic');\n if (dynamic && dynamic.kind === 'dynamic') {\n return `className={${exprText(doc, dynamic.expr).text}}`;\n }\n\n const tokens = staticTokensOf(classes);\n return `className=\"${tokens.join(' ')}\"`;\n}\n\nfunction attrText(doc: IRDocument, name: string, value: AttrValue): string {\n if (value.kind === 'static') {\n if (value.value === true) return name;\n if (value.value === false) return '';\n return `${name}=\"${String(value.value)}\"`;\n }\n return `${name}={${exprText(doc, value.expr).text}}`;\n}\n\nfunction printElement(doc: IRDocument, el: IRElement): string {\n const parts: string[] = [];\n\n const cls = classText(doc, el.classes);\n if (cls !== null) parts.push(cls);\n\n for (const name of el.attrs.order) {\n const v = el.attrs.entries.get(name);\n if (!v) continue;\n const text = attrText(doc, name, v);\n if (text.length > 0) parts.push(text);\n }\n\n for (const ref of el.attrs.spreads) parts.push(`{...${exprText(doc, ref).text}}`);\n\n const attrStr = parts.length > 0 ? ` ${parts.join(' ')}` : '';\n const tag = el.tag;\n\n if (el.children.length === 0) {\n return el.selfClosing ? `<${tag}${attrStr} />` : `<${tag}${attrStr}></${tag}>`;\n }\n\n const inner = el.children.map((c) => printNode(doc, c)).join('');\n return `<${tag}${attrStr}>${inner}</${tag}>`;\n}\n\nfunction printNode(doc: IRDocument, id: IRNodeId): string {\n const node = doc.nodes.get(id);\n if (!node) return '';\n switch (node.kind) {\n case 'text':\n return node.value;\n case 'comment':\n return `{/*${node.value}*/}`;\n case 'expr': {\n const { text, spread } = exprText(doc, node.expr);\n return spread ? `{...${text}}` : `{${text}}`;\n }\n case 'fragment':\n return `<>${node.children.map((c) => printNode(doc, c)).join('')}</>`;\n case 'element':\n return printElement(doc, node);\n }\n}\n\nfunction rePrint(doc: IRDocument): string {\n const root = doc.nodes.get(doc.root);\n if (!root || root.kind !== 'fragment') return printNode(doc, doc.root);\n return root.children.map((c) => printNode(doc, c)).join('');\n}\n\n/* ───────────────────────── public backend ───────────────────────── */\n\nfunction doPrint(doc: IRDocument): string {\n const surgical = surgicalPrint(doc);\n return surgical ?? rePrint(doc);\n}\n\nexport const jsxBackend: Backend = {\n name: 'babel-jsx',\n langs: JSX_LANGS,\n print(doc: IRDocument, _plan: EditPlan, _ctx: BackendContext): CodegenResult {\n const code = doPrint(doc);\n return { code, map: null, edits: [], diagnostics: [] };\n },\n};\n\n/** Factory mirror — returns a fresh handle to the (stateless) JSX backend. */\nexport function createJsxBackend(): Backend {\n return jsxBackend;\n}\n","/**\n * domflax — the single-file JSX/TSX pipeline runner (parse → resolve → flatten → reverse-emit →\n * print), split out of `index.ts` so the meta package's barrel + adapters stay focused.\n *\n * {@link runJsxPipeline} is SYNC and fully static (gate `'provably-safe'`): it never changes rendering\n * and never launches a browser.\n */\n\nimport {\n buildSelectorIndex,\n createSyntheticSink,\n runPasses,\n syncClassesFromComputed,\n} from '@domflax/core';\nimport type {\n ApplyContext,\n FileKind,\n FlattenGate,\n IRDocument,\n Pass,\n PassCategory,\n PassPhase,\n Pattern,\n SafetyLevel,\n StyleResolver,\n} from '@domflax/core';\nimport { createHtmlBackend, createHtmlFrontend } from '@domflax/frontend-html';\nimport { createJsxBackend, createJsxFrontend } from '@domflax/frontend-jsx';\nimport { normalizer } from '@domflax/pattern-kit';\n\nimport type { FileStatDelta } from './summary';\n\n/** Output of a pipeline run: the printed code plus the per-file optimization delta. */\nexport interface PipelineOutput {\n readonly code: string;\n readonly stats: FileStatDelta;\n}\n\n/** UTF-8 byte length (matches the CLI's `bytes()` — bytesSaved is measured in real bytes). */\nfunction bytes(s: string): number {\n return Buffer.byteLength(s, 'utf8');\n}\n\n/**\n * Rough class-token count (provider-independent, string-level) — identical to the CLI's\n * `countClassTokens`, so both surfaces report the same \"classes compressed\" figure.\n */\nfunction countClassTokens(code: string): number {\n let total = 0;\n const re = /\\b(?:className|class)\\s*=\\s*\"([^\"]*)\"/g;\n let m: RegExpExecArray | null;\n while ((m = re.exec(code)) !== null) {\n total += m[1]!.split(/\\s+/).filter((t) => t.length > 0).length;\n }\n return total;\n}\n\n/**\n * Compute the per-file stat delta the same way the CLI's `finish()` does: nodes from the IR\n * node-count delta, classes from the class-token delta, bytes from the UTF-8 byte-length delta.\n */\nfunction computeStats(code: string, out: string, nodesIn: number, nodesOut: number): FileStatDelta {\n const classesBefore = countClassTokens(code);\n const classesAfter = countClassTokens(out);\n return {\n nodesRemoved: Math.max(0, nodesIn - nodesOut),\n classesSaved: Math.max(0, classesBefore - classesAfter),\n bytesSaved: bytes(code) - bytes(out),\n };\n}\n\n/** `.tsx`/`.jsx` ⇒ the matching {@link FileKind}; anything else ⇒ null (no JSX frontend). */\nexport function jsxKindOf(id: string): FileKind | null {\n const clean = id.split('?', 1)[0] ?? id;\n if (clean.endsWith('.tsx')) return 'tsx';\n if (clean.endsWith('.jsx')) return 'jsx';\n return null;\n}\n\n/** `.html`/`.htm` ⇒ `'html'`; anything else ⇒ null (no HTML frontend). */\nexport function htmlKindOf(id: string): FileKind | null {\n const clean = (id.split('?', 1)[0] ?? id).toLowerCase();\n if (clean.endsWith('.html') || clean.endsWith('.htm')) return 'html';\n return null;\n}\n\n/** First registered source's EOL, defaulting to `\\n`. */\nfunction eolOf(doc: IRDocument): '\\n' | '\\r\\n' {\n for (const src of doc.sources.values()) return src.eol;\n return '\\n';\n}\n\n/** Group the flat pattern list into one {@link Pass} per {@link PassPhase} (derived from category). */\nfunction buildPasses(patterns: readonly Pattern[]): Pass[] {\n const byPhase = new Map<PassPhase, Pattern[]>();\n for (const p of patterns) {\n const phase = (p.category.split('/', 1)[0] ?? 'flatten') as PassPhase;\n let bucket = byPhase.get(phase);\n if (!bucket) {\n bucket = [];\n byPhase.set(phase, bucket);\n }\n bucket.push(p);\n }\n const passes: Pass[] = [];\n for (const [phase, pats] of byPhase) {\n passes.push({ phase, category: `${phase}/builtin` as PassCategory, patterns: pats });\n }\n return passes;\n}\n\n/** The parsed, authorized doc + the apply context + grouped passes, shared by sync + async runs. */\ninterface PreparedRun {\n readonly doc: IRDocument;\n readonly ctx: ApplyContext;\n readonly passes: readonly Pass[];\n}\n\n/** PARSE (JSX → IR, resolving classes onto `computed`) + AUTHORIZE + build the apply context. */\nfunction preparePipeline(\n code: string,\n id: string,\n kind: FileKind,\n resolver: StyleResolver,\n patterns: readonly Pattern[],\n safety: SafetyLevel,\n gate: FlattenGate,\n): PreparedRun {\n const parsed = createJsxFrontend().parse(code, {\n id,\n kind,\n resolver,\n normalizer,\n config: {},\n onDiagnostic: () => {},\n });\n const doc = parsed.doc;\n\n // AUTHORIZE — the JSX frontend defaults every node's safety floor to 0. The orchestrator opens the\n // floor to the max; the configured ceiling + each pattern's opacity predicates are the real gate.\n for (const node of doc.nodes.values()) node.meta.safetyFloor = 3;\n\n const ctx: ApplyContext = {\n doc,\n safetyCeiling: safety,\n normalizer,\n // Real CSS-selector-safety index from the active resolver: a wrapper a combinator/structural\n // selector depends on is flagged so the flatten guards refuse to flatten it. Tailwind (no\n // complexSelectors) degrades to the null index — behaviour unchanged.\n selectors: buildSelectorIndex(doc, resolver),\n resolver,\n gate,\n };\n return { doc, ctx, passes: buildPasses(patterns) };\n}\n\n/** REVERSE-EMIT optimized computed styles back into class tokens, then PRINT IR → JSX/TSX text. */\nfunction finishPipeline(optimized: IRDocument, id: string, resolver: StyleResolver): string {\n syncClassesFromComputed(optimized, resolver, normalizer);\n const printed = createJsxBackend().print(\n optimized,\n { moduleId: id, ops: [], provenance: new Map() },\n {\n normalizer,\n resolver,\n sink: createSyntheticSink(),\n eol: eolOf(optimized),\n onDiagnostic: () => {},\n },\n );\n return printed.code;\n}\n\n/** SYNC full pipeline (gate `'provably-safe'` — never changes rendering, never launches a browser). */\nexport function runJsxPipeline(\n code: string,\n id: string,\n kind: FileKind,\n resolver: StyleResolver,\n patterns: readonly Pattern[],\n safety: SafetyLevel,\n): PipelineOutput {\n const { doc, ctx, passes } = preparePipeline(code, id, kind, resolver, patterns, safety, 'provably-safe');\n const nodesIn = doc.nodes.size;\n const { doc: optimized } = runPasses(doc, passes, ctx);\n const out = finishPipeline(optimized, id, resolver);\n return { code: out, stats: computeStats(code, out, nodesIn, optimized.nodes.size) };\n}\n\n/* ───────────────────────── HTML pipeline (parse5 frontend/backend) ───────────────────────── */\n\n/**\n * PARSE (HTML → IR, resolving classes onto `computed`) + AUTHORIZE + build the apply context. Unlike\n * the JSX path, the HTML frontend sets per-node `safetyFloor` itself (opaque nodes → 0), so we must\n * NOT blanket-open every node to 3 (that would strip the opacity floors).\n */\nfunction prepareHtml(\n code: string,\n id: string,\n resolver: StyleResolver,\n patterns: readonly Pattern[],\n safety: SafetyLevel,\n gate: FlattenGate,\n): PreparedRun {\n const parsed = createHtmlFrontend().parse(code, {\n id,\n kind: 'html',\n resolver,\n normalizer,\n config: {},\n onDiagnostic: () => {},\n });\n const doc = parsed.doc;\n const ctx: ApplyContext = {\n doc,\n safetyCeiling: safety,\n normalizer,\n selectors: buildSelectorIndex(doc, resolver),\n resolver,\n gate,\n };\n return { doc, ctx, passes: buildPasses(patterns) };\n}\n\n/** REVERSE-EMIT optimized computed styles back into class tokens, then PRINT IR → HTML text. */\nfunction finishHtmlPipeline(optimized: IRDocument, id: string, resolver: StyleResolver): string {\n syncClassesFromComputed(optimized, resolver, normalizer);\n const printed = createHtmlBackend().print(\n optimized,\n { moduleId: id, ops: [], provenance: new Map() },\n {\n normalizer,\n resolver,\n sink: createSyntheticSink(),\n eol: eolOf(optimized),\n onDiagnostic: () => {},\n },\n );\n return printed.code;\n}\n\n/** SYNC full HTML pipeline (gate `'provably-safe'` — surgical span edits over verbatim source). */\nexport function runHtmlPipeline(\n code: string,\n id: string,\n resolver: StyleResolver,\n patterns: readonly Pattern[],\n safety: SafetyLevel,\n): PipelineOutput {\n const { doc, ctx, passes } = prepareHtml(code, id, resolver, patterns, safety, 'provably-safe');\n const nodesIn = doc.nodes.size;\n const { doc: optimized } = runPasses(doc, passes, ctx);\n const out = finishHtmlPipeline(optimized, id, resolver);\n return { code: out, stats: computeStats(code, out, nodesIn, optimized.nodes.size) };\n}\n","/**\n * domflax — build-end optimization SUMMARY.\n *\n * A tiny, dependency-free formatter shared by the Vite and webpack/Next adapters. Each adapter\n * accumulates {@link FileStatDelta} numbers across the build into a {@link Totals}, then prints ONE\n * boxed {@link renderSummary} block at build end — so the user sees the aggregate payoff without any\n * per-file spam in between.\n *\n * ```\n * ▲ domflax\n * ────────────────────────────────\n * files optimized 42\n * DOM nodes removed 318\n * classes compressed 1,204\n * size saved 18.7 KB\n * ────────────────────────────────\n * ```\n */\n\n/** Per-file optimization delta (from a single {@link Domflax.transform}). */\nexport interface FileStatDelta {\n /** DOM/IR nodes removed by provably-safe flattens. */\n readonly nodesRemoved: number;\n /** Class tokens eliminated by semantic compression. */\n readonly classesSaved: number;\n /** Bytes saved = original byte length − output byte length (may be negative in edge cases). */\n readonly bytesSaved: number;\n}\n\n/** All-zero delta, for unsupported / unchanged files. */\nexport function zeroStats(): FileStatDelta {\n return { nodesRemoved: 0, classesSaved: 0, bytesSaved: 0 };\n}\n\n/** Aggregate accumulator across a whole build. `files` counts only files that actually changed. */\nexport interface Totals {\n files: number;\n nodesRemoved: number;\n classesCompressed: number;\n bytesSaved: number;\n}\n\n/** A fresh, zeroed {@link Totals}. */\nexport function emptyTotals(): Totals {\n return { files: 0, nodesRemoved: 0, classesCompressed: 0, bytesSaved: 0 };\n}\n\n/** Reset a {@link Totals} in place (used to clear per rebuild in watch/serve mode). */\nexport function resetTotals(t: Totals): void {\n t.files = 0;\n t.nodesRemoved = 0;\n t.classesCompressed = 0;\n t.bytesSaved = 0;\n}\n\n/** Fold one file's delta into the running totals. Only `changed` files count toward `files`. */\nexport function addStats(t: Totals, s: FileStatDelta, changed: boolean): void {\n if (!changed) return;\n t.files += 1;\n t.nodesRemoved += s.nodesRemoved;\n t.classesCompressed += s.classesSaved;\n t.bytesSaved += s.bytesSaved;\n}\n\n/* ────────────────────────────────────────────────────────────────────────── *\n * Formatting\n * ────────────────────────────────────────────────────────────────────────── */\n\nconst BYTE_UNITS = ['KB', 'MB', 'GB', 'TB'] as const;\n\n/** Human byte size: `< 1 KiB` stays `B`, otherwise KB/MB/GB/TB with one decimal (1024-based). */\nexport function formatBytes(n: number): string {\n const abs = Math.abs(n);\n if (abs < 1024) return `${n} B`;\n let value = n / 1024;\n let unit = 0;\n while (Math.abs(value) >= 1024 && unit < BYTE_UNITS.length - 1) {\n value /= 1024;\n unit += 1;\n }\n return `${value.toFixed(1)} ${BYTE_UNITS[unit]}`;\n}\n\n/** Integer with thousands separators, e.g. `1204` → `1,204` (locale-independent). */\nexport function formatCount(n: number): string {\n return Math.trunc(n)\n .toString()\n .replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',');\n}\n\n/** Width of the label column (values align to this offset within the 3-space row indent). */\nconst LABEL_WIDTH = 20;\n/** The horizontal rule inside the box. */\nconst RULE = ` ${'─'.repeat(32)}`;\n\nfunction row(label: string, value: string): string {\n return ` ${label.padEnd(LABEL_WIDTH)}${value}`;\n}\n\n/**\n * Render the boxed build-end summary. Callers should only invoke this when `totals.files > 0`\n * (i.e. at least one file changed) so a no-op build stays silent.\n */\nexport function renderSummary(totals: Totals): string {\n return [\n '',\n ' ▲ domflax',\n RULE,\n row('files optimized', formatCount(totals.files)),\n row('DOM nodes removed', formatCount(totals.nodesRemoved)),\n row('classes compressed', formatCount(totals.classesCompressed)),\n row('size saved', formatBytes(totals.bytesSaved)),\n RULE,\n '',\n ].join('\\n');\n}\n\n/* ────────────────────────────────────────────────────────────────────────── *\n * webpack loader ↔ plugin bridge\n *\n * The webpack loader (`webpack-loader.cjs`) and the plugin (`index.cjs`) ship as SEPARATE bundles,\n * so a module-level accumulator would not be shared between them. Instead the loader stashes the\n * running {@link Totals} directly on the webpack `compilation` object under a GLOBAL-REGISTRY symbol\n * (`Symbol.for`, shared process-wide across both bundles); the plugin reads the same key from the\n * compilation in its `done` hook. A fresh compilation per (re)build gives per-build totals for free.\n * ────────────────────────────────────────────────────────────────────────── */\n\n/** Global-registry keys — identical string ⇒ identical symbol across the separately-bundled files. */\nconst TOTALS_KEY = Symbol.for('domflax.buildTotals');\nconst PRINTED_KEY = Symbol.for('domflax.summaryPrinted');\n\n/** Accumulate one file's delta onto a webpack `compilation` (called from the loader). Defensive. */\nexport function accumulateOnCompilation(compilation: unknown, stats: FileStatDelta, changed: boolean): void {\n if (compilation === null || typeof compilation !== 'object') return;\n const bag = compilation as Record<symbol, unknown>;\n let totals = bag[TOTALS_KEY] as Totals | undefined;\n if (!totals) {\n totals = emptyTotals();\n bag[TOTALS_KEY] = totals;\n }\n addStats(totals, stats, changed);\n}\n\n/**\n * Print the summary stashed on a `compilation` exactly once (called from the plugin's `done` hook).\n * Silent when nothing was stashed or nothing changed. The once-latch guards a double-tap.\n */\nexport function printCompilationSummary(compilation: unknown): void {\n if (compilation === null || typeof compilation !== 'object') return;\n const bag = compilation as Record<symbol, unknown>;\n if (bag[PRINTED_KEY]) return;\n bag[PRINTED_KEY] = true;\n const totals = bag[TOTALS_KEY] as Totals | undefined;\n if (totals && totals.files > 0) process.stdout.write(renderSummary(totals));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACKA,IAAM,mBAAmB,MACvB,OAAO,aAAa,cAChB,IAAI,IAAI,QAAQ,UAAU,EAAE,EAAE,OAC7B,SAAS,iBAAiB,SAAS,cAAc,QAAQ,YAAY,MAAM,WAC1E,SAAS,cAAc,MACvB,IAAI,IAAI,WAAW,SAAS,OAAO,EAAE;AAEtC,IAAM,gBAAgC,iCAAiB;;;ACgCvD,SAAS,kBAAkB,QAAQ,GAAgB;AACxD,MAAI,IAAI;AACR,SAAO;AAAA,IACL,OAAiB;AACf,YAAM,KAAK;AACX,WAAK;AACL,aAAO;AAAA,IACT;AAAA,IACA,IAAI,OAAiB;AACnB,aAAO;AAAA,IACT;AAAA,EACF;AACF;AAGO,SAAS,mBAAmB,QAAQ,GAAiB;AAC1D,QAAM,MAAM,oBAAI,IAAyB;AACzC,MAAI,IAAI;AACR,SAAO;AAAA,IACL,IAAI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asElement","asEl","metaFlag","declaresCustomProperties","targetedByStructuralPseudo","DISPLAY","isComponentNode","metaOf","hasSpreadAttrs","isComponentNode","hasOwnAttrs","targetedByStructuralPseudo","asEl","metaOf","establishesContext","hasSpreadAttrs","isComponentNode","hasOwnAttrs","targetedByStructuralPseudo","DISPLAY","path","import_node_fs","path","opaque","opaque","cover","LEGACY_PSEUDO_ELEMENTS","import_node_module","path","moduleBase","import_node_fs","path","LEGACY_PSEUDO_ELEMENTS","staticTokensOf","sameTokens","MagicString","import_node_module","document","opaque","computed","babelTraverse","FILE_ID","doParse","babelParse","FILE_ID","span","staticTokensOf","computed","path","doParse","import_magic_string","JSX_LANGS","staticTokensOf","primarySource","collectKept","strictlyContains","editClasses","surgicalPrint","MagicString","backrefIds","span","doPrint","eolOf"]}