Skip to content

borghei/Claude-Skills / engineering/senior-frontend

senior-frontend

Verified

Scaffold Next.js 16 or React + Vite 8 apps, generate components with tests and stories, and flag heavy bundle dependencies. Use when starting a React project, adding components or hooks, or reviewing frontend code or performance.

FileKindSize
SKILL.mdskill md12.2 KB
assets/sample-project-flawed/package.jsonmanifest413 B
assets/sample-project-flawed/src/App.tsxother268 B
assets/sample-project-sound/app/page.tsxother131 B
assets/sample-project-sound/next.config.jsscript255 B
assets/sample-project-sound/package.jsonmanifest476 B
assets/templates/component/client.tsx.tmplother297 B
assets/templates/component/hook.ts.tmplother826 B
assets/templates/component/index.ts.tmplother84 B
assets/templates/component/index_hook.ts.tmplother115 B
assets/templates/component/server.tsx.tmplother447 B
assets/templates/component/story.tsx.tmplother601 B
assets/templates/component/test.tsx.tmplother538 B
assets/templates/scaffold/config/eslint.config.mjs.tmplother190 B
assets/templates/scaffold/config/gitignore.tmplother246 B
assets/templates/scaffold/config/next.config.js.tmplother248 B
assets/templates/scaffold/config/postcss.config.js.tmplother151 B
assets/templates/scaffold/config/prettierrc.tmplother106 B
assets/templates/scaffold/config/tailwind.config.ts.tmplother1.3 KB
assets/templates/scaffold/config/tsconfig.json.tmplother572 B
assets/templates/scaffold/config/vite/eslint.config.js.tmplother361 B
assets/templates/scaffold/config/vite/index.html.tmplother303 B
assets/templates/scaffold/config/vite/postcss.config.js.tmplother149 B
assets/templates/scaffold/config/vite/tsconfig.app.json.tmplother649 B
assets/templates/scaffold/config/vite/tsconfig.json.tmplother119 B
assets/templates/scaffold/config/vite/tsconfig.node.json.tmplother557 B
assets/templates/scaffold/config/vite/vite.config.ts.tmplother282 B
assets/templates/scaffold/files/api_client.tsscript2.1 KB
assets/templates/scaffold/files/auth_client.tsscript1.3 KB
assets/templates/scaffold/files/auth_lib.tsscript2.7 KB
assets/templates/scaffold/files/auth_page.tsxother281 B
assets/templates/scaffold/files/auth_proxy.tsscript525 B
assets/templates/scaffold/files/constants.tsscript327 B
assets/templates/scaffold/files/empty.txtmarkdown0 B
assets/templates/scaffold/files/form_field.tsxother1.7 KB
assets/templates/scaffold/files/form_utils.tsscript762 B
assets/templates/scaffold/files/globals_css.cssother856 B
assets/templates/scaffold/files/health_route.tsscript171 B
assets/templates/scaffold/files/home_page.tsxother304 B
assets/templates/scaffold/files/hook_debounce.tsscript357 B
assets/templates/scaffold/files/hook_local_storage.tsscript659 B
assets/templates/scaffold/files/layout_footer.tsxother265 B
assets/templates/scaffold/files/layout_header.tsxother518 B
assets/templates/scaffold/files/layout_sidebar.tsxother287 B
assets/templates/scaffold/files/login_form.tsxother2.2 KB
assets/templates/scaffold/files/query_client.tsscript662 B
assets/templates/scaffold/files/query_provider.tsxother353 B
assets/templates/scaffold/files/react_app.tsxother403 B
assets/templates/scaffold/files/react_main.tsxother236 B
assets/templates/scaffold/files/register_form.tsxother3.2 KB
assets/templates/scaffold/files/require_auth.tsxother821 B
assets/templates/scaffold/files/root_layout.tsxother512 B
assets/templates/scaffold/files/storybook_main_next.tsscript302 B
assets/templates/scaffold/files/storybook_main_react.tsscript231 B
assets/templates/scaffold/files/storybook_preview_next.tsscript264 B
assets/templates/scaffold/files/storybook_preview_react.tsscript261 B
assets/templates/scaffold/files/test_setup.tsscript244 B
assets/templates/scaffold/files/test_utils.tsxother541 B
assets/templates/scaffold/files/types_index.tsscript309 B
assets/templates/scaffold/files/ui_button.tsxother1.4 KB
assets/templates/scaffold/files/ui_card.tsxother984 B
assets/templates/scaffold/files/ui_index.tsscript147 B
assets/templates/scaffold/files/ui_input.tsxother1.1 KB
assets/templates/scaffold/files/utils.tsscript478 B
assets/templates/scaffold/files/vitest_config_next.tsscript438 B
assets/templates/scaffold/files/vitest_config_react.tsscript389 B
assets/templates/scaffold/manifest.jsonconfig12.6 KB
references/bundle_rules.jsonconfig3.4 KB
references/code-patterns.mdmarkdown5.7 KB
references/frontend_best_practices.mdmarkdown19.4 KB
references/nextjs_optimization_guide.mdmarkdown17.3 KB
references/react_patterns.mdmarkdown16.9 KB
references/tooling-guide.mdmarkdown15.1 KB
scripts/bundle_analyzer.pyexecutablescript11.6 KB
scripts/component_generator.pyexecutablescript8.5 KB
scripts/frontend_scaffolder.pyexecutablescript11.0 KB

