Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions plugins/postcss-private-rule/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
# Changes to PostCSS Private Rule

### Unreleased (major)

- Removed the undocumented `Transpiler` export; use `@csstools/utilities-for-private-properties` instead
- Support `@property` rules in `@private` rules, including multi-name preludes and the shorthand form, and hoist registrations out of `@container`, `@scope` and `@starting-style` while preserving `@media`, `@supports` and `@layer` context
- Rename private properties in `transition`, `transition-property`, `inherit()` and `var()` inside `@container` preludes
- Leave style rules untouched when they contain `@apply`, `@contents`, `!important` declarations or unsupported at-rules, when they are inside a `@mixin` or `@function`, or when a registration is inside an anonymous layer
- Remove conditional group rules that only contained a `@private` rule, and transpile `@private` rules inside `@container` and `@starting-style` when they have no registrations
- Use a separate namespace for generated names so they do not collide with mixin generated names

### 1.1.1

_October 2, 2026_
Expand Down
6 changes: 6 additions & 0 deletions plugins/postcss-private-rule/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,12 @@ npm install @csstools/postcss-private-rule --save-dev

[PostCSS Private Rule] lets you declare private custom properties following the [CSS Mixins Specification].

`@property` rules inside `@private` rules are hoisted to the root. Registrations inside `@container`, `@scope` and `@starting-style` are hoisted as if they were defined outside of those rules, matching their specifications. Registrations inside `@layer` and inside `@media` or `@supports` keep their enclosing rules.

Style rules are left unchanged when the private properties can not be transpiled faithfully: when a registration is inside an anonymous layer, or when `@apply` or `@contents` is still present.

Run this plugin after `@csstools/postcss-mixins` and before `@csstools/postcss-custom-functions` so that mixin bodies can use private properties and function bodies do not capture them.

