javascript-ops
JavaScript and Node.js patterns, async programming, modules, runtime internals, and modern ES2024+ features. Use for: javascript, js, node, nodejs, esm, commonjs, promise, async await, event loop, v8, npm, es6, es2024, worker threads, streams, event emitter, prototype, closure.
What this skill does
# JavaScript Operations
Comprehensive reference for modern JavaScript and Node.js — async patterns, module systems, runtime internals, and ES2022-2025 features.
---
## Async Decision Tree
```
What are you doing asynchronously?
│
├─ Simple one-off operation (DB query, HTTP call)
│ └─ async/await with try/catch ✓ default choice
│
├─ Multiple independent operations
│ ├─ All must succeed → Promise.all([a(), b(), c()])
│ ├─ Don't care about failures → Promise.allSettled([...])
│ └─ First one wins → Promise.race([...]) or Promise.any([...])
│
├─ Need external resolve/reject control (deferred)
│ └─ Promise.withResolvers() (ES2024)
│
├─ Processing a sequence of async values
│ ├─ Known array → for...of with await inside loop
│ └─ Unknown/infinite sequence → async generator + for await...of
│
├─ Large data / backpressure concerns
│ └─ Streams (ReadableStream / node:stream)
│ ├─ Transform data in flight → TransformStream / Transform
│ └─ Pipe chain → stream.pipeline() (Node) / pipeThrough() (Web)
│
├─ CPU-intensive work (would block event loop)
│ ├─ Short burst → offload with setTimeout(fn, 0) to yield
│ └─ Real work → Worker (browser) / worker_threads (Node)
│ └─ Shared memory needed → SharedArrayBuffer + Atomics
│
└─ Legacy code uses callbacks
└─ Wrap with util.promisify() (Node) or new Promise() constructor
```
---
## Module System Decision Tree
```
Which module system should I use?
│
├─ New project / Node 18+
│ └─ ESM (set "type": "module" in package.json)
│ ├─ import / export syntax
│ ├─ Top-level await supported
│ └─ Better tree-shaking with bundlers
│
├─ Publishing a library
│ ├─ ESM-only → simplest, but breaks older CJS consumers
│ ├─ CJS-only → safe but no tree-shaking
│ └─ Dual package (recommended) → "exports" field with conditions
│ ├─ "import": "./dist/index.mjs"
│ └─ "require": "./dist/index.cjs"
│
├─ Existing CJS project, want ESM
│ ├─ Per-file migration → rename to .mjs, update require → import
│ ├─ Whole-project → add "type": "module", rename .cjs exceptions
│ └─ Keep CJS, add ESM wrapper → create thin .mjs re-export layer
│
├─ Browser (no bundler)
│ └─ Native ESM — <script type="module"> + importmap
│
└─ Need dynamic loading
└─ import() — works in both ESM and CJS files
├─ Lazy routes / code splitting
└─ Conditional platform code
```
**Migration path:** CJS → Dual → ESM-only
---
## Event Loop Quick Reference
```
┌─────────────────────────────────────────────────────────┐
│ Call Stack │
│ (synchronous code executes here) │
└─────────────────────────┬───────────────────────────────┘
│ stack empty?
▼
┌─────────────────────────────────────────────────────────┐
│ Microtask Queue (drained fully) │
│ • Promise.then / .catch / .finally callbacks │
│ • queueMicrotask(fn) │
│ • MutationObserver callbacks (browser) │
│ • process.nextTick (Node — runs BEFORE other microtasks)│
└─────────────────────────┬───────────────────────────────┘
│ microtasks empty?
▼
┌─────────────────────────────────────────────────────────┐
│ Macrotask Queue (one task per loop tick) │
│ • setTimeout / setInterval callbacks │
│ • setImmediate (Node — runs in "check" phase) │
│ • I/O callbacks (network, file system) │
│ • requestAnimationFrame (browser) │
│ • MessagePort / Worker messages │
└─────────────────────────────────────────────────────────┘
Node.js event loop PHASES (libuv):
timers → pending callbacks → idle/prepare → poll → check → close callbacks
└─ process.nextTick + microtasks drain after EVERY phase
```
**Key rules:**
- Microtasks always run before the next macrotask
- `process.nextTick` fires before other microtasks (Promise.then)
- `setImmediate` fires in the "check" phase, after I/O callbacks
- `setTimeout(fn, 0)` fires in "timers" phase — after I/O in same iteration
---
## Modern JS Cheat Sheet (ES2022–2025)
| Feature | Year | Usage |
|---------|------|-------|
| `Array.at(-1)` | ES2022 | Last element without `.length - 1` |
| `Object.hasOwn(obj, key)` | ES2022 | Replaces `obj.hasOwnProperty(key)` |
| `#privateField` in class | ES2022 | True private (not just convention) |
| `static {}` class block | ES2022 | One-time class initialization |
| Top-level `await` | ES2022 | `await` at module top — ESM only |
| `Error cause` | ES2022 | `new Error('msg', { cause: err })` |
| `structuredClone(obj)` | ES2022 | Deep clone — built-in, no lodash |
| `Array.findLast()` | ES2023 | Find from end |
| `WeakMap(Symbol)` | ES2023 | Symbols as WeakMap keys |
| `Object.groupBy(iter, fn)` | ES2024 | Group into plain object |
| `Map.groupBy(iter, fn)` | ES2024 | Group into Map |
| `Promise.withResolvers()` | ES2024 | Deferred pattern |
| `ArrayBuffer.prototype.resize()` | ES2024 | Grow/shrink buffer in-place |
| `String.prototype.isWellFormed()` | ES2024 | Check valid Unicode |
| `import assert { type: 'json' }` | ES2024 | Import attributes |
| `Set.prototype.union(other)` | ES2025 | Set algebra methods |
| `Set.prototype.intersection(other)` | ES2025 | Set algebra methods |
| `Set.prototype.difference(other)` | ES2025 | Set algebra methods |
| Iterator helpers (`map`, `filter`, `take`…) | ES2025 | Lazy iterator protocol |
| `using` / `Symbol.dispose` | ES2025 | Explicit resource management |
| `Temporal` API | Stage 3 | Modern date/time (replaces Date) |
| `import defer` | Stage 3 | Deferred module evaluation |
---
## Node.js Quick Start
```javascript
// Built-in test runner (Node 18+, stable in Node 20)
import { describe, it, before, after, mock } from 'node:test';
import assert from 'node:assert/strict';
describe('my module', () => {
it('adds numbers', () => {
assert.equal(1 + 1, 2);
});
});
// Run: node --test
// Watch: node --test --watch
// Coverage: node --test --experimental-test-coverage
```
```javascript
// fs/promises — built-in, no third-party needed
import { readFile, writeFile, readdir } from 'node:fs/promises';
const content = await readFile('./config.json', 'utf8');
const files = await readdir('./src', { recursive: true }); // Node 18.17+
// .env loading — Node 21+ (no dotenv package required)
// node --env-file=.env server.js
```
**Key built-in modules:**
| Module | Purpose |
|--------|---------|
| `node:fs/promises` | Async file system |
| `node:path` | Path manipulation |
| `node:url` | URL parsing, `fileURLToPath` |
| `node:crypto` | Hashing, encryption, UUIDs |
| `node:stream` | Streams + `pipeline()` |
| `node:worker_threads` | CPU parallelism |
| `node:child_process` | Subprocess execution |
| `node:test` | Built-in test runner |
| `node:http` / `node:http2` | HTTP servers |
| `node:diagnostics_channel` | Observability hooks |
| `node:perf_hooks` | Performance measurement |
---
## Error Handling Patterns
```javascript
// 1. Standard async try/catch
async function fetchUser(id) {
try {
const res = await fetch(`/api/users/${id}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`, { cause: res });
return await res.json();
} catch (err) {
console.error('fetchUser failed:', err);
throw err; // re-throw unless you can recover
}
}
// 2. Abort with timeout (Node 17.3+ / browsers)
const signal = AbortSignal.timeout(5000);
const res = await fetch(url, { signal });
// 3. Global unhandled rejection handler
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled rejection:', reason);
process.exit(1); // always exit — unknown state
});
// 4. AggregateError — wraps multiple errors
const results = await Promise.allSettled([a(), b(), c()]);
const failures = results.filter(r => r.status === 'rejected');
if (faRelated in Design
contribute
IncludedLocal-only OSS contribution command center. Auto-refreshes the user's in-flight PR and issue state on invoke so conversations start with full context — no need to brief Claude on what's in flight. Helps the user find issues to contribute to on GitHub, builds per-repo dossiers of what each upstream expects (CLA, DCO, branch convention, AI policy, draft-first, review bots, issue templates), runs deterministic gates before any external action so AI-assisted contributions don't reach maintainers as slop. State is markdown-only: candidate files at ~/.contribute-system/candidates/, repo dossiers at ~/.contribute-system/research/, append-only event log at ~/.contribute-system/log.jsonl. No database, no cloud calls. Use when the user asks about their PRs / issues / contributions, wants to find new work to take on, claim an issue, build/refresh a repo's dossier, or draft a Design Issue or PR. Trigger with "/contribute", "what's my PR status", "find a contribution", "claim issue X", "draft a Design Issue for Y", "refresh dossier for Z".
architectural-analysis
IncludedUser-triggered deep architectural analysis of a codebase or scoped subtree across eight modes — information architecture, data flow, integration points, UI surfaces, interaction patterns, data model, control flow, and failure modes. This skill should be used when the user asks to "diagram this codebase," "map the architecture," "show the data flow," "give me an ERD," "trace control flow," "find the integration points," "verify the layout pattern," "audit the UX architecture," or any similar request whose primary deliverable is mermaid diagrams plus cited reports under docs/architecture/. Dispatches haiku/sonnet sub-agents in parallel for per-mode exploration, then verifies every citation mechanically before any node lands in a diagram. Not for one-off prose explanations of code (use code-explanation) or for high-level system design from scratch (use system-design).
mcp
IncludedModel Context Protocol (MCP) server development and tool management. Languages: Python, TypeScript. Capabilities: build MCP servers, integrate external APIs, discover/execute MCP tools, manage multi-server configs, design agent-centric tools. Actions: create, build, integrate, discover, execute, configure MCP servers/tools. Keywords: MCP, Model Context Protocol, MCP server, MCP tool, stdio transport, SSE transport, tool discovery, resource provider, prompt template, external API integration, Gemini CLI MCP, Claude MCP, agent tools, tool execution, server config. Use when: building MCP servers, integrating external APIs as MCP tools, discovering available MCP tools, executing MCP capabilities, configuring multi-server setups, designing tools for AI agents.
react-native-skia
IncludedDesign, build, debug, and optimise high-polish animated graphics in React Native or Expo using @shopify/react-native-skia, Reanimated, and Gesture Handler. Use when the user wants canvas-driven UI, shaders, paths, rich text, image filters, sprite fields, Skottie, video frames, snapshots, web CanvasKit setup, or performance tuning for custom motion-heavy elements such as loaders, hero art, cards, charts, progress indicators, particle systems, or gesture-driven surfaces. Also use when the user asks for fluid, glow, glass, blob, parallax, 60fps/120fps, or GPU-friendly animated effects in React Native, even if they do not explicitly say "Skia". Do not use for ordinary form/layout work with standard views.
plaid
IncludedProduct Led AI Development — guides founders from idea to launched product. Six capabilities: Idea (discover a product idea), Validate (pressure-test the idea against fatal flaws, problem reality, competition, and 2-week MVP feasibility), Plan (vision intake + document generation), Design (translate image references into a design.md spec), Launch (go-to-market strategy), and Build (roadmap execution). Use when someone says "PLAID", "plaid idea", "help me find an idea", "product idea", "idea from my business", "idea from my expertise", "plaid validate", "validate my idea", "pressure-test", "is this idea good", "find fatal flaws", "validate the problem", "plan a product", "define my vision", "generate a PRD", "product strategy", "plaid design", "design from image", "translate image to design", "create design.md", "extract design tokens", "plaid launch", "go-to-market", "launch plan", "GTM strategy", "launch playbook", "plaid build", "build the app", "start building", or "execute the roadmap".
nextjs-framer-motion-animations
IncludedAdds production-safe Motion for React or Framer Motion animations to Next.js apps, including reveal, hover and tap micro-interactions, whileInView, stagger, AnimatePresence, layout and layoutId transitions, reorder, scroll-linked UI, and lightweight route-content transitions. Use when the user asks to add, refactor, or debug Motion or Framer Motion in App Router or Pages Router codebases, especially around server/client boundaries, reduced motion, LazyMotion, bundle size, hydration, or route transitions. Avoid for GSAP-style timelines, WebGL or 3D scenes, heavy scroll storytelling, or CSS-only effects unless Motion is explicitly requested.