scripts/frontend_scaffolder.py

View on GitHub
#!/usr/bin/env python3
"""
Frontend Project Scaffolder

Generates a complete Next.js/React project structure with TypeScript,
Tailwind CSS, and best practice configurations. Every file body lives in
assets/templates/scaffold/ (manifest.json maps paths to template files),
so templates can be edited without touching this script.

Usage:
    python frontend_scaffolder.py my-app --template nextjs
    python frontend_scaffolder.py dashboard --template react --features auth,api
    python frontend_scaffolder.py landing --template nextjs --dry-run --format json

Exit codes: 0 ok, 2 bad input (target exists, unknown feature, unwritable path,
missing or broken template assets).
"""

import argparse
import copy
import json
import re
import sys
from pathlib import Path
from typing import Dict, List, Optional

TEMPLATE_DIR = Path(__file__).resolve().parent.parent / "assets" / "templates" / "scaffold"


def load_manifest(template_dir: Path = TEMPLATE_DIR) -> Dict:
    """Load the scaffold manifest (templates, features, content and config file maps)."""
    with open(template_dir / "manifest.json", encoding="utf-8") as f:
        return json.load(f)


def read_template(rel_path: str, template_dir: Path = TEMPLATE_DIR) -> str:
    """Read one template file relative to the scaffold template folder."""
    return (template_dir / rel_path).read_text(encoding="utf-8")


try:
    MANIFEST = load_manifest()
except (OSError, json.JSONDecodeError) as _exc:
    print(f"error: cannot load scaffold templates from {TEMPLATE_DIR}: {_exc}", file=sys.stderr)
    sys.exit(2)

TEMPLATES: Dict = MANIFEST["templates"]
FEATURES: Dict = MANIFEST["features"]


def file_content(key: str, default: Optional[str] = "", template: str = "") -> Optional[str]:
    """Return the body for a content key, or ``default`` when the key has no template.

    Keys listed in the manifest's ``use_client`` get the directive in the nextjs
    template only; Vite has no Server Components, so it never needs one.
    """
    rel = MANIFEST["contents"].get(key)
    if rel is None:
        return default
    body = read_template(rel)
    if template == "nextjs" and key in MANIFEST.get("use_client", []):
        body = "'use client';\n\n" + body
    return body


def feature_spec(feature: str, template: str) -> Dict:
    """Return the per-template part of a feature (files, deps, scripts, notes)."""
    return FEATURES[feature].get(template, {})


