@workingpayload/agent-skills 1.0.0 → 2.0.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/APIForge/skill.md +150 -17
- package/AccessPlus/skill.md +122 -18
- package/AlgoMaster/skill.md +110 -17
- package/Architekt AI/skill.md +125 -17
- package/AuthCraft/skill.md +129 -17
- package/AutoScriptor/skill.md +122 -17
- package/BoilerCore/skill.md +121 -17
- package/BugHunter Pro/skill.md +118 -17
- package/ChangeScribe/skill.md +98 -17
- package/CodeSage/skill.md +148 -17
- package/CommitCraft/skill.md +97 -16
- package/CoverageMax/skill.md +145 -16
- package/CronGenius/skill.md +141 -16
- package/DataPolish/skill.md +126 -16
- package/DataWeaver/skill.md +135 -16
- package/DockMaster/skill.md +142 -16
- package/DocuGenie/skill.md +122 -16
- package/EdgeGuard/skill.md +144 -16
- package/EnvWizard/skill.md +140 -16
- package/ErrorMedic/skill.md +136 -16
- package/FeatureSmith/skill.md +123 -16
- package/FlexiLayout/skill.md +128 -16
- package/FlowTester/skill.md +138 -16
- package/FunctionForge/skill.md +120 -16
- package/InputShield/skill.md +128 -16
- package/IssueForge/skill.md +132 -16
- package/KubeCrafter/skill.md +133 -16
- package/LogicLens/skill.md +116 -16
- package/MockSmith/skill.md +130 -16
- package/ModelSensei/skill.md +122 -16
- package/PRMentor/skill.md +103 -32
- package/PerfDetective/skill.md +90 -32
- package/PipelinePro/skill.md +146 -32
- package/PolyglotShift/skill.md +94 -32
- package/PromptForge/skill.md +118 -32
- package/QueryPulse/skill.md +123 -32
- package/README.md +416 -329
- package/ReadMeCraft/skill.md +127 -32
- package/RefactorX/skill.md +84 -32
- package/RenderBoost/skill.md +148 -32
- package/SEOMancer/skill.md +140 -16
- package/ScrapeMaster/skill.md +157 -32
- package/SecretSniffer/skill.md +107 -16
- package/SecureScan/skill.md +114 -16
- package/ServiceSplitter/skill.md +137 -16
- package/SpeedSmith/skill.md +139 -16
- package/StackWise/skill.md +139 -16
- package/TaskOrchestrator/skill.md +119 -16
- package/TestCrafter/skill.md +142 -16
- package/TraceMind/skill.md +127 -16
- package/UISmith/skill.md +115 -16
- package/bin/cli.js +377 -0
- package/extension-extender/SKILL.md +122 -0
- package/fastapi-furious/SKILL.md +148 -0
- package/package.json +41 -28
- package/python-master/SKILL.md +108 -0
- package/react-ranger/SKILL.md +93 -0
- package/scripts/build_index.py +282 -0
- package/scripts/doctor.py +541 -0
- package/scripts/install.py +397 -0
- package/scripts/route.py +348 -0
- package/scripts/score.py +355 -0
- package/scripts/test_skill.py +473 -0
- package/scripts/validate.py +254 -0
- package/skills-routing.json +1131 -0
- package/skills.json +3261 -0
- package/Extension-Extender/SKILL.md +0 -41
- package/Extension-Extender/references/ui-guidelines.md +0 -26
- package/Fastapi-Furious/README.md +0 -16
- package/Fastapi-Furious/SKILL.md +0 -37
- package/Python-Master/README.md +0 -11
- package/Python-Master/SKILL.md +0 -37
- package/React-Ranger/README.md +0 -17
- package/React-Ranger/SKILL.md +0 -37
- package/cli.js +0 -181
- package/parse_skills.py +0 -44
- /package/{Extension-Extender → extension-extender}/assets/manifest.json +0 -0
- /package/{Extension-Extender → extension-extender}/assets/popup.css +0 -0
- /package/{Extension-Extender → extension-extender}/assets/popup.html +0 -0
- /package/{Extension-Extender → extension-extender}/assets/popup.js +0 -0
package/bin/cli.js
ADDED
|
@@ -0,0 +1,377 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
const { execSync, spawnSync } = require("child_process");
|
|
4
|
+
const fs = require("fs");
|
|
5
|
+
const path = require("path");
|
|
6
|
+
const os = require("os");
|
|
7
|
+
|
|
8
|
+
// ── Resolve paths ──────────────────────────────────────────────────
|
|
9
|
+
const PKG_ROOT = path.resolve(__dirname, "..");
|
|
10
|
+
const SCRIPTS_DIR = path.join(PKG_ROOT, "scripts");
|
|
11
|
+
const HOME = os.homedir();
|
|
12
|
+
|
|
13
|
+
const TARGETS = {
|
|
14
|
+
claude: path.join(HOME, ".claude", "commands"),
|
|
15
|
+
gemini: path.join(HOME, ".gemini", "commands"),
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
// ── Helpers ────────────────────────────────────────────────────────
|
|
19
|
+
function hasPython() {
|
|
20
|
+
for (const cmd of ["python3", "python"]) {
|
|
21
|
+
try {
|
|
22
|
+
execSync(`${cmd} --version`, { stdio: "ignore" });
|
|
23
|
+
return cmd;
|
|
24
|
+
} catch (_) {}
|
|
25
|
+
}
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function runPythonScript(scriptName, args = []) {
|
|
30
|
+
const py = hasPython();
|
|
31
|
+
if (!py) {
|
|
32
|
+
console.error("Error: Python 3 is required but not found in PATH.");
|
|
33
|
+
console.error("Install Python 3: https://python.org/downloads/");
|
|
34
|
+
process.exit(1);
|
|
35
|
+
}
|
|
36
|
+
const scriptPath = path.join(SCRIPTS_DIR, scriptName);
|
|
37
|
+
if (!fs.existsSync(scriptPath)) {
|
|
38
|
+
console.error(`Error: Script not found: ${scriptPath}`);
|
|
39
|
+
process.exit(1);
|
|
40
|
+
}
|
|
41
|
+
const result = spawnSync(py, [scriptPath, ...args], {
|
|
42
|
+
stdio: "inherit",
|
|
43
|
+
cwd: PKG_ROOT,
|
|
44
|
+
});
|
|
45
|
+
process.exit(result.status || 0);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function findSkillFiles() {
|
|
49
|
+
const skills = [];
|
|
50
|
+
const entries = fs.readdirSync(PKG_ROOT, { withFileTypes: true });
|
|
51
|
+
for (const entry of entries) {
|
|
52
|
+
if (!entry.isDirectory() || entry.name.startsWith(".") || entry.name === "node_modules" || entry.name === "bin" || entry.name === "scripts") continue;
|
|
53
|
+
const dir = path.join(PKG_ROOT, entry.name);
|
|
54
|
+
for (const fname of ["skill.md", "SKILL.md"]) {
|
|
55
|
+
const fpath = path.join(dir, fname);
|
|
56
|
+
if (fs.existsSync(fpath)) {
|
|
57
|
+
skills.push({ name: entry.name, file: fname, fullPath: fpath, dir: entry.name });
|
|
58
|
+
break;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return skills;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function slugify(name) {
|
|
66
|
+
return name.toLowerCase().replace(/\s+/g, "-").replace(/[^a-z0-9-]/g, "");
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// ── Commands ───────────────────────────────────────────────────────
|
|
70
|
+
|
|
71
|
+
function cmdInstall(args) {
|
|
72
|
+
const flags = parseFlags(args, { target: "t", skills: "s", force: null, "dry-run": null, validate: null });
|
|
73
|
+
|
|
74
|
+
// Detect target
|
|
75
|
+
let target = flags.target;
|
|
76
|
+
if (!target) {
|
|
77
|
+
if (fs.existsSync(TARGETS.claude)) target = "claude";
|
|
78
|
+
else if (fs.existsSync(TARGETS.gemini)) target = "gemini";
|
|
79
|
+
else target = "claude"; // default
|
|
80
|
+
}
|
|
81
|
+
if (!TARGETS[target]) {
|
|
82
|
+
console.error(`Unknown target: ${target}. Use "claude" or "gemini".`);
|
|
83
|
+
process.exit(1);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
const installDir = TARGETS[target];
|
|
87
|
+
const dryRun = flags["dry-run"] || false;
|
|
88
|
+
const force = flags.force || false;
|
|
89
|
+
|
|
90
|
+
// Ensure install directory
|
|
91
|
+
if (!dryRun) {
|
|
92
|
+
fs.mkdirSync(installDir, { recursive: true });
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// Find skills
|
|
96
|
+
let skills = findSkillFiles();
|
|
97
|
+
if (flags.skills) {
|
|
98
|
+
const wanted = new Set(flags.skills.split(",").map(s => s.trim().toLowerCase()));
|
|
99
|
+
skills = skills.filter(s => wanted.has(s.name.toLowerCase()) || wanted.has(slugify(s.name)));
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
console.log(`Target : ${target}`);
|
|
103
|
+
console.log(`Install: ${installDir}`);
|
|
104
|
+
console.log(`Skills : ${skills.length}`);
|
|
105
|
+
if (dryRun) console.log("[DRY RUN — no files will be written]\n");
|
|
106
|
+
else console.log();
|
|
107
|
+
|
|
108
|
+
let installed = 0, skipped = 0, failed = 0;
|
|
109
|
+
const meta = loadMeta(installDir);
|
|
110
|
+
|
|
111
|
+
for (const skill of skills) {
|
|
112
|
+
const slug = slugify(skill.name);
|
|
113
|
+
const dest = path.join(installDir, `${slug}.md`);
|
|
114
|
+
|
|
115
|
+
if (fs.existsSync(dest) && !force) {
|
|
116
|
+
if (!dryRun) console.log(` SKIP ${slug} (already exists, use --force to overwrite)`);
|
|
117
|
+
skipped++;
|
|
118
|
+
continue;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
if (flags.validate) {
|
|
122
|
+
const content = fs.readFileSync(skill.fullPath, "utf8");
|
|
123
|
+
const issues = validateSkill(content);
|
|
124
|
+
if (issues.length > 0) {
|
|
125
|
+
console.log(` FAIL ${slug} — validation errors:`);
|
|
126
|
+
issues.forEach(i => console.log(` - ${i}`));
|
|
127
|
+
failed++;
|
|
128
|
+
continue;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
if (dryRun) {
|
|
133
|
+
console.log(` Would install ${slug}`);
|
|
134
|
+
console.log(` src : ${skill.fullPath}`);
|
|
135
|
+
console.log(` dest: ${dest}`);
|
|
136
|
+
} else {
|
|
137
|
+
try {
|
|
138
|
+
fs.copyFileSync(skill.fullPath, dest);
|
|
139
|
+
meta[slug] = {
|
|
140
|
+
name: slug,
|
|
141
|
+
source: skill.fullPath,
|
|
142
|
+
installed_at: new Date().toISOString(),
|
|
143
|
+
directory: skill.dir,
|
|
144
|
+
};
|
|
145
|
+
installed++;
|
|
146
|
+
console.log(` OK ${slug}`);
|
|
147
|
+
} catch (err) {
|
|
148
|
+
console.log(` FAIL ${slug} — ${err.message}`);
|
|
149
|
+
failed++;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
if (!dryRun) {
|
|
155
|
+
saveMeta(installDir, meta);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
console.log(`\n${installed} installed, ${skipped} skipped, ${failed} failed.`);
|
|
159
|
+
|
|
160
|
+
if (!dryRun && installed > 0) {
|
|
161
|
+
console.log(`\n How to use:`);
|
|
162
|
+
if (target === "claude") {
|
|
163
|
+
console.log(` In Claude Code, type /<skill-name> to invoke a skill.`);
|
|
164
|
+
console.log(` Examples: /codesage, /testcrafter, /dockmaster, /python-master`);
|
|
165
|
+
} else {
|
|
166
|
+
console.log(` Skills are now available in your Gemini context.`);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
function cmdUninstall(args) {
|
|
172
|
+
const flags = parseFlags(args, { target: "t" });
|
|
173
|
+
const target = flags.target || "claude";
|
|
174
|
+
const installDir = TARGETS[target];
|
|
175
|
+
const names = flags._.filter(n => n !== "uninstall");
|
|
176
|
+
|
|
177
|
+
if (names.length === 0) {
|
|
178
|
+
console.error("Usage: agent-skills uninstall <skill-name> [<skill-name>...] [-t claude|gemini]");
|
|
179
|
+
process.exit(1);
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
const meta = loadMeta(installDir);
|
|
183
|
+
let removed = 0;
|
|
184
|
+
|
|
185
|
+
for (const name of names) {
|
|
186
|
+
const slug = slugify(name);
|
|
187
|
+
const dest = path.join(installDir, `${slug}.md`);
|
|
188
|
+
if (fs.existsSync(dest)) {
|
|
189
|
+
fs.unlinkSync(dest);
|
|
190
|
+
delete meta[slug];
|
|
191
|
+
console.log(` Removed ${slug}`);
|
|
192
|
+
removed++;
|
|
193
|
+
} else {
|
|
194
|
+
console.log(` Not found: ${slug}`);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
saveMeta(installDir, meta);
|
|
199
|
+
console.log(`\n${removed} skill(s) removed.`);
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
function cmdList(args) {
|
|
203
|
+
const flags = parseFlags(args, { target: "t" });
|
|
204
|
+
const target = flags.target || "claude";
|
|
205
|
+
const installDir = TARGETS[target];
|
|
206
|
+
|
|
207
|
+
if (!fs.existsSync(installDir)) {
|
|
208
|
+
console.log(`No skills installed for ${target} (${installDir} does not exist).`);
|
|
209
|
+
return;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
const meta = loadMeta(installDir);
|
|
213
|
+
const entries = Object.values(meta);
|
|
214
|
+
|
|
215
|
+
if (entries.length === 0) {
|
|
216
|
+
console.log(`No skills installed for ${target}.`);
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
console.log(`Installed skills (${target}): ${entries.length}\n`);
|
|
221
|
+
console.log(" Name Installed At");
|
|
222
|
+
console.log(" " + "-".repeat(60));
|
|
223
|
+
for (const e of entries.sort((a, b) => a.name.localeCompare(b.name))) {
|
|
224
|
+
const date = e.installed_at ? e.installed_at.slice(0, 19).replace("T", " ") : "unknown";
|
|
225
|
+
console.log(` ${e.name.padEnd(30)} ${date}`);
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function cmdDoctor(args) {
|
|
230
|
+
runPythonScript("doctor.py", args);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
function cmdRoute(args) {
|
|
234
|
+
runPythonScript("route.py", args);
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
function cmdValidate(args) {
|
|
238
|
+
runPythonScript("validate.py", args);
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
function cmdScore(args) {
|
|
242
|
+
runPythonScript("score.py", args);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
function cmdTest(args) {
|
|
246
|
+
runPythonScript("test_skill.py", args);
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
function cmdBuildIndex(args) {
|
|
250
|
+
runPythonScript("build_index.py", args);
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
function cmdHelp() {
|
|
254
|
+
console.log(`
|
|
255
|
+
agent-skills — AI-powered developer skills for Claude and Gemini
|
|
256
|
+
|
|
257
|
+
Usage:
|
|
258
|
+
agent-skills <command> [options]
|
|
259
|
+
|
|
260
|
+
Commands:
|
|
261
|
+
install Install skills to Claude or Gemini
|
|
262
|
+
-t, --target Target: "claude" or "gemini" (default: auto-detect)
|
|
263
|
+
-s, --skills Comma-separated skill names (default: all)
|
|
264
|
+
--force Overwrite existing skills
|
|
265
|
+
--dry-run Preview without writing files
|
|
266
|
+
--validate Validate skills before installing
|
|
267
|
+
|
|
268
|
+
uninstall <names> Remove installed skills
|
|
269
|
+
-t, --target Target: "claude" or "gemini"
|
|
270
|
+
|
|
271
|
+
list List installed skills
|
|
272
|
+
-t, --target Target: "claude" or "gemini"
|
|
273
|
+
|
|
274
|
+
route "<prompt>" Find the best skill for a task
|
|
275
|
+
-n, --top-n Number of results (default: 3)
|
|
276
|
+
--json Output as JSON
|
|
277
|
+
--interactive Interactive prompt mode
|
|
278
|
+
|
|
279
|
+
doctor Check health of installed skills
|
|
280
|
+
-t, --target Target: "claude" or "gemini" (default: both)
|
|
281
|
+
|
|
282
|
+
validate Lint all skill files
|
|
283
|
+
--fix Auto-fix known issues
|
|
284
|
+
|
|
285
|
+
score Score all skills on quality metrics
|
|
286
|
+
--json Output as JSON
|
|
287
|
+
|
|
288
|
+
test Run adversarial tests on all skills
|
|
289
|
+
|
|
290
|
+
build-index Regenerate skills.json and skills-routing.json
|
|
291
|
+
|
|
292
|
+
Examples:
|
|
293
|
+
npx agent-skills install # Install all to Claude
|
|
294
|
+
npx agent-skills install -t gemini -s CodeSage,TestCrafter
|
|
295
|
+
npx agent-skills route "review my Python code"
|
|
296
|
+
npx agent-skills doctor
|
|
297
|
+
npx agent-skills list
|
|
298
|
+
npx agent-skills score --json > report.json
|
|
299
|
+
`);
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
// ── Utilities ──────────────────────────────────────────────────────
|
|
303
|
+
|
|
304
|
+
function parseFlags(args, aliases = {}) {
|
|
305
|
+
const result = { _: [] };
|
|
306
|
+
let i = 0;
|
|
307
|
+
while (i < args.length) {
|
|
308
|
+
const arg = args[i];
|
|
309
|
+
if (arg.startsWith("--")) {
|
|
310
|
+
const key = arg.slice(2);
|
|
311
|
+
if (i + 1 < args.length && !args[i + 1].startsWith("-")) {
|
|
312
|
+
result[key] = args[++i];
|
|
313
|
+
} else {
|
|
314
|
+
result[key] = true;
|
|
315
|
+
}
|
|
316
|
+
} else if (arg.startsWith("-") && arg.length === 2) {
|
|
317
|
+
const short = arg.slice(1);
|
|
318
|
+
const long = Object.entries(aliases).find(([, v]) => v === short)?.[0];
|
|
319
|
+
const key = long || short;
|
|
320
|
+
if (i + 1 < args.length && !args[i + 1].startsWith("-")) {
|
|
321
|
+
result[key] = args[++i];
|
|
322
|
+
} else {
|
|
323
|
+
result[key] = true;
|
|
324
|
+
}
|
|
325
|
+
} else {
|
|
326
|
+
result._.push(arg);
|
|
327
|
+
}
|
|
328
|
+
i++;
|
|
329
|
+
}
|
|
330
|
+
return result;
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
function validateSkill(content) {
|
|
334
|
+
const issues = [];
|
|
335
|
+
if (!content.startsWith("---")) issues.push("Missing frontmatter (---)");
|
|
336
|
+
if (!content.match(/^#{1}\s/m)) issues.push("No H1 heading found");
|
|
337
|
+
if (!content.match(/^#{2}\s/m)) issues.push("No H2 section found");
|
|
338
|
+
if (!content.includes("```")) issues.push("No code examples found");
|
|
339
|
+
if (content.length < 500) issues.push("Content too short (< 500 chars)");
|
|
340
|
+
return issues;
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
function loadMeta(installDir) {
|
|
344
|
+
const metaPath = path.join(installDir, ".skills-meta.json");
|
|
345
|
+
if (fs.existsSync(metaPath)) {
|
|
346
|
+
try { return JSON.parse(fs.readFileSync(metaPath, "utf8")); } catch (_) {}
|
|
347
|
+
}
|
|
348
|
+
return {};
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
function saveMeta(installDir, meta) {
|
|
352
|
+
const metaPath = path.join(installDir, ".skills-meta.json");
|
|
353
|
+
fs.writeFileSync(metaPath, JSON.stringify(meta, null, 2) + "\n");
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
// ── Main ───────────────────────────────────────────────────────────
|
|
357
|
+
|
|
358
|
+
const [, , command, ...args] = process.argv;
|
|
359
|
+
|
|
360
|
+
switch (command) {
|
|
361
|
+
case "install": cmdInstall(args); break;
|
|
362
|
+
case "uninstall": cmdUninstall(args); break;
|
|
363
|
+
case "list": cmdList(args); break;
|
|
364
|
+
case "route": cmdRoute(args); break;
|
|
365
|
+
case "doctor": cmdDoctor(args); break;
|
|
366
|
+
case "validate": cmdValidate(args); break;
|
|
367
|
+
case "score": cmdScore(args); break;
|
|
368
|
+
case "test": cmdTest(args); break;
|
|
369
|
+
case "build-index": cmdBuildIndex(args); break;
|
|
370
|
+
case "help":
|
|
371
|
+
case "--help":
|
|
372
|
+
case "-h":
|
|
373
|
+
case undefined: cmdHelp(); break;
|
|
374
|
+
default:
|
|
375
|
+
console.error(`Unknown command: ${command}\nRun "agent-skills help" for usage.`);
|
|
376
|
+
process.exit(1);
|
|
377
|
+
}
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: extension-extender
|
|
3
|
+
description: Creates, fixes, and debugs Manifest V3 browser extensions for Chrome and Firefox with secure permissions scoping, CSP compliance, cross-browser compatibility, storage management, and version migration. Use when a user asks to build, fix, or debug a Chrome/Firefox extension, create a popup, or handle extension manifest issues.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Extension Extender
|
|
7
|
+
|
|
8
|
+
## Overview
|
|
9
|
+
|
|
10
|
+
Builds modern Manifest V3 browser extensions with secure permissions, cross-browser compatibility (Chrome + Firefox), CSP compliance, storage management, and structured debugging. Produces `chrome://extensions`-ready code.
|
|
11
|
+
|
|
12
|
+
## Workflow
|
|
13
|
+
|
|
14
|
+
### 1. Project Initialization
|
|
15
|
+
|
|
16
|
+
Use `assets/manifest.json`, `assets/popup.html`, `assets/popup.css`, `assets/popup.js` as boilerplate if available. If assets are missing, generate inline:
|
|
17
|
+
|
|
18
|
+
```json
|
|
19
|
+
{
|
|
20
|
+
"manifest_version": 3,
|
|
21
|
+
"name": "My Extension",
|
|
22
|
+
"version": "1.0",
|
|
23
|
+
"action": { "default_popup": "popup.html" },
|
|
24
|
+
"permissions": [],
|
|
25
|
+
"host_permissions": []
|
|
26
|
+
}
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
### 2. Permissions Scoping (Principle of Least Privilege)
|
|
30
|
+
|
|
31
|
+
1. List every browser API the extension uses (`storage`, `tabs`, `scripting`).
|
|
32
|
+
2. Use `optional_permissions` where possible — granted at runtime via `chrome.permissions.request()`, reduces install friction.
|
|
33
|
+
3. URL patterns go in `host_permissions`, not `permissions`. Be specific: `"https://example.com/*"` over `"<all_urls>"`.
|
|
34
|
+
4. Never request `"tabs"` just for current tab URL — use `"activeTab"` instead.
|
|
35
|
+
5. After editing permissions, reload in `chrome://extensions` and verify no errors.
|
|
36
|
+
|
|
37
|
+
### 3. Firefox WebExtensions Compatibility
|
|
38
|
+
|
|
39
|
+
- Replace `chrome.*` with `browser.*` using `webextension-polyfill` for cross-browser support.
|
|
40
|
+
- Firefox MV3 background support differs: use `"background": { "scripts": ["background.js"] }` for Firefox (check MDN for current MV3 status).
|
|
41
|
+
- `chrome.scripting.executeScript` → `browser.tabs.executeScript` (MV2) or `browser.scripting` (MV3 when supported).
|
|
42
|
+
- `browser.action` is standard in both Chrome/Firefox MV3. Do not use `browser.browserAction`.
|
|
43
|
+
- Test Firefox: `about:debugging#/runtime/this-firefox` → "Load Temporary Add-on".
|
|
44
|
+
|
|
45
|
+
### 4. Content Security Policy (CSP)
|
|
46
|
+
|
|
47
|
+
- No inline `<script>` or `onclick="..."` — move all JS to external `.js` files.
|
|
48
|
+
- No `eval()`, `new Function()`, or dynamic code execution.
|
|
49
|
+
- Remote resources (fonts, images): explicitly allow in manifest:
|
|
50
|
+
```json
|
|
51
|
+
"content_security_policy": {
|
|
52
|
+
"extension_pages": "script-src 'self'; object-src 'self'; img-src 'self' https://cdn.example.com"
|
|
53
|
+
}
|
|
54
|
+
```
|
|
55
|
+
- Never relax `script-src` beyond `'self'`. Vendor third-party code locally.
|
|
56
|
+
|
|
57
|
+
### 5. Storage Management
|
|
58
|
+
|
|
59
|
+
**`chrome.storage.sync` vs `local`:**
|
|
60
|
+
|
|
61
|
+
| Feature | `sync` | `local` |
|
|
62
|
+
|---------|--------|---------|
|
|
63
|
+
| Synced across devices | Yes (Google account) | No |
|
|
64
|
+
| Quota | 100KB total, 8KB/item, 512 items | 5MB default (2GB with `unlimitedStorage`) |
|
|
65
|
+
| Use for | Preferences, small config | Cached data, history, large datasets |
|
|
66
|
+
|
|
67
|
+
Always check `chrome.runtime.lastError` after storage calls. Batch writes to avoid hitting quota.
|
|
68
|
+
|
|
69
|
+
**Version upgrade data migration:**
|
|
70
|
+
```javascript
|
|
71
|
+
chrome.runtime.onInstalled.addListener(({ reason, previousVersion }) => {
|
|
72
|
+
if (reason === 'update') {
|
|
73
|
+
chrome.storage.local.get(['settings'], ({ settings }) => {
|
|
74
|
+
if (settings && !settings.schemaVersion) {
|
|
75
|
+
chrome.storage.local.set({
|
|
76
|
+
settings: { ...settings, schemaVersion: 2, newKey: settings.oldKey }
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
});
|
|
82
|
+
```
|
|
83
|
+
Always track a `schemaVersion` field. Test migrations by loading the old version, saving data, then upgrading.
|
|
84
|
+
|
|
85
|
+
### 6. Styling (Beautiful UI Defaults)
|
|
86
|
+
|
|
87
|
+
- CSS custom properties for theming (`--color-primary`, `--bg-surface`).
|
|
88
|
+
- Dark mode: `@media (prefers-color-scheme: dark)`.
|
|
89
|
+
- Popup: 300–400px width, under 600px height. `rem` for fonts, `px` for borders/shadows.
|
|
90
|
+
|
|
91
|
+
### 7. Debugging Decision Workflow
|
|
92
|
+
|
|
93
|
+
1. **Manifest errors** → confirm `"manifest_version": 3`. Service worker: `"background": { "service_worker": "background.js" }` (not `"scripts"` array).
|
|
94
|
+
2. **Popup errors** → right-click popup → Inspect. Background errors → `chrome://extensions` → service worker → Inspect.
|
|
95
|
+
3. **Content script not injecting** → verify `content_scripts` in manifest or programmatic `chrome.scripting.executeScript`. Content scripts run in isolated world — can't access page JS vars.
|
|
96
|
+
4. **DOM not ready** → wrap logic in `document.addEventListener('DOMContentLoaded', ...)`.
|
|
97
|
+
5. **Message passing fails** → verify both sides use matching `type` fields in `chrome.runtime.sendMessage`/`onMessage`. Return `true` in listener if response is async.
|
|
98
|
+
6. **Permission denied at runtime** → add missing permission to manifest, reload, re-test.
|
|
99
|
+
7. **Service worker terminates mid-task** → MV3 service workers are ephemeral (30s idle timeout). Use `chrome.alarms` for periodic tasks; persist state in `chrome.storage` rather than in-memory variables.
|
|
100
|
+
|
|
101
|
+
### 8. Content Script vs Host Page
|
|
102
|
+
|
|
103
|
+
Content scripts share the DOM but not JS context (isolated world). Host page CSP does **not** block content scripts. To interact with page JS:
|
|
104
|
+
- Inject via `chrome.scripting.executeScript({ world: "MAIN" })` (Chrome 95+).
|
|
105
|
+
- Code in `MAIN` world **is** subject to host page CSP — no `eval()` or inline scripts.
|
|
106
|
+
|
|
107
|
+
## Edge Cases
|
|
108
|
+
|
|
109
|
+
1. **Service worker killed during long operation**: MV3 service workers terminate after ~30s of inactivity. For long-running work, use `chrome.offscreen.createDocument()` to get a persistent page, or break work into chunks persisted in storage.
|
|
110
|
+
2. **Storage quota exceeded silently**: `chrome.storage.sync.set()` fails silently if quota is exceeded. Always check `chrome.runtime.lastError` and implement a fallback to `local` storage.
|
|
111
|
+
3. **Cross-browser manifest differences**: Chrome requires `"service_worker"` for background; Firefox uses `"scripts"` array. Maintain two manifests or use a build step (webpack/vite) to generate platform-specific versions.
|
|
112
|
+
|
|
113
|
+
## Testing
|
|
114
|
+
|
|
115
|
+
- **Manual**: load unpacked via `chrome://extensions` (Chrome) or `about:debugging` (Firefox).
|
|
116
|
+
- **Automated**: use `web-ext lint` (Mozilla) for manifest/CSP validation. For E2E: Playwright supports Chrome extensions via `--load-extension` launch arg.
|
|
117
|
+
- **Web Store submission checklist**: single-purpose description, minimal permissions justification, privacy policy if using `host_permissions` or user data.
|
|
118
|
+
|
|
119
|
+
## Output Format
|
|
120
|
+
|
|
121
|
+
- Provide complete updated files.
|
|
122
|
+
- State: (a) root cause (if debugging), (b) what changed, (c) how to verify.
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: fastapi-furious
|
|
3
|
+
description: Builds, debugs, and fixes FastAPI applications with structured project scaffolding, endpoint checklists, Alembic migrations, security (CORS, rate limiting, JWT), async testing with httpx, and advanced patterns (WebSockets, file uploads, BackgroundTasks). Use when a user asks to build, create, fix, debug, or improve FastAPI code.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# FastAPI Furious
|
|
7
|
+
|
|
8
|
+
## Overview
|
|
9
|
+
|
|
10
|
+
Production-ready FastAPI development covering project structure, endpoint design with validation checklists, database/migrations with Alembic, security hardening, async testing, and advanced patterns (WebSockets, file uploads, background tasks).
|
|
11
|
+
|
|
12
|
+
## Workflow
|
|
13
|
+
|
|
14
|
+
### 1. Project Scaffold
|
|
15
|
+
|
|
16
|
+
```
|
|
17
|
+
project/
|
|
18
|
+
├── app/
|
|
19
|
+
│ ├── main.py # App instance, middleware, lifespan events
|
|
20
|
+
│ ├── api/v1/
|
|
21
|
+
│ │ ├── router.py # Includes all v1 sub-routers
|
|
22
|
+
│ │ └── endpoints/ # One file per resource (users.py, items.py)
|
|
23
|
+
│ ├── core/
|
|
24
|
+
│ │ ├── config.py # pydantic-settings BaseSettings; reads .env
|
|
25
|
+
│ │ └── security.py # Password hashing, JWT encode/decode
|
|
26
|
+
│ ├── crud/ # DB query functions (no business logic)
|
|
27
|
+
│ ├── models/ # SQLAlchemy ORM models
|
|
28
|
+
│ ├── schemas/ # Pydantic v2 request/response models
|
|
29
|
+
│ └── deps.py # Shared dependencies (get_db, get_current_user)
|
|
30
|
+
├── alembic/
|
|
31
|
+
├── tests/
|
|
32
|
+
│ ├── conftest.py # Async test client, test DB setup
|
|
33
|
+
│ └── test_*.py
|
|
34
|
+
├── pyproject.toml
|
|
35
|
+
└── .env.example
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
### 2. Endpoint Checklist
|
|
39
|
+
|
|
40
|
+
Apply to every endpoint before it is complete:
|
|
41
|
+
|
|
42
|
+
- [ ] `response_model=Schema` declared for validated, documented output.
|
|
43
|
+
- [ ] `async def` for any I/O (DB, file, HTTP). Never `time.sleep` in async.
|
|
44
|
+
- [ ] `HTTPException` with standard status codes; never error detail in a 200.
|
|
45
|
+
- [ ] `Depends()` for DB sessions, auth, config — never instantiate in route body.
|
|
46
|
+
- [ ] Pydantic `Field(...)` constraints (`min_length`, `ge`, `pattern`) over manual `if` checks.
|
|
47
|
+
- [ ] Status: `201` for creation, `204` for delete with no body.
|
|
48
|
+
|
|
49
|
+
### 3. Database & Migrations (Alembic)
|
|
50
|
+
|
|
51
|
+
- Async engine: `create_async_engine(settings.DATABASE_URL)`.
|
|
52
|
+
- Session dependency:
|
|
53
|
+
```python
|
|
54
|
+
async def get_db() -> AsyncGenerator[AsyncSession, None]:
|
|
55
|
+
async with AsyncSessionLocal() as session:
|
|
56
|
+
yield session
|
|
57
|
+
```
|
|
58
|
+
- Migration workflow: edit model → `alembic revision --autogenerate -m "description"` → review generated file → `alembic upgrade head`.
|
|
59
|
+
- **Pitfall**: `autogenerate` misses some changes (column type changes, constraints). Always review the diff before applying.
|
|
60
|
+
- Never edit applied migrations; create a new revision instead.
|
|
61
|
+
|
|
62
|
+
### 4. Security
|
|
63
|
+
|
|
64
|
+
- **CORS**: explicit `allow_origins` list. Never `["*"]` in production.
|
|
65
|
+
- **Rate limiting**: `slowapi` or `fastapi-limiter` (Redis-backed) on public endpoints. Stricter limits on auth endpoints.
|
|
66
|
+
- **Auth**: `python-jose` for JWT. Secrets via `pydantic-settings`; never hardcoded.
|
|
67
|
+
- **SQL injection**: always ORM queries or parameterized statements — never f-string SQL.
|
|
68
|
+
|
|
69
|
+
### 5. Error Handling
|
|
70
|
+
|
|
71
|
+
```python
|
|
72
|
+
@app.exception_handler(Exception)
|
|
73
|
+
async def unhandled_exception_handler(request, exc):
|
|
74
|
+
logger.error("Unhandled error", exc_info=exc)
|
|
75
|
+
return JSONResponse(status_code=500, content={"detail": "Internal server error"})
|
|
76
|
+
```
|
|
77
|
+
- Custom exceptions for domain errors with dedicated handlers.
|
|
78
|
+
- Never expose raw stack traces to API consumers.
|
|
79
|
+
|
|
80
|
+
### 6. Testing
|
|
81
|
+
|
|
82
|
+
`pytest` + `httpx.AsyncClient` (all async). Per endpoint:
|
|
83
|
+
- Happy path: correct response model + status.
|
|
84
|
+
- `422` on bad input (missing field, wrong type).
|
|
85
|
+
- `401` on missing/invalid token.
|
|
86
|
+
- `404` on missing resource.
|
|
87
|
+
|
|
88
|
+
Mock external HTTP with `respx`. Use SQLite in-memory or separate Postgres schema — never production DB.
|
|
89
|
+
|
|
90
|
+
### 7. Debugging Decision Workflow
|
|
91
|
+
|
|
92
|
+
1. **Server won't start** → read traceback; usually missing env var or import error.
|
|
93
|
+
2. **422 Unprocessable Entity** → log `await request.body()`; compare against Pydantic schema.
|
|
94
|
+
3. **500 in production** → check structured logs for request ID; correlate with exception handler.
|
|
95
|
+
4. **Slow query** → `echo=True` on SQLAlchemy engine to log SQL; add index or rewrite.
|
|
96
|
+
5. **Event loop blocked** → `run_in_executor` for CPU-bound or synchronous blocking calls.
|
|
97
|
+
6. **Startup hangs** → check `lifespan` context manager; ensure `yield` is reached and async DB connections resolve.
|
|
98
|
+
|
|
99
|
+
### 8. Advanced Patterns
|
|
100
|
+
|
|
101
|
+
**WebSocket endpoints:**
|
|
102
|
+
```python
|
|
103
|
+
@router.websocket("/ws/{client_id}")
|
|
104
|
+
async def ws(websocket: WebSocket, client_id: str):
|
|
105
|
+
await websocket.accept()
|
|
106
|
+
try:
|
|
107
|
+
while True:
|
|
108
|
+
data = await websocket.receive_text()
|
|
109
|
+
await websocket.send_text(f"Echo: {data}")
|
|
110
|
+
except WebSocketDisconnect:
|
|
111
|
+
pass # Clean up connection state
|
|
112
|
+
```
|
|
113
|
+
Multi-instance: broadcast via Redis pub/sub, not in-process state. Add auth via query param token or first-message handshake.
|
|
114
|
+
|
|
115
|
+
**BackgroundTasks vs. task queue:** `BackgroundTasks` for fire-and-forget < 5s (emails, logging). External queue (Celery, ARQ, Dramatiq) for long-running, retriable, or critical work (payments, exports). Never `BackgroundTasks` for anything requiring failure tracking.
|
|
116
|
+
|
|
117
|
+
**File uploads:**
|
|
118
|
+
```python
|
|
119
|
+
@router.post("/upload")
|
|
120
|
+
async def upload(file: UploadFile = File(...)):
|
|
121
|
+
if file.size and file.size > 10_000_000:
|
|
122
|
+
raise HTTPException(413, "File too large")
|
|
123
|
+
contents = await file.read()
|
|
124
|
+
return {"filename": file.filename, "size": len(contents)}
|
|
125
|
+
```
|
|
126
|
+
Large files: stream to S3/GCS via `file.read(chunk_size)` loop. Set `client_max_body_size` at nginx level.
|
|
127
|
+
|
|
128
|
+
**Lifespan events (replacing deprecated `on_startup`/`on_shutdown`):**
|
|
129
|
+
```python
|
|
130
|
+
from contextlib import asynccontextmanager
|
|
131
|
+
|
|
132
|
+
@asynccontextmanager
|
|
133
|
+
async def lifespan(app: FastAPI):
|
|
134
|
+
pool = await create_pool() # startup
|
|
135
|
+
yield {"pool": pool}
|
|
136
|
+
await pool.close() # shutdown
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
## Edge Cases
|
|
140
|
+
|
|
141
|
+
1. **ASGI lifespan not supported by test client**: use `httpx.ASGITransport(app=app)` in test `conftest.py` to handle lifespan events during testing.
|
|
142
|
+
2. **Pydantic v1 vs v2 migration**: FastAPI 0.100+ uses Pydantic v2. If upgrading, run `bump-pydantic` to auto-migrate models. Key changes: `orm_mode` → `from_attributes`, `validator` → `field_validator`.
|
|
143
|
+
3. **Async DB session leaks**: if `get_db` doesn't use `async with`, sessions may not close on exceptions. Always use context manager pattern.
|
|
144
|
+
|
|
145
|
+
## Output Format
|
|
146
|
+
|
|
147
|
+
- Provide the complete updated file for changed files.
|
|
148
|
+
- State: (a) root cause (if debugging), (b) what changed, (c) how to verify.
|