### Configure Meson Build Options Source: https://github.com/themackabu/ant/blob/master/BUILDING.md Examples for customizing the build process, such as selecting the TLS backend or enabling static linking. ```bash # Custom configuration meson setup build -Dtls_library=mbedtls -Dstatic_link=true --prefer-static # Build with mbedTLS specifically meson setup build -Dtls_library=mbedtls ``` -------------------------------- ### Build Ant on Windows via MSYS2 Source: https://github.com/themackabu/ant/blob/master/BUILDING.md Steps to install required toolchains and build the Ant binary within the MINGW64 environment. ```bash # Install dependencies pacman -S mingw-w64-x86_64-toolchain mingw-w64-x86_64-meson \ mingw-w64-x86_64-ninja mingw-w64-x86_64-cmake \ mingw-w64-x86_64-openssl mingw-w64-x86_64-libsodium \ mingw-w64-x86_64-lld mingw-w64-x86_64-nodejs git # Build process git clone https://github.com/theMackabu/ant.git cd ant meson subprojects download meson setup build -Dc_std=gnu2x meson compile -C build ``` -------------------------------- ### Install Ant Runtime Source: https://context7.com/themackabu/ant/llms.txt Commands to install the Ant runtime via the official shell script, with optional support for MbedTLS. ```bash # Standard installation curl -fsSL https://ant.themackabu.com/install | bash # With MbedTLS support curl -fsSL https://ant.themackabu.com/install | MBEDTLS=1 bash ``` -------------------------------- ### Build Ant from Source using Meson Source: https://github.com/themackabu/ant/blob/master/CONTRIBUTING.md Commands to clone the repository and compile the project using the Meson build system. This process requires Meson and a compatible C compiler installed on the host system. ```bash git clone https://github.com/theMackabu/ant.git && cd ant meson subprojects download meson setup build meson compile -C build ``` -------------------------------- ### Utilize Utility Functions Source: https://context7.com/themackabu/ant/llms.txt Provides examples for string formatting, object inspection, promisifying callback-based functions, and styling console output. These utilities simplify common debugging and data processing tasks. ```javascript import { format, inspect, promisify, styleText } from 'util'; console.log(format('Hello %s!', 'World')); const obj = { name: 'test', nested: { deep: { value: 42 } } }; console.log(inspect(obj, { depth: 2, colors: true })); const readFileAsync = promisify(require('fs').readFile); console.log(styleText('green', 'Success!')); ``` -------------------------------- ### Perform File System Operations Source: https://context7.com/themackabu/ant/llms.txt Provides examples of synchronous file system operations using the 'ant:fs' module. Includes directory management, file reading/writing, appending, and metadata retrieval. ```javascript import fs from 'ant:fs'; import path from 'ant:path'; const testDir = '/tmp/ant-test'; const testFile = path.join(testDir, 'test.txt'); fs.mkdirSync(testDir, { recursive: true }); fs.writeFileSync(testFile, 'Hello, Ant!'); const content = fs.readFileSync(testFile, 'utf8'); console.log(`Content: ${content}`); fs.appendFileSync(testFile, '\nAppended line'); const stat = fs.statSync(testFile); console.log(`Size: ${stat.size}`); fs.copyFileSync(testFile, path.join(testDir, 'copy.txt')); fs.unlinkSync(testFile); fs.rmdirSync(testDir); ``` -------------------------------- ### Manipulate Binary Data with Buffer Source: https://context7.com/themackabu/ant/llms.txt Provides examples for creating, reading, writing, and transforming binary data using the Node.js Buffer class. Includes methods for encoding conversions, concatenation, and comparison. ```javascript // Create buffers const buf1 = Buffer.alloc(10); // Zero-filled buffer const buf2 = Buffer.from('Hello'); // From string const buf3 = Buffer.from([72, 101, 108, 108, 111]); // From array // Read buffer contents console.log(buf2.toString()); // 'Hello' console.log(buf2.toString('hex')); // '48656c6c6f' console.log(buf2.toString('base64')); // 'SGVsbG8=' // Write to buffer const buf4 = Buffer.alloc(10); const bytesWritten = buf4.write('Hello', 0); console.log(`Wrote ${bytesWritten} bytes`); // Encoding conversions const base64Encoded = Buffer.from('Hello, World!').toString('base64'); console.log(`Base64: ${base64Encoded}`); // 'SGVsbG8sIFdvcmxkIQ==' const decoded = Buffer.from('SGVsbG8sIFdvcmxkIQ==', 'base64'); console.log(`Decoded: ${decoded.toString()}`); // 'Hello, World!' // Hex encoding const hexEncoded = Buffer.from('Hello').toString('hex'); console.log(`Hex: ${hexEncoded}`); // '48656c6c6f' const fromHex = Buffer.from('48656c6c6f', 'hex'); console.log(`From hex: ${fromHex.toString()}`); // 'Hello' // Buffer concatenation const combined = Buffer.concat([ Buffer.from('Hello'), Buffer.from(' '), Buffer.from('World') ]); console.log(combined.toString()); // 'Hello World' // Buffer comparison const a = Buffer.from('abc'); const b = Buffer.from('abc'); const c = Buffer.from('abd'); console.log(Buffer.compare(a, b)); // 0 (equal) console.log(Buffer.compare(a, c)); // -1 (less than) // Buffer utilities console.log(Buffer.isBuffer(buf1)); // true console.log(Buffer.isBuffer('string')); // false console.log(Buffer.isEncoding('utf8')); // true console.log(Buffer.byteLength('Hello')); // 5 ``` -------------------------------- ### Perform HTTP Requests with Fetch API Source: https://context7.com/themackabu/ant/llms.txt Illustrates the use of the standard Fetch API for making GET and POST requests. It covers parsing JSON responses, setting custom headers, and executing parallel requests using Promise.all. ```javascript const response = await fetch('https://api.github.com/zen'); console.log(`Status: ${response.status}`); const data = await fetch('https://httpbingo.org/json'); const json = data.json(); console.log(json); const postResponse = await fetch('https://httpbingo.org/post', { method: 'POST', headers: { 'Content-Type': 'application/json', 'User-Agent': 'ant/1.0' }, body: JSON.stringify({ runtime: 'ant', timestamp: Date.now() }) }); const result = postResponse.json(); const [ip, quote, test] = await Promise.all([ fetch('https://ifconfig.co/json').then(r => r.json()), fetch('https://api.github.com/zen').then(r => r.body), fetch('https://httpbingo.org/get').then(r => r.json()) ]); ``` -------------------------------- ### JavaScript Proxy for Intercepting Get Operations Source: https://github.com/themackabu/ant/blob/master/examples/quirks.txt This snippet creates a Proxy that intercepts `get` operations on an array. It logs the numeric index being accessed and allows further access up to index 4. ```javascript (p=new Proxy([],{get:(t,k)=>k<5?(console.log(+k),p[+k+1]):0}))[0] ``` -------------------------------- ### JavaScript Proxy with Reflect for Get Operations Source: https://github.com/themackabu/ant/blob/master/examples/quirks.txt This snippet uses a Proxy with `Reflect` to intercept `get` operations. It logs the numeric index accessed and allows further access up to index 4. ```javascript new Proxy([],{get:(t,k,r)=>k<5?(console.log(+k),r[+k+1]):0})[0] ``` -------------------------------- ### Create HTTP Server with Ant.serve Source: https://context7.com/themackabu/ant/llms.txt Shows how to initialize an HTTP server, handle requests via the context object, and send various response types. ```javascript Ant.serve(8000, (ctx) => { const method = ctx.req.method; const uri = ctx.req.uri; const query = ctx.req.query; const body = ctx.req.body; const userAgent = ctx.req.header('User-Agent'); ctx.res.header('X-Custom', 'value'); ctx.res.header('Cache-Control', 'no-cache'); ctx.res.body('Hello, World!'); ctx.res.body('Not Found', 404); ctx.res.body('{"ok":true}', 200, 'application/json'); ctx.res.html('