def generate_structure(base_path: Path, structure: Dict, dry_run: bool = False) -> List[str]:
    """Generate directory structure recursively."""
    created_files = []
    for name, content in structure.items():
        current_path = base_path / name

        if isinstance(content, dict):  # a directory
            if not dry_run:
                current_path.mkdir(parents=True, exist_ok=True)
            created_files.extend(generate_structure(current_path, content, dry_run))
        else:  # a file
            if not dry_run:
                current_path.parent.mkdir(parents=True, exist_ok=True)
                current_path.write_text(file_content(content, ""))
            created_files.append(str(current_path))
    return created_files


def generate_config_files(project_path: Path, template: str, project_name: str,
                          features: List[str], dry_run: bool = False) -> List[str]:
    """Generate configuration files."""
    created_files = []
    config_templates = get_config_templates(project_name, template, features)
    template_config = TEMPLATES[template]
    for config_file in template_config["config_files"]:
        file_path = project_path / config_file
        if config_file in config_templates:
            if not dry_run:
                file_path.write_text(config_templates[config_file])
            created_files.append(str(file_path))
    return created_files


def get_config_templates(name: str, template: str, features: List[str]) -> Dict[str, str]:
    """Get configuration file contents."""
    package = copy.deepcopy(MANIFEST["package"][template])

    # Feature scripts and dependencies are appended, in the order the features were given
    for feature in features:
        if feature in FEATURES:
            spec = feature_spec(feature, template)
            for field in ("scripts", "dependencies", "devDependencies"):
                package[field].update(spec.get(field, {}))

    package_json = {"name": name, "version": "0.1.0", "private": True}
    for field in ("type", "scripts", "dependencies", "devDependencies"):
        if field in package:
            package_json[field] = package[field]

    configs = {"package.json": json.dumps(package_json, indent=2)}
    placeholder = MANIFEST["name_placeholder"]
    for config_file, rel in MANIFEST["configs"][template].items():
        configs[config_file] = read_template(rel).replace(placeholder, name)
    return configs


def scaffold_project(
    name: str,
    output_dir: Path,
    template: str = "nextjs",
    features: Optional[List[str]] = None,
    dry_run: bool = False,
) -> Dict:
    """Scaffold a complete frontend project."""
    features = features or []
    project_path = output_dir / name
    # npm package names (unscoped): lowercase, URL-safe, no leading dot/underscore, <= 214 chars.
    # The same rule keeps the project folder inside --dir: no "/", "\\" or "..".
    if not (len(name) <= 214 and re.fullmatch(r"[a-z0-9~-][a-z0-9._~-]*", name)):
        return {"error": f"invalid project name {name!r}: use a lowercase npm package name "
                         "(letters, digits, '-', '.', '_', '~'; no spaces or slashes)"}
    if project_path.resolve().parent != output_dir.resolve():
        return {"error": f"project path escapes --dir: {project_path}"}

    if project_path.exists() and not dry_run:
        return {"error": f"Directory already exists: {project_path}"}

    template_config = TEMPLATES.get(template)
    if not template_config:
        return {"error": f"Unknown template: {template}"}

    created_files = []
    notes: List[str] = []

    if not dry_run:
        project_path.mkdir(parents=True, exist_ok=True)

    created_files.extend(
        generate_structure(project_path, template_config["structure"], dry_run)
    )

    created_files.extend(
        generate_config_files(project_path, template, name, features, dry_run)
    )

    # Add feature files
    for feature in features:
        if feature in FEATURES:
            spec = feature_spec(feature, template)
            for file_path, content_key in spec.get("files", {}).items():
                full_path = project_path / file_path
                if not dry_run:
                    full_path.parent.mkdir(parents=True, exist_ok=True)
                    content = file_content(content_key, f"// TODO: Implement {content_key}", template)
                    full_path.write_text(content)
                created_files.append(str(full_path))
            notes.extend(n for n in spec.get("notes", []) if n not in notes)

    return {
        "name": name,
        "template": template,
        "template_name": template_config["name"],
        "features": features,
        "path": str(project_path),
        "files_created": len(created_files),
        "files": created_files,
        "notes": notes,
        "next_steps": [
            f"cd {name}",
            "npm install",
            "npm run dev",
        ],
    }


