"use strict";var e=require("@csstools/cascade-layer-name-parser"),r=require("@csstools/css-tokenizer"),t=require("@csstools/media-query-list-parser");const n=e.parse("csstools-implicit-layer")[0];function collectCascadeLayerOrder(r){const t=new Map,a=new Map,o=[];r.walkAtRules((r=>{if("layer"!==r.name.toLowerCase())return;{let e=r.parent;for(;e;){if("atrule"!==e.type||"layer"!==e.name.toLowerCase()){if(e===r.root())break;return}e=e.parent}}let s;if(r.nodes)s=normalizeLayerName(r.params,1);else{if(!r.params.trim())return;s=r.params}let i=e.parse(s);if(i?.length){{let e=r.parent;for(;e&&"atrule"===e.type&&"layer"===e.name.toLowerCase();){const r=a.get(e);r?(i=i.map((e=>r.concat(e))),e=e.parent):e=e.parent}}if(e.addLayerToModel(o,i),r.nodes){const e=i[0].concat(n);t.set(r,e),a.set(r,i[0])}}}));for(const r of t.values())e.addLayerToModel(o,[r]);const s=new WeakMap;for(const[e,r]of t)s.set(e,o.findIndex((e=>r.equal(e))));return s}function normalizeLayerName(e,r){return e.trim()?e:"csstools-anon-layer--"+r++}const a=new Set(["scope","container","layer"]);function isProcessableCustomMediaRule(e){if("custom-media"!==e.name.toLowerCase())return!1;if(!e.params||!e.params.includes("--"))return!1;if(e.nodes&&e.nodes.length>0)return!1;let r=e.parent;for(;r;){if("atrule"===r.type&&!a.has(r.name.toLowerCase()))return!1;r=r.parent}return!0}function removeCyclicReferences(e,r){const t=new Set;for(;e.size>0;){const n=findCyclicNode(Array.from(e.keys()),r);if(!n)return t;e.delete(n),t.add(n),r=r.filter((e=>-1===e.indexOf(n)))}return t}function findCyclicNode(e,r){let t=e.length;const n=new Array(t),a={};let o=t;const s=makeOutgoingEdges(r),i=makeNodesHash(e);for(;o--;)if(!a[o]){const r=visit(e[o],o,new Set);if(!r)continue;return r}function visit(e,r,o){if(o.has(e))return e;if(!i.has(e))return;if(a[r])return;a[r]=!0;const l=Array.from(s.get(e)||new Set);if(r=l.length){o.add(e);do{const e=l[--r],t=visit(e,i.get(e),o);if(t)return t}while(r);o.delete(e)}n[--t]=e}}function makeOutgoingEdges(e){const r=new Map;for(let t=0,n=e.length;t{throw new Error(`Unable to parse media query "${e}"`)}}),n=[];for(;!t.endOfFile();)n.push(t.nextToken());return n}const o=[[r.TokenType.Ident,"max-color",0,0,{value:"max-color"}],[r.TokenType.Colon,":",0,0,void 0],[r.TokenType.Number,"2147477350",0,0,{value:2147477350,type:r.NumberType.Integer}]],s=[[r.TokenType.Ident,"color",0,0,{value:"color"}],[r.TokenType.Colon,":",0,0,void 0],[r.TokenType.Number,"2147477350",0,0,{value:2147477350,type:r.NumberType.Integer}]];function replaceTrueAndFalseTokens(e){let t,n=[];for(let a=0;a{throw new Error(`Unable to parse media query "${r.stringify(...s)}"`)}}),l=t.parseFromTokens(r.cloneTokens(s),{preserveInvalidMediaQueries:!0,onParseError:()=>{throw new Error(`Unable to parse media query "${r.stringify(...s)}"`)}}).map((e=>e.negateQuery()));return{name:o,truthy:i,falsy:l,dependencies:Array.from(a).map((e=>[o,e]))}}function getCustomMedia(e,r,t){const n=new Map,a=new Map,o=[],s=collectCascadeLayerOrder(e);e.walkAtRules((e=>{if(!isProcessableCustomMediaRule(e))return;const r=parseCustomMedia(e.params);if(!r)return;if(0===r.truthy.length)return;const i=(u=s,(l=e).parent&&"atrule"===l.parent.type&&"layer"===l.parent.name.toLowerCase()?u.has(l.parent)?u.get(l.parent)+1:0:1e7);var l,u;const c=a.get(r.name)??-1;if(i&&i>=c&&(a.set(r.name,i),n.set(r.name,{truthy:r.truthy,falsy:r.falsy}),o.push(...r.dependencies)),!t.preserve){const r=e.parent;e.remove(),removeEmptyAncestorBlocks(r)}}));const i=removeCyclicReferences(n,o);for(const t of i.values())e.warn(r,`@custom-media rules have cyclic dependencies for "${t}"`);return n}function removeEmptyAncestorBlocks(e){if(!e)return;let r=e;for(;r;){if(r.nodes&&r.nodes.length>0)return;const e=r.parent;r.remove(),r=e}}function transformAtMediaListTokens(e,r){const n=t.parse(e,{preserveInvalidMediaQueries:!0,onParseError:()=>{throw new Error(`Unable to parse media query "${e}"`)}}),a=n.map((e=>e.toString()));for(let e=0;et===e?n:{replaceWith:r}))}const s=transformComplexMediaQuery(t,r);if(s&&0!==s.length&&s[0].replaceWith!==o)return a.flatMap(((r,t)=>t===e?s:[{replaceWith:r}]))}return[]}function transformSimpleMediaQuery(e,r){if(!mediaQueryIsSimple(e))return null;let n=null;return e.walk((e=>{const a=e.node;if(!t.isMediaFeatureBoolean(a))return;const o=a.getName();if(!o.startsWith("--"))return;const s=r.get(o);return s?(n={replaceWith:s.truthy.map((e=>e.toString().trim())).join(",")},!1):void 0})),n}function transformComplexMediaQuery(e,r){let n=[];return e.walk((a=>{const i=a.node;if(!t.isMediaFeatureBoolean(i))return;const l=a.parent;if(!t.isMediaFeature(l))return;const u=i.getName();if(!u.startsWith("--"))return;const c=r.get(u);if(c){if(1===c.truthy.length&&mediaQueryIsSimple(c.truthy[0])){let r=null;if(c.truthy[0].walk((e=>{if(t.isMediaFeature(e.node))return r=e.node,!1})),r&&r.feature)return l.feature=r.feature,n=[{replaceWith:e.toString()}],!1}const r=t.newMediaFeaturePlain(o[0][4].value,o[2]);l.feature=r.feature;const a=e.toString(),i=t.newMediaFeaturePlain(s[0][4].value,s[2]);l.feature=i.feature;const u=e.toString();return n=[{replaceWith:a,encapsulateWith:[c.truthy.map((e=>e.toString().trim())).join(",")]},{replaceWith:u,encapsulateWith:c.falsy.map((e=>e.map((e=>e.toString().trim())).join(",").toString().trim()))}],!1}})),n}function mediaQueryIsSimple(e){if(t.isMediaQueryInvalid(e))return!1;if(t.isMediaQueryWithType(e))return!1;let r=!0;return e.walk((e=>{if(t.isMediaAnd(e.node)||t.isMediaOr(e.node)||t.isMediaNot(e.node)||t.isMediaConditionList(e.node)||t.isGeneralEnclosed(e.node))return r=!1,!1})),r}const creator=e=>{const r=e?.preserve??!1;if("importFrom"in Object(e))throw new Error('[postcss-custom-media] "importFrom" is no longer supported');if("exportTo"in Object(e))throw new Error('[postcss-custom-media] "exportTo" is no longer supported');return{postcssPlugin:"postcss-custom-media",prepare(){const e=new WeakSet;let t=new Map;return{postcssPlugin:"postcss-custom-media",Once(e,{result:n}){t=getCustomMedia(e,n,{preserve:r})},AtRule(n,{result:a}){if(e.has(n))return;if("media"!==n.name.toLowerCase())return;if(!n.params)return;if(!n.params.includes("--"))return;let o=[];try{o=transformAtMediaListTokens(n.params,t)}catch(e){return void n.warn(a,`Failed to parse @custom-media params with error message: "${e instanceof Error?e.message:e}"`)}if(!o||0===o.length)return;if(1===o.length){if(n.params.trim()===o[0].replaceWith.trim())return;return e.add(n),n.cloneBefore({params:o[0].replaceWith.trim()}),r?void 0:void n.remove()}if(!!!o.find((e=>!!e.encapsulateWith?.length)))return e.add(n),n.cloneBefore({params:o.map((e=>e.replaceWith)).join(",").trim()}),void(r||n.remove());o.forEach((r=>{if(!r.encapsulateWith?.length)return void n.cloneBefore({params:r.replaceWith.trim()});const t=n.clone({params:r.replaceWith});t.parent=void 0;let a=n.clone({params:r.encapsulateWith[0],nodes:[]});a.parent=void 0,a.append(t),r.encapsulateWith.slice(1).forEach((e=>{const r=n.clone({params:e,nodes:[]});r.parent=void 0,r.append(a),a=r})),e.add(n),n.before(a)})),r||n.remove()}}}}};creator.postcss=!0,module.exports=creator;