sw-best-practices
This Claude Code skill specifies Service Worker cache architecture and management patterns for the Magic Web implementation. Use it when designing or troubleshooting cache routing strategies, API caching policies, static resource partitioning, Service Worker lifecycle management, or emergency cache clearing, particularly when adjusting TTL rules, implementing stale-while-revalidate patterns, or configuring environment-variable-driven rollback behaviors.
git clone --depth 1 https://github.com/dtyq/magic /tmp/sw-best-practices && cp -r /tmp/sw-best-practices/frontend/magic-web/.agents/skills/sw-best-practices ~/.claude/skills/sw-best-practicesSKILL.md
# Service Worker Best Practices ## Scope and Activation Keywords Use this specification as a priority when the Agent or developer needs to handle the following tasks: - Adjusting or designing Service Worker cache routing, TTL, cache capacity, and partitioning rules. - Adjusting page-level Service Worker registration, auto-activation, and force-update reload logic. - Configuring, optimizing, or troubleshooting critical first-screen API caching (Stale-While-Revalidate). - Handling online Service Worker self-healing failures, rollbacks, and emergency clearing of specific cache buckets. Typical activation keywords: "modify cache rules", "add API cache", "SW troubleshooting", "PWA cache optimization", "clear SW", "MAGIC_SW_MODE", "MAGIC_SW_CLEAR_CACHES". --- ## 1. Core Design Philosophy and Security Gates When handling Service Worker development for this repository, the following design philosophy and security gates must be strictly followed to prevent cache pollution and accidental interception risks: ### 1.1 Static Resource Partitioning Decision Matrix (Cache-First) Static resources prioritize the `CacheFirst` strategy. To ensure a balance between performance and stability, resources must be strictly partitioned with the following restrictions: - **Same-Origin Hash Resources** (JS/CSS): Dynamically collected during the Vite build phase in `generateBundle`, pre-cached during SW installation (`install`) to warm up, and written to the `magic-web-app-static-assets-v1` bucket. - **Same-Origin Hashed Images**: Uses runtime interception, limits the maximum number of items, and is written to the `magic-web-app-image-assets-v1` bucket. - **Fixed-Path Resources**: Fixed WASM/WebWorker resources without hashes. When requested by the page, they are tagged with `swCache=runtime` via helper functions and written to the `magic-web-app-marked-resource-assets-v1` bucket. - **Runtime Cache Exclusions**: `/sw.js`, entry HTML, `config.js`, `mockServiceWorker.js`, and `/sw/canvas-design-media/**` must stay out of the main runtime cache buckets. Current code enforces this by route matching boundaries and, for `kill`/`off`, by server-side takeover of `/sw.js`. ### 1.2 Credential Isolation for Cross-Origin Caching When performing `CacheFirst` caching and interception on cross-origin CDN resources, `credentials: "omit"` must be explicitly applied during SW match and fetch. This prevents user sensitive Tokens/Cookies from being sent, avoiding cross-origin privilege escalation or identity pollution. ### 1.3 API Caching Strategy and Three-Level Control (SWR & Request-Level Overrides) To accelerate first-screen rendering, `StaleWhileRevalidate` (SWR) cache is introduced for critical read-only GET interfaces. **Caching APIs with frequent write operations or high data consistency requirements is strictly prohibited**. During HttpClient calls, developers can use the `swCacheOption` option to determine whether to enable caching: - **`swCacheOption: "no-cache"` (Highest Priority)**: Forces direct network fetch to obtain the latest data, completely bypassing the SW cache. Suitable for scenarios like pull-to-refresh and fetching configurations after successful form submission. - **`swCacheOption: "cache"` (High Priority)**: Ignores global switches and path whitelists, forcing the response to be stored in the SW cache. Suitable for customized cold-start acceleration on specific pages. - **`swCacheOption: "default"` or unspecified (Default)**: Follows "Global Switch + Path Whitelist". As long as the global environment variable `MAGIC_ENABLE_API_CACHE` is not `"false"` and the interface path hits the whitelist validation, caching is enabled. ### 1.3.1 Environment Variable Semantics - **`MAGIC_SW_MODE`**: The browser-side registration code treats `on` and `kill` as registerable modes. `none`, `off`, empty, or unknown values mean "do not register the normal app SW" and unregister existing app SW registrations on the client. - **`MAGIC_SW_MODE=kill|off` on the server**: `server/middleware/serviceWorkerMiddleware.js` takes over `/sw.js`. `kill` returns a cleanup SW that deletes caches and unregisters itself; `off` returns a lightweight unregister-only SW. - **`MAGIC_SW_CLEAR_CACHES`**: Only meaningful when the server is serving `MAGIC_SW_MODE=kill`. It accepts a comma-separated cache bucket list, or `ALL` (case-insensitive) to clear all CacheStorage buckets for the current origin. If omitted in `kill` mode, the middleware falls back to the `off` behavior. - **`MAGIC_ENABLE_API_CACHE`**: Controls the default behavior of the request interceptor. Any value except `"false"` keeps whitelist-based API caching enabled by default. - **`MAGIC_MOCK` / `MAGIC_FORCE_ENABLE_SW_IN_DEV`**: In development, the app unregisters the normal SW unless local mock mode is enabled or `MAGIC_FORCE_ENABLE_SW_IN_DEV=true` is set. - **`MAGIC_CDNHOST` / `MAGIC_PUBLIC_CDN_URL`**: Used to build the Workbox runtime URL and vendor cache host allowlist during SW registration. ### 1.4 Anti-Nesting Misalignment and Self-Cleaning Mechanism To avoid accidental matching of unrelated interfaces that pass whitelisted APIs as query parameters (e.g., `/api/v1/proxy?url=/api/v1/settings/all`): - **Purification Before Path Matching**: `isCacheableApiRequest` must first parse the request using `new URL` to extract a clean `pathname` (stripping Query and Hash) before performing the match. - **Strict Regex Standards**: Regular expression rules defined in the whitelist **must be enforced to start with `^` and end with `$`**, prohibiting loose substring regex. - **CORS-Friendly Self-Cleaning**: The main thread interceptor guides the SW by adding `?swCache=api-runtime`, while the SW must **automatically remove this query parameter** before initiating the network fetch (`requestWillFetch`). This ensures that the actual request sent to the backend is not polluted and eliminates the impact of CORS preflight on cross-origin requests. ### 1.5 Response Envelope Strict Validati
Core canvas design skill covering project management, multimedia principles, AI image generation, web image search, and design marker processing. Load for any canvas design task. CRITICAL - When user message contains [@design_canvas_project:...] or [@design_marker:...] mentions, or when the user wants to generate video/animation/clip on a canvas project, you MUST load this skill first before any operations.
Summarize and compress the current conversation history into a structured context snapshot, then call compact_chat_history to save it. Read this skill only when the user explicitly asks to compact/summarize — system-triggered compaction injects the instructions directly without requiring a skill read.
Slide/PPT creation skill that provides complete slide creation, editing, and management capabilities. Use when users need to create slides, make presentations, edit slide content, or manage slide projects. CRITICAL - When user message contains [@slide_project:...] mention, you MUST load this skill first before any operations.
|
|
Data analysis dashboard (instrument panel) development skill. Use when users need to develop data dashboards, create/edit Dashboard projects, build large-screen data boards, or perform dashboard data cleaning. Includes dashboard project creation, card plan, data cleaning (data_cleaning.py), card management tools (create_dashboard_cards, update_dashboard_cards, delete_dashboard_cards, query_dashboard_cards), map download tool (download_dashboard_maps), dashboard development, and validation.
Use when the user wants to interact with DingTalk/钉钉 in any way — including but not limited to: reading, querying, searching, sending, replying to, forwarding, or recalling DingTalk/钉钉 chat messages and chat history; managing group chats and conversations; sending DING alerts; querying contacts, org structure, AI search, or coworkers; reading, searching, creating, or editing DingTalk/钉钉 docs, drive files, sheets, AI tables, wiki, mail, calendar events, meeting rooms, AI meeting minutes, attendance, OA approvals, todos, reports/logs, live sessions, AI apps, permissions, or open-platform docs.