```css
section {
@private {
Expand Down
27 changes: 0 additions & 27 deletions plugins/postcss-private-rule/dist/index.d.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@
import type { AtRule } from 'postcss';
import type { Declaration } from 'postcss';
import type { Node } from 'postcss';
import type { PluginCreator } from 'postcss';
import type { Rule } from 'postcss';

declare const creator: PluginCreator<pluginOptions>;
export default creator;
Expand All @@ -11,27 +7,4 @@ export { creator as 'module.exports' }
/** postcss-private-rule plugin options */
export declare type pluginOptions = never;

export declare class Transpiler {
privateForRule: WeakMap<Rule | AtRule, {
prefix: string;
privateProperties: Set<string>;
}>;
counter: number;
hashes: Map<string, string>;
getOrFillPrivateForRule(rule: Rule | AtRule): {
prefix: string;
privateProperties: Set<string>;
};
getStyleRulesWithPrivateProperties(node: Node): Array<{
prefix: string;
privateProperties: Set<string>;
rule: Rule;
}>;
registerAndRemovePrivateRules(atRule: AtRule, ownerNode: AtRule | Rule): void;
transpileDeclaration(decl: Declaration): void;
transpileDeclarationPropertyNames(decl: Declaration): void;
transpileDeclarationValues(decl: Declaration): void;
transpileAtRule(atRule: AtRule): void;
}

export { }
2 changes: 1 addition & 1 deletion plugins/postcss-private-rule/dist/index.mjs
Original file line number Diff line number Diff line change
@@ -1 +1 @@
import{tokenize as e,isTokenIdent as t,mutateIdent as r}from"@csstools/css-tokenizer";import{parseListOfComponentValues as s,walk as i,isFunctionNode as a,isWhiteSpaceOrCommentNode as n,isTokenNode as o,stringify as l}from"@csstools/css-parser-algorithms";const u=/^keyframes$/i,p=/^(container|layer|media|scope|starting-style|supports)$/i,c=/^private$/i;function findStyleRule(e){if(!e.parent)return!1;if("rule"===e.parent.type){const t=e.parent;return("atrule"!==t.parent?.type||!u.test(t.parent.name))&&t}if("atrule"===e.parent.type){const t=e.parent;if(p.test(t.name))return findStyleRule(t)}return!1}function findAllStyleRules(e){let t=e;const r=[];for(;;){const e=findStyleRule(t);if(!e)break;r.push(e),t=e}return r.reverse(),r}function findPrivateRule(e){return"atrule"===e.parent?.type&&(p.test(e.parent.name)?findPrivateRule(e.parent):!!c.test(e.parent.name)&&e.parent)}const f=/\b(var|if)\(/i,v=/^container$/i,h=/^if$/i,m=/^style$/i,g=/^var$/i;class Transpiler{privateForRule=new Map;counter=0;hashes=new Map;getOrFillPrivateForRule(e){const t=this.privateForRule.get(e);if(t)return t;let r;e.source?.input.from?(r=this.hashes.get(e.source.input.from),r||(r=sourceHashFor(e.source.input.from),this.hashes.set(e.source.input.from,r))):r="0";const s=`--_csstools-p-${r}-${this.counter.toString(36)}`;this.counter++;const i={prefix:s,privateProperties:new Set};return this.privateForRule.set(e,i),i}getStyleRulesWithPrivateProperties(e){return findAllStyleRules(e).map(e=>{const t=this.privateForRule.get(e);return!!t&&{prefix:t.prefix,privateProperties:t.privateProperties,rule:e}}).filter(Boolean).reverse()}registerAndRemovePrivateRules(e,t){if(!e.nodes?.length)return;const{prefix:r,privateProperties:s}=this.getOrFillPrivateForRule(t);e.walk(t=>{if("decl"===t.type&&t.variable&&t.prop.startsWith("--"))return s.add(t.prop),void(t.prop=`${r}${t.prop}`);"atrule"===t.type&&findPrivateRule(t)===e||t.remove()}),e.before(e.nodes.map(e=>e.clone())),e.remove()}transpileDeclaration(e){this.transpileDeclarationPropertyNames(e),this.transpileDeclarationValues(e)}transpileDeclarationPropertyNames(e){if(!e.variable||!e.prop.startsWith("--"))return;const t=this.getStyleRulesWithPrivateProperties(e);if(!t.length)return;let r=!1;for(const{prefix:s,privateProperties:i}of t)if(i.has(e.prop)){r=s;break}if(!r)return;const s=`${r}${e.prop}`;e.prop!==s&&(e.prop=s)}transpileDeclarationValues(u){if(!f.test(u.value))return;const p=this.getStyleRulesWithPrivateProperties(u);if(!p.length)return;const c=s(e({css:u.value}));i(c,e=>{if(a(e.node)){if(g.test(e.node.getName())){const s=e.node.value;for(let e=0;e<s.length;e++){const i=s[e];if(n(i))continue;if(!o(i)||!t(i.value)||!i.value[4].value.startsWith("--"))break;const a=i.value[4].value;let l=!1;for(const{prefix:e,privateProperties:t}of p)if(t.has(a)){l=e;break}if(!l)break;r(i.value,`${l}${i.value[4].value}`);break}return}if(h.test(e.node.getName())){const s=e.node.value;for(let e=0;e<s.length;e++){const i=s[e];if(n(i))continue;if(!a(i)||!m.test(i.getName()))break;const l=i.value;for(let e=0;e<l.length;e++){const s=l[e];if(n(s))continue;if(!o(s)||!t(s.value)||!s.value[4].value.startsWith("--"))break;const i=s.value[4].value;let a=!1;for(const{prefix:e,privateProperties:t}of p)if(t.has(i)){a=e;break}if(!a)return;r(s.value,`${a}${s.value[4].value}`);break}}}}});const v=l([c]);v!==u.value&&(u.value=v)}transpileAtRule(u){if(!v.test(u.name))return;if(!u.params.includes("--"))return;const p=this.getStyleRulesWithPrivateProperties(u);if(!p.length)return;const c=s(e({css:u.params}));i(c,e=>{if(!a(e.node))return;if(!m.test(e.node.getName()))return;const s=e.node.value;for(let e=0;e<s.length;e++){const i=s[e];if(n(i))continue;if(!o(i)||!t(i.value)||!i.value[4].value.startsWith("--"))break;const a=i.value[4].value;let l=!1;for(const{prefix:e,privateProperties:t}of p)if(t.has(a)){l=e;break}if(!l)break;r(i.value,`${l}${i.value[4].value}`);break}});const f=l([c]);f!==u.params&&(u.params=f)}}function sourceHashFor(e){let t=2166136261;const r=sourceKey(e);for(let e=0;e<r.length;e++)t^=r.charCodeAt(e),t=Math.imul(t,16777619);return(t>>>0).toString(36)}function sourceKey(e){const t=e.replaceAll("\\","/").split("/").filter(e=>e.length>0);return 0===t.length?".":1===t.length?`./${t[0]}`:t.slice(-2).join("/")}const creator=()=>({postcssPlugin:"postcss-private-rule",prepare(){const e=new Transpiler;return{postcssPlugin:"postcss-private-rule",Once(t){t.walkAtRules(c,t=>{const r=findStyleRule(t);r&&e.registerAndRemovePrivateRules(t,r)}),t.walkDecls(t=>{e.transpileDeclaration(t)}),t.walkAtRules(t=>{e.transpileAtRule(t)})}}}});creator.postcss=!0;export{Transpiler,creator as default,creator as"module.exports"};
import{createPrivatePropertyTranspiler as s}from"@csstools/utilities-for-private-properties";const creator=()=>({postcssPlugin:"postcss-private-rule",prepare(){const t=s();return{postcssPlugin:"postcss-private-rule",Once(s){s.append(t.transpile(s.nodes))}}}});creator.postcss=!0;export{creator as default,creator as"module.exports"};
6 changes: 6 additions & 0 deletions plugins/postcss-private-rule/docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,12 @@

[<humanReadableName>] lets you declare private custom properties following the [CSS Mixins Specification].

`@property` rules inside `@private` rules are hoisted to the root. Registrations inside `@container`, `@scope` and `@starting-style` are hoisted as if they were defined outside of those rules, matching their specifications. Registrations inside `@layer` and inside `@media` or `@supports` keep their enclosing rules.

Style rules are left unchanged when the private properties can not be transpiled faithfully: when a registration is inside an anonymous layer, or when `@apply` or `@contents` is still present.

Run this plugin after `@csstools/postcss-mixins` and before `@csstools/postcss-custom-functions` so that mixin bodies can use private properties and function bodies do not capture them.

```css
<example.css>