def print_result(result: Dict) -> None:
    """Print scaffolding result."""
    print(f"\n{'='*60}")
    print(f"Project Scaffolded: {result['name']}")
    print(f"{'='*60}")
    print(f"Template: {result['template_name']}")
    print(f"Location: {result['path']}")
    print(f"Files Created: {result['files_created']}")

    if result["features"]:
        print(f"Features: {', '.join(result['features'])}")

    if result["notes"]:
        print("\nNotes:")
        for note in result["notes"]:
            print(f"  - {note}")

    print("\nNext Steps:")
    for step in result["next_steps"]:
        print(f"  $ {step}")

    print(f"{'='*60}\n")


def build_parser() -> argparse.ArgumentParser:
    """Build the command-line parser."""
    parser = argparse.ArgumentParser(
        description="Scaffold a frontend project with best practices"
    )
    parser.add_argument("name", nargs="?",
                        help="Project name, a lowercase npm package name (optional with --list-*)")
    parser.add_argument("--dir", "-d", default=".",
                        help="Output directory (default: current directory)")
    parser.add_argument("--template", "-t", choices=list(TEMPLATES.keys()), default="nextjs",
                        help="Project template (default: nextjs)")
    parser.add_argument("--features", "-f",
                        help="Comma-separated features to add (auth,api,forms,testing,storybook)")
    parser.add_argument("--list-templates", action="store_true", help="List available templates")
    parser.add_argument("--list-features", action="store_true", help="List available features")
    parser.add_argument("--dry-run", action="store_true",
                        help="Show what would be created without creating files")
    parser.add_argument("--format", choices=["text", "json"], default="text",
                        help="Output format (default: text)")
    parser.add_argument("--json", action="store_true", help="Shorthand for --format json")
    return parser


def main():
    args = build_parser().parse_args()

    if args.list_templates:
        print("\nAvailable Templates:")
        for key, template in TEMPLATES.items():
            print(f"  {key}: {template['name']}")
            print(f"    {template['description']}")
        return

    if args.list_features:
        print("\nAvailable Features:")
        for key, feature in FEATURES.items():
            print(f"  {key}: {feature['description']}")
            for template in TEMPLATES:
                spec = feature.get(template, {})
                deps = ", ".join([*spec.get("dependencies", {}), *spec.get("devDependencies", {})])
                if deps:
                    print(f"    Adds ({template}): {deps}")
        return

    if not args.name:
        build_parser().error("the following arguments are required: name")

    features = []
    if args.features:
        features = [f.strip() for f in args.features.split(",")]
        invalid = [f for f in features if f not in FEATURES]
        if invalid:
            print(f"error: unknown features: {', '.join(invalid)} "
                  f"(valid: {', '.join(FEATURES.keys())})", file=sys.stderr)
            sys.exit(2)

    try:
        result = scaffold_project(
            name=args.name,
            output_dir=Path(args.dir),
            template=args.template,
            features=features,
            dry_run=args.dry_run,
        )
    except OSError as exc:
        print(f"error: cannot write project: {exc}", file=sys.stderr)
        sys.exit(2)
    if result.get("error"):
        print(f"error: {result['error']}", file=sys.stderr)
        sys.exit(2)

    if args.json or args.format == "json":
        print(json.dumps(result, indent=2))
    else:
        print_result(result)


if __name__ == "__main__":
    main()
finishing-a-development-branchobra/superpowersUse when implementation is complete, all tests pass, and you need to decide how to integrate the workStars: 322kUpdated Claude CodeCodexVerifiedInstall
systematic-debuggingobra/superpowersUse when encountering any bug, test failure, or unexpected behavior, before proposing fixesStars: 322kUpdated Claude CodeCodexVerifiedInstall
test-driven-developmentobra/superpowersUse when implementing any feature or bugfix, before writing implementation codeStars: 322kUpdated Claude CodeCodexVerifiedInstall
skill-creatoranthropics/skillsCreate new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an existing skill, run evals to test a skill, benchmark skill performance with variance analysis, or optimize a skill's description for better triggering accuracy.Stars: 198kUpdated Claude CodeCodexVerifiedInstall