Welcome

'); ctx.res.json({ users: [], count: 0 }); ctx.res.redirect('/new-location', 302); ctx.res.notFound(); ctx.res.status(201); ctx.set('userId', 123); const userId = ctx.get('userId'); }); console.log('Server running on http://localhost:8000'); ``` -------------------------------- ### Troubleshoot and Clean Build Environment Source: https://github.com/themackabu/ant/blob/master/BUILDING.md Commands to resolve stale build errors, download missing subprojects, or manage memory usage during compilation. ```bash # Clean and reconfigure rm -rf build meson setup build meson compile -C build # Download dependencies meson subprojects download # Reduce parallelism if out of memory meson compile -C build -j2 ``` -------------------------------- ### Build Async HTTP Server with Routing Source: https://context7.com/themackabu/ant/llms.txt Demonstrates how to create an asynchronous HTTP server using the Ant runtime. It includes a custom router implementation to handle different HTTP methods and paths, supporting JSON responses and file reading. ```javascript import { join } from 'ant:path'; import { readFile } from 'ant:fs'; const routes = new Map(); function addRoute(method, path, handler) { routes.set(`${method}:${path}`, handler); } addRoute('GET', '/', async (ctx) => { ctx.res.body(`Welcome to Ant ${Ant.version}!`); }); addRoute('GET', '/api/users', async (ctx) => { const users = [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' } ]; ctx.res.json({ users, total: users.length }); }); addRoute('POST', '/api/data', async (ctx) => { const data = JSON.parse(ctx.req.body); ctx.res.json({ received: data, timestamp: Date.now() }); }); addRoute('GET', '/file', async (ctx) => { const content = await readFile(join(import.meta.dirname, 'data.txt'), 'utf8'); ctx.res.body(content); }); addRoute('GET', '/external', async (ctx) => { const response = await fetch('https://api.github.com/zen'); ctx.res.body(await response.text()); }); Ant.serve(8000, async (ctx) => { console.log(`${ctx.req.method} ${ctx.req.uri}`); const handler = routes.get(`${ctx.req.method}:${ctx.req.uri}`); if (handler) { await handler(ctx); } else { ctx.res.body('Not Found', 404); } }); ``` -------------------------------- ### Optimize Build Performance with ccache and lld Source: https://github.com/themackabu/ant/blob/master/BUILDING.md Configure ccache and lld to accelerate compilation and linking times. These settings are applicable to Unix-like systems and help reduce frequent rebuild durations. ```bash # GNU/Linux sudo apt install ccache export CC="ccache gcc" # macOS brew install ccache export CC="ccache cc" # Linker configuration export CC_LD="$(which ld64.lld)" # macOS export CC_LD="$(which lld)" # Linux ``` -------------------------------- ### JavaScript: Call Native C Libraries with Ant FFI Source: https://context7.com/themackabu/ant/llms.txt Illustrates how to use the Ant project's Foreign Function Interface (FFI) to load and call functions from native C libraries, specifically demonstrating interaction with SQLite3. It covers loading libraries, defining function signatures, allocating memory, calling functions, handling callbacks, and freeing resources. ```javascript import { dlopen, suffix, FFIType, alloc, free, read, callback, freeCallback } from 'ant:ffi'; const lib = dlopen(`libsqlite3.${suffix}`); lib.define('sqlite3_libversion', { args: [], returns: FFIType.string }); lib.define('sqlite3_open', { args: [FFIType.string, FFIType.pointer], returns: FFIType.int }); lib.define('sqlite3_close', { args: [FFIType.pointer], returns: FFIType.int }); lib.define('sqlite3_exec', { args: [FFIType.pointer, FFIType.string, FFIType.pointer, FFIType.pointer, FFIType.pointer], returns: FFIType.int }); console.log(`SQLite version: ${lib.call('sqlite3_libversion')}`); const dbPtrPtr = alloc(8); const result = lib.call('sqlite3_open', ':memory:', dbPtrPtr); if (result === 0) { const db = read(dbPtrPtr, FFIType.pointer); free(dbPtrPtr); lib.call('sqlite3_exec', db, 'CREATE TABLE users (id INTEGER, name TEXT)', 0, 0, 0); lib.call('sqlite3_exec', db, "INSERT INTO users VALUES (1, 'Alice')", 0, 0, 0); const rowCallback = callback( (userData, argc, argv, colNames) => { console.log(`Row received with ${argc} columns`); return 0; }, { args: [FFIType.pointer, FFIType.int, FFIType.pointer, FFIType.pointer], returns: FFIType.int } ); lib.call('sqlite3_exec', db, 'SELECT * FROM users', rowCallback, 0, 0); freeCallback(rowCallback); lib.call('sqlite3_close', db); } else { free(dbPtrPtr); console.log('Failed to open database'); } console.log(`Available types:`); console.log(` void: ${FFIType.void}`); console.log(` int: ${FFIType.int}`); console.log(` int64: ${FFIType.int64}`); console.log(` float: ${FFIType.float}`); console.log(` double: ${FFIType.double}`); console.log(` pointer: ${FFIType.pointer}`); console.log(` string: ${FFIType.string}`); ``` -------------------------------- ### Configure Meson Build Options Source: https://github.com/themackabu/ant/blob/master/vendor/packagefiles/libuv/meson_options.txt Defines boolean options for the Meson build system to toggle the compilation of unit tests, benchmarks, and QEMU support. These options are typically defined in a meson_options.txt file and can be toggled via the command line during project configuration. ```meson option( 'build_tests', type: 'boolean', value: false, description: 'build the unit tests', ) option( 'build_benchmarks', type: 'boolean', value: false, description: 'build the benchmarks', ) option( 'build_for_qemu', type: 'boolean', value: false, description: 'build for qemu', ) ``` -------------------------------- ### Access System Information with OS Module Source: https://context7.com/themackabu/ant/llms.txt Demonstrates how to retrieve platform details, memory usage, CPU information, network interfaces, and user data using the Ant OS module. This module provides a cross-platform interface for interacting with system resources. ```javascript import os from 'ant:os'; console.log(`Platform: ${os.platform()}`); console.log(`Architecture: ${os.arch()}`); console.log(`Total memory: ${os.totalmem()} bytes`); console.log(`Uptime: ${os.uptime()} seconds`); const cpus = os.cpus(); cpus.forEach((cpu, i) => { console.log(`CPU ${i}: ${cpu.model} @ ${cpu.speed}MHz`); }); ``` -------------------------------- ### Manage Child Processes with Node.js child_process Source: https://context7.com/themackabu/ant/llms.txt Demonstrates spawning and managing child processes using both synchronous and asynchronous methods. It covers input handling, event listeners for process lifecycle, and process termination. ```javascript import { spawn, exec, execSync, spawnSync } from 'child_process'; const output = execSync('echo "Hello from shell"'); const result = spawnSync('ls', ['-la', '/tmp']); const catResult = spawnSync('cat', [], { input: 'Hello from stdin' }); const execResult = await exec('echo "Async hello"'); const child = spawn('sh', ['-c', 'echo line1; sleep 0.1; echo line2']); child.on('exit', (code) => console.log(`Exited with code: ${code}`)); const longProcess = spawn('sleep', ['10']); longProcess.kill('SIGTERM'); ``` -------------------------------- ### Organize Code with ES Modules Source: https://context7.com/themackabu/ant/llms.txt Illustrates the use of ES module syntax for importing and exporting functionality. Includes named, default, namespace, and dynamic imports, as well as metadata access. ```javascript import { readFile, writeFile } from 'ant:fs'; import * as crypto from 'crypto'; import { helper } from './utils.js'; export function helper() { return 'helper'; } export default class Utils { static format(s) { return s.trim(); } } ``` -------------------------------- ### Perform Asynchronous File System Operations with ant:fs Source: https://context7.com/themackabu/ant/llms.txt Demonstrates promise-based file system operations such as directory creation, file reading/writing, and metadata retrieval. These operations are non-blocking and utilize the 'ant:fs' module. ```javascript import { readFile, writeFile, mkdir, stat, readdir, unlink } from 'ant:fs'; async function fileOperations() { const dir = '/tmp/async-test'; const file = `${dir}/data.json`; await mkdir(dir, { recursive: true }); const data = { name: 'Ant', version: Ant.version }; await writeFile(file, JSON.stringify(data, null, 2)); const content = await readFile(file, 'utf8'); console.log(`Read: ${content}`); const bytes = await readFile(file); console.log(`Bytes: ${bytes.length}`); const fileStat = await stat(file); console.log(`Size: ${fileStat.size} bytes`); const files = await readdir(dir); console.log(`Files: ${files}`); const exists = await fs.exists(file); console.log(`Exists: ${exists}`); await unlink(file); } fileOperations(); ``` -------------------------------- ### Execute JavaScript with Ant Source: https://context7.com/themackabu/ant/llms.txt Commands to run JavaScript files using the Ant runtime, including passing command-line arguments. ```bash # Run a JavaScript file ant script.js # Run with arguments ant server.js --port 8080 ``` -------------------------------- ### Schedule Execution with Timers Source: https://context7.com/themackabu/ant/llms.txt Demonstrates how to schedule code execution using setTimeout, setInterval, setImmediate, and queueMicrotask. These functions manage the event loop, allowing for delayed, repeated, or prioritized task execution. ```javascript const timeoutId = setTimeout(() => { console.log('Executed after 1 second'); }, 1000); setTimeout((name, value) => { console.log(`Hello ${name}, value is ${value}`); }, 500, 'World', 42); const cancelMe = setTimeout(() => { console.log('This will not run'); }, 1000); clearTimeout(cancelMe); let count = 0; const intervalId = setInterval(() => { count++; console.log(`Interval tick: ${count}`); if (count >= 5) { clearInterval(intervalId); console.log('Interval stopped'); } }, 200); setImmediate(() => { console.log('Executed immediately (next tick)'); }); queueMicrotask(() => { console.log('Microtask executed'); }); ``` -------------------------------- ### Access Ant Global Object Utilities Source: https://context7.com/themackabu/ant/llms.txt Demonstrates how to access runtime information, perform type inspection, manage memory, and use synchronous sleep functions. ```javascript // Runtime information console.log(`Ant version: ${Ant.version}`); console.log(`Target: ${Ant.target}`); console.log(`Host: ${Ant.host}`); console.log(`Build date: ${Ant.buildDate}`); // Type inspection (more specific than typeof) Ant.inspect({ key: 'value' }); // Pretty prints objects console.log(Ant.typeof([])); // 'array' (not 'object') console.log(Ant.typeof(null)); // 'null' (not 'object') console.log(Ant.typeof(async () => {})); // 'function' // Memory management const gcResult = Ant.gc(); console.log(`Freed: ${gcResult.freed} bytes`); const allocInfo = Ant.alloc(); console.log(`Heap size: ${allocInfo.heapSize}`); console.log(`Used bytes: ${allocInfo.usedBytes}`); const stats = Ant.stats(); console.log(`Arena used: ${stats.arenaUsed}`); console.log(`RSS: ${stats.rss}`); // Synchronous sleep functions Ant.sleep(1); // Sleep 1 second Ant.msleep(100); // Sleep 100 milliseconds Ant.usleep(1000); // Sleep 1000 microseconds ``` -------------------------------- ### Implement Event-Driven Logic with EventEmitter Source: https://context7.com/themackabu/ant/llms.txt Shows how to create custom event emitters by extending the EventEmitter class. It covers emitting events, adding and removing listeners, and managing event lifecycles. ```javascript import { EventEmitter } from 'events'; class Server extends EventEmitter { start() { this.emit('ready', { port: 8000 }); } } const server = new Server(); server.on('ready', (info) => console.log(`Server ready on port ${info.port}`)); server.start(); ``` -------------------------------- ### Ant Project Directory Structure Source: https://github.com/themackabu/ant/blob/master/CONTRIBUTING.md An overview of the source tree organization, highlighting core components like the CLI, ES module system, bytecode VM, and package manager. ```text src/ ├── cli/ # Command line interface helpers ├── core/ # Bundled snapshot code ├── esm/ # ES module system (loader, resolver, cache) ├── highlight/ # Syntax highlighting (emit, iterators) ├── modules/ # Built-in JS modules (fs, path, shell, etc.) ├── pkg/ # Zig-based package manager ├── silver/ # Silver bytecode compiler and VM │ └── ops/ # Bytecode operation definitions ├── strip/ # Rust-based type stripping (oxc) ├── tools/ # Code generation scripts (snapshot gen) ├── types/ # TypeScript type declarations include/ # C header files tests/ # JavaScript test files vendor/ # External dependencies ``` -------------------------------- ### Configure Build Options (Ant) Source: https://github.com/themackabu/ant/blob/master/meson_options.txt Defines configuration options for the Ant build system. These options control features like the JIT compiler, static linking, TLS library usage, build timestamps, and dependency path prefixes. ```Ant option('jit', type: 'boolean', value: true, description: 'enable JIT compiler') option('static_link', type: 'boolean', value: false, description: 'statically link the binary') option('tls_library', type: 'combo', choices: ['openssl', 'mbedtls'], value: 'openssl', description: 'TLS library to use') option('build_timestamp', type: 'string', value: '', description: 'build timestamp (defaults to current time if empty)') option('deps_prefix_cmake', type: 'string', value: '', description: 'prefix path for finding dependencies in cmake subprojects') ``` -------------------------------- ### JavaScript: Work with Binary Data using TypedArrays and DataView Source: https://context7.com/themackabu/ant/llms.txt Demonstrates the use of ArrayBuffer, TypedArray views (Uint8Array, Uint16Array, etc.), and DataView for manipulating raw binary data in JavaScript. It covers creating buffers, accessing data with different types, explicit endianness control, slicing, sub-array views, buffer transfer, and BigInt typed arrays. ```javascript const buffer = new ArrayBuffer(16); console.log(`Buffer size: ${buffer.byteLength}`); const uint8 = new Uint8Array(buffer); const uint16 = new Uint16Array(buffer); const uint32 = new Uint32Array(buffer); const float64 = new Float64Array(buffer); console.log(`Uint8 length: ${uint8.length}`); console.log(`Uint16 length: ${uint16.length}`); console.log(`Uint32 length: ${uint32.length}`); console.log(`Float64 length: ${float64.length}`); uint8[0] = 0x12; uint8[1] = 0x34; console.log(`Uint16[0]: 0x${uint16[0].toString(16)}`); const view = new DataView(buffer); view.setUint16(0, 0x1234, true); view.setUint16(2, 0x5678, false); console.log(`LE read: 0x${view.getUint16(0, true).toString(16)}`); console.log(`BE read: 0x${view.getUint16(2, false).toString(16)}`); const slice = uint8.slice(4, 8); const subarray = uint8.subarray(4, 8); const original = new ArrayBuffer(32); const originalView = new Uint8Array(original); originalView[0] = 42; const transferred = original.transfer(64); console.log(`Original detached: ${original.detached}`); console.log(`Transferred size: ${transferred.byteLength}`); console.log(`Data preserved: ${new Uint8Array(transferred)[0]}`); const bigInt64 = new BigInt64Array(2); bigInt64[0] = 9007199254740993n; console.log(`BigInt64: ${bigInt64[0]}`); ``` -------------------------------- ### JavaScript Console API Logging and Debugging Source: https://context7.com/themackabu/ant/llms.txt Demonstrates various methods of the JavaScript Console API for logging messages, formatting output, inspecting objects, timing operations, grouping logs, performing assertions, counting calls, clearing the console, and tracing execution. This API is crucial for debugging and monitoring application behavior. ```javascript // Basic logging console.log('Info message'); console.info('Info message'); console.warn('Warning message'); console.error('Error message'); console.debug('Debug message'); // String formatting console.log('Hello %s, you have %d messages', 'Alice', 5); // Object logging console.log({ name: 'test', value: 42 }); // Multiple arguments console.log('Multiple', 'arguments', 123, { key: 'value' }); // Timing console.time('operation'); // ... some work ... console.timeEnd('operation'); // operation: 123ms // Grouping console.group('User Details'); console.log('Name: Alice'); console.log('Age: 30'); console.groupEnd(); // Assertions console.assert(1 === 1, 'This will not show'); console.assert(1 === 2, 'This assertion failed!'); // Count calls console.count('loop'); // loop: 1 console.count('loop'); // loop: 2 console.countReset('loop'); console.count('loop'); // loop: 1 // Clear console console.clear(); // Stack trace console.trace('Trace message'); // Table (if supported) console.table([ { name: 'Alice', age: 30 }, { name: 'Bob', age: 25 } ]); ``` -------------------------------- ### Implement Inter-thread Communication with MessageChannel Source: https://context7.com/themackabu/ant/llms.txt Shows how to establish a direct communication channel between threads using MessageChannel. This allows for asynchronous message passing between two ports. ```javascript import { MessageChannel, Worker, isMainThread, parentPort } from 'worker_threads'; if (isMainThread) { // Create a channel const channel = new MessageChannel(); // Set up port1 handler channel.port1.on('message', (msg) => { console.log(`Port1 received: ${msg}`); }); // Send message through port2 channel.port2.postMessage('Hello through channel'); // Start receiving channel.port1.start(); // Close when done setTimeout(() => { channel.port1.close(); channel.port2.close(); }, 100); } ``` -------------------------------- ### Execute Shell Commands with Ant Shell Module Source: https://context7.com/themackabu/ant/llms.txt Provides a clean syntax for executing shell commands using template literals. It supports variable interpolation, command chaining, and convenient helper methods for processing output. ```javascript import { $ } from 'ant:shell'; const result = $`echo "Hello from shell"`; console.log(result.text()); const dir = '/home'; const files = $`ls ${dir}`; const pipeline = $`echo "hello world" | tr ' ' '\n' | sort`; ``` -------------------------------- ### Handle Events with EventTarget API Source: https://context7.com/themackabu/ant/llms.txt Illustrates the use of the EventTarget API for browser-style event handling, including global events, custom data payloads, and one-time event listeners. ```javascript const button = new EventTarget(); button.addEventListener('click', (event) => { console.log('Button clicked'); }); button.dispatchEvent('click'); // Using once option button.addEventListener('init', () => console.log('Fires once'), { once: true }); ``` -------------------------------- ### Execute Parallel Tasks with Worker Threads Source: https://context7.com/themackabu/ant/llms.txt Demonstrates how to spawn worker threads in Node.js to perform parallel computations. It covers thread creation, data passing via workerData, and message exchange between main and worker threads. ```javascript import { Worker, isMainThread, parentPort, workerData } from 'worker_threads'; if (isMainThread) { // Main thread code console.log('Main thread starting workers...'); // Create a worker with data const worker = new Worker(new URL(import.meta.url), { workerData: { task: 'compute', value: 100 } }); // Handle messages from worker worker.on('message', (result) => { console.log(`Result from worker: ${result}`); }); worker.on('exit', (code) => { console.log(`Worker exited with code: ${code}`); }); // Send message to worker worker.postMessage({ action: 'start' }); // Terminate worker after timeout setTimeout(async () => { const exitCode = await worker.terminate(); console.log(`Worker terminated: ${exitCode}`); }, 1000); } else { // Worker thread code console.log(`Worker received data: ${JSON.stringify(workerData)}`); parentPort.postMessage(`Computed: ${workerData.value * 2}`); } ``` -------------------------------- ### Handle Asynchronous Operations with Promises and Async/Await Source: https://context7.com/themackabu/ant/llms.txt Covers modern asynchronous patterns including async functions, sequential and parallel execution, error handling, and Promise chaining. These tools are essential for managing non-blocking I/O operations. ```javascript async function fetchData() { const response = await fetch('https://api.github.com/zen'); return response.body; } async function parallel() { const [a, b, c] = await Promise.all([ Promise.resolve(1), Promise.resolve(2), Promise.resolve(3) ]); return a + b + c; } Promise.resolve(1) .then(v => v + 1) .then(v => v * 2) .then(v => console.log(`Result: ${v}`)); ``` -------------------------------- ### Access Process Information and Control Execution with process Source: https://context7.com/themackabu/ant/llms.txt The global process object provides information about the current runtime environment, including system metrics, environment variables, and standard I/O streams. It also allows for controlling process lifecycle and exit events. ```javascript console.log(`PID: ${process.pid}`); console.log(`Platform: ${process.platform}`); console.log(`Ant version: ${process.version}`); process.env.MY_VAR = 'custom value'; console.log(`CWD: ${process.cwd()}`); process.on('exit', (code) => { console.log(`Exiting with code: ${code}`); }); process.stdout.write('Hello to stdout\n'); process.exit(0); ``` -------------------------------- ### Manipulate File Paths with ant:path Source: https://context7.com/themackabu/ant/llms.txt Provides utilities for joining, resolving, parsing, and formatting file system paths. This module ensures consistent path handling across different operating systems. ```javascript import path from 'ant:path'; console.log(path.join('/home', 'user', 'docs', 'file.txt')); console.log(path.resolve('relative', 'path')); console.log(path.dirname('/home/user/file.txt')); console.log(path.basename('/home/user/file.txt')); console.log(path.extname('/home/user/file.txt')); console.log(path.normalize('/home//user/../user/./docs')); console.log(path.isAbsolute('/home/user')); console.log(path.relative('/home/user', '/home/user/docs/file.txt')); const parsed = path.parse('/home/user/docs/file.txt'); const formatted = path.format({ root: '/', dir: '/home/user', base: 'file.txt' }); console.log(`Separator: ${path.sep}`); console.log(`Delimiter: ${path.delimiter}`); ``` -------------------------------- ### Array Map for Logging Indices in JavaScript Source: https://github.com/themackabu/ant/blob/master/examples/quirks.txt This snippet creates an array of length 10 and uses the `map` method to log the index of each element to the console. ```javascript [...Array(10)].map((_,i)=>console.log(i)) ``` -------------------------------- ### Proxying Window Object for Sentient Behavior in JavaScript Source: https://github.com/themackabu/ant/blob/master/examples/quirks.txt This snippet creates a Proxy for the `window` object. Each time `window` is accessed recursively, it logs an incrementing counter and returns the proxy itself, creating a loop. ```javascript (i=0,w=new Proxy(window,{get:(t,k)=>k==='window'?(console.log(i++),w):t[k]})) w.window.window.window.window.window.window ``` -------------------------------- ### Register Signal Handlers Source: https://context7.com/themackabu/ant/llms.txt Shows how to register signal handlers for process control, such as SIGINT and SIGTERM. This is essential for implementing graceful shutdown logic in long-running Ant applications. ```javascript import { constants } from 'ant:os'; let isRunning = true; Ant.signal(constants.signals.SIGINT, (signum) => { console.log(`\nReceived SIGINT (signal ${signum})`); console.log('Shutting down gracefully...'); isRunning = false; }); Ant.signal(constants.signals.SIGTERM, (signum) => { console.log(`\nReceived SIGTERM (signal ${signum})`); console.log('Terminating...'); process.exit(0); }); console.log('Press Ctrl+C to trigger graceful shutdown'); while (isRunning) { Ant.msleep(100); } console.log('Cleanup complete'); ``` -------------------------------- ### Perform Cryptographic Operations with Crypto Module Source: https://context7.com/themackabu/ant/llms.txt Covers generation of secure random values, UUIDs (v4 and v7), and filling typed arrays. It leverages both standard Node.js crypto and Web Crypto API patterns. ```javascript import crypto from 'crypto'; const random = crypto.webcrypto.random(); const uuid = crypto.randomUUID(); const uuidv7 = crypto.webcrypto.randomUUIDv7(); const array = new Uint8Array(16); crypto.getRandomValues(array); ``` -------------------------------- ### String Replace with Callback Logging Index in JavaScript Source: https://github.com/themackabu/ant/blob/master/examples/quirks.txt This snippet uses the `replace` method on a string. The callback function logs the index of each matched character 'x'. ```javascript 'xxxxx'.replace(/x/g,(_,i)=>console.log(i)) ``` -------------------------------- ### Sloppy Mode with Statement in JavaScript Source: https://github.com/themackabu/ant/blob/master/examples/quirks.txt This snippet demonstrates the `with` statement in a sloppy mode context. It iterates from 0 to 4, logging the value of `i` in each iteration. ```javascript with({i:0}){while(i<5)console.log(i++)} ``` -------------------------------- ### Print Numbers 0-9 in JavaScript Source: https://github.com/themackabu/ant/blob/master/examples/quirks.txt This snippet demonstrates a recursive function to print numbers from 0 to 9 to the console. It uses a closure to maintain the state of the counter `i`. ```javascript i=0,f=_=>i<10&&(console.log(i++),f``) ``` -------------------------------- ### String Concatenation and NaN in JavaScript Source: https://github.com/themackabu/ant/blob/master/examples/quirks.txt This snippet showcases string concatenation in JavaScript. It results in 'bana' followed by 'NaN' and then converted to lowercase. ```javascript ('b' + 'a' + + 'a' + 'a').toLowerCase() ``` -------------------------------- ### toString Method for Custom String Coercion in JavaScript Source: https://github.com/themackabu/ant/blob/master/examples/quirks.txt This snippet defines an object with a `toString` method. When the object is coerced to a string, it logs numbers from 0 to 4 and returns the string representation of the object. ```javascript ''+{i:0,toString(){return this.i<5?(console.log(this.i++),this+''):''}} ``` -------------------------------- ### Error Handling with Try-Catch and Recursion in JavaScript Source: https://github.com/themackabu/ant/blob/master/examples/quirks.txt This snippet defines a recursive function that throws an error with the current count `i` if `i` is less than 5. The `catch` block logs the error and calls the function recursively with `e+1`. ```javascript (f=i=>{try{if(i<5)throw i}catch(e){console.log(e),f(e+1)}})(0) ``` -------------------------------- ### JavaScript Getter for Looping and Logging Source: https://github.com/themackabu/ant/blob/master/examples/quirks.txt This snippet defines an object with a getter property `n`. When accessed, the getter logs numbers from 0 to 4 to the console. ```javascript ({get n(){for(var i=0;i<5;)console.log(i++)}}).n ``` -------------------------------- ### Delayed Execution with setTimeout in JavaScript Source: https://github.com/themackabu/ant/blob/master/examples/quirks.txt This snippet uses `setTimeout` to recursively call a function, incrementing a counter up to 5. Each call is scheduled with a 0ms delay, effectively creating a microtask queue. ```javascript void function f(i){i<5&&setTimeout(f,0,i+1,console.log(i))}(0) ``` -------------------------------- ### Async Function for Asynchronous Operations in JavaScript Source: https://github.com/themackabu/ant/blob/master/examples/quirks.txt This snippet defines an asynchronous recursive function that logs a number and then calls itself with a delay. The `await` keyword ensures sequential execution. ```javascript void async function f(i){i<5&&await f(i+1,console.log(i))}(0) ``` -------------------------------- ### Recursive Function with Console Output in JavaScript Source: https://github.com/themackabu/ant/blob/master/examples/quirks.txt This snippet defines a recursive function that logs numbers from 0 to 4 to the console. The function returns 0 after its execution. ```javascript (f=i=>(i<5&&(console.log(i),f(i+1)),0))(0) ``` -------------------------------- ### Concatenate Numbers 0-9 into a String in JavaScript Source: https://github.com/themackabu/ant/blob/master/examples/quirks.txt This snippet concatenates numbers from 0 to 9 into a single string using a recursive function. The result string `s` is returned after the function completes. ```javascript (s='',i=0,f=_=>i<10&&(s+=i++,f``),f``,s) ``` -------------------------------- ### Symbol.iterator for Custom Iteration with Yield in JavaScript Source: https://github.com/themackabu/ant/blob/master/examples/quirks.txt This snippet defines an iterable object using `Symbol.iterator`. The generator function logs numbers from 0 to 4 and yields each value. ```javascript [...{*[Symbol.iterator](){for(let i=0;i<5;)yield console.log(i++)}}] ``` -------------------------------- ### Symbol.toPrimitive for Custom Type Coercion in JavaScript Source: https://github.com/themackabu/ant/blob/master/examples/quirks.txt This snippet defines an object with a `Symbol.toPrimitive` method. When the object is coerced to a primitive, it logs numbers from 0 to 4 and returns the current value of `i`. ```javascript +{i:0,[Symbol.toPrimitive](){return this.i<5?(console.log(this.i++),+this):0}} ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.