Expand Down
6 changes: 3 additions & 3 deletions plugins/postcss-private-rule/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,15 +41,15 @@
"dist"
],
"dependencies": {
"@csstools/css-parser-algorithms": "^4.0.2",
"@csstools/css-tokenizer": "^4.0.2"
"@csstools/utilities-for-private-properties": "^0.0.0"
},
"peerDependencies": {
"postcss": "^8.4"
},
"devDependencies": {
"@csstools/postcss-bundler": "*",
"@csstools/postcss-tape": "*"
"@csstools/postcss-tape": "*",
"puppeteer": "^25.14.0"
},
"scripts": {
"build": "rollup -c ../../rollup/default.mjs",
Expand Down
26 changes: 4 additions & 22 deletions plugins/postcss-private-rule/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
import type { Plugin, PluginCreator } from 'postcss';
import { findStyleRule, IS_PRIVATE_RULE_REGEX } from './valid-atrules';
import { Transpiler } from './transpiler';

export { Transpiler } from './transpiler';
import { createPrivatePropertyTranspiler } from '@csstools/utilities-for-private-properties';

/** postcss-private-rule plugin options */
export type pluginOptions = never;
Expand All @@ -11,30 +8,15 @@ const creator: PluginCreator<pluginOptions> = () => {
return {
postcssPlugin: 'postcss-private-rule',
prepare(): Plugin {
const transpiler = new Transpiler();
const transpiler = createPrivatePropertyTranspiler();

return {
postcssPlugin: 'postcss-private-rule',
Once(root): void {
root.walkAtRules(IS_PRIVATE_RULE_REGEX, (atRule) => {
const styleRule = findStyleRule(atRule);
if (!styleRule) {
return;
}

transpiler.registerAndRemovePrivateRules(atRule, styleRule);
});

root.walkDecls((decl) => {
transpiler.transpileDeclaration(decl);
});

root.walkAtRules((atRule) => {
transpiler.transpileAtRule(atRule);
});
root.append(transpiler.transpile(root.nodes));
},
};
}
},
};
};

