@barocss/browser 0.8.1 → 0.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,9 @@
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("@barocss/kit");var t=class{insertSorted(t,n,r){let i=t.keys??=[],a=(0,e.upperBound)(i,r),o=t.styleElement.sheet;o&&o.cssRules.length===i.length?(o.insertRule(this.escapeCssRule(n),a),t.styles.splice(a,0,n)):(t.styles.splice(a,0,n),t.styleElement.textContent=t.styles.join(`
2
+ `)+`
3
+ `),i.splice(a,0,r)}constructor(t,n=50,r=`barocss-style-partition-`,i=t=>(0,e.parseClassName)(t).utility?.category){this.partitions=[],this.categoryPartitions=new Map,this.partitionCounter=0,this.maxRulesPerPartition=50,this.classToPartitionMap=new Map,this.classToCategoryPartitionMap=new Map,this.styleIdPrefix=`barocss-style-partition-`,this.insertionPoint=t,this.maxRulesPerPartition=n,this.styleIdPrefix=r,this.getCategory=i,this.initializeDefaultPartition()}initializeDefaultPartition(){this.createNewPartition()}createNewCategoryPartition(e,t=!1){let n={id:this.styleIdPrefix+`-${e}`,styles:[],styleElement:document.createElement(`style`)};n.styleElement.id=n.id,n.styleElement.setAttribute(`data-barocss`,`partition`),n.styleElement.setAttribute(`data-category`,e);let r=this.insertionPoint.ownerDocument?.head;return t&&r?r.insertBefore(n.styleElement,r.firstChild):this.insertionPoint.appendChild(n.styleElement),this.categoryPartitions.set(e,n),n}createNewPartition(){let e={id:this.styleIdPrefix+`-${this.partitionCounter++}`,styles:[],styleElement:document.createElement(`style`)};return this.partitions.push(e),e.styleElement.id=e.id,e.styleElement.setAttribute(`data-barocss`,`partition`),e.styleElement.setAttribute(`data-partition-index`,this.partitionCounter.toString()),this.insertionPoint.appendChild(e.styleElement),e}hasRule(e){return this.classToPartitionMap.has(e)}hasCategoryRule(e,t){return this.classToCategoryPartitionMap.get(e)===t}setRuleCache(e,t){this.classToPartitionMap.set(e,t)}setCategoryRuleCache(e,t){this.classToCategoryPartitionMap.set(e,t)}get currentPartition(){return this.partitions[this.partitions.length-1]}getCategoryPartition(e){return this.categoryPartitions.get(e)}hasDetachedPartitions(){return[...this.partitions,...this.categoryPartitions.values()].some(e=>!e.styleElement.isConnected)}escapeCssRule(e){return e.replace(/\\\//g,`\\/`)}addRule(t){if(this.hasRule(t))return!1;let n=(0,e.ruleSortKey)(t),r=this.partitions.findIndex(t=>{let r=t.keys;return!!r&&r.length>0&&(0,e.compareKeys)(r[r.length-1],n)>0});r===-1&&(this.currentPartition.styles.length>=this.maxRulesPerPartition&&this.createNewPartition(),r=this.partitions.length-1);let i=this.partitions[r];try{return this.insertSorted(i,t,n),this.setRuleCache(t,r),!0}catch(n){return(0,e.isDebug)()&&console.warn(`[StylePartitionManager] Failed to insert rule: ${t}`,n),!1}}addCategoryRule(t,n){if(this.hasCategoryRule(t,n))return!1;let r=this.getCategoryPartition(n);r||=this.createNewCategoryPartition(n);try{this.insertSorted(r,t,(0,e.ruleSortKey)(t))}catch(r){return(0,e.isDebug)()&&console.warn(`[StylePartitionManager] Failed to insert rule in category: ${n} ${t}`,r),!1}return this.setCategoryRuleCache(t,n),!0}addRootRules(t){let n=this.getCategoryPartition(`root`);n||=this.createNewCategoryPartition(`root`);try{let e=n.styleElement.sheet;for(let r of t)e?e.insertRule(this.escapeCssRule(r),e.cssRules.length):n.styleElement.textContent+=r+`
4
+ `}catch(n){return(0,e.isDebug)()&&console.warn(`[StylePartitionManager] Failed to insert rule in category: root ${t.join(`
5
+ `)}`,n),{success:0,failed:t.length}}return{success:t.length,failed:0}}addRules(e){let t=0,n=0;for(let r of e){let e=this.getCategory(r.cls);if(e)for(let t of r.cssList)this.addCategoryRule(t,e);else for(let e of r.cssList)this.addRule(e)?t++:n++}return{success:t,failed:n}}removeRule(e,t){let n;if(t){if(this.classToCategoryPartitionMap.get(e)!==t)return!1;n=this.categoryPartitions.get(t)}else{let t=this.classToPartitionMap.get(e);n=t===void 0?void 0:this.partitions[t]}if(!n)return!1;let r=n.styles.indexOf(e);if(r===-1)return!1;let i=n.styleElement.sheet,a=!!i&&i.cssRules.length===n.styles.length;return n.styles.splice(r,1),n.keys?.splice(r,1),a&&i?i.deleteRule(r):n.styleElement.textContent=n.styles.length?n.styles.join(`
6
+ `)+`
7
+ `:``,t?this.classToCategoryPartitionMap.delete(e):this.classToPartitionMap.delete(e),!0}get ruleCount(){return this.classToPartitionMap.size+this.classToCategoryPartitionMap.size}findRulePartition(e){let t=this.classToPartitionMap.get(e);if(t!==void 0&&this.partitions[t])return this.partitions[t];let n=this.classToCategoryPartitionMap.get(e);return n===void 0?null:this.categoryPartitions.get(n)||null}updateRuleContent(t,n,r=!1){let i=this.getCategoryPartition(t);if(i)i.styleElement.textContent=n;else{let i=this.createNewCategoryPartition(t,r);(0,e.isDebug)()&&console.log(`[StylePartitionManager] Created new partition for category: ${t}`),i.styleElement.textContent=n}}cleanup(){this.partitions.forEach(e=>{e.styleElement.parentNode&&e.styleElement.parentNode.removeChild(e.styleElement)}),this.categoryPartitions.forEach(e=>{e.styleElement.parentNode&&e.styleElement.parentNode.removeChild(e.styleElement)}),this.partitions=[],this.categoryPartitions.clear(),this.partitionCounter=0,this.classToPartitionMap.clear(),this.classToCategoryPartitionMap.clear()}};function n(e){return e?typeof e==`object`&&typeof e.baseVal==`string`?e.baseVal:e.toString():``}function r(e){return e?n(e).split(/\s+/).filter(Boolean):[]}var i=class{constructor(t,n,r=t=>(0,e.parseClassName)(t).utility?.category){this.observer=null,this.gc=null,this.incrementalParser=t,this.BrowserRuntime=n,this.getCategory=r}setGc(e){this.gc=e}setParser(e){this.incrementalParser=e}observe(e=document.body,t){return typeof window>`u`?new MutationObserver(()=>{}):(this.observer&&this.observer.disconnect(),this.gc?.setRoot(e),this.observer=new MutationObserver(t=>{let n=new Set,i=this.gc;if(t.forEach(t=>{if(i&&(t.type===`attributes`?i.reconcile(t.target):t.type===`childList`&&(t.removedNodes.forEach(e=>i.reconcileTree(e)),t.addedNodes.forEach(e=>i.reconcileTree(e)))),t.type===`attributes`&&t.attributeName===`class`&&e.contains(t.target)){let e=t.target;e.className&&r(e.className).forEach(e=>{this.incrementalParser.isProcessed(e)||n.add(e)})}t.type===`childList`&&t.addedNodes.forEach(t=>{if(t.nodeType===Node.ELEMENT_NODE&&e.contains(t)){let e=t;this.processElement(e,n),e.querySelectorAll(`[class]`).forEach(e=>{this.processElement(e,n)})}})}),n.size>0){let e=Array.from(n),t=this.incrementalParser.processClasses(e);this.BrowserRuntime?.applyParseResults(t)}else this.BrowserRuntime?.applyParseResults([]);i?.afterBatch()}),this.observer.observe(e,{attributes:!0,subtree:!0,attributeFilter:[`class`],childList:!0}),t?.scan&&this.scanExistingClasses(e,t),this.observer)}scanExistingClasses(e,t){let n=new Set;e.className&&r(e.className).forEach(e=>{this.incrementalParser.isProcessed(e)||n.add(e)});let i=e.querySelectorAll(`[class]`);for(let e of i)if(e.className){let t=r(e.className);for(let e of t)this.incrementalParser.isProcessed(e)||n.add(e)}if(n.size>0){let e=Array.from(n),r=this.incrementalParser.processClasses(e),i=r.filter(e=>this.getCategory(e.cls)===`layout`),a=r.filter(e=>this.getCategory(e.cls)!==`layout`);this.BrowserRuntime?.applyParseResults(i),t?.onReady?.(),this.BrowserRuntime?.applyParseResults(a)}else t?.onReady?.()}processElement(e,t){e.className&&r(e.className).forEach(e=>{this.incrementalParser.isProcessed(e)||t.add(e)})}disconnect(){this.observer&&=(this.observer.disconnect(),null)}};function a(e){return e.replace(/\\([0-9a-fA-F]{1,6})\s?|\\(.)/g,(e,t,n)=>t?String.fromCodePoint(parseInt(t,16)):n)}var o=/^\s*(?::(?:where|is)\(\s*)?\.((?:\\[0-9a-fA-F]{1,6}\s?|\\.|[\w-]|[^\x00-\x7F])+)/;function s(e){let t=[],n=0,r=0;for(let i=0;i<e.length;i++){let a=e[i];a===`\\`?i++:a===`(`||a===`[`?n++:a===`)`||a===`]`?n--:a===`,`&&n===0&&(t.push(e.slice(r,i)),r=i+1)}return t.push(e.slice(r)),t}function c(e,t=new Set){for(let n of Array.from(e)){if(n.type===7&&typeof n.name==`string`){t.add(n.name);continue}let e=n.cssRules;e&&e.length&&c(e,t)}return t}function l(e,t=new Set){for(let n of Array.from(e)){let e=n.selectorText;if(typeof e==`string`)for(let n of s(e)){let e=o.exec(n);e&&t.add(a(e[1]))}let r=n.cssRules;r&&r.length&&l(r,t)}return t}var u=class{constructor(e,t,n,r=()=>Date.now()){this.host=e,this.graceMs=t,this.maxRules=n,this.now=r,this.counts=new Map,this.counted=new WeakMap,this.candidates=new Map,this.timer=null,this.root=null}setRoot(e){this.counts.clear(),this.counted=new WeakMap,this.candidates.clear(),this.cancel(),this.root=e,this.reconcileTree(e)}count(e){return this.counts.get(e)??0}reconcileTree(e){if(e.nodeType!==1)return;let t=e;this.reconcile(t),t.querySelectorAll(`[class]`).forEach(e=>this.reconcile(e))}reconcile(e){let t=this.root,n=t&&t.contains(e)?Array.from(new Set(r(e.getAttribute(`class`)))):[],i=this.counted.get(e);if(!i&&n.length===0)return;let a=new Set(i??[]),o=new Set(n);for(let e of o){if(a.has(e))continue;let t=(this.counts.get(e)??0)+1;this.counts.set(e,t),this.candidates.delete(e)}for(let e of a){if(o.has(e))continue;let t=(this.counts.get(e)??0)-1;t>0?this.counts.set(e,t):(this.counts.delete(e),this.candidates.delete(e),this.candidates.set(e,this.now()))}n.length?this.counted.set(e,n):this.counted.delete(e)}afterBatch(){this.candidates.size!==0&&(this.host.cachedCount()>this.maxRules?this.schedule(0):this.schedule(this.graceMs))}schedule(e){if(this.timer!==null){if(e>0)return;clearTimeout(this.timer)}this.timer=setTimeout(()=>{this.timer=null,this.sweep()},e)}sweep(){let e=this.now(),t=Math.max(0,this.host.cachedCount()-this.maxRules),n=[],r=0;for(let[i,a]of this.candidates){let o=e-a>=this.graceMs;!o&&r>=t||(this.candidates.delete(i),!(this.count(i)>0||this.inDom(i)||this.host.isPermanent(i))&&(n.push(i),o||r++))}n.length&&this.host.reclaim(n),this.candidates.size&&this.schedule(this.graceMs)}inDom(e){let t=this.root;if(!t)return!1;let n=t.ownerDocument??document;return t.classList.contains(e)||n.documentElement.classList.contains(e)||n.getElementsByClassName(e).length>0}cancel(){this.timer!==null&&clearTimeout(this.timer),this.timer=null}stats(){return{trackedClasses:this.counts.size,candidates:this.candidates.size}}},d=`style[data-barocss-ssr]`,f=`@layer theme, base, components, utilities;`,p=class{constructor(n={}){this.cache=new Map,this.rootCache=new Set,this.isDestroyed=!1,this.existing=null,this.existingKeyframes=new Set,this.existingSheetCount=-1,this.pinned=new Set,this.gc=null,this.reclaimedCount=0,this.ssrRules=[],this.ssrClasses=new Set,this.observedOnce=!1,this.getCategory=t=>(0,e.parseClassName)(t,this.context).utility?.category;let r={};this.options={config:n.config||r,styleId:n.styleId||`barocss-runtime`,insertionPoint:n.insertionPoint||`head`,maxRulesPerPartition:n.maxRulesPerPartition||50,skipExisting:n.skipExisting??!1,gc:n.gc??!0,gcGraceMs:n.gcGraceMs??3e3,maxRules:n.maxRules??1/0},this.context=(0,e.createContext)(this.options.config),this.incrementalParser=new e.IncrementalParser(this.context),this.changeDetector=new i(this.incrementalParser,this,this.getCategory),this.stylePartitionManager=new t(this.getInsertionPoint(),this.options.maxRulesPerPartition,`${this.options.styleId}-partition`,this.getCategory),this.options.gc&&(this.gc=new u({reclaim:e=>this.reclaim(e),isPermanent:e=>this.isPermanent(e),cachedCount:()=>this.cache.size},this.options.gcGraceMs,this.options.maxRules),this.changeDetector.setGc(this.gc)),this.init()}debugLog(t,n,r){(0,e.isDebug)()&&(console[t]||console.log)(`[BrowserRuntime:${t.toUpperCase()}] ${n}`,r||``)}init(){this.debugLog(`debug`,`init`),this.injectPreflightCSS(),this.ensureCssVars(),this.adoptSsrSheets()}adoptSsrSheets(){if(typeof document>`u`)return;let e=[];if(document.head){for(let t of Array.from(document.head.querySelectorAll(`${d}:not([data-barocss-adopted])`))){let n=t.sheet;if(!n)continue;t.setAttribute(`data-barocss-adopted`,``);let r=[];for(let e=n.cssRules.length-1;e>=0;e--){let t=n.cssRules[e],i=l([t]);i.size!==0&&(i.forEach(e=>this.ssrClasses.add(e)),r.unshift({css:t.cssText,cls:i.values().next().value}),n.deleteRule(e))}e.push(...r)}e.length!==0&&(this.ssrRules.push(...e),this.insertSsrRules(e))}}insertSsrRules(e){for(let{css:t,cls:n}of e){let e=this.getCategory(n);e?this.stylePartitionManager.addCategoryRule(t,e):this.stylePartitionManager.addRule(t)}}injectPreflightCSS(){let e=this.options.config.preflight??!0;if(e){let t=this.context.getPreflightCSS(e);this.stylePartitionManager.updateRuleContent(`preflight`,`${f}\n@layer base {\n${t}\n}`,!0)}}ensureCssVars(){if(this.isDestroyed)return;let e=this.context.themeToCssVars?this.context.themeToCssVars():`:root { /* CSS Variables will be generated here */ }`;this.stylePartitionManager.updateRuleContent(`css-vars`,e)}getInsertionPoint(){if(typeof this.options.insertionPoint!=`string`)return this.options.insertionPoint;switch(this.options.insertionPoint){case`body`:return document.body||document.head;default:return document.head}}addClass(e){if(this.isDestroyed)return;let t=this.normalizeClasses(e).filter(Boolean);t.forEach(e=>this.pinned.add(e)),this.processClasses(t)}processClasses(e){this.processClassesIncremental(e)}processClassesIncremental(e){let t=typeof window<`u`,n=this.incrementalParser.processClasses(e);this.debugLog(`debug`,`results`,{results:n,classList:e}),this.applyParseResults(n,{isBrowser:t})}applyParseResults(e,t){if(this.isDestroyed)return;if(this.getInsertionPoint().isConnected&&this.stylePartitionManager.hasDetachedPartitions()){let t=Array.from(this.cache.values());this.reset(),e=[...t,...e],e.forEach(e=>this.incrementalParser.markProcessed(e.cls))}if(this.ssrClasses.size>0&&(e=e.filter(e=>!this.ssrClasses.has(e.cls))),this.options.skipExisting&&e.length>0&&typeof document<`u`){let t=this.getExistingClasses();e=e.filter(e=>!t.has(e.cls))}if(e.length===0)return;let n=[],r=[],i=this.options.skipExisting&&typeof document<`u`?(this.getExistingClasses(),this.existingKeyframes):null;for(let t of e)if(t.css&&Array.isArray(t.cssList)&&(n.push(t),this.cache.set(t.cls,t)),t.rootCss&&Array.isArray(t.rootCssList))for(let e of t.rootCssList){if(i?.size){let t=/^\s*@keyframes\s+([^\s{]+)/.exec(e)?.[1];if(t&&i.has(t))continue}this.rootCache.has(e)||(this.rootCache.add(e),r.push(e))}r.length>0&&this.stylePartitionManager.addRootRules(r.filter(Boolean)),n.length>0&&this.stylePartitionManager.addRules(n),this.debugLog(`info`,`Applied ${e.length} parser results`,{cssRuleCount:n.length,rootCssCount:r.length})}isPermanent(e){return this.pinned.has(e)||this.ssrClasses.has(e)||typeof document>`u`?!0:this.getExistingClasses().has(e)}reclaim(e){if(this.isDestroyed)return;let t=e.filter(e=>this.cache.has(e));if(t.length===0)return;let n=t.map(e=>this.cache.get(e));t.forEach(e=>{this.cache.delete(e),this.incrementalParser.unmarkProcessed(e)});let r=new Set;for(let e of this.cache.values())e.cssList.forEach(e=>r.add(e));for(let e of n){let t=this.getCategory(e.cls);for(let n of e.cssList)r.has(n)||this.stylePartitionManager.removeRule(n,t)}this.reclaimedCount+=t.length}getExistingClasses(){let e=new Set(Array.from(document.querySelectorAll(`style[data-barocss]`),e=>e.sheet)),t=Array.from(document.styleSheets).filter(t=>{if(e.has(t))return!1;let n=t.ownerNode;return!(n&&typeof n.hasAttribute==`function`&&(n.hasAttribute(`data-barocss`)||(n.id||``).startsWith(this.options.styleId)))});if(this.existing&&t.length===this.existingSheetCount)return this.existing;let n=new Set,r=new Set;for(let e of t){let t;try{t=e.cssRules}catch{continue}l(t,n),c(t,r)}return this.existingKeyframes=r,this.existing=n,this.existingSheetCount=t.length,n}observe(e=document.body,t){return this.observedOnce||(this.observedOnce=!0,this.adoptSsrSheets()),this.changeDetector.observe(e,t)}normalizeClasses(e){return Array.isArray(e)?e.flatMap(e=>e.split(/\s+/)):e.split(/\s+/)}has(e){return this.cache.has(e)}getCss(e){return this.cache.get(e)?.cssList.join(`
8
+ `)}getAllCss(){return[...this.rootCache,...Array.from(this.cache.values()).flatMap(e=>e.cssList)].join(`
9
+ `)}getClasses(){return Array.from(this.cache.keys())}getCacheStats(){let e=this.incrementalParser.getStats();return{runtime:{cachedClasses:this.cache.size,rootCacheSize:this.rootCache.size,ruleCount:this.stylePartitionManager.ruleCount,reclaimedClasses:this.reclaimedCount,gc:this.gc?.stats()??null},ast:e.cacheStats.ast,incremental:e}}clearCaches(){this.isDestroyed||(this.cache.clear(),this.rootCache.clear(),(0,e.clearAstCache)(this.context),this.incrementalParser.clearProcessed(),this.stylePartitionManager.cleanup(),this.stylePartitionManager=new t(this.getInsertionPoint(),this.options.maxRulesPerPartition,`${this.options.styleId}-partition`,this.getCategory),this.injectPreflightCSS(),this.ensureCssVars(),this.insertSsrRules(this.ssrRules))}reset(){this.isDestroyed||(this.cache.clear(),this.rootCache.clear(),this.incrementalParser.clearProcessed(),this.stylePartitionManager.cleanup(),this.stylePartitionManager=new t(this.getInsertionPoint(),this.options.maxRulesPerPartition,`${this.options.styleId}-partition`,this.getCategory),this.injectPreflightCSS(),this.ensureCssVars(),this.insertSsrRules(this.ssrRules))}updateConfig(t){if(this.isDestroyed)return;let n=Array.from(this.cache.keys());this.options.config=t,this.context=(0,e.createContext)(t),this.incrementalParser=new e.IncrementalParser(this.context),this.changeDetector.setParser(this.incrementalParser),this.reset(),n.length>0&&this.addClass(n)}removeClass(e){if(this.isDestroyed)return;let t=new Set(this.normalizeClasses(e)),n=Array.from(this.cache.values()).filter(e=>!t.has(e.cls));n.length!==this.cache.size&&(this.reset(),n.forEach(e=>this.incrementalParser.markProcessed(e.cls)),this.applyParseResults(n))}destroy(){this.isDestroyed||=(this.changeDetector.disconnect(),this.gc?.cancel(),this.stylePartitionManager.cleanup(),this.cache.clear(),this.rootCache.clear(),!0)}getStats(){return{cachedClasses:this.cache.size,styleElementId:this.options.styleId,isDestroyed:this.isDestroyed,config:this.options.config,cacheStats:this.getCacheStats()}}},m=null,h;function g(e={}){return!m||m.getStats().isDestroyed?(m=new p(e),h=e.config):e.config&&e.config!==h&&(m.updateConfig(e.config),h=e.config),m}function _({loadingClassName:e=`baro-boot`,...t}={}){if(!document.body){document.addEventListener(`DOMContentLoaded`,()=>_({loadingClassName:e,...t}),{once:!0});return}let n=`${e}-doing`,r=`${e}-done`;try{document.body.classList.add(n),g(t).observe(document.body,{scan:!0,onReady:()=>{document.body.classList.remove(n),document.body.classList.add(r)}})}catch(e){document.body?.classList.remove(n),console.error(`BaroCSS boot failed:`,e)}}var v=_;function y(e){if(!e||typeof e!=`object`||Array.isArray(e))return[];let t=e.elements;if(!t||typeof t!=`object`||Array.isArray(t))return[];let n=new Set;for(let e of Object.keys(t)){let r=t[e];if(!r||typeof r!=`object`||Array.isArray(r))continue;let i=r.props;if(!i||typeof i!=`object`||Array.isArray(i))continue;let a=i.className;if(typeof a==`string`)for(let e of a.split(/\s+/))e&&n.add(e)}return Array.from(n)}function b(e,t){let n=y(e);n.length>0&&t.addClass(n)}var x={colors:Object.fromEntries(`background.foreground.card.card-foreground.popover.popover-foreground.primary.primary-foreground.secondary.secondary-foreground.muted.muted-foreground.accent.accent-foreground.destructive.border.input.ring.chart-1.chart-2.chart-3.chart-4.chart-5.sidebar.sidebar-foreground.sidebar-primary.sidebar-primary-foreground.sidebar-accent.sidebar-accent-foreground.sidebar-border.sidebar-ring`.split(`.`).map(e=>[e,`var(--${e})`])),borderRadius:{sm:`calc(var(--radius) - 4px)`,md:`calc(var(--radius) - 2px)`,lg:`var(--radius)`,xl:`calc(var(--radius) + 4px)`}};exports.BrowserRuntime=p,exports.ChangeDetector=i,exports.LAYER_ORDER=f,exports.SSR_STYLE_SELECTOR=d,exports.StylePartitionManager=t,exports.baroBoot=_,exports.baroStart=v,exports.collectJsonRenderClassNames=y,exports.getRuntime=g,exports.normalizeClassName=n,exports.normalizeClassNameList=r,exports.preloadJsonRenderClasses=b,exports.shadcnTheme=x;
@@ -0,0 +1,435 @@
1
+ import { Config } from '@barocss/kit';
2
+ import { GenerateCssRulesResult } from '@barocss/kit';
3
+ import { IncrementalParser } from '@barocss/kit';
4
+ import { RuleKey } from '@barocss/kit';
5
+
6
+ export declare function baroBoot({ loadingClassName, ...options }?: BaroBootOptions): void;
7
+
8
+ declare type BaroBootOptions = BrowserRuntimeOptions & {
9
+ loadingClassName?: string;
10
+ };
11
+
12
+ export declare const baroStart: typeof baroBoot;
13
+
14
+ export declare class BrowserRuntime {
15
+ private cache;
16
+ private rootCache;
17
+ private context;
18
+ private options;
19
+ private isDestroyed;
20
+ private existing;
21
+ /** #274: @keyframes names the page's own sheets define (filled with `existing`). */
22
+ private existingKeyframes;
23
+ private existingSheetCount;
24
+ /** #269: classes requested explicitly through addClass(); never reclaimed. */
25
+ private pinned;
26
+ private gc;
27
+ private reclaimedCount;
28
+ /** #268: class rules adopted from `<style data-barocss-ssr>`, in sheet order, and the classes they lead. */
29
+ private ssrRules;
30
+ private ssrClasses;
31
+ private observedOnce;
32
+ private incrementalParser;
33
+ private changeDetector;
34
+ private stylePartitionManager;
35
+ private getCategory;
36
+ constructor(options?: BrowserRuntimeOptions);
37
+ /**
38
+ * Add debug logs (by level)
39
+ */
40
+ private debugLog;
41
+ private init;
42
+ /**
43
+ * #268: adopt the class rules of server-rendered `<style data-barocss-ssr>` sheets in <head>, at startup
44
+ * (constructor and the first observe()). Each rule moves
45
+ * (same task, so no paint in between) into the partition its class would get if generated here, at
46
+ * its #254 sorted position, so a later client `sm:` rule lands before a server `lg:` rule. Its classes
47
+ * are never regenerated and never reclaimed. `:root`, `@property` and `@keyframes` stay in the sheet.
48
+ */
49
+ private adoptSsrSheets;
50
+ private insertSsrRules;
51
+ private injectPreflightCSS;
52
+ private ensureCssVars;
53
+ private getInsertionPoint;
54
+ /**
55
+ * Dynamically add one or more class names and generate/insert CSS
56
+ */
57
+ addClass(classes: string | string[]): void;
58
+ /**
59
+ * Process classes
60
+ */
61
+ private processClasses;
62
+ /**
63
+ * Process classes using incremental parsing
64
+ */
65
+ private processClassesIncremental;
66
+ /**
67
+ * Public method to apply parser results, update internal caches, and inject CSS
68
+ */
69
+ applyParseResults(results: Array<GenerateCssRulesResult>, _opts?: {
70
+ isBrowser?: boolean;
71
+ }): void;
72
+ /** #269: a class that must never be reclaimed. */
73
+ private isPermanent;
74
+ /**
75
+ * #269: delete the generated rules of classes no live element uses. Root/@property/@keyframes rules stay
76
+ * (they are shared and harmless); a rule text another cached class still emits is kept.
77
+ */
78
+ private reclaim;
79
+ /** Class names defined by the page's own stylesheets (BaroCSS's sheets and cross-origin sheets excluded). */
80
+ getExistingClasses(): Set<string>;
81
+ /**
82
+ * MutationObserver instance method to automatically call addClass when class attributes change in DOM
83
+ */
84
+ observe(root?: HTMLElement, options?: {
85
+ scan?: boolean;
86
+ onReady?: () => void;
87
+ }): MutationObserver;
88
+ private normalizeClasses;
89
+ has(cls: string): boolean;
90
+ getCss(cls: string): string | undefined;
91
+ getAllCss(): string;
92
+ getClasses(): string[];
93
+ /**
94
+ * Get comprehensive cache statistics
95
+ */
96
+ getCacheStats(): {
97
+ runtime: {
98
+ cachedClasses: number;
99
+ rootCacheSize: number;
100
+ ruleCount: number;
101
+ reclaimedClasses: number;
102
+ gc: {
103
+ trackedClasses: number;
104
+ candidates: number;
105
+ } | null;
106
+ };
107
+ ast: {
108
+ size: number;
109
+ maxSize: number;
110
+ hitRate: number;
111
+ };
112
+ incremental: {
113
+ processedClasses: number;
114
+ pendingClasses: number;
115
+ cacheStats: {
116
+ ast: {
117
+ size: number;
118
+ maxSize: number;
119
+ hitRate: number;
120
+ };
121
+ css: {};
122
+ };
123
+ };
124
+ };
125
+ /**
126
+ * Clear all caches (useful for debugging or memory management)
127
+ */
128
+ clearCaches(): void;
129
+ reset(): void;
130
+ updateConfig(newConfig: Config): void;
131
+ removeClass(classes: string | string[]): void;
132
+ destroy(): void;
133
+ getStats(): {
134
+ cachedClasses: number;
135
+ styleElementId: string;
136
+ isDestroyed: boolean;
137
+ config: Config;
138
+ cacheStats: {
139
+ runtime: {
140
+ cachedClasses: number;
141
+ rootCacheSize: number;
142
+ ruleCount: number;
143
+ reclaimedClasses: number;
144
+ gc: {
145
+ trackedClasses: number;
146
+ candidates: number;
147
+ } | null;
148
+ };
149
+ ast: {
150
+ size: number;
151
+ maxSize: number;
152
+ hitRate: number;
153
+ };
154
+ incremental: {
155
+ processedClasses: number;
156
+ pendingClasses: number;
157
+ cacheStats: {
158
+ ast: {
159
+ size: number;
160
+ maxSize: number;
161
+ hitRate: number;
162
+ };
163
+ css: {};
164
+ };
165
+ };
166
+ };
167
+ };
168
+ }
169
+
170
+ export declare interface BrowserRuntimeOptions {
171
+ config?: Config;
172
+ styleId?: string;
173
+ insertionPoint?: 'head' | 'body' | HTMLElement;
174
+ maxRulesPerPartition?: number;
175
+ /**
176
+ * #210: skip classes the page's existing (non-BaroCSS, same-origin) stylesheets already define,
177
+ * so a built app plus the runtime injects only what the build is missing. Opt-in. A class counts
178
+ * as covered only when a rule's selector starts with it (e.g. `.p-4`, `.md\:p-4` inside @media,
179
+ * `.hover\:x:hover`), so a class seen only as a descendant (`.group:hover .x`) is not skipped.
180
+ * The index is rebuilt when `document.styleSheets.length` changes. A page class that leads a selector
181
+ * with the same name is treated as covered, and rules added later to an already-indexed sheet aren't seen.
182
+ */
183
+ skipExisting?: boolean;
184
+ /**
185
+ * #269: reclaim the rules of classes that no element inside the observed root carries any more.
186
+ * On by default; it only acts on classes seen through `observe()`. A class is deleted only after
187
+ * its refcount has stayed 0 for `gcGraceMs` and a live-DOM re-check finds no element with it.
188
+ * Never reclaimed: classes passed to `addClass()`, classes any pre-existing (non-BaroCSS) sheet
189
+ * defines (build output, server sheet), root/@property/preflight rules. `false` disables it.
190
+ */
191
+ gc?: boolean;
192
+ /** #269: how long a class must stay unused before its rules are deleted (default 3000 ms). */
193
+ gcGraceMs?: number;
194
+ /**
195
+ * #269: soft cap on cached classes. When exceeded, unused (refcount 0) classes are evicted
196
+ * oldest-first without waiting for the grace period; classes in use are never evicted. Default: no cap.
197
+ */
198
+ maxRules?: number;
199
+ }
200
+
201
+ /**
202
+ * Change detection system for DOM mutations
203
+ *
204
+ * ⚠️ BROWSER-ONLY: This class is designed for browser environments only.
205
+ * It uses MutationObserver and DOM APIs that are not available in Node.js.
206
+ *
207
+ * This class monitors DOM changes and automatically processes new CSS classes
208
+ * that are added to elements. It uses MutationObserver to detect:
209
+ * - Class attribute changes on existing elements
210
+ * - New elements being added to the DOM
211
+ * - Changes in child elements
212
+ *
213
+ * For server-side usage, use IncrementalParser directly with processClassesSync()
214
+ * or processClasses() methods.
215
+ */
216
+ export declare class ChangeDetector {
217
+ /** MutationObserver instance for DOM change detection */
218
+ private observer;
219
+ /** Reference to IncrementalParser for class processing */
220
+ private incrementalParser;
221
+ /** Reference to BrowserRuntime for CSS injection (optional) */
222
+ private BrowserRuntime?;
223
+ private getCategory;
224
+ /**
225
+ * Create a new ChangeDetector instance
226
+ *
227
+ * @param incrementalParser - IncrementalParser instance for class processing
228
+ * @param BrowserRuntime - Optional BrowserRuntime instance for CSS injection
229
+ */
230
+ constructor(incrementalParser: IncrementalParser, BrowserRuntime?: BrowserRuntime, getCategory?: (cls: string) => string | undefined);
231
+ /** #269: refcount/GC tracker, when the runtime has GC enabled. */
232
+ private gc;
233
+ setGc(gc: ClassGc | null): void;
234
+ setParser(parser: IncrementalParser): void;
235
+ /**
236
+ * Starts observing DOM changes for new CSS classes
237
+ *
238
+ * This method sets up a MutationObserver that monitors:
239
+ * - Attribute changes (specifically class attribute modifications)
240
+ * - Child list changes (new elements being added)
241
+ * - Subtree changes (changes in descendant elements)
242
+ *
243
+ * The observer automatically processes any new classes it discovers
244
+ * by adding them to the IncrementalParser's pending queue.
245
+ *
246
+ * @param root - The root element to observe (defaults to document.body)
247
+ * @param options - Configuration options including initial scan and onReady callback
248
+ * @returns The MutationObserver instance for external control
249
+ */
250
+ observe(root?: HTMLElement, options?: {
251
+ scan?: boolean;
252
+ onReady?: () => void;
253
+ }): MutationObserver;
254
+ /**
255
+ * Scan existing classes in the DOM and process them
256
+ */
257
+ private scanExistingClasses;
258
+ /**
259
+ * Processes an individual element and extracts new classes
260
+ *
261
+ * This method is called for each element discovered during DOM mutations.
262
+ * It:
263
+ * - Extracts all class names from the element's className
264
+ * - Filters out already processed classes
265
+ * - Adds new classes to the collection for batch processing
266
+ *
267
+ * @param element - The HTML element to process
268
+ * @param newClasses - Set to collect newly discovered class names
269
+ */
270
+ private processElement;
271
+ /**
272
+ * Stops observing DOM changes and cleans up resources
273
+ *
274
+ * This method disconnects the MutationObserver and clears the
275
+ * observer reference to prevent memory leaks and allow the
276
+ * ChangeDetector to be properly garbage collected.
277
+ */
278
+ disconnect(): void;
279
+ }
280
+
281
+ declare class ClassGc {
282
+ private host;
283
+ private graceMs;
284
+ private maxRules;
285
+ private now;
286
+ private counts;
287
+ private counted;
288
+ /** class -> time its count reached 0 (insertion order = oldest first). */
289
+ private candidates;
290
+ private timer;
291
+ private root;
292
+ constructor(host: ClassGcHost, graceMs: number, maxRules: number, now?: () => number);
293
+ /** Start counting for a new root: count every element currently inside it. */
294
+ setRoot(root: Element): void;
295
+ count(cls: string): number;
296
+ /** Re-count `el` and (optionally) all its descendants from their current state. */
297
+ reconcileTree(node: Node): void;
298
+ reconcile(el: Element): void;
299
+ /** Call after a mutation batch has been counted and its classes inserted. */
300
+ afterBatch(): void;
301
+ private schedule;
302
+ /** Reclaim candidates whose grace period elapsed (plus LRU overflow). Public for tests. */
303
+ sweep(): void;
304
+ private inDom;
305
+ cancel(): void;
306
+ stats(): {
307
+ trackedClasses: number;
308
+ candidates: number;
309
+ };
310
+ }
311
+
312
+ /**
313
+ * #269: per-class refcount over the observed root, plus a delayed sweep that
314
+ * reclaims classes no live element carries any more.
315
+ *
316
+ * Counting is reconciliation, not delta arithmetic: for every element a
317
+ * mutation batch touches (attribute target, added subtree, removed subtree) we
318
+ * compare the classes we last counted for it with what it carries *now*
319
+ * (nothing if it is no longer inside the root). That makes the count
320
+ * independent of record order, so remove-then-re-add in one batch, moves
321
+ * between parents and edits made while detached all settle to the true state.
322
+ * An element we miss can only leak a count (rule kept), never drop one.
323
+ *
324
+ * Before a class is reclaimed the sweep re-checks the live DOM
325
+ * (`getElementsByClassName`), so even a miscount cannot unstyle a live element.
326
+ */
327
+ declare interface ClassGcHost {
328
+ /** Delete the rules of these classes. */
329
+ reclaim(classes: string[]): void;
330
+ /** Whether a class must never be reclaimed (pinned, found in a pre-existing sheet, ...). */
331
+ isPermanent(cls: string): boolean;
332
+ /** Number of generated rules/classes currently cached (for the LRU cap). */
333
+ cachedCount(): number;
334
+ }
335
+
336
+ /** Collect literal className tokens from a json-render Spec's flat elements map. */
337
+ export declare function collectJsonRenderClassNames(spec: unknown): string[];
338
+
339
+ /**
340
+ * Returns the shared runtime, creating it on first use. If a live runtime
341
+ * already exists and `options.config` is a different config object, it is
342
+ * applied via `updateConfig` (which replaces the whole config), so an early
343
+ * `getRuntime()` never makes a later `baroStart({ config })` lose its config.
344
+ */
345
+ export declare function getRuntime(options?: BrowserRuntimeOptions): BrowserRuntime;
346
+
347
+ /** Tailwind 4 layer order, declared by BaroCSS's first <style> in <head>. */
348
+ export declare const LAYER_ORDER = "@layer theme, base, components, utilities;";
349
+
350
+ export declare function normalizeClassName(className: any): string;
351
+
352
+ export declare function normalizeClassNameList(className: any): string[];
353
+
354
+ /** Submit literal classes synchronously before UI mount; the caller validates class support. */
355
+ export declare function preloadJsonRenderClasses(spec: unknown, runtime: Pick<BrowserRuntime, 'addClass'>): void;
356
+
357
+ export declare const shadcnTheme: {
358
+ colors: Record<string, string>;
359
+ borderRadius: Record<string, string>;
360
+ };
361
+
362
+ /** #268: marks a server-rendered sheet (`@barocss/server` `ssrStyleTag()`); the runtime adopts its class rules. */
363
+ export declare const SSR_STYLE_SELECTOR = "style[data-barocss-ssr]";
364
+
365
+ export declare interface StylePartition {
366
+ id: string;
367
+ styles: string[];
368
+ styleElement: HTMLStyleElement;
369
+ /** Sort keys parallel to `styles` / the sheet's cssRules (#254). */
370
+ keys?: RuleKey[];
371
+ }
372
+
373
+ export declare class StylePartitionManager {
374
+ /**
375
+ * Insert `rule` at its Tailwind variant position within `partition` (#254):
376
+ * one insertRule at a binary-searched index, no sheet rewrite.
377
+ */
378
+ private insertSorted;
379
+ private partitions;
380
+ private categoryPartitions;
381
+ private partitionCounter;
382
+ private maxRulesPerPartition;
383
+ private insertionPoint;
384
+ private classToPartitionMap;
385
+ private classToCategoryPartitionMap;
386
+ private styleIdPrefix;
387
+ private getCategory;
388
+ constructor(insertionPoint: HTMLElement, maxRulesPerPartition?: number, styleIdPrefix?: string, getCategory?: (cls: string) => string | undefined);
389
+ private initializeDefaultPartition;
390
+ private createNewCategoryPartition;
391
+ private createNewPartition;
392
+ hasRule(rule: string): boolean;
393
+ hasCategoryRule(rule: string, category: string): boolean;
394
+ setRuleCache(rule: string, partitionIndex: number): void;
395
+ setCategoryRuleCache(rule: string, category: string): void;
396
+ get currentPartition(): StylePartition;
397
+ getCategoryPartition(category: string): StylePartition | undefined;
398
+ hasDetachedPartitions(): boolean;
399
+ /**
400
+ * Escape CSS rule text
401
+ * - Properly escape special characters
402
+ * - Prevent CSS syntax errors
403
+ */
404
+ private escapeCssRule;
405
+ addRule(rule: string): boolean;
406
+ addCategoryRule(rule: string, category: string): boolean;
407
+ addRootRules(rules: string[]): {
408
+ success: number;
409
+ failed: number;
410
+ };
411
+ addRules(rules: GenerateCssRulesResult[]): {
412
+ success: number;
413
+ failed: number;
414
+ };
415
+ /**
416
+ * Remove one generated rule (#269 GC). Keeps `styles`, the #254 `keys` and the
417
+ * sheet's cssRules parallel: one deleteRule at the rule's index, or a text
418
+ * rebuild when the sheet isn't solely ours / has no CSSOM. Returns whether
419
+ * the rule was found.
420
+ */
421
+ removeRule(rule: string, category?: string): boolean;
422
+ /** Number of generated (non-root, non-preflight) rules currently held. */
423
+ get ruleCount(): number;
424
+ /**
425
+ * 특정 규칙이 어느 파티션에 있는지 찾기
426
+ */
427
+ findRulePartition(rule: string): StylePartition | null;
428
+ updateRuleContent(category: string, ruleContent: string, atDocumentStart?: boolean): void;
429
+ /**
430
+ * 모든 파티션 정리
431
+ */
432
+ cleanup(): void;
433
+ }
434
+
435
+ export { }