lilith-skill 0.0.0-stage → 0.1.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.
- package/LICENSE +21 -0
- package/README.md +132 -2
- package/THIRD_PARTY_NOTICES.md +79 -0
- package/bin/lilith.mjs +147 -0
- package/package.json +43 -4
- package/skills/lilith/SKILL.md +61 -0
- package/skills/lilith/agents/openai.yaml +4 -0
- package/skills/lilith/checks/firebase_check.md +45 -0
- package/skills/lilith/checks/supabase_check.sql +211 -0
- package/skills/lilith/guides/cleanup-code.md +56 -0
- package/skills/lilith/guides/cleanup-ui.md +54 -0
- package/skills/lilith/guides/fixes/S1.md +6 -0
- package/skills/lilith/guides/fixes/S10.md +3 -0
- package/skills/lilith/guides/fixes/S11.md +3 -0
- package/skills/lilith/guides/fixes/S12.md +3 -0
- package/skills/lilith/guides/fixes/S13.md +3 -0
- package/skills/lilith/guides/fixes/S14.md +9 -0
- package/skills/lilith/guides/fixes/S2.md +15 -0
- package/skills/lilith/guides/fixes/S3.md +25 -0
- package/skills/lilith/guides/fixes/S4.md +11 -0
- package/skills/lilith/guides/fixes/S5.md +3 -0
- package/skills/lilith/guides/fixes/S6.md +7 -0
- package/skills/lilith/guides/fixes/S7.md +16 -0
- package/skills/lilith/guides/fixes/S8.md +11 -0
- package/skills/lilith/guides/fixes/S9.md +3 -0
- package/skills/lilith/guides/fixing.md +9 -0
- package/skills/lilith/guides/security-core.md +66 -0
- package/skills/lilith/guides/server.md +73 -0
- package/skills/lilith/guides/stacks/ai.md +14 -0
- package/skills/lilith/guides/stacks/firebase.md +13 -0
- package/skills/lilith/guides/stacks/stripe.md +13 -0
- package/skills/lilith/guides/stacks/supabase.md +31 -0
- package/skills/lilith/guides/ui/charts.md +10 -0
- package/skills/lilith/guides/ui/examples.md +30 -0
- package/skills/lilith/guides/ui/surface.md +11 -0
- package/skills/lilith/scripts/count_tells.py +384 -0
- package/skills/lilith/scripts/lilith_scan.py +750 -0
- package/skills/lilith/templates/report.md +64 -0
- package/src/agents.mjs +54 -0
- package/src/install.mjs +71 -0
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
# AI API details (load when the scanner detects OpenAI, Anthropic or another AI SDK)
|
|
2
|
+
|
|
3
|
+
## S2
|
|
4
|
+
`new OpenAI(` / `new Anthropic(` in browser code, `dangerouslyAllowBrowser: true`, `VITE_OPENAI_API_KEY`, direct calls to `api.openai.com` from React: the key ships to every visitor.
|
|
5
|
+
|
|
6
|
+
## S8 (🟠 for AI endpoints)
|
|
7
|
+
- Require login for AI endpoints and add a per-user limit; cap `max_tokens` and the length of user input.
|
|
8
|
+
- Clients that send the whole message history let one user grow every request.
|
|
9
|
+
- Owner checklist: monthly spending limit in the AI provider dashboard.
|
|
10
|
+
|
|
11
|
+
## S9 / S11
|
|
12
|
+
- Model output rendered with `dangerouslySetInnerHTML` or a Markdown renderer allowing raw HTML: prompt-injected documents can run script.
|
|
13
|
+
- System prompts with discount codes, internal URLs or logins: any user can extract them.
|
|
14
|
+
- Tools that write data or send messages: scope them to the current user and ask before acting.
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
# Firebase details (load when the scanner detects Firebase)
|
|
2
|
+
|
|
3
|
+
## S3: rules
|
|
4
|
+
- `firestore.rules` / `storage.rules` / `database.rules.json` with `allow read, write: if true;`, `".read": true`, or a test-mode `request.time < timestamp.date(...)`: open to everyone.
|
|
5
|
+
- `if request.auth != null` on data that belongs to one user (users, orders, messages): any logged-in user can read or change everyone's data, and signing up is free.
|
|
6
|
+
- A wildcard `match /{document=**}` with a broad `allow` covers every collection, including future ones.
|
|
7
|
+
- Deployed rules can differ from the repo: follow `checks/firebase_check.md` (the user pastes the live rules).
|
|
8
|
+
|
|
9
|
+
## S4
|
|
10
|
+
Server code must verify the ID token (`admin.auth().verifyIdToken`) before trusting a user id.
|
|
11
|
+
|
|
12
|
+
## S10
|
|
13
|
+
`storage.rules` should limit each user to their own path (`request.auth.uid == userId`).
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
# Stripe and payments details (load when the scanner detects Stripe or another payment provider)
|
|
2
|
+
|
|
3
|
+
## S6
|
|
4
|
+
- `unit_amount`, `price` or `amount` taken from the request body: look prices up on the server (Stripe Price IDs or your database).
|
|
5
|
+
- Plans and credits granted from request fields instead of from the verified payment.
|
|
6
|
+
|
|
7
|
+
## S7
|
|
8
|
+
- Webhook handlers need `stripe.webhooks.constructEvent(rawBody, signature, whsec)` (or `constructEventAsync`). Lemon Squeezy, Paddle, Clerk (svix) and GitHub have their own signature checks.
|
|
9
|
+
- Signature verification needs the raw body: `req.text()` / `express.raw`, not `req.json()` first.
|
|
10
|
+
- Access must be granted only from the verified webhook. A success page (`?success=true`, `?paid=1`) that updates the plan lets anyone skip paying.
|
|
11
|
+
|
|
12
|
+
## Not secrets
|
|
13
|
+
Stripe publishable keys (`pk_live_`, `pk_test_`) belong in the browser.
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
# Supabase details (load when the scanner detects Supabase)
|
|
2
|
+
|
|
3
|
+
## S2
|
|
4
|
+
`createClient(url, SERVICE_ROLE)` or a `service_role` key anywhere in browser code: the service role skips every database rule.
|
|
5
|
+
|
|
6
|
+
## S3: Row Level Security (RLS)
|
|
7
|
+
- In `supabase/migrations/*.sql`, every `create table` in `public` needs `alter table ... enable row level security;`.
|
|
8
|
+
- Policies with `using (true)` or `with check (true)` for update/delete/all let anyone do it. Insert-only `with check (true)` is fine for a contact form (add a rate limit).
|
|
9
|
+
- `for select to authenticated using (true)`: every logged-in user reads every row (S5).
|
|
10
|
+
- An update policy without column limits lets users change their own `role`, `is_admin` or `plan` (S6).
|
|
11
|
+
- `insert into storage.buckets (..., public) values (..., true)` for private files (S10).
|
|
12
|
+
- Migrations are not the live database. Always run the live check below.
|
|
13
|
+
|
|
14
|
+
## Live check (2 minutes, do this whenever the stack has Supabase)
|
|
15
|
+
1. Tell the user: "This query only reads your database settings (which tables are protected and how), never the data inside them, and changes nothing."
|
|
16
|
+
2. Where: Supabase dashboard → project → **SQL Editor** → **New query**.
|
|
17
|
+
3. Copy the query into their project without reading it (saves ~3,000 tokens): `cp <this-skill-folder>/checks/supabase_check.sql ./lilith-supabase-check.sql`. Tell them to open that file, copy everything into the SQL Editor, click **Run**, paste the result table back, then delete the file (it holds no secrets, but it doesn't belong in the app). Only if they can't open files (web chat, phone), read the file and give it to them in one code block.
|
|
18
|
+
4. Turn each row into what / why / fix. `severity` critical → 🔴, high → 🟠, medium → 🟡, info → 💡 (✅ for `all_checks_passed`). Explain `fix_sql` before offering it; they run it, never you.
|
|
19
|
+
5. `rls_disabled`, `policies_ignored`, `open_write_policy` confirm S3 leads from the code: merge, don't repeat.
|
|
20
|
+
6. Point them to **Advisors → Security Advisor** for the fuller official check.
|
|
21
|
+
If they skip: the report says **Live database: NOT checked**, and running the check goes on their list.
|
|
22
|
+
|
|
23
|
+
## S4 / S5
|
|
24
|
+
- On the server use `supabase.auth.getUser()` (verifies the token), not `getSession()` alone (reads a cookie the user can change).
|
|
25
|
+
- Prefer the user's own client (RLS applies) over the service-role client; with the service role, filter by owner yourself.
|
|
26
|
+
|
|
27
|
+
## S10
|
|
28
|
+
Private buckets + signed URLs; storage policies limiting each user to their folder: `(storage.foldername(name))[1] = auth.uid()::text`.
|
|
29
|
+
|
|
30
|
+
## Owner checklist
|
|
31
|
+
Security Advisor shows no errors; Auth → email confirmation on, minimum password length 8+.
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
# Charts and dashboards (U12 to U16)
|
|
2
|
+
|
|
3
|
+
Load when the scanner lists a chart library or the screen has charts. Same rule of the cut: same chart type, same data, same series colors.
|
|
4
|
+
|
|
5
|
+
- **U12.** Title names the chart type ("Bar chart of revenue") → "Monthly revenue".
|
|
6
|
+
- **U13.** "Hover for details", "Each bar is a month" → delete.
|
|
7
|
+
- **U14.** The same value said 3 times (bar + label + gridline + sentence) → keep one. KPI: number, one direction cue, period ("▲ 12% vs last month").
|
|
8
|
+
- **U15.** Boxes, heavy gridlines, 3D, shadows and glows on chart marks → delete or make hairline gray.
|
|
9
|
+
- **U16.** Legend for 1 to 4 series → label lines directly.
|
|
10
|
+
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
# Before and after
|
|
2
|
+
|
|
3
|
+
Read when unsure how far to cut.
|
|
4
|
+
|
|
5
|
+
**Hero with eyebrow (U1, U3, U8)**
|
|
6
|
+
```html
|
|
7
|
+
<p class="text-xs uppercase tracking-widest">Introducing Ledger</p>
|
|
8
|
+
<h1>Finance. Simplified. Finally.</h1>
|
|
9
|
+
<p>The all-in-one platform that helps modern teams seamlessly manage their money.</p>
|
|
10
|
+
```
|
|
11
|
+
→ `<h1>Manage your team's money</h1>`. The eyebrow goes; the slogan becomes the one thing the subtitle actually said; nothing new is invented (no numbers, no features the page doesn't name).
|
|
12
|
+
|
|
13
|
+
**Numbered feature (U2, U4)**
|
|
14
|
+
`<span>01 //</span><h3>Smart sync</h3><p>Our smart sync feature automatically keeps your files in sync across all of your devices.</p>`
|
|
15
|
+
→ `<h3>Smart sync</h3><p>Your files stay in sync across your devices.</p>`. The order isn't real, so the number goes; the description keeps only what the title doesn't say.
|
|
16
|
+
|
|
17
|
+
**Card that explains itself (U4, U5)**
|
|
18
|
+
`<CardDescription>This card shows your most recent activity (updates in real time).</CardDescription>` → delete it; the title "Recent activity" and the list say it.
|
|
19
|
+
|
|
20
|
+
**Badge with and without state (U9)**
|
|
21
|
+
`<Badge>LIVE</Badge>` always rendered → delete. `{stream.isLive && <Badge>Live</Badge>}` → keep: it reflects real state.
|
|
22
|
+
|
|
23
|
+
**Form field (U7)**
|
|
24
|
+
Label "Email", placeholder "Enter your email address", helper "We'll use this email to contact you" → keep the visible label; the placeholder becomes a format (`name@company.com`) or goes; the helper goes. A real constraint ("At least 12 characters") stays.
|
|
25
|
+
|
|
26
|
+
**Empty state (U4)**
|
|
27
|
+
"Oops! Looks like there's nothing here yet! 🎉" → "No invoices yet. Create one to send it to a client."
|
|
28
|
+
|
|
29
|
+
**Claim you cannot verify**
|
|
30
|
+
"Trusted by 10,000+ teams", a testimonial with a name → don't edit or delete; list as a task for the owner to confirm or remove.
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# Surface (U17 to U20)
|
|
2
|
+
|
|
3
|
+
Only when the user asks for visual cleanup. If the project has tokens (Tailwind theme, CSS variables, a design-system package), fix toward those values.
|
|
4
|
+
|
|
5
|
+
- **U17. Gradients and glows.** Purple-to-blue gradients, gradient text (`bg-clip-text`), colored glows (`shadow-purple-500/50`), blurred blobs → solid neutral surface, solid text, small neutral shadow `0 1px 2px rgb(0 0 0 / 0.05)` or a hairline border.
|
|
6
|
+
- **U18. Random spacing.** `mt-[13px]`, `gap: 7px` → nearest of 4, 8, 12, 16, 20, 24, 32, 40, 48, 64.
|
|
7
|
+
- **U19. Extra-heavy fonts.** `font-black`, `font-extrabold`, 800/900 → 600 or 500.
|
|
8
|
+
- **U20. Bouncy motion.** `transition-all`, `hover:scale-105` on cards, `animate-bounce` → `transition-colors` 150ms ease-out; buttons may press to 0.97.
|
|
9
|
+
|
|
10
|
+
Never change the palette, font family, sizes, radii or section order. Replace a value, don't redesign.
|
|
11
|
+
|
|
@@ -0,0 +1,384 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Count UI slop candidates in a file or folder.
|
|
3
|
+
|
|
4
|
+
Derived from MIT-licensed work (license in THIRD_PARTY_NOTICES.md). Compact text
|
|
5
|
+
output by default; --json keeps the original JSON format.
|
|
6
|
+
|
|
7
|
+
Usage: python3 count_tells.py [--surface] [--json] [--max N] <file-or-folder> [...]
|
|
8
|
+
|
|
9
|
+
Prints one line per rule with hits (count and up to 3 places), then the total.
|
|
10
|
+
--json prints the original format:
|
|
11
|
+
{rule: {"count": n, "examples": ["file:line", ...]}, "total": n}.
|
|
12
|
+
Regex heuristic for before/after comparison. It misses tells that need
|
|
13
|
+
reading (U3, U4, U5, U7, U8, U14) and can flag legitimate cases.
|
|
14
|
+
--surface adds the visual rules U17 to U20 (gradients and glows, off-scale
|
|
15
|
+
spacing, extra-heavy weights, motion).
|
|
16
|
+
--max N exits 1 when the total is above N, for CI.
|
|
17
|
+
"""
|
|
18
|
+
import argparse
|
|
19
|
+
import bisect
|
|
20
|
+
import json
|
|
21
|
+
import os
|
|
22
|
+
import re
|
|
23
|
+
import sys
|
|
24
|
+
|
|
25
|
+
KINDS = {
|
|
26
|
+
"markup": {".html", ".htm", ".jsx", ".tsx", ".js", ".mjs", ".cjs", ".ts", ".vue", ".svelte", ".astro"},
|
|
27
|
+
"prose": {".md", ".mdx"},
|
|
28
|
+
"style": {".css", ".scss", ".less"},
|
|
29
|
+
"data": {".json"},
|
|
30
|
+
"python": {".py"},
|
|
31
|
+
}
|
|
32
|
+
KIND_OF = {ext: kind for kind, exts in KINDS.items() for ext in exts}
|
|
33
|
+
SKIP_DIRS = {"node_modules", ".git", "dist", "build", ".next", ".svelte-kit", ".astro", "coverage", ".venv", "venv", "__pycache__"}
|
|
34
|
+
SKIP_FILES = {"package-lock.json", "package.json"}
|
|
35
|
+
# Minified bundles and data dumps are not hand-written interface code.
|
|
36
|
+
MAX_BYTES = 1_000_000
|
|
37
|
+
# Enough to show where to look without flooding the agent's context.
|
|
38
|
+
MAX_EXAMPLES = 5
|
|
39
|
+
|
|
40
|
+
ALL = set(KINDS)
|
|
41
|
+
TEXT = ALL - {"style"}
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def blank(match):
|
|
45
|
+
return re.sub(r"[^\n]", " ", match.group(0))
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
COMMENTS = {
|
|
49
|
+
"block": re.compile(r"^[ \t]*/\*.*?\*/", re.S | re.M),
|
|
50
|
+
"jsx": re.compile(r"\{/\*.*?\*/\}", re.S),
|
|
51
|
+
"html": re.compile(r"<!--.*?-->", re.S),
|
|
52
|
+
"line": re.compile(r"^[ \t]*//.*$", re.M),
|
|
53
|
+
# After code punctuation only, so "https://" and a "01 // Features" text node survive.
|
|
54
|
+
"trailing": re.compile(r"(?<=[;,{}()\[\]])[ \t]*//(?!/)[^<\n]*$", re.M),
|
|
55
|
+
"hash": re.compile(r"^[ \t]*#.*$", re.M),
|
|
56
|
+
}
|
|
57
|
+
COMMENTS_FOR = {
|
|
58
|
+
"markup": ("jsx", "html", "block", "line", "trailing"),
|
|
59
|
+
"prose": ("jsx", "html"),
|
|
60
|
+
"style": ("block", "line"),
|
|
61
|
+
"data": (),
|
|
62
|
+
"python": ("hash",),
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def strip_comments(text, kind):
|
|
67
|
+
"""Blank comments out, keeping every offset and line number."""
|
|
68
|
+
for name in COMMENTS_FOR[kind]:
|
|
69
|
+
text = COMMENTS[name].sub(blank, text)
|
|
70
|
+
return text
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def rx(pattern, flags=0):
|
|
74
|
+
regex = re.compile(pattern, flags)
|
|
75
|
+
return lambda text: [m.start() for m in regex.finditer(text)]
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def once_per_line(find):
|
|
79
|
+
"""One hit per line, for patterns where two matches are one sentence."""
|
|
80
|
+
def wrapped(text):
|
|
81
|
+
hits, last_line_start = [], -1
|
|
82
|
+
for pos in find(text):
|
|
83
|
+
line_start = text.rfind("\n", 0, pos) + 1
|
|
84
|
+
if line_start != last_line_start:
|
|
85
|
+
hits.append(pos)
|
|
86
|
+
last_line_start = line_start
|
|
87
|
+
return hits
|
|
88
|
+
|
|
89
|
+
return wrapped
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def enclosing_tag(text, pos):
|
|
93
|
+
"""Name of the tag opened last before pos, or ''."""
|
|
94
|
+
start = text.rfind("<", max(0, pos - 400), pos + 1)
|
|
95
|
+
match = re.match(r"</?([A-Za-z][\w.]*)", text[start:start + 60]) if start != -1 else None
|
|
96
|
+
return match.group(1) if match else ""
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def quoted_segment(text, pos):
|
|
100
|
+
"""The string literal around pos, or its line when there are no quotes."""
|
|
101
|
+
lo = max(0, pos - 400)
|
|
102
|
+
before = max(text.rfind(q, lo, pos) for q in "\"'`")
|
|
103
|
+
after = [i for i in (text.find(q, pos, pos + 400) for q in "\"'`") if i != -1]
|
|
104
|
+
if before == -1 or not after:
|
|
105
|
+
return text.rfind("\n", 0, pos) + 1, (text.find("\n", pos) + 1 or len(text))
|
|
106
|
+
return before + 1, min(after)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
# U1: uppercase plus widened tracking in one class string. Table headers and
|
|
110
|
+
# key caps use the same styling and are not eyebrows.
|
|
111
|
+
EYEBROW = re.compile(
|
|
112
|
+
r"\buppercase\b[^\"'`<>]{0,200}?\btracking-(?!tight|normal)"
|
|
113
|
+
r"|\btracking-(?!tight|normal)[^\"'`<>]{0,200}?\buppercase\b"
|
|
114
|
+
r"|text-transform:\s*uppercase|textTransform:\s*[\"']uppercase"
|
|
115
|
+
)
|
|
116
|
+
NOT_EYEBROW_TAGS = {"th", "TableHead", "TableHeader", "kbd", "abbr"}
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def eyebrows(text):
|
|
120
|
+
return [m.start() for m in EYEBROW.finditer(text) if enclosing_tag(text, m.start()) not in NOT_EYEBROW_TAGS]
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
# U2: "01", "01.", "01 //" as text, a zero-padded index, or "//" used as an
|
|
124
|
+
# ornament inside a text node. Dates and times ("01/02", "01:30") are not it.
|
|
125
|
+
NUMBERING = (
|
|
126
|
+
r">\s*0[1-9](?![/:.\-]\d)(?:\s|<|\.|/)"
|
|
127
|
+
r"|(?<![=\w])['\"`]0[1-9]['\"`]"
|
|
128
|
+
r"|>[^<>{}\n]*?(?<!:)//[^<>\n]*<"
|
|
129
|
+
r"|padStart\(\s*2\s*,\s*['\"`]0['\"`]\s*\)"
|
|
130
|
+
r"|>\s*0\{"
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
# U6: two or more separators close together make a chain. One separator
|
|
134
|
+
# ("Jan 3 · 14:02") is ordinary punctuation.
|
|
135
|
+
SEPARATOR = re.compile(r"·|•|·|·|•|\\u00b7|\\u2022")
|
|
136
|
+
JOINED = re.compile(r"join\(\s*['\"`]\s*(?:·|•|\|)\s*['\"`]\s*\)")
|
|
137
|
+
PIPED = re.compile(r">[^<>{}\n]*\s\|\s[^<>{}\n]*\s\|\s[^<>{}\n]*<")
|
|
138
|
+
CHAIN_GAP = 200
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def status_strings(text):
|
|
142
|
+
hits = [m.start() for m in JOINED.finditer(text)] + [m.start() for m in PIPED.finditer(text)]
|
|
143
|
+
cluster = []
|
|
144
|
+
for pos in [m.start() for m in SEPARATOR.finditer(text)] + [None]:
|
|
145
|
+
if cluster and (pos is None or pos - cluster[-1] > CHAIN_GAP):
|
|
146
|
+
if len(cluster) > 1:
|
|
147
|
+
hits.append(cluster[0])
|
|
148
|
+
cluster = []
|
|
149
|
+
if pos is not None:
|
|
150
|
+
cluster.append(pos)
|
|
151
|
+
return hits
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
# U9: a flavor word standing alone in a text node. Uppercase words count
|
|
155
|
+
# anywhere except inside a control; "New", "Pro" and friends only inside
|
|
156
|
+
# something badge-shaped, because <Button>New</Button> is an action.
|
|
157
|
+
BADGE_NODE = re.compile(
|
|
158
|
+
r">\s*(?:(LIVE|NEW|BETA|AI|PRO|HOT)|(Live|New|Beta|Pro|Hot|Popular|Most popular|Coming soon|Featured|Trending|AI-powered|Powered by AI))\s*<"
|
|
159
|
+
)
|
|
160
|
+
BADGE_LITERAL = re.compile(r"['\"`](?:LIVE|NEW|BETA|HOT)['\"`]")
|
|
161
|
+
CONTROL_TAGS = {
|
|
162
|
+
"button", "Button", "a", "Link", "NavLink", "option", "label", "Label", "th", "td", "title",
|
|
163
|
+
"MenuItem", "DropdownMenuItem", "SelectItem", "CommandItem", "TabsTrigger", "Tab",
|
|
164
|
+
"h1", "h2", "h3", "h4", "h5", "h6",
|
|
165
|
+
}
|
|
166
|
+
BADGE_TAGS = {"span", "sup", "small", "mark", "Badge", "Pill", "Chip", "Tag"}
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def badge_words(text):
|
|
170
|
+
hits = [m.start() for m in BADGE_LITERAL.finditer(text)]
|
|
171
|
+
for m in BADGE_NODE.finditer(text):
|
|
172
|
+
tag = enclosing_tag(text, m.start())
|
|
173
|
+
if tag in CONTROL_TAGS:
|
|
174
|
+
continue
|
|
175
|
+
if m.group(1) or tag in BADGE_TAGS:
|
|
176
|
+
hits.append(m.start())
|
|
177
|
+
return hits
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
# U10: a small round element, or a pulse that is not a loading skeleton.
|
|
181
|
+
DOT_TOKEN = re.compile(r"\brounded-full\b|\banimate-(?:pulse|ping)\b")
|
|
182
|
+
SMALL = r"(?:1|1\.5|2|2\.5|3|px)(?![\w.])"
|
|
183
|
+
SMALL_SIZE = re.compile(r"(?<![\w:-])size-" + SMALL)
|
|
184
|
+
SMALL_H = re.compile(r"(?<![\w:-])h-" + SMALL)
|
|
185
|
+
SMALL_W = re.compile(r"(?<![\w:-])w-" + SMALL)
|
|
186
|
+
SKELETON = re.compile(r"skeleton|\bbg-(?:muted|accent|secondary|(?:gray|slate|zinc|neutral|stone)-\d)", re.I)
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def status_dots(text):
|
|
190
|
+
hits, seen = [], set()
|
|
191
|
+
for m in DOT_TOKEN.finditer(text):
|
|
192
|
+
start, end = quoted_segment(text, m.start())
|
|
193
|
+
if start in seen:
|
|
194
|
+
continue
|
|
195
|
+
seen.add(start)
|
|
196
|
+
segment = text[start:end]
|
|
197
|
+
dot = "rounded-full" in segment and (
|
|
198
|
+
SMALL_SIZE.search(segment) or (SMALL_H.search(segment) and SMALL_W.search(segment))
|
|
199
|
+
)
|
|
200
|
+
skeleton = SKELETON.search(segment) or "skeleton" in enclosing_tag(text, start).lower()
|
|
201
|
+
if dot or "animate-ping" in segment or ("animate-pulse" in segment and not skeleton):
|
|
202
|
+
hits.append(start)
|
|
203
|
+
return hits
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
# U11: pictographs. Check marks and crosses (U+2713 to U+2718) are left out:
|
|
207
|
+
# they are usually the control or the value itself.
|
|
208
|
+
EMOJI = (
|
|
209
|
+
"[\U0001F300-\U0001FAFF\U00002600-\U00002712\U00002719-\U000027BF\U0001F000-\U0001F2FF"
|
|
210
|
+
"\U00002B50\U00002B55\U0000231A-\U0000231B\U000023E9-\U000023FA]"
|
|
211
|
+
)
|
|
212
|
+
|
|
213
|
+
# U11: an icon in a tinted tile. A small fixed-size box with a tinted fill and
|
|
214
|
+
# rounded corners whose first child is an icon. The icon-only control, an
|
|
215
|
+
# avatar and a tile that also holds text are not it.
|
|
216
|
+
CLASS_ATTR = re.compile(r"""class(?:Name)?\s*=\s*(?:"([^"]*)"|\{?\s*[`']([^`']*)[`']\s*\}?)""")
|
|
217
|
+
TILE_FILL = re.compile(r"(?<![\w:-])bg-(?!(?:white|transparent|black)\b)[a-z]+(?:-(?:50|100|200)\b|-\d{3}/\d{1,2}\b|/\d{1,2}\b)")
|
|
218
|
+
TILE_BOX = re.compile(r"(?<![\w:-])(?:size-(?:7|8|9|10|11|12)|(?:h|w)-(?:7|8|9|10|11|12))(?![\w.])")
|
|
219
|
+
TILE_ROUND = re.compile(r"(?<![\w:-])rounded(?:-(?:md|lg|xl|2xl|full))?(?![\w-])")
|
|
220
|
+
TILE_CHILD = re.compile(r"\s*>\s*<(?:svg\b|i\b|[A-Z]\w*\b[^<>]*/>)")
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def icon_tiles(text):
|
|
224
|
+
hits = []
|
|
225
|
+
for m in CLASS_ATTR.finditer(text):
|
|
226
|
+
classes = m.group(1) or m.group(2) or ""
|
|
227
|
+
if TILE_FILL.search(classes) and TILE_BOX.search(classes) and TILE_ROUND.search(classes):
|
|
228
|
+
if TILE_CHILD.match(text, m.end()):
|
|
229
|
+
hits.append(m.start())
|
|
230
|
+
return hits
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
CHART_TYPE_TITLE = r"\b(?:bar|line|pie|area|scatter|donut|column) (?:chart|graph|plot) (?:of|showing|for)\b"
|
|
234
|
+
READING_INSTRUCTIONS = r"\beach (?:bar|point|dot|line|slice|column|row) (?:represents|shows|is)\b|\bhover (?:over|for|to see)\b"
|
|
235
|
+
|
|
236
|
+
# U15 and U16 run on the whole file, so a config formatted over several
|
|
237
|
+
# lines counts the same as a one-liner.
|
|
238
|
+
SCAFFOLDING = (
|
|
239
|
+
r"feDropShadow|drop-shadow\(|shadowBlur|shadowColor|\bminor\s*:\s*\{"
|
|
240
|
+
r"|border\s*:\s*\{[^}]*\bwidth\s*:\s*(?:[2-9]|1\.[5-9])"
|
|
241
|
+
r"|grid\s*:\s*\{[^}]*\blineWidth\s*:\s*(?:[2-9]|1\.[5-9])"
|
|
242
|
+
)
|
|
243
|
+
SCAFFOLDING_PY = r"\.grid\([^)]*\b(?:linewidth|lw)\s*=\s*(?:[2-9]|1\.[5-9])|\bshadow\s*=\s*True"
|
|
244
|
+
LEGEND = r"legend\s*:\s*\{[^}]*\b(?:display|show)\s*:\s*true|\bshowlegend\s*:\s*true|<(?:Chart)?Legend\b"
|
|
245
|
+
LEGEND_PY = r"\.legend\(|\bshowlegend\s*=\s*True"
|
|
246
|
+
|
|
247
|
+
# A lone dash standing for "no value" is a table convention, not prose.
|
|
248
|
+
EM_DASH = re.compile(r"—|—|—|\\u2014")
|
|
249
|
+
LONE_DASH = re.compile(r"(?<=[\"'`>])\s*(?:—|—|—|\\u2014)\s*(?=[\"'`<])")
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def em_dashes(text):
|
|
253
|
+
return [m.start() for m in EM_DASH.finditer(LONE_DASH.sub(blank, text))]
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
# U18: odd pixel values, and anything over 16 that is not a multiple of 4.
|
|
257
|
+
# 2, 6, 10 and 14 are Tailwind's half steps (0.5, 1.5, 2.5, 3.5).
|
|
258
|
+
SPACING = re.compile(
|
|
259
|
+
r"(?<![\w-])-?(?:[mp][trblxyse]?|gap(?:-[xy])?|space-[xy])-\[(\d+)px\]"
|
|
260
|
+
r"|\b(?:margin|padding)(?:-(?:top|right|bottom|left))?\s*:\s*(\d+)px\s*(?:[;}\"']|$)"
|
|
261
|
+
r"|\bgap\s*:\s*(\d+)px",
|
|
262
|
+
re.M,
|
|
263
|
+
)
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def off_scale(text):
|
|
267
|
+
hits = []
|
|
268
|
+
for m in SPACING.finditer(text):
|
|
269
|
+
value = int(next(g for g in m.groups() if g))
|
|
270
|
+
if value % 2 or (value > 16 and value % 4):
|
|
271
|
+
hits.append(m.start())
|
|
272
|
+
return hits
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
MARKUP = {"markup", "prose"}
|
|
276
|
+
RULES = [
|
|
277
|
+
("U1 eyebrow", eyebrows, MARKUP | {"style"}),
|
|
278
|
+
("U2 decorative numbering", rx(NUMBERING), MARKUP),
|
|
279
|
+
("U6 status string", status_strings, TEXT),
|
|
280
|
+
("U9 badge word", badge_words, MARKUP | {"data"}),
|
|
281
|
+
("U10 status dot", status_dots, MARKUP),
|
|
282
|
+
("U11 emoji", rx(EMOJI), ALL),
|
|
283
|
+
("U11 icon tile", icon_tiles, MARKUP),
|
|
284
|
+
("U12 chart-type title", rx(CHART_TYPE_TITLE, re.I), TEXT),
|
|
285
|
+
("U13 reading instructions", once_per_line(rx(READING_INSTRUCTIONS, re.I)), TEXT),
|
|
286
|
+
("U15 chart scaffolding", rx(SCAFFOLDING), MARKUP),
|
|
287
|
+
("U15 chart scaffolding", rx(SCAFFOLDING_PY), {"python"}),
|
|
288
|
+
("U16 legend", rx(LEGEND), MARKUP),
|
|
289
|
+
("U16 legend", rx(LEGEND_PY), {"python"}),
|
|
290
|
+
("unslop 13 em dash", em_dashes, TEXT),
|
|
291
|
+
]
|
|
292
|
+
STYLED = MARKUP | {"style"}
|
|
293
|
+
SURFACE_RULES = [
|
|
294
|
+
("U17 gradient or glow", rx(
|
|
295
|
+
r"\bbg-(?:gradient|linear|radial|conic)-to?-?|(?:linear|radial|conic)-gradient\(|\bbg-clip-text\b|background-clip:\s*text"
|
|
296
|
+
r"|\bblur-(?:2xl|3xl)\b|\bshadow-\[0_0_|\bshadow-[a-z]+-\d{2,3}(?:/\d+)?\b|box-shadow:[^;]*\b0\s+0\s+\d+px"
|
|
297
|
+
), STYLED),
|
|
298
|
+
("U18 off-scale spacing", off_scale, STYLED),
|
|
299
|
+
("U19 extra-heavy weight", rx(
|
|
300
|
+
r"\bfont-(?:extrabold|black)\b|font-?[wW]eight\W{0,3}[89]00\b|\bfont-\[[89]00\]"
|
|
301
|
+
), STYLED),
|
|
302
|
+
("U20 motion", rx(
|
|
303
|
+
r"\btransition-all\b|transition:\s*all\b|\bhover:scale-|\banimate-bounce\b"
|
|
304
|
+
), STYLED),
|
|
305
|
+
]
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def iter_files(targets):
|
|
309
|
+
for target in targets:
|
|
310
|
+
if os.path.isfile(target):
|
|
311
|
+
yield target
|
|
312
|
+
continue
|
|
313
|
+
for root, dirs, files in os.walk(target):
|
|
314
|
+
dirs[:] = sorted(d for d in dirs if d not in SKIP_DIRS)
|
|
315
|
+
for name in sorted(files):
|
|
316
|
+
if name in SKIP_FILES or ".min." in name:
|
|
317
|
+
continue
|
|
318
|
+
if os.path.splitext(name)[1].lower() in KIND_OF:
|
|
319
|
+
yield os.path.join(root, name)
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def count(targets, surface=False):
|
|
323
|
+
rules = RULES + (SURFACE_RULES if surface else [])
|
|
324
|
+
results = {name: {"count": 0, "examples": []} for name, _, _ in rules}
|
|
325
|
+
for path in iter_files(targets):
|
|
326
|
+
# A file named on the command line is scanned whatever its extension.
|
|
327
|
+
kind = KIND_OF.get(os.path.splitext(path)[1].lower(), "markup")
|
|
328
|
+
try:
|
|
329
|
+
if os.path.getsize(path) > MAX_BYTES:
|
|
330
|
+
continue
|
|
331
|
+
with open(path, encoding="utf-8", errors="replace") as f:
|
|
332
|
+
text = strip_comments(f.read(), kind)
|
|
333
|
+
except OSError as e:
|
|
334
|
+
print("Skipped {}: {}".format(path, e), file=sys.stderr)
|
|
335
|
+
continue
|
|
336
|
+
line_starts = [m.end() for m in re.finditer(r"\n", text)]
|
|
337
|
+
for name, find, kinds in rules:
|
|
338
|
+
if kind not in kinds:
|
|
339
|
+
continue
|
|
340
|
+
entry = results[name]
|
|
341
|
+
for pos in sorted(find(text)):
|
|
342
|
+
entry["count"] += 1
|
|
343
|
+
if len(entry["examples"]) < MAX_EXAMPLES:
|
|
344
|
+
entry["examples"].append("{}:{}".format(path, bisect.bisect_right(line_starts, pos) + 1))
|
|
345
|
+
results["total"] = sum(r["count"] for r in results.values())
|
|
346
|
+
return results
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
def compact(results, examples=3):
|
|
350
|
+
"""Only rules with hits, one line each, then the total."""
|
|
351
|
+
lines = []
|
|
352
|
+
for name, entry in results.items():
|
|
353
|
+
if name == "total" or not entry["count"]:
|
|
354
|
+
continue
|
|
355
|
+
where = ", ".join(entry["examples"][:examples]) + (" ..." if entry["count"] > examples else "")
|
|
356
|
+
lines.append("{} {}: {}".format(name, entry["count"], where))
|
|
357
|
+
lines.append("total {}".format(results["total"]))
|
|
358
|
+
return "\n".join(lines)
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
def main():
|
|
362
|
+
parser = argparse.ArgumentParser(description="Count UI slop candidates in files or folders.")
|
|
363
|
+
parser.add_argument("targets", nargs="+", metavar="file-or-folder")
|
|
364
|
+
parser.add_argument("--surface", action="store_true", help="also count U17 to U20")
|
|
365
|
+
parser.add_argument("--max", type=int, metavar="N", help="exit 1 when the total is above N")
|
|
366
|
+
parser.add_argument("--json", action="store_true", help="print the full JSON result (original format)")
|
|
367
|
+
args = parser.parse_args()
|
|
368
|
+
|
|
369
|
+
missing = [t for t in args.targets if not os.path.exists(t)]
|
|
370
|
+
if missing:
|
|
371
|
+
print("Not found: " + ", ".join(missing), file=sys.stderr)
|
|
372
|
+
sys.exit(2)
|
|
373
|
+
|
|
374
|
+
results = count(args.targets, args.surface)
|
|
375
|
+
if args.json:
|
|
376
|
+
print(json.dumps(results, indent=2, ensure_ascii=False))
|
|
377
|
+
else:
|
|
378
|
+
print(compact(results))
|
|
379
|
+
if args.max is not None and results["total"] > args.max:
|
|
380
|
+
sys.exit(1)
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
if __name__ == "__main__":
|
|
384
|
+
main()
|