### Install Tessl Tooling Source: https://github.com/mcollina/skills/blob/main/docs/skill-benchmarking.md Installs the Tessl command-line tool. Run this command to get started with Tessl. ```bash curl -fsSL https://get.tessl.io | sh ``` -------------------------------- ### Diátaxis Framework: How-to Guide Example Source: https://context7.com/mcollina/skills/llms.txt Structure documentation as a how-to guide, which is problem-oriented and assumes some prior knowledge. This example shows adding JWT authentication to an existing Fastify app. ```markdown # How to add JWT authentication to an existing Fastify app This guide assumes a working Fastify server and basic knowledge of middleware. 1. Install `@fastify/jwt`: `npm install @fastify/jwt` 2. Register the plugin with your secret ... ``` -------------------------------- ### Minimal Fastify Server Setup Source: https://github.com/mcollina/skills/blob/main/skills/fastify/SKILL.md A basic Fastify server to get started quickly. It includes logger configuration and a simple health check route. ```typescript import Fastify from 'fastify' const app = Fastify({ logger: true }) app.get('/health', async (request, reply) => { return { status: 'ok' } }) const start = async () => { await app.listen({ port: 3000, host: '0.0.0.0' }) } start() ``` -------------------------------- ### JavaScript Setup Function Pattern: Default OFF Source: https://github.com/mcollina/skills/blob/main/skills/nodejs-core/rules/cli-options.md Example of a JavaScript setup function that only executes if a specific experimental CLI option is enabled. Used for opt-in features. ```javascript function setupFoo() { if (!getOptionValue('--experimental-foo')) { return; // Not enabled, don't allow } const { BuiltinModule } = require('internal/bootstrap/realm'); BuiltinModule.allowRequireByUsers('foo'); } ``` -------------------------------- ### Install Dependencies Source: https://github.com/mcollina/skills/blob/main/AGENTS.md Run this command to install all necessary project dependencies. ```bash npm install ``` -------------------------------- ### JavaScript Setup Function Pattern: Default ON Source: https://github.com/mcollina/skills/blob/main/skills/nodejs-core/rules/cli-options.md Example of a JavaScript setup function that executes unless a specific CLI option is explicitly disabled. Used for opt-out features. ```javascript function setupSQLite() { if (getOptionValue('--no-experimental-sqlite')) { return; // User explicitly disabled it } const { BuiltinModule } = require('internal/bootstrap/realm'); BuiltinModule.allowRequireByUsers('sqlite'); } ``` -------------------------------- ### Install Neostandard and ESLint Source: https://github.com/mcollina/skills/blob/main/skills/linting-neostandard-eslint9/rules/neostandard.md Install neostandard and eslint as development dependencies. ```bash npm install --save-dev neostandard eslint ``` -------------------------------- ### Build System Prerequisites Installation Source: https://github.com/mcollina/skills/blob/main/skills/nodejs-core/rules/build-system.md Commands to install necessary build tools on Ubuntu/Debian, macOS, and Windows. ```bash # Ubuntu/Debian sudo apt-get install -y \ build-essential \ python3 \ g++ \ make \ ninja-build # macOS xcode-select --install # Windows # Install Visual Studio 2022 with C++ workload # Install Python 3 ``` -------------------------------- ### Install ESLint and Neostandard Source: https://github.com/mcollina/skills/blob/main/skills/linting-neostandard-eslint9/rules/eslint-v9-flat-config.md Install ESLint and neostandard as development dependencies. ```bash npm install --save-dev eslint neostandard ``` -------------------------------- ### node-gyp Installation and Basic Commands Source: https://github.com/mcollina/skills/blob/main/skills/nodejs-core/rules/build-system.md Instructions for installing node-gyp globally and performing common build operations like configure, build, rebuild, and clean. ```bash # Install globally npm install -g node-gyp # Configure (generates build files) node-gyp configure # Build node-gyp build # Rebuild (clean + configure + build) node-gyp rebuild # Clean node-gyp clean # Debug build node-gyp configure --debug node-gyp build --debug ``` -------------------------------- ### Typical Development Setup Source: https://github.com/mcollina/skills/blob/main/skills/nodejs-core/rules/configure.md Run the configure script for a standard development build. ```bash ./configure ``` -------------------------------- ### Install node-addon-api Source: https://github.com/mcollina/skills/blob/main/skills/nodejs-core/rules/node-addon-api.md Install the node-addon-api package using npm. ```bash npm install node-addon-api ``` -------------------------------- ### Install Benchmark Skill with Tessl Source: https://github.com/mcollina/skills/blob/main/docs/skill-benchmarking.md Installs the 'review-model-performance' benchmark skill using Tessl. This skill is used to evaluate model performance. ```bash tessl i tessl-labs/review-model-performance ``` -------------------------------- ### Quick JS Iteration Setup Source: https://github.com/mcollina/skills/blob/main/skills/nodejs-core/rules/configure.md Configure to load lib/ from disk, avoiding rebuilds for lib/ changes. ```bash ./configure --node-builtin-modules-path "$(pwd)/lib" ``` -------------------------------- ### Start LLDB with Node.js Source: https://github.com/mcollina/skills/blob/main/skills/nodejs-core/rules/debugging-native.md Launch LLDB and load the Node.js executable to debug a script. ```bash lldb -- ./node script.js ``` -------------------------------- ### Install ESLint Dependencies for Manual Config Source: https://github.com/mcollina/skills/blob/main/skills/linting-neostandard-eslint9/rules/eslint-v9-flat-config.md Install ESLint, ESLint JS, and typescript-eslint for manual configuration. ```bash npm install --save-dev eslint @eslint/js typescript-eslint ``` -------------------------------- ### Reference Entry Example Source: https://github.com/mcollina/skills/blob/main/skills/documentation/SKILL.md Demonstrates the structure for a reference entry, including name, type, default value, description, and an example. Use this format for API endpoints, configuration options, or CLI flags. ```text `timeout` (integer, default: `5000`) Maximum time in milliseconds to wait for a response before the request fails. *Example:* { timeout: 3000 } ``` -------------------------------- ### Commit Message Examples Source: https://github.com/mcollina/skills/blob/main/skills/nodejs-core/rules/contributing.md Examples demonstrating the commit message format for different types of changes. ```text # Bug fix fs: fix race condition in readdir ``` ```text # New feature stream: add toArray method ``` ```text # Test test: add missing coverage for http ``` ```text # Documentation doc: clarify buffer.slice behavior ``` ```text # Build build: fix gyp warnings on Windows ``` -------------------------------- ### GDB Init File Configuration Source: https://github.com/mcollina/skills/blob/main/skills/nodejs-core/rules/debugging-native.md Example configuration for the ~/.gdbinit file to enhance GDB usability for Node.js debugging. ```bash # ~/.gdbinit set print pretty on set print object on set print static-members on set print vtbl on set print demangle on set pagination off set history save on set history size 10000 # Load Node.js helpers source /path/to/node/tools/gdb/v8-gdb-helpers.py ``` -------------------------------- ### Install Node.js Development Headers Source: https://github.com/mcollina/skills/blob/main/skills/nodejs-core/rules/build-system.md If you encounter 'fatal error: node.h: No such file or directory', install the Node.js development headers. ```bash node-gyp install ``` -------------------------------- ### Diátaxis Framework: Tutorial Example Source: https://context7.com/mcollina/skills/llms.txt Structure documentation as a tutorial, which is learning-oriented and requires no prior experience. Each step should produce a verifiable result. ```markdown # Build your first Fastify REST API In this tutorial, you will create a running HTTP server that responds to GET requests. No prior Fastify experience is required. **Step 1:** Install Fastify ```bash npm install fastify ``` **Step 2:** Create `server.ts` ... (each step produces a verifiable result) ``` -------------------------------- ### Install OAuth Dependencies Source: https://github.com/mcollina/skills/blob/main/skills/oauth/SKILL.md Install the necessary npm packages for OAuth 2.0/2.1 integration with Fastify. ```bash npm install @fastify/oauth2 @fastify/cookie @fastify/session fastify-plugin ``` -------------------------------- ### Install prebuildify for Prebuilding Binaries Source: https://github.com/mcollina/skills/blob/main/skills/nodejs-core/rules/build-system.md Install `prebuildify` as a development dependency to automate the prebuilding of native Node.js modules. ```bash npm install prebuildify --save-dev ``` -------------------------------- ### Install ESLint v9 and NeoStandard Source: https://github.com/mcollina/skills/blob/main/skills/linting-neostandard-eslint9/SKILL.md Install the necessary dependencies for ESLint v9 and neostandard using npm. ```bash npm install --save-dev eslint@9 neostandard ``` -------------------------------- ### Start GDB with Node.js Arguments Source: https://github.com/mcollina/skills/blob/main/skills/nodejs-core/rules/debugging-native.md Launch GDB and provide arguments to the Node.js executable for debugging. ```bash gdb --args ./node script.js ``` -------------------------------- ### Calling Setup Functions in Node.js Bootstrap Source: https://github.com/mcollina/skills/blob/main/skills/nodejs-core/rules/cli-options.md Illustrates where to call custom setup functions within the Node.js bootstrap process, typically within `prepareExecution()`. ```javascript function prepareExecution(options) { // ... existing setup calls ... setupFoo(); // Add alongside setupSQLite(), setupQuic(), etc. } ``` -------------------------------- ### Node.js fs_event_wrap Start Function Source: https://github.com/mcollina/skills/blob/main/skills/nodejs-core/rules/fs-internals.md The C++ implementation detail for starting file system event watchers, abstracting platform-specific APIs like inotify, FSEvents, or ReadDirectoryChangesW. ```cpp // From src/fs_event_wrap.cc void FSEventWrap::Start(const FunctionCallbackInfo& args) { FSEventWrap* wrap; ASSIGN_OR_RETURN_UNWRAP(&wrap, args.This()); node::Utf8Value path(env->isolate(), args[0]); // Platform-specific: inotify (Linux), FSEvents (macOS), // ReadDirectoryChangesW (Windows) int err = uv_fs_event_start(&wrap->handle_, OnEvent, *path, 0); args.GetReturnValue().Set(err); } ``` -------------------------------- ### Install why-is-node-running for Diagnostics Source: https://github.com/mcollina/skills/blob/main/skills/node/rules/stuck-processes-and-tests.md Install the `why-is-node-running` package as a development dependency. Use it for diagnostics, but gate noisy output behind an environment flag in CI. ```bash # ESM / modern Node: `npm i -D why-is-node-running` # older CommonJS projects: `npm i -D why-is-node-running@v2` ``` -------------------------------- ### CMake.js Alternative for CMake Projects Source: https://github.com/mcollina/skills/blob/main/skills/nodejs-core/rules/build-system.md Demonstrates how to install and use CMake.js as an alternative build system for Node.js projects that prefer CMake. ```bash npm install cmake-js --save-dev ``` ```cmake # CMakeLists.txt cmake_minimum_required(VERSION 3.15) project(addon) include_directories(${CMAKE_JS_INC}) add_library(${PROJECT_NAME} SHARED src/addon.cpp ) set_target_properties(${PROJECT_NAME} PROPERTIES PREFIX "" SUFFIX ".node" ) target_link_libraries(${PROJECT_NAME} ${CMAKE_JS_LIB}) ``` -------------------------------- ### Diátaxis Framework: Reference Example Source: https://context7.com/mcollina/skills/llms.txt Structure documentation as a reference, which is information-oriented and designed for quick scanning. This example details the `closeWithGrace` function signature and options. ```markdown ## `closeWithGrace(options, handler)` **options.delay** *(number, default: `10000`)* — milliseconds to wait before forcing exit. **handler** *`({ signal, err }) => Promise`* — async cleanup function. ``` -------------------------------- ### Basic Pino Logger Setup Source: https://github.com/mcollina/skills/blob/main/skills/node/rules/logging.md Initialize a Pino logger with a configurable log level. Use this for general application logging. ```typescript import pino from 'pino'; const logger = pino({ level: process.env.LOG_LEVEL || 'info', }); logger.info({ userId: user.id }, 'User created'); logger.error({ err, orderId: order.id }, 'Failed to process payment'); ``` -------------------------------- ### Install and Use Clinic.js for Profiling Source: https://github.com/mcollina/skills/blob/main/skills/nodejs-core/rules/profiling-v8.md Install Clinic.js globally and use its tools like `doctor` (overview), `flame` (CPU profiling), and `bubbleprof` (async profiling) to diagnose performance issues in Node.js applications. ```bash # Install npm install -g clinic # Doctor (overview) clinic doctor -- node app.js # Flame (CPU profiling) clinic flame -- node app.js # Bubbleprof (async profiling) clinic bubbleprof -- node app.js ``` -------------------------------- ### Example Commit Metadata Source: https://github.com/mcollina/skills/blob/main/skills/nodejs-core/rules/contributing.md Illustrates the format for commit metadata, including subsystem, detailed explanation, PR URL, fixes, and reviewed-by. ```text subsystem: description Detailed explanation of the change. PR-URL: https://github.com/nodejs/node/pull/12345 Fixes: https://github.com/nodejs/node/issues/12344 Reviewed-By: James M Snell Reviewed-By: Anna Henningsen ``` -------------------------------- ### Example .env File Structure Source: https://github.com/mcollina/skills/blob/main/skills/node/rules/environment.md Illustrates a recommended structure for organizing `.env` files, including `.env.example` for documentation, `.env` for local development, and `.env.test` for testing environments. ```bash # .env.example - committed to git, documents all variables PORT=3000 DATABASE_URL=postgresql://user:pass@localhost:5432/db API_KEY=your-api-key-here # .env - local development, NOT committed PORT=3000 DATABASE_URL=postgresql://dev:dev@localhost:5432/myapp API_KEY=sk-dev-key-123 # .env.test - test environment DATABASE_URL=postgresql://test:test@localhost:5432/myapp_test ``` -------------------------------- ### Set Up Development Environment Source: https://github.com/mcollina/skills/blob/main/skills/nodejs-core/rules/contributing.md Clone the Node.js repository and set up the upstream remote for tracking changes. ```bash git clone https://github.com/YOUR_USERNAME/node.git cd node git remote add upstream https://github.com/nodejs/node.git ``` -------------------------------- ### Bad Example: Common Resource Leak in Test Source: https://github.com/mcollina/skills/blob/main/skills/node/rules/stuck-processes-and-tests.md This example demonstrates a common pattern where resources like servers or intervals are started but not deterministically cleaned up within the test scope, leading to potential hangs. ```typescript it('serves requests', async () => { const server = await startServer({ port: 0 }); const id = setInterval(() => {}, 1000); // test body... // ❌ no deterministic teardown }); ``` -------------------------------- ### package.json Scripts for TypeScript Source: https://github.com/mcollina/skills/blob/main/skills/fastify/rules/typescript.md Configure package.json scripts to easily start and develop Fastify applications with TypeScript. This setup assumes you are using Node.js modules. ```json { "type": "module", "scripts": { "start": "node app.ts", "dev": "node --watch app.ts" } } ``` -------------------------------- ### Inspect napi_value with LLDB Source: https://github.com/mcollina/skills/blob/main/skills/nodejs-core/rules/debugging-native.md A `napi_value` is an opaque pointer. You can cast it to a V8 type in LLDB to inspect its underlying value, for example, to get the length of a string. ```lldb # napi_value is an opaque pointer (lldb) p (v8::Value*)value # Cast and inspect (lldb) p ((v8::String*)value)->Utf8Length(isolate) ``` -------------------------------- ### Writing V8 Heap Snapshots Source: https://github.com/mcollina/skills/blob/main/skills/nodejs-core/rules/v8-garbage-collection.md Provides Node.js code examples for generating heap snapshots, both synchronously to a file and by streaming to a file. ```javascript const v8 = require('node:v8'); const fs = require('node:fs'); // Write heap snapshot function writeHeapSnapshot() { const filename = v8.writeHeapSnapshot(); console.log(`Heap snapshot written to ${filename}`); return filename; } // Stream heap snapshot (lower memory overhead) function streamHeapSnapshot() { const filename = `heap-${Date.now()}.heapsnapshot`; const stream = fs.createWriteStream(filename); v8.writeHeapSnapshot(filename); return filename; } ``` -------------------------------- ### Test Plugins in Isolation Source: https://github.com/mcollina/skills/blob/main/skills/fastify/rules/testing.md This example demonstrates testing a Fastify plugin independently. It registers the `cachePlugin` with specific options and then asserts that Fastify has been decorated with the expected cache methods (`get`, `set`). The tests verify the plugin's functionality by caching and retrieving a value. ```typescript import { describe, it, before, after } from 'node:test'; import Fastify from 'fastify'; import cachePlugin from './plugins/cache.js'; describe('Cache Plugin', () => { let app; before(async () => { app = Fastify(); app.register(cachePlugin, { ttl: 1000 }); await app.ready(); }); after(async () => { await app.close(); }); it('should decorate fastify with cache', (t) => { t.assert.ok(app.hasDecorator('cache')); t.assert.equal(typeof app.cache.get, 'function'); t.assert.equal(typeof app.cache.set, 'function'); }); it('should cache and retrieve values', (t) => { app.cache.set('key', 'value'); t.assert.equal(app.cache.get('key'), 'value'); }); }); ``` -------------------------------- ### Allocation Site Feedback Example Source: https://github.com/mcollina/skills/blob/main/skills/nodejs-core/rules/v8-garbage-collection.md Shows how V8 tracks allocation sites to optimize object placement, potentially allocating long-lived objects directly in the old space after profiling. ```javascript // V8 learns that objects from this function live long function createLongLivedConfig() { return { setting1: 'value1', setting2: 'value2', // After profiling, V8 may allocate directly in old space }; } // Called once at startup const config = createLongLivedConfig(); ``` -------------------------------- ### N-API vs V8 API Example Source: https://github.com/mcollina/skills/blob/main/skills/nodejs-core/rules/napi.md Illustrates the difference between the old V8 API and the stable N-API for creating strings. Use N-API for cross-version compatibility. ```cpp // OLD: V8 API (breaks between Node.js versions) v8::Local str = v8::String::NewFromUtf8(isolate, "hello"); // NEW: N-API (stable across versions) napi_value str; napi_create_string_utf8(env, "hello", NAPI_AUTO_LENGTH, &str); ``` -------------------------------- ### Find Installed Package Version Source: https://github.com/mcollina/skills/blob/main/skills/node/rules/node-modules-exploration.md Check the installed version of a package by inspecting its package.json file or using npm ls. ```bash cat node_modules/fastify/package.json | grep "version" # For scoped packages cat node_modules/@fastify/cors/package.json | grep "version" # List all versions with npm npm ls fastify ``` -------------------------------- ### Example Bytecode for Addition Source: https://github.com/mcollina/skills/blob/main/skills/nodejs-core/rules/v8-jit-compilation.md This is an example of the bytecode generated by V8's Ignition interpreter for a simple JavaScript addition function. ```javascript function add(a, b) { return a + b; } ``` ```text Bytecode: Ldar a1 ; Load argument 1 to accumulator Add a0, [0] ; Add argument 0 to accumulator Return ; Return accumulator ``` -------------------------------- ### Verify NeoStandard CLI Help Source: https://github.com/mcollina/skills/blob/main/skills/linting-neostandard-eslint9/rules/migration-from-standard.md Before generating the configuration, verify that the 'neostandard' command-line interface is installed correctly and accessible by checking its help output. ```bash npx neostandard --help ``` -------------------------------- ### Type-Safe Access Control Example Source: https://github.com/mcollina/skills/blob/main/skills/typescript-magician/rules/array-index-access.md A practical example demonstrating type-safe role-based access control using derived action types. ```typescript const userAccessModel = { user: ["update-self", "view"], admin: ["create", "update-self", "update-any", "delete", "view"], anonymous: ["view"], } as const; type Role = keyof typeof userAccessModel; type Action = typeof userAccessModel[Role][number]; const canUserAccess = (role: Role, action: Action): boolean => { // Need to cast because TypeScript can't narrow the array type return (userAccessModel[role] as ReadonlyArray).includes(action); }; // Type-safe usage canUserAccess("admin", "delete"); // OK canUserAccess("user", "delete"); // OK at compile time, false at runtime canUserAccess("admin", "invalid"); // Error: "invalid" is not assignable to Action ``` -------------------------------- ### Performance Sampling with 'sample' (macOS) Source: https://github.com/mcollina/skills/blob/main/skills/nodejs-core/rules/debugging-native.md Use the 'sample' command on macOS to collect performance data for a Node.js process. Specify the duration and an output file. ```bash # macOS sample sample node 10 -file /tmp/sample.txt ``` -------------------------------- ### Disable ESLint Rule in Example Source: https://github.com/mcollina/skills/blob/main/skills/nodejs-core/rules/documentation.md Use eslint-disable comments to bypass lint rule conflicts when necessary within code examples. ```javascript // eslint-disable-next-line no-unused-vars for await (const chunk of readable) { // Consume until done } ``` -------------------------------- ### Implement Resource Cleanup with RAII Source: https://github.com/mcollina/skills/blob/main/skills/nodejs-core/rules/node-addon-api.md Shows how to use Resource Acquisition Is Initialization (RAII) patterns with a ScopedLock class to ensure mutexes are properly unlocked, preventing deadlocks. ```cpp // Use RAII patterns class ScopedLock { public: ScopedLock(std::mutex& m) : mutex_(m) { mutex_.lock(); } ~ScopedLock() { mutex_.unlock(); } private: std::mutex& mutex_; }; Napi::Value ThreadSafeAccess(const Napi::CallbackInfo& info) { ScopedLock lock(mutex_); // Safe access to shared resource return Napi::Number::New(info.Env(), sharedValue_); } ``` -------------------------------- ### Initialize Snipgrapher Configuration Source: https://github.com/mcollina/skills/blob/main/skills/snipgrapher/rules/setup-and-configuration.md Run this command to create a baseline configuration file in your current project. Supported filenames include .json, .yaml, .yml, and .toml. ```bash snipgrapher init ``` -------------------------------- ### Basic Fastify WebSocket Setup Source: https://github.com/mcollina/skills/blob/main/skills/fastify/rules/websockets.md Integrates WebSocket support into a Fastify application and sets up a basic echo server. Requires the @fastify/websocket plugin. ```typescript import Fastify from 'fastify'; import websocket from '@fastify/websocket'; const app = Fastify(); app.register(websocket); app.get('/ws', { websocket: true }, (socket, request) => { socket.on('message', (message) => { const data = message.toString(); console.log('Received:', data); // Echo back socket.send(`Echo: ${data}`); }); socket.on('close', () => { console.log('Client disconnected'); }); socket.on('error', (error) => { console.error('WebSocket error:', error); }); }); await app.listen({ port: 3000 }); ``` -------------------------------- ### Deoptimization Example Source: https://github.com/mcollina/skills/blob/main/skills/nodejs-core/rules/v8-jit-compilation.md This example demonstrates V8 deoptimization. Initially, the `add` function is optimized for numbers. When called with strings, it triggers a 'not a number' deoptimization. ```javascript function add(a, b) { return a + b; } for (let i = 0; i < 100000; i++) { add(i, i + 1); // Optimized for numbers } add("hello", "world"); // Type mismatch! // DEOPTIMIZATION: eager - not a number ``` -------------------------------- ### Registering CLI Options in C++ Source: https://github.com/mcollina/skills/blob/main/skills/nodejs-core/rules/cli-options.md Examples of using `AddOption` to register CLI flags within different option parser constructors. Shows how to set default values and control environment variable inheritance. ```cpp // In EnvironmentOptionsParser::EnvironmentOptionsParser(): // Default OFF — user must pass --experimental-foo AddOption("--experimental-foo", "experimental foo module", &EnvironmentOptions::experimental_foo, kAllowedInEnvvar); // Default ON — user can pass --no-experimental-sqlite to disable AddOption("--experimental-sqlite", "experimental node:sqlite module", &EnvironmentOptions::experimental_sqlite, kAllowedInEnvvar, true); // default_is_true → help text shows --no-* variant ``` ```cpp // In PerIsolateOptionsParser::PerIsolateOptionsParser(eop): AddOption("--track-heap-objects", "track heap object allocations for heap snapshots", &PerIsolateOptions::track_heap_objects, kAllowedInEnvvar); ``` ```cpp // In PerProcessOptionsParser::PerProcessOptionsParser(iop): AddOption("--title", "the process title to use on startup", &PerProcessOptions::title, kAllowedInEnvvar); ``` ```cpp // In DebugOptionsParser::DebugOptionsParser(): AddOption("--inspect", "activate inspector on host:port (default: 127.0.0.1:9229)", &DebugOptions::inspector_enabled, kAllowedInEnvvar); ``` -------------------------------- ### Full Test Cycle Command Source: https://github.com/mcollina/skills/blob/main/skills/nodejs-core/rules/build-and-test-workflow.md Execute this command to perform the complete build and test cycle, recommended before pushing changes. ```bash # Build + all tests (recommended before pushing): make test ``` -------------------------------- ### Check Package Main Entry Point Source: https://github.com/mcollina/skills/blob/main/skills/node/rules/node-modules-exploration.md Examine the 'main' or 'exports' field in package.json to determine the package's entry point. ```bash cat node_modules/fastify/package.json | grep "main"\|grep "exports" ``` -------------------------------- ### Complete Example: Type-Safe HTTP Methods Source: https://github.com/mcollina/skills/blob/main/skills/typescript-magician/rules/as-const-typeof.md Shows a complete example of defining HTTP methods with `as const` and deriving type-safe union types for function parameters. ```typescript // Single source of truth for HTTP methods const HTTP_METHODS = { GET: "GET", POST: "POST", PUT: "PUT", DELETE: "DELETE", PATCH: "PATCH", } as const; type HttpMethod = typeof HTTP_METHODS[keyof typeof HTTP_METHODS]; // Type: "GET" | "POST" | "PUT" | "DELETE" | "PATCH" type SafeMethod = typeof HTTP_METHODS["GET"]; // Type: "GET" type MutatingMethod = typeof HTTP_METHODS["POST" | "PUT" | "DELETE" | "PATCH"]; // Type: "POST" | "PUT" | "DELETE" | "PATCH" function makeRequest(method: HttpMethod, url: string): void { // method is type-safe } makeRequest(HTTP_METHODS.GET, "/api/users"); // OK makeRequest("INVALID", "/api/users"); // Error ``` -------------------------------- ### Debug Build and Make Source: https://github.com/mcollina/skills/blob/main/skills/nodejs-core/rules/configure.md Build a debug version of the application and then compile it using make. ```bash ./configure --debug make -j$(nproc) ``` -------------------------------- ### LLDB Python Scripting Example Source: https://github.com/mcollina/skills/blob/main/skills/nodejs-core/rules/debugging-native.md Write custom commands for LLDB using Python. This example defines a command 'mycommand' that prints the current function name. ```python # LLDB Python script import lldb def my_command(debugger, command, result, internal_dict): target = debugger.GetSelectedTarget() process = target.GetProcess() thread = process.GetSelectedThread() frame = thread.GetSelectedFrame() # Custom logic print(f"In function: {frame.GetFunctionName()}") lldb.debugger.HandleCommand('command script add -f my_script.my_command mycommand') ``` -------------------------------- ### Dual CJS/ESM Code Example - ESM Source: https://github.com/mcollina/skills/blob/main/skills/nodejs-core/rules/documentation.md Provide an ESM variant for code examples using the `mjs` language tag. Top-level await can be used directly. ```mjs import { Readable } from 'node:stream'; import { from, text } from 'node:stream/iter'; const readable = Readable.fromStreamIter(from('hello')); console.log(await text(from(readable))); ``` -------------------------------- ### Test Hooks for Setup and Teardown Source: https://github.com/mcollina/skills/blob/main/skills/node/rules/testing.md Use lifecycle hooks (`before`, `after`, `beforeEach`, `afterEach`) to manage setup and teardown logic for tests, ensuring a clean state for each test or suite. ```typescript import { describe, it, before, after, beforeEach, afterEach } from 'node:test'; describe('Database tests', () => { let db: Database; before(async () => { db = await Database.connect(testConfig); }); after(async () => { await db.disconnect(); }); beforeEach(async () => { await db.beginTransaction(); }); afterEach(async () => { await db.rollback(); }); it('should insert record', async (t) => { await db.insert({ name: 'test' }); const records = await db.findAll(); t.assert.equal(records.length, 1); }); }); ``` -------------------------------- ### Enable Static Linking on Linux Source: https://github.com/mcollina/skills/blob/main/skills/nodejs-core/rules/build-system.md Configure the build system for static linking on Linux by passing the `--fully-static` flag to `./configure`. ```bash ./configure --fully-static ``` -------------------------------- ### Sequential Plugin Registration with after() Source: https://github.com/mcollina/skills/blob/main/skills/fastify/rules/plugins.md Illustrates how to ensure plugins are loaded in a specific order using the `after()` method for explicit sequencing of dependencies. ```typescript import Fastify from 'fastify'; import databasePlugin from './plugins/database.js'; import authPlugin from './plugins/auth.js'; import routesPlugin from './routes/index.js'; const app = Fastify(); // Database must be ready before auth app.register(databasePlugin); // Auth depends on database app.register(authPlugin); // Routes depend on both app.register(routesPlugin); // Or use after() for explicit sequencing app.register(databasePlugin).after(() => { app.register(authPlugin).after(() => { app.register(routesPlugin); }); }); await app.ready(); ``` -------------------------------- ### Initialize Snipgrapher Project Configuration Source: https://github.com/mcollina/skills/blob/main/skills/snipgrapher/SKILL.md Run this command to create a default snipgrapher configuration file (`snipgrapher.config.json`) for your project. This is recommended for ongoing use and defining reusable profiles. ```bash npx snipgrapher init ``` -------------------------------- ### Dual CJS/ESM Code Example - CJS Source: https://github.com/mcollina/skills/blob/main/skills/nodejs-core/rules/documentation.md Provide a CommonJS variant for code examples using the `cjs` language tag. Top-level await must be wrapped in an async function. ```cjs const { Readable } = require('node:stream'); const { from, text } = require('node:stream/iter'); async function run() { const readable = Readable.fromStreamIter(from('hello')); console.log(await text(from(readable))); } run().catch(console.error); ``` -------------------------------- ### Browse Good First Issues Source: https://github.com/mcollina/skills/blob/main/skills/nodejs-core/rules/contributing.md Find issues suitable for newcomers using GitHub's web interface or the GitHub CLI. ```bash # Browse issues labeled "good first issue" # https://github.com/nodejs/node/labels/good%20first%20issue ``` ```bash # Or use GitHub CLI gh issue list --label "good first issue" --repo nodejs/node ``` -------------------------------- ### Minimal Type-Stripped TypeScript Example Source: https://github.com/mcollina/skills/blob/main/skills/node/SKILL.md A basic example of a TypeScript file that can be run directly with Node.js 22.6+ using type stripping. Ensure all type-only imports use 'import type'. ```typescript // greet.ts import type { IncomingMessage } from 'node:http'; const greet = (name: string): string => `Hello, ${name}!`; console.log(greet('world')); ``` ```bash node greet.ts ``` -------------------------------- ### Package.json Scripts for TypeScript Source: https://github.com/mcollina/skills/blob/main/skills/fastify/rules/typescript.md This `package.json` configuration includes scripts for starting the application with TypeScript (`start`), performing type checking (`typecheck`), and running tests that include a type check (`test`). ```json { "scripts": { "start": "node app.ts", "typecheck": "tsc --noEmit", "test": "npm run typecheck && node --test" } } ``` -------------------------------- ### Standard Build Command Source: https://github.com/mcollina/skills/blob/main/skills/nodejs-core/rules/build-and-test-workflow.md Execute this command to build the Node.js binary. It produces a './node' symlink pointing to 'out/Release/node'. ```bash make -j$(nproc) ``` -------------------------------- ### Configure node-pre-gyp Binary Path Source: https://github.com/mcollina/skills/blob/main/skills/nodejs-core/rules/build-system.md Configure `node-pre-gyp` settings in `package.json` to specify module name, path, host, remote path, and package name for prebuilt binaries. ```json { "binary": { "module_name": "addon", "module_path": "./lib/binding/{platform}-{arch}", "host": "https://github.com/user/repo/releases/download/", "remote_path": "v{version}", "package_name": "{module_name}-v{version}-{platform}-{arch}.tar.gz" } } ``` -------------------------------- ### DOM querySelector Overload Example Source: https://github.com/mcollina/skills/blob/main/skills/typescript-magician/rules/function-overloads.md A simplified example of how `querySelector` uses overloads to infer specific element types based on the tag name provided. This improves type safety when interacting with the DOM. ```typescript interface Document { querySelector( selectors: K ): HTMLElementTagNameMap[K] | null; querySelector(selectors: string): Element | null; } const body = document.querySelector("body"); // Type: HTMLBodyElement | null const custom = document.querySelector(".my-class"); // Type: Element | null ``` -------------------------------- ### Install and Use `ncu-ci` for CI Status Source: https://github.com/mcollina/skills/blob/main/skills/nodejs-core/rules/reviewing-prs.md Install the `node-core-utils` package globally to use `ncu-ci` for checking the CI status of a pull request. This tool helps interpret CI results for a given PR. ```bash npm install -g node-core-utils ``` ```bash ncu-ci https://github.com/nodejs/node/pull/12345 ``` ```bash ncu-ci 12345 ``` -------------------------------- ### Complete Example: User Registration with Opaque Types Source: https://github.com/mcollina/skills/blob/main/skills/typescript-magician/rules/opaque-types.md Demonstrates a full user registration flow using opaque types for email, password, and user ID. Validation functions ensure type safety before data is passed to database functions. ```typescript type Opaque = TValue & { __brand: TBrand }; type ValidEmail = Opaque; type ValidPassword = Opaque; type UserId = Opaque; // Validation functions function assertValidEmail(email: string): asserts email is ValidEmail { if (!email.includes("@") || email.length < 5) { throw new Error("Invalid email format"); } } function assertValidPassword(password: string): asserts password is ValidPassword { if (password.length < 8) { throw new Error("Password must be at least 8 characters"); } } // Database functions require validated types async function createUser(data: { email: ValidEmail; password: ValidPassword; }): Promise<{ id: UserId }> { // We know email and password are validated return { id: crypto.randomUUID() as UserId }; } // API handler async function handleRegistration(input: { email: string; password: string }) { // Must validate before calling createUser assertValidEmail(input.email); assertValidPassword(input.password); // Now we can safely call createUser const user = await createUser({ email: input.email, password: input.password, }); return user; } ``` -------------------------------- ### MessageChannel Structured Clone Example Source: https://github.com/mcollina/skills/blob/main/skills/nodejs-core/rules/worker-threads-internals.md This JavaScript example demonstrates sending various data types via `MessageChannel`, highlighting the use of the structured clone algorithm for serialization. Note that functions and symbols are not supported. ```javascript // Messages are serialized using structured clone const { MessageChannel } = require('worker_threads'); const { port1, port2 } = new MessageChannel(); // Supported types: port1.postMessage({ number: 42, string: 'hello', date: new Date(), regexp: /pattern/g, array: [1, 2, 3], map: new Map([['key', 'value']]), set: new Set([1, 2, 3]), buffer: Buffer.from('data'), typedArray: new Float64Array([1.1, 2.2]), arrayBuffer: new ArrayBuffer(8), error: new Error('message'), // NOT supported: functions, symbols, WeakMap, WeakSet }); ``` -------------------------------- ### Implement Database Connection Pooling Source: https://github.com/mcollina/skills/blob/main/skills/fastify/rules/performance.md Use connection pools for databases to improve performance by reusing connections. This example shows how to create a connection pool at startup using the 'postgres' library and decorate the Fastify instance with it. ```typescript import postgres from 'postgres'; // Create pool at startup const sql = postgres(process.env.DATABASE_URL, { max: 20, // Maximum pool size idle_timeout: 20, connect_timeout: 10, }); app.decorate('db', sql); // Connections are reused app.get('/users', async () => { return app.db`SELECT * FROM users LIMIT 100`; }); ``` -------------------------------- ### Start Node.js Inspector for Heap Snapshots Source: https://github.com/mcollina/skills/blob/main/skills/node/rules/profiling.md Start your Node.js application with the --inspect flag to enable the V8 inspector. This allows you to use Chrome DevTools for heap snapshots and allocation timeline recording. ```bash node --inspect app.js ``` -------------------------------- ### TypeScript Example for Native Node.js Execution Source: https://context7.com/mcollina/skills/llms.txt Example of TypeScript code structured for native execution in Node.js using type-only imports and explicit class properties. Ensure type checking with 'tsc --noEmit'. ```typescript // GOOD — type-only imports, const object instead of enum import type { User } from './types.ts' import { fetchUser } from './db.ts' const Status = { Active: 'active', Inactive: 'inactive' } as const type Status = (typeof Status)[keyof typeof Status] // GOOD — explicit class properties (no constructor parameter properties) class UserService { private status: Status constructor(status: Status) { this.status = status } } // Run: node --test test/*.test.ts (Node 22.6+) // Typecheck: tsc --noEmit ``` -------------------------------- ### Good Example: Deterministic Teardown in Node.js Tests Source: https://github.com/mcollina/skills/blob/main/skills/node/rules/stuck-processes-and-tests.md This example shows how to properly clean up resources like servers and intervals using `t.after()` and `node:events.once` to ensure they are closed before the test finishes. This prevents hangs. ```typescript import { once } from 'node:events'; it('serves requests', async (t) => { const server = await startServer({ port: 0 }); const id = setInterval(() => {}, 1000); t.after(async () => { clearInterval(id); server.close(); await once(server, 'close'); }); // test body... }); ``` -------------------------------- ### Examine Package Source Files Source: https://github.com/mcollina/skills/blob/main/skills/node/rules/node-modules-exploration.md List the source files within a package's 'lib' directory and view the beginning of a specific source file. ```bash ls node_modules/fastify/lib/ head -50 node_modules/fastify/lib/server.js ``` -------------------------------- ### Fastify Type Coercion Example Source: https://github.com/mcollina/skills/blob/main/skills/fastify/rules/schemas.md Fastify automatically coerces types for query strings and parameters. This example shows how string inputs like "5" and "true" are converted to number and boolean types respectively, and comma-separated strings are converted to arrays. ```typescript // Query string "?page=5&active=true" becomes: // { page: 5, active: true } (number and boolean, not strings) app.get('/items', { schema: { querystring: { type: 'object', properties: { page: { type: 'integer' }, // "5" -> 5 active: { type: 'boolean' }, // "true" -> true tags: { type: 'array', items: { type: 'string' }, // "a,b,c" -> ["a", "b", "c"] }, }, }, }, }, handler); ``` -------------------------------- ### Build Universal Binary for macOS Source: https://github.com/mcollina/skills/blob/main/skills/nodejs-core/rules/build-system.md Create a universal binary for macOS by building separately for Intel (x64) and Apple Silicon (arm64) architectures and then merging them using `lipo`. ```bash # Universal binary (Intel + Apple Silicon) ./configure --dest-cpu=arm64 make -j$(nproc) mv out/Release/node node-arm64 ./configure --dest-cpu=x64 make -j$(nproc) mv out/Release/node node-x64 lipo -create -output node node-arm64 node-x64 ```