Expand Down
129 changes: 129 additions & 0 deletions plugins/postcss-private-rule/test/_browser.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
import puppeteer from 'puppeteer';
import http from 'node:http';
import fs from 'node:fs/promises';
import plugin from '@csstools/postcss-private-rule';
import postcss from 'postcss';
import test from 'node:test';
import process from 'node:process';

// The transformed cases run the source through this plugin.
//
// No browser implements `@private` yet, so only the transformed form is tested.

const PAGES = [
'wpt/private.html',
'wpt/private-rule-types.html',
];

const requestListener = async function (req, res) {

const parsedUrl = new URL(req.url, 'http://localhost:8080');
const pathname = parsedUrl.pathname;

if (PAGES.includes(pathname.replace(/^\//, ''))) {
res.setHeader('Content-type', 'text/html');
res.writeHead(200);
res.end(await fs.readFile('test' + pathname, 'utf8'));
return;
}

if (pathname === '' || pathname === '/') {
res.setHeader('Content-type', 'text/html');
res.writeHead(200);

res.end(`<!DOCTYPE html>
<html>
<head>
<title>Private Rule Test</title>
</head>
<body>
<h1>Private Rule Test</h1>
<ul>
${PAGES.map((page) => `<li><a href="/${page}">${page}</a></li>`).join('\n')}
</ul>
</body>
</html>
`);
return;
}

if (pathname === '/test/styles.css' && req.method === 'POST') {
const data = await new Promise((resolve, reject) => {
let buf = [];
req.on('data', (chunk) => {
buf.push(chunk);
});

req.on('end', () => {
resolve(Buffer.concat(buf).toString());
});

req.on('error', (err) => {
reject(err);
});
});

const css = parsedUrl.searchParams.get('transform') === 'false'
? data
: (await postcss([plugin()]).process(data, { from: 'test/styles.css', to: 'test/styles.css' })).css;

res.setHeader('Content-type', 'text/css');
res.writeHead(200);
res.end(css);
return;
}

res.setHeader('Content-type', 'text/plain');
res.writeHead(404);
res.end('Not found');
};

function startServers() {
const server = http.createServer(requestListener);
server.listen(8080);

return () => {
server.close();
};
}

if (!process.env.DEBUG) {
test('browser', { skip: process.env.GITHUB_ACTIONS && !process.env.BROWSER_TESTS }, async () => {
const cleanup = startServers();

let browser;

try {
browser = await puppeteer.launch({
headless: 'new',
executablePath: process.env.PUPPETEER_EXECUTABLE_PATH,
args: ['--enable-experimental-web-platform-features'],
});

const page = await browser.newPage();
page.on('pageerror', (msg) => {
throw msg;
});

for (const url of PAGES) {
await page.goto('http://localhost:8080/' + url);
const result = await page.evaluate(async () => {
// eslint-disable-next-line no-undef
return await window.runTest();
});
if (!result) {
throw new Error('Test failed, expected "window.runTest()" to return true');
}
}
} finally {
await browser?.close();

await cleanup();
}
});
} else {
startServers();

// eslint-disable-next-line no-console
console.log('visit : http://localhost:8080');
}
3 changes: 3 additions & 0 deletions plugins/postcss-private-rule/test/_tape.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ postcssTape(plugin)({
encoding: {
message: 'all encoded values are valid css',
},
property: {
message: 'supports @property rules in @private rules',
},
bundled: {
message: 'all encoded values are valid css',
plugins: [
Expand Down
Loading
Loading