Merge catppuccin-userstyles-nix: flake exports stylusSettings, builds from in-repo styles offline
Build Stylus Export / build (push) Skipped
CI / ci (push) Skipped
Deno Check / check (push) Skipped
Lint Userstyles / lint (push) Skipped

This commit is contained in:
bug committed 2026-10-18 02:04:31 -05:00
1 parent 7e3ce35890
commit 68285a17b1
12 files changed
+1173 -18

No files matched your search

+86
View File
@@ -0,0 +1,86 @@
> [!WARNING]
> This repository has been superseded and is now archived
>
> The project has moved a fork of catppuccin/nix: https://github.com/different-name/catppuccin-nix/tree/userstyles
>
> Follow the PR progress here: https://github.com/catppuccin/nix/pull/591
# catppuccin-userstyles-nix
Generate Stylus settings with Catppuccin Userstyles configured & installed
## Usage
Add `catppuccin-userstyles-nix` to your flake inputs
```nix
catppuccin-userstyles-nix = {
url = "github:different-name/catppuccin-userstyles-nix";
inputs.nixpkgs.follows = "nixpkgs";
};
```
### Install via Home Manager Module (Firefox, LibreWolf, Floorp)
You can configure Stylus settings declaratively using the Firefox, LibreWolf, or Floorp Home Manager modules
This flake provides a `stylusSettings.<system>` function that generates Stylus settings with Catppuccin Userstyles configured & installed
```nix
let
profile = "YOUR_PROFILE_NAME";
catppuccinStylusSettings = inputs.catppuccin-userstyles-nix.stylusSettings.${pkgs.system} {
# global userstyle settings
global = {
lightFlavor = "latte";
darkFlavor = "mocha";
accentColor = "red";
};
# per-userstyle settings
"Userstyle GitHub Catppuccin" = {
darkFlavor = "frappe";
accentColor = "mauve";
};
};
in
{
programs.firefox.profiles.${profile}.extensions = {
# install Stylus (from NUR https://github.com/nix-community/NUR)
packages = with pkgs.nur.repos.rycee.firefox-addons; [
stylus
];
settings = {
# UUID of the Stylus extension — fixed for all installs
"{7a7a4a92-a2a0-41d1-9fd7-1e92480d612d}" = {
settings = catppuccinStylusSettings // {
# optional: additional Stylus settings
};
};
};
};
}
```
### Manual install via `home.file`
Another option is to install the `catppuccin-stylus-storage` package directly through `home.file`:
```nix
let
profile = "YOUR_PROFILE_NAME";
inherit (inputs.catppuccin-userstyles-nix.packages.${pkgs.system}) catppuccin-stylus-storage;
in
{
home.file = {
".mozilla/firefox/${profile}/browser-extension-data/{7a7a4a92-a2a0-41d1-9fd7-1e92480d612d}/storage.js".source =
catppuccin-stylus-storage + /share/storage.js;
};
}
```
## Acknowledgements
- https://github.com/catppuccin/userstyles for the userstyles & base script
Generated
+10 -7
View File
@@ -2,15 +2,18 @@
"nodes": {
"nixpkgs": {
"locked": {
"lastModified": 315532800,
"narHash": "sha256-gVTEpnfY0A1e9++s9s6t26RMTQvRoWexvUGxYhbnzHg=",
"rev": "e4b09e47ace7d87de083786b404bf232eb6c89d8",
"type": "tarball",
"url": "https://releases.nixos.org/nixpkgs/nixpkgs-25.11pre809757.e4b09e47ace7/nixexprs.tar.xz?rev=e4b09e47ace7d87de083786b404bf232eb6c89d8"
"lastModified": 1792094642,
"narHash": "sha256-zp8ToDMnqZcu4o4IH9pdwXFXGp7yLm/M0dEnNWnyd7I=",
"owner": "nixos",
"repo": "nixpkgs",
"rev": "fe13242281a67641c0102cdb1087f0ebe586c7df",
"type": "github"
},
"original": {
"type": "tarball",
"url": "https://channels.nixos.org/nixpkgs-unstable/nixexprs.tar.xz"
"owner": "nixos",
"ref": "nixos-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"root": {
+19 -11
View File
@@ -1,20 +1,28 @@
{
description = "Catppuccin userstyles";
description = "Catppuccin userstyles (bug fork) + Stylus settings generator";
inputs.nixpkgs.url = "https://channels.nixos.org/nixpkgs-unstable/nixexprs.tar.xz";
inputs.nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable";
outputs =
{ nixpkgs, ... }:
{ self, nixpkgs, ... }:
let
forAllSystems =
function:
nixpkgs.lib.genAttrs nixpkgs.lib.systems.flakeExposed (
system: function nixpkgs.legacyPackages.${system}
);
forAllSystems = f: nixpkgs.lib.genAttrs [ "x86_64-linux" "aarch64-linux" ] (s: f nixpkgs.legacyPackages.${s});
packagesFor = pkgs: rec {
stylus-storage-gen = pkgs.callPackage ./pkgs/stylus-storage-gen.nix { };
catppuccin-stylus-storage = pkgs.callPackage ./pkgs/catppuccin-stylus-storage.nix {
inherit stylus-storage-gen;
src = self;
};
};
in
{
devShells = forAllSystems (pkgs: {
default = pkgs.callPackage ./shell.nix { };
});
packages = forAllSystems packagesFor;
# stylusSettings.<system> { global = { ... }; "Userstyle X Catppuccin" = { ... }; }
stylusSettings = forAllSystems (pkgs: userstylesOptions:
builtins.fromJSON (builtins.readFile
((packagesFor pkgs).catppuccin-stylus-storage.override { inherit userstylesOptions; } + /share/storage.js)));
devShells = forAllSystems (pkgs: { default = pkgs.callPackage ./shell.nix { }; });
};
}
+37
View File
@@ -0,0 +1,37 @@
{
lib,
stdenv,
src,
stylus-storage-gen,
userstylesOptions ? { },
}:
let
userstylesOptionsFile = builtins.toFile "catppuccin-userstyles-options" (
builtins.toJSON userstylesOptions
);
in
stdenv.mkDerivation {
pname = "catppuccin-stylus-storage";
version = "0.1.0";
inherit src;
nativeBuildInputs = [
stylus-storage-gen
];
buildPhase = ''
mkdir -p $out/share ./deno_cache
# styles @import lib.less from the web; use the in-repo copy (sandbox has no network)
grep -rl 'https://userstyles.catppuccin.com/lib/lib.less' styles | xargs sed -i "s|https://userstyles.catppuccin.com/lib/lib.less|$src/lib/lib.less|"
DENO_DIR=$PWD/deno_cache stylus-storage-gen "$PWD/styles" "${userstylesOptionsFile}"
cp storage.js $out/share/
'';
meta = {
description = "Soothing pastel userstyles";
homepage = "https://github.com/catppuccin/userstyles";
license = with lib.licenses; [ mit ];
platforms = lib.platforms.all;
};
}
+22
View File
@@ -0,0 +1,22 @@
{
lib,
buildNpmPackage,
}:
buildNpmPackage (finalAttrs: {
pname = "stylus-storage-gen";
version = "0.2.0";
src = builtins.path {
path = ../stylus-storage-gen;
name = finalAttrs.pname + "-src";
};
npmDepsHash = "sha256-lD9SbhexYCu0yYRkNihLz3xRMMwrl3Ls3aV2EDe5k5U=";
meta = {
description = "Stylus storage.js file generator, compatible with Catppuccin Userstyles";
license = with lib.licenses; [ mit ];
platforms = lib.platforms.all;
mainProgram = "stylus-storage-gen";
};
})
+331
View File
@@ -0,0 +1,331 @@
{
"name": "stylus-storage-gen",
"version": "0.2.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "stylus-storage-gen",
"version": "0.2.0",
"license": "MIT",
"dependencies": {
"less": "^4.3.0",
"postcss": "^8.5.6",
"usercss-meta": "^0.12.0"
},
"devDependencies": {
"@types/less": "^3.0.8",
"@types/node": "^20.0.0",
"typescript": "^5.0.0"
}
},
"node_modules/@types/less": {
"version": "3.0.8",
"resolved": "https://registry.npmjs.org/@types/less/-/less-3.0.8.tgz",
"integrity": "sha512-Gjm4+H9noDJgu5EdT3rUw5MhPBag46fiOy27BefvWkNL8mlZnKnCaVVVTLKj6RYXed9b62CPKnPav9govyQDzA==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/node": {
"version": "20.19.1",
"resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.1.tgz",
"integrity": "sha512-jJD50LtlD2dodAEO653i3YF04NWak6jN3ky+Ri3Em3mGR39/glWiboM/IePaRbgwSfqM1TpGXfAg8ohn/4dTgA==",
"dev": true,
"license": "MIT",
"dependencies": {
"undici-types": "~6.21.0"
}
},
"node_modules/copy-anything": {
"version": "2.0.6",
"resolved": "https://registry.npmjs.org/copy-anything/-/copy-anything-2.0.6.tgz",
"integrity": "sha512-1j20GZTsvKNkc4BY3NpMOM8tt///wY3FpIzozTOFO2ffuZcV61nojHXVKIy3WM+7ADCy5FVhdZYHYDdgTU0yJw==",
"license": "MIT",
"dependencies": {
"is-what": "^3.14.1"
},
"funding": {
"url": "https://github.com/sponsors/mesqueeb"
}
},
"node_modules/errno": {
"version": "0.1.8",
"resolved": "https://registry.npmjs.org/errno/-/errno-0.1.8.tgz",
"integrity": "sha512-dJ6oBr5SQ1VSd9qkk7ByRgb/1SH4JZjCHSW/mr63/QcXO9zLVxvJ6Oy13nio03rxpSnVDDjFor75SjVeZWPW/A==",
"license": "MIT",
"optional": true,
"dependencies": {
"prr": "~1.0.1"
},
"bin": {
"errno": "cli.js"
}
},
"node_modules/graceful-fs": {
"version": "4.2.11",
"resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",
"integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==",
"license": "ISC",
"optional": true
},
"node_modules/iconv-lite": {
"version": "0.6.3",
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz",
"integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==",
"license": "MIT",
"optional": true,
"dependencies": {
"safer-buffer": ">= 2.1.2 < 3.0.0"
},
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/image-size": {
"version": "0.5.5",
"resolved": "https://registry.npmjs.org/image-size/-/image-size-0.5.5.tgz",
"integrity": "sha512-6TDAlDPZxUFCv+fuOkIoXT/V/f3Qbq8e37p+YOiYrUv3v9cc3/6x78VdfPgFVaB9dZYeLUfKgHRebpkm/oP2VQ==",
"license": "MIT",
"optional": true,
"bin": {
"image-size": "bin/image-size.js"
},
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/is-what": {
"version": "3.14.1",
"resolved": "https://registry.npmjs.org/is-what/-/is-what-3.14.1.tgz",
"integrity": "sha512-sNxgpk9793nzSs7bA6JQJGeIuRBQhAaNGG77kzYQgMkrID+lS6SlK07K5LaptscDlSaIgH+GPFzf+d75FVxozA==",
"license": "MIT"
},
"node_modules/less": {
"version": "4.3.0",
"resolved": "https://registry.npmjs.org/less/-/less-4.3.0.tgz",
"integrity": "sha512-X9RyH9fvemArzfdP8Pi3irr7lor2Ok4rOttDXBhlwDg+wKQsXOXgHWduAJE1EsF7JJx0w0bcO6BC6tCKKYnXKA==",
"license": "Apache-2.0",
"dependencies": {
"copy-anything": "^2.0.1",
"parse-node-version": "^1.0.1",
"tslib": "^2.3.0"
},
"bin": {
"lessc": "bin/lessc"
},
"engines": {
"node": ">=14"
},
"optionalDependencies": {
"errno": "^0.1.1",
"graceful-fs": "^4.1.2",
"image-size": "~0.5.0",
"make-dir": "^2.1.0",
"mime": "^1.4.1",
"needle": "^3.1.0",
"source-map": "~0.6.0"
}
},
"node_modules/make-dir": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/make-dir/-/make-dir-2.1.0.tgz",
"integrity": "sha512-LS9X+dc8KLxXCb8dni79fLIIUA5VyZoyjSMCwTluaXA0o27cCK0bhXkpgw+sTXVpPy/lSO57ilRixqk0vDmtRA==",
"license": "MIT",
"optional": true,
"dependencies": {
"pify": "^4.0.1",
"semver": "^5.6.0"
},
"engines": {
"node": ">=6"
}
},
"node_modules/mime": {
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz",
"integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==",
"license": "MIT",
"optional": true,
"bin": {
"mime": "cli.js"
},
"engines": {
"node": ">=4"
}
},
"node_modules/nanoid": {
"version": "3.3.11",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz",
"integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/ai"
}
],
"license": "MIT",
"bin": {
"nanoid": "bin/nanoid.cjs"
},
"engines": {
"node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
}
},
"node_modules/needle": {
"version": "3.3.1",
"resolved": "https://registry.npmjs.org/needle/-/needle-3.3.1.tgz",
"integrity": "sha512-6k0YULvhpw+RoLNiQCRKOl09Rv1dPLr8hHnVjHqdolKwDrdNyk+Hmrthi4lIGPPz3r39dLx0hsF5s40sZ3Us4Q==",
"license": "MIT",
"optional": true,
"dependencies": {
"iconv-lite": "^0.6.3",
"sax": "^1.2.4"
},
"bin": {
"needle": "bin/needle"
},
"engines": {
"node": ">= 4.4.x"
}
},
"node_modules/parse-node-version": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/parse-node-version/-/parse-node-version-1.0.1.tgz",
"integrity": "sha512-3YHlOa/JgH6Mnpr05jP9eDG254US9ek25LyIxZlDItp2iJtwyaXQb57lBYLdT3MowkUFYEV2XXNAYIPlESvJlA==",
"license": "MIT",
"engines": {
"node": ">= 0.10"
}
},
"node_modules/picocolors": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
"integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
"license": "ISC"
},
"node_modules/pify": {
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/pify/-/pify-4.0.1.tgz",
"integrity": "sha512-uB80kBFb/tfd68bVleG9T5GGsGPjJrLAUpR5PZIrhBnIaRTQRjqdJSsIKkOP6OAIFbj7GOrcudc5pNjZ+geV2g==",
"license": "MIT",
"optional": true,
"engines": {
"node": ">=6"
}
},
"node_modules/postcss": {
"version": "8.5.6",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.6.tgz",
"integrity": "sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg==",
"funding": [
{
"type": "opencollective",
"url": "https://opencollective.com/postcss/"
},
{
"type": "tidelift",
"url": "https://tidelift.com/funding/github/npm/postcss"
},
{
"type": "github",
"url": "https://github.com/sponsors/ai"
}
],
"license": "MIT",
"dependencies": {
"nanoid": "^3.3.11",
"picocolors": "^1.1.1",
"source-map-js": "^1.2.1"
},
"engines": {
"node": "^10 || ^12 || >=14"
}
},
"node_modules/prr": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/prr/-/prr-1.0.1.tgz",
"integrity": "sha512-yPw4Sng1gWghHQWj0B3ZggWUm4qVbPwPFcRG8KyxiU7J2OHFSoEHKS+EZ3fv5l1t9CyCiop6l/ZYeWbrgoQejw==",
"license": "MIT",
"optional": true
},
"node_modules/safer-buffer": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
"license": "MIT",
"optional": true
},
"node_modules/sax": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/sax/-/sax-1.4.1.tgz",
"integrity": "sha512-+aWOz7yVScEGoKNd4PA10LZ8sk0A/z5+nXQG5giUO5rprX9jgYsTdov9qCchZiPIZezbZH+jRut8nPodFAX4Jg==",
"license": "ISC",
"optional": true
},
"node_modules/semver": {
"version": "5.7.2",
"resolved": "https://registry.npmjs.org/semver/-/semver-5.7.2.tgz",
"integrity": "sha512-cBznnQ9KjJqU67B52RMC65CMarK2600WFnbkcaiwWq3xy/5haFJlshgnpjovMVJ+Hff49d8GEn0b87C5pDQ10g==",
"license": "ISC",
"optional": true,
"bin": {
"semver": "bin/semver"
}
},
"node_modules/source-map": {
"version": "0.6.1",
"resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz",
"integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==",
"license": "BSD-3-Clause",
"optional": true,
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/source-map-js": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
"integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",
"license": "BSD-3-Clause",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/tslib": {
"version": "2.8.1",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
"license": "0BSD"
},
"node_modules/typescript": {
"version": "5.8.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.8.3.tgz",
"integrity": "sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
},
"engines": {
"node": ">=14.17"
}
},
"node_modules/undici-types": {
"version": "6.21.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
"integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
"dev": true,
"license": "MIT"
},
"node_modules/usercss-meta": {
"version": "0.12.0",
"resolved": "https://registry.npmjs.org/usercss-meta/-/usercss-meta-0.12.0.tgz",
"integrity": "sha512-zKrXCKdpeIwtVe87omxGo9URf+7mbozduMZEg79dmT4KB3XJwfIkEi/Uk0PcTwR/nZLtAK1+k7isgbGB/g6E7Q==",
"license": "MIT",
"engines": {
"node": ">=8.3"
}
}
}
}
+35
View File
@@ -0,0 +1,35 @@
{
"name": "stylus-storage-gen",
"version": "0.2.0",
"description": "Stylus storage.js file generator, compatible with Catppuccin Userstyles",
"homepage": "https://github.com/different-name/catppuccin-userstyles-nix#readme",
"bugs": {
"url": "https://github.com/different-name/catppuccin-userstyles-nix/issues"
},
"repository": {
"type": "git",
"url": "git+https://github.com/different-name/catppuccin-userstyles-nix.git"
},
"license": "MIT",
"author": "different-name",
"type": "module",
"main": "dist/main.js",
"scripts": {
"build": "tsc && cp src/sections-util.js dist/",
"start": "node dist/main.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"bin": {
"stylus-storage-gen": "dist/main.js"
},
"devDependencies": {
"@types/less": "^3.0.8",
"@types/node": "^20.0.0",
"typescript": "^5.0.0"
},
"dependencies": {
"less": "^4.3.0",
"postcss": "^8.5.6",
"usercss-meta": "^0.12.0"
}
}
+248
View File
@@ -0,0 +1,248 @@
import fs from "fs";
import path from "path";
import usercssMeta from "usercss-meta";
import { calcStyleDigest } from "./sections-util.js";
import less from "less";
import postcss from "postcss";
async function getStylesDir(): Promise<string | null> {
if (process.argv.length < 3) return null;
const stylesPath = process.argv[2];
const stylesStat = await fs.promises.stat(stylesPath);
if (!stylesStat.isDirectory) return null;
return stylesPath;
}
type UserstylesOptions = Record<string, Record<string, string | number>>;
function isRecord(obj: unknown): obj is Record<string, unknown> {
return typeof obj === "object" && obj !== null && !Array.isArray(obj);
}
function isStringOrNumber(value: unknown): value is string | number {
return typeof value === "string" || typeof value === "number";
}
function isValidUserstylesOptions(obj: unknown): obj is UserstylesOptions {
if (!isRecord(obj)) return false;
for (const value of Object.values(obj)) {
if (!isRecord(value)) return false;
if (!Object.values(value).every(isStringOrNumber)) return false;
}
return true;
}
async function getUserstylesOptions(): Promise<UserstylesOptions> {
if (process.argv.length < 4) return {};
const jsonPath = process.argv[3];
const rawData = await fs.promises.readFile(jsonPath, "utf8");
const json = JSON.parse(rawData);
if (!isValidUserstylesOptions(json)) {
throw new Error("Invalid JSON");
}
return json;
}
function getUserstylesFiles(stylesDir: string): string[] {
const files: string[] = [];
for (const dir of fs.readdirSync(stylesDir, { withFileTypes: true })) {
if (!dir.isDirectory) continue;
files.push(
path.join(stylesDir, dir.name, "catppuccin.user.less"),
);
}
return files;
}
function getUserstylesOption(
userstylesOptions: UserstylesOptions,
key: string,
subKey: string,
): string | number | null {
if (!(key in userstylesOptions)) return null;
if (!(subKey in userstylesOptions[key])) return null;
return userstylesOptions[key][subKey];
}
function bakeUserstyleVar(
name: string,
info: unknown,
metadata: usercssMeta.Metadata,
userstylesOptions: UserstylesOptions,
): string {
let value = getUserstylesOption(
userstylesOptions,
`Userstyle ${metadata.name}`,
name,
);
if (value === null) {
value = getUserstylesOption(userstylesOptions, "global", name);
}
if (
value === null &&
isRecord(info) &&
"default" in info &&
isStringOrNumber(info.default)
) {
value = info.default;
}
if (value === null) {
throw new Error(`Could not find value for ${metadata.name} ${name}`);
}
return `@${name}: ${value};`;
}
function generateSections(
userstyleBlock: string,
css: string,
): Record<string, unknown>[] {
const cssRoot: postcss.Root = postcss.parse(css);
const sections = [
{
code: userstyleBlock,
start: 0,
},
] as Record<string, unknown>[];
cssRoot.walkAtRules("-moz-document", (rule: postcss.AtRule) => {
const innerCss = rule.nodes?.map((n) => n.toString()).join("\n") ?? "";
const section = {
code: innerCss,
start: sections.map((s) => s.code).join().length,
} as Record<string, unknown>;
function addRule(rule: string, value: string) {
if (Array.isArray(section[rule])) {
section[rule].push(value);
} else {
section[rule] = [value];
}
}
const conditions: string[] = (rule.params ?? "").split(", ");
conditions.forEach((condition) => {
const match = condition.match(/^([\w-]+)\("(.+)"\)$/);
if (match) {
const value = match[2].replace(/\\\\/g, "\\");
switch (match[1]) {
case "domain":
addRule("domains", value);
break;
case "regexp":
addRule("regexps", value);
break;
case "url-prefix":
addRule("urlPrefixes", value);
break;
}
}
});
rule.remove();
sections.push(section);
});
cssRoot.walkComments((comment) => {
comment.remove();
return;
});
const unhandledCss = cssRoot.toString().trim();
if (unhandledCss.length > 0) {
throw new Error(`Unhandled CSS '${unhandledCss}'`);
}
return sections;
}
async function generateStorageData(): Promise<Record<string, unknown>> {
const data: Record<string, unknown> = {
// required for stylus to continue to use storage.js file
dbInChromeStorage: true,
};
const stylesDir = await getStylesDir();
if (stylesDir === null) throw new Error("Expected path to styles directory");
const userstylesOptions = await getUserstylesOptions();
for (const [index, file] of getUserstylesFiles(stylesDir).entries()) {
const content = await fs.promises.readFile(file, "utf8");
const { metadata } = usercssMeta.parse(content);
if ("updateURL" in metadata) {
delete metadata.updateURL;
}
const fileInfo = await fs.promises.stat(file);
const mtime = fileInfo.mtime ? fileInfo.mtime.getTime() : 0;
const vars = metadata.vars || {};
const lessVars = Object.entries(vars).map(
([name, info]) =>
bakeUserstyleVar(name, info, metadata, userstylesOptions),
).join("\n");
for (const key in metadata.vars) {
delete metadata.vars[key];
}
const userstyleBlockNoVars =
usercssMeta.stringify(metadata, { alignKeys: true }) + "\n";
const contentBakedVars = lessVars + "\n" +
content.replace(/\/\*\s*==UserStyle==[\s\S]*?==\/UserStyle==\s*\*\//, "");
const compiledCss = await (async () => {
try {
return (await less.render(contentBakedVars, { filename: file })).css;
} catch (err) {
throw new Error(`Failed to compile LESS in ${file}: ${err}`);
}
})();
const sections = (() => {
try {
return generateSections(userstyleBlockNoVars, compiledCss);
} catch (err) {
throw new Error(`Failed to compile LESS in ${file}: ${err}`);
}
})();
const userstyle = {
enabled: true,
name: metadata.name,
description: metadata.description,
author: metadata.author,
url: metadata.url,
usercssData: metadata,
sourceCode: userstyleBlockNoVars + contentBakedVars,
sections: sections,
_id: crypto.randomUUID(),
_rev: mtime,
id: index + 1,
} as Record<string, unknown>;
userstyle.originalDigest = await calcStyleDigest(userstyle);
data[`style-${index + 1}`] = userstyle;
}
return data;
}
(async () => {
const storageData = await generateStorageData();
await fs.promises.writeFile("storage.js", JSON.stringify(storageData));
})();
+1
View File
@@ -0,0 +1 @@
export function calcStyleDigest(userstyle: unknown): Promise<string>;
+143
View File
@@ -0,0 +1,143 @@
// https://raw.githubusercontent.com/openstyles/stylus/8fe35a4b90d85fb911bd7aa1deab4e4733c31150/src/js/sections-util.js
export const TO_CSS = {
urls: 'url',
urlPrefixes: 'url-prefix',
domains: 'domain',
regexps: 'regexp',
};
export const FROM_CSS = {
'url': 'urls',
'url-prefix': 'urlPrefixes',
'domain': 'domains',
'regexp': 'regexps',
};
/**
* @param {Object} section
* @param {function(func:string, value:string)} fn
*/
export const forEachProp = (section, fn) => {
for (const [propName, func] of Object.entries(TO_CSS)) {
section[propName]?.forEach(value => fn(func, value));
}
};
/**
* @param {Array<?[type,value]>} funcItems
* @param {?Object} [section]
* @returns {Object} section
*/
export const toSection = (funcItems, section = {}) => {
for (const item of funcItems) {
const [func, value] = item || [];
const propName = FROM_CSS[func];
if (propName) {
const props = section[propName] || (section[propName] = []);
if (Array.isArray(value)) props.push(...value);
else props.push(value);
}
}
return section;
};
/**
* @param {StyleObj} style
* @returns {string}
*/
export const styleToCss = style => {
const res = [];
for (const section of style.sections) {
const funcs = [];
forEachProp(section, (type, value) =>
funcs.push(`${type}("${value.replace(/[\\"]/g, '\\$&')}")`));
res.push(funcs.length
? `@-moz-document ${funcs.join(', ')} {\n${section.code}\n}`
: section.code);
}
return res.join('\n\n');
};
const STYLE_CODE_EMPTY_RE = /\s+|\/\*([^*]+|\*(?!\/))*(\*\/|$)|@namespace[^;]+;|@charset[^;]+;/giyu;
const abEqual = (a, b) => a === b;
const SECTION_TARGETS = ['urls', 'urlPrefixes', 'domains', 'regexps'];
/** @param {StyleSection} sec */
export function styleCodeEmpty(sec) {
const { code } = sec;
let res = !code;
if (res || (res = sec._empty) != null) return res;
const len = code.length;
const rx = STYLE_CODE_EMPTY_RE; rx.lastIndex = 0;
let i = 0; while (rx.exec(code) && (i = rx.lastIndex) !== len) {/**/ }
Object.defineProperty(sec, '_empty', { value: res = i === len, configurable: true });
styleCodeEmpty.lastIndex = i;
return res;
}
/**
* The sections are checked in successive order because it matters when many sections
* match the same URL and they have rules with the same CSS specificity
* @param {Object} a - first style object
* @param {Object} b - second style object
* @returns {?boolean}
*/
export function styleSectionsEqual({ sections: a }, { sections: b }) {
return a && b && a.length === b.length && a.every(sameSection, b);
}
function sameSection(secA, i) {
if (!equalOrEmpty(secA.code, this[i].code, 'string', abEqual)) {
return;
}
for (const target of SECTION_TARGETS) {
if (!equalOrEmpty(secA[target], this[i][target], 'array', arrayMirrors)) {
return;
}
}
return true;
}
function equalOrEmpty(a, b, type, comparator) {
const typeA = type === 'array' ? Array.isArray(a) : typeof a === type;
const typeB = type === 'array' ? Array.isArray(b) : typeof b === type;
return typeA && typeB && comparator(a, b) ||
(a == null || typeA && !a.length) &&
(b == null || typeB && !b.length);
}
function arrayMirrors(a, b) {
return a.length === b.length &&
a.every(thisIncludes, b) &&
b.every(thisIncludes, a);
}
function thisIncludes(el) {
return this.includes(el);
}
export async function calcStyleDigest(style) {
// retain known properties in an arbitrarily predefined order
const src = style.usercssData
? style.sourceCode
// retain known properties in an arbitrarily predefined order
: JSON.stringify((style.sections || []).map(section => ({
code: section.code || '',
urls: section.urls || [],
urlPrefixes: section.urlPrefixes || [],
domains: section.domains || [],
regexps: section.regexps || [],
})));
const srcBytes = new TextEncoder().encode(src);
const res = await crypto.subtle.digest('SHA-1', srcBytes);
return Array.from(new Uint8Array(res), b => (0x100 + b).toString(16).slice(1)).join('');
}
export function styleJSONseemsValid(json) {
return json
&& typeof json.name == 'string'
&& json.name.trim()
&& Array.isArray(json.sections)
&& typeof json.sections[0]?.code === 'string';
}
+223
View File
@@ -0,0 +1,223 @@
declare namespace usercssMeta {
export const ParseError: ParseError;
export interface ParseError extends Error {
code:
| "invalidCheckboxDefault"
| "invalidRange"
| "invalidRangeMultipleUnits"
| "invalidRangeTooManyValues"
| "invalidRangeValue"
| "invalidRangeDefault"
| "invalidRangeMin"
| "invalidRangeMax"
| "invalidRangeStep"
| "invalidRangeUnits"
| "invalidNumber"
| "invalidSelect"
| "invalidSelectValue"
| "invalidSelectEmptyOptions"
| "invalidSelectLabel"
| "invalidSelectMultipleDefaults"
| "invalidSelectNameDuplicated"
| "invalidString"
| "invalidURLProtocol"
| "invalidVersion"
| "invalidWord"
| "missingChar"
| "missingEOT"
| "missingMandatory"
| "missingValue"
| "unknownJSONLiteral"
| "unknownMeta"
| "unknownVarType";
message: string;
/**
* The string index where the error occurs
*/
index: number;
/**
* An array of values that is used to compose the error message.
* This allows other clients to generate i18n error message.
*/
args: unknown[];
}
// TODO: export util types
// export const util: {};
/**
* This is a shortcut of `createParser(options).parse(text);`
*/
export function parse(
content: string,
options?: ParserOptions,
): ParseResult;
/**
* Create a metadata parser.
*/
export function createParser(options?: ParserOptions): Parser;
// TODO: export stringify types
export function stringify(
metadata: Metadata,
options: StringifierOptions,
): string;
// export function createStringifier(options: StringifierOptions): Stringifier;
type Parser = {
/**
* Parse the text (metadata header) and return the result.
*/
parse: typeof parse;
/**
* Validate the value of the variable object.
* This function uses the validators defined in `createParser`.
*/
validateVar: (varObj: VarObj) => void;
};
type ParserOptions = {
/**
* `unknownKey` decides how to parse unknown keys. Possible values are:
* - `ignore`: The directive is ignored. Default.
* - `assign`: Assign the text value (characters before `\s*\n`) to result object.
* - `throw`: Throw a `ParseError`.
* @default "ignore"
*/
unknownKey?: "ignore" | "assign" | "throw";
/**
* mandatoryKeys marks multiple keys as mandatory. If some keys are missing then throw a ParseError
* @default ["name", "namespace", "version"]
*/
mandatoryKeys?: string[];
/**
* A `key`/`parseFunction` map.
* It allows users to extend the parser.
*
* @example
* const parser = createParser({
* mandatoryKeys: [],
* parseKey: {
* myKey: util.parseNumber
* }
* });
* const {metadata} = parser.parse(`
* /* ==UserStyle==
* \@myKey 123456
* ==/UserStyle==
* `);
* assert.equal(metadata.myKey, 123456);
*/
parseKey?: Record<string, unknown>;
/**
* A `variableType`/`parseFunction` map.
* It extends the parser to parse additional variable types.
*
* @example
* const parser = createParser({
* mandatoryKeys: [],
* parseVar: {
* myvar: util.parseNumber
* }
* });
* const {metadata} = parser.parse(`/* ==UserStyle==
* \@var myvar var-name 'Customized variable' 123456
* ==/UserStyle== *\/`);
* const va = metadata.vars['var-name'];
* assert.equal(va.type, 'myvar');
* assert.equal(va.label, 'Customized variable');
* assert.equal(va.default, 123456);
*/
parseVar?: Record<string, unknown>;
/**
* A `key`/`validateFunction` map, which is used to validate the metadata value.
* The function accepts a state object.
*
* @example
* const parser = createParser({
* validateKey: {
* updateURL: state => {
* if (/example\.com/.test(state.value)) {
* throw new ParseError({
* message: 'Example.com is not a good URL',
* index: state.valueIndex
* });
* }
* }
* }
* });
*/
validateKey?: Record<string, validateFn>;
/**
* A `variableType`/`validateFunction` map, which is used to validate variables.
* The function accepts a state object.
*
* @example
* const parser = createParser({
* validateVar: {
* color: state => {
* if (state.value === 'red') {
* throw new ParseError({
* message: '`red` is not allowed',
* index: state.valueIndex
* });
* }
* }
* }
* });
*/
validateVar?: Record<string, (state: StateObject) => void>;
/**
* If allowErrors is true, the parser will collect parsing errors while
* `parser.parse()` and return them as {@link ParseResult.errors}
* Otherwise, the first parsing error will be thrown.
* @default false
*/
allowErrors?: boolean;
};
export type StateObject = {
key: string;
type: string;
value: string;
varResult: unknown;
text: string;
lastIndex: number;
valueIndex: number;
shouldIgnore: boolean;
};
type validateFn = (state: StateObject) => void;
type VarObj = {
label: string;
name: string;
value?: string;
default?: string;
options?: unknown;
};
type Metadata = {
vars: VarObj[];
[key: string]: unknown;
};
type ParseResult = {
metadata: Metadata;
errors: ParseError[];
};
}
declare module "usercss-meta" {
export = usercssMeta;
}
+18
View File
@@ -0,0 +1,18 @@
{
"compilerOptions": {
"moduleResolution": "nodenext",
"target": "es2020",
"module": "nodenext",
"lib": [
"es2020"
],
"outDir": "dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true
},
"include": [
"."
]
}