### Install node-ray with npm or bun
Source: https://github.com/permafrost-dev/node-ray/blob/main/README.md
This snippet shows how to install the node-ray package using either npm or bun package managers. It's the first step to integrating node-ray into your project.
```bash
npm install node-ray
```
```bash
bun add node-ray
```
--------------------------------
### Basic Node Ray API Usage Examples
Source: https://github.com/permafrost-dev/node-ray/blob/main/README.md
Provides examples of common `node-ray` API calls, including sending strings, arrays, tables, images, and clearing the Ray screen. It also demonstrates disabling Ray output and sending XML data.
```javascript
ray('a string');
ray(['several', 'arguments'], 'can', {be: provided});
ray().table(['one two', {a: 100, b: 200, c: 300}, [9, 8, 7]]).blue();
ray().chain(ray => ray.html('large text').large().green());
ray().image('https://placekitten.com/200/300');
ray().clearAll();
ray().disable(); // disable sending data to Ray at runtime
ray().xml('11'); // previous call disabled sending data, XML not sent to Ray
```
--------------------------------
### NodeJS Configuration File Example (ray.config.js)
Source: https://github.com/permafrost-dev/node-ray/blob/main/README.md
Illustrates the structure and options for a `ray.config.js` file in NodeJS. This file allows for centralized configuration of `node-ray`, including enabling/disabling, host/port settings, and custom callbacks for sending and modifying payloads.
```javascript
// ray.config.js
export default {
enable: true,
host: 'localhost',
port: 23517,
scheme: 'http', //only change this if you know what you're doing!
// calls to console.log() are redirected to Ray
intercept_console_log: true,
// determine the enabled state using the specified callback
// the 'enable' setting is also considered when using this setting.
enabled_callback: () => {
return functionThatReturnsABoolean();
},
sending_payload_callback: (rayInstance, payloads) => {
if (payloads[0].getType() === 'custom') {
payloads[0].html += ' - modified!';
}
},
sent_payload_callback: (rayInstance) => {
// automatically make all payloads sent to Ray green.
rayInstance.green();
},
}
```
--------------------------------
### Display Class Name with Ray
Source: https://github.com/permafrost-dev/node-ray/blob/main/docs/usage.md
Get and display the class name of an object. Use the `className()` method, passing the object as an argument.
```javascript
const obj = new MyClass1();
ray().className(obj);
```
--------------------------------
### Get Object Class Name with className()
Source: https://context7.com/permafrost-dev/node-ray/llms.txt
Retrieves and displays the class name of a given object. This method works with instances of custom classes as well as built-in JavaScript objects.
```javascript
import { ray } from 'node-ray';
class UserService {
debug() {
ray().className(this); // Displays: UserService
}
}
const service = new UserService();
service.debug();
// With any object
ray().className(new Date()); // Displays: Date
ray().className(new Map()); // Displays: Map
```
--------------------------------
### Node-Ray Feature Demonstration
Source: https://github.com/permafrost-dev/node-ray/blob/main/docs/usage.md
A sample script demonstrating various node-ray features. It covers basic logging, counters with custom labels and colors, HTML output, tables, custom data sending, image display, and pausing execution. Requires Node.js and the 'node-ray' package.
```javascript
import { ray } from 'node-ray';
function test1() {
return ray().count('test one');
}
function test2() {
return ray().count();
}
async function alternatingColorCounter() {
return new Promise(resolve => {
const myRay = ray();
for(const i in [...Array(10).keys()]) {
setTimeout( () => {
const colorName = ['green', 'red', 'blue', 'orange'][i % 4];
myRay.html(`counter: ${i + 1}`).color(colorName);
if (i === 9) {
resolve(true);
}
}, i * 1500);
}
});
}
async function main() {
ray().showApp();
ray().xml('3333');
ray().table(['a string', true, [1, 2, 3], {a:1, b:2}]);
ray().sendCustom({ name: 'object' });
await alternatingColorCounter();
await ray().pause();
[1,2].forEach(n => test1());
[1,2,3,4].forEach(n => test2());
ray().image('https://placekitten.com/200/300').blue();
ray().html('hello world').small();
}
main();
```
--------------------------------
### Configuring Host and Port for Node Ray
Source: https://github.com/permafrost-dev/node-ray/blob/main/README.md
Shows how to configure the host and port for the `node-ray` package by importing the `Ray` class and using the `useDefaultSettings` method. This allows you to direct debugging output to a specific Ray instance.
```javascript
// make sure you import the Ray class (capital "R")
import { Ray, ray } from 'node-ray';
Ray.useDefaultSettings({ host: '127.0.0.1', port: 3000 });
// or just modify the port:
Ray.useDefaultSettings({ port: 3000 });
// ...and use ray() as normal
```
--------------------------------
### Configure Ray Connection Settings
Source: https://context7.com/permafrost-dev/node-ray/llms.txt
Use `Ray.useDefaultSettings()` to configure Ray connection details like host, port, and scheme. These settings apply globally to all `ray()` calls. For Node.js, `Ray.initSettings()` can load settings from a configuration file.
```javascript
import { Ray, ray } from 'node-ray';
// Configure connection settings
Ray.useDefaultSettings({
host: '192.168.1.100',
port: 23517,
scheme: 'http',
intercept_console_log: true
});
// For NodeJS, initialize settings from config file
await Ray.initSettings();
// Use ray normally after configuration
ray('Connected to custom host');
```
--------------------------------
### Display Syntax-Highlighted HTML Markup
Source: https://context7.com/permafrost-dev/node-ray/llms.txt
Use the `htmlMarkup()` method to display raw HTML code in Ray with syntax highlighting. This is useful for inspecting the structure and content of HTML without it being rendered.
```javascript
import { ray } from 'node-ray';
// Display HTML markup with syntax highlighting
ray().htmlMarkup('
Hello World
');
// With options
ray().htmlMarkup('', {
// Additional formatting options
});
```
--------------------------------
### Display Node.js Info with nodeinfo() (Node.js)
Source: https://context7.com/permafrost-dev/node-ray/llms.txt
Outputs detailed information about the Node.js runtime environment, including V8 engine version and memory usage statistics. This is a Node.js-specific utility.
```javascript
import { ray } from 'node-ray';
// Display all node info
ray().nodeinfo();
// Display specific properties
ray().nodeinfo('v8', 'memory');
```
--------------------------------
### Programmatically Show or Hide the Ray Application Window - JavaScript
Source: https://context7.com/permafrost-dev/node-ray/llms.txt
The `showApp()` and `hideApp()` methods provide programmatic control over the visibility of the Ray application window. This allows you to toggle the Ray UI on or off during runtime.
```javascript
import { ray } from 'node-ray';
// Show the Ray app window
ray().showApp();
// Send some debug data
ray('Important debug information');
// Hide the Ray app window
ray().hideApp();
```
--------------------------------
### Initialize ray for Laravel Mix
Source: https://github.com/permafrost-dev/node-ray/blob/main/README.md
This code demonstrates how to integrate node-ray with Laravel Mix by importing the `/web` export and assigning it to the global `window.ray` object in `resources/js/bootstrap.js`.
```javascript
import { ray } from 'node-ray/web';
window.ray = ray;
```
--------------------------------
### Node.js Configuration File (ray.config.js)
Source: https://context7.com/permafrost-dev/node-ray/llms.txt
Create a `ray.config.js` file in your project root for persistent Node.js settings. This file allows for advanced configuration, including enabling/disabling Ray, custom callbacks for payload sending, and console log interception.
```javascript
// ray.config.js
export default {
enable: true,
host: 'localhost',
port: 23517,
scheme: 'http',
intercept_console_log: true,
enabled_callback: () => process.env.DEBUG === 'true',
sending_payload_callback: (rayInstance, payloads) => {
// Modify payloads before sending
console.log('Sending payload:', payloads[0].getType());
},
sent_payload_callback: (rayInstance) => {
// Automatically color all payloads
rayInstance.green();
}
};
```
--------------------------------
### Manage Ray Screens for Organizing Debug Output - JavaScript
Source: https://context7.com/permafrost-dev/node-ray/llms.txt
The `newScreen()`, `clearScreen()`, and `clearAll()` methods allow for the creation and management of screens within the Ray application. This helps in organizing and isolating different sets of debug information.
```javascript
import { ray } from 'node-ray';
// Create a new unnamed screen
ray().newScreen();
ray('This appears on the new screen');
// Create a named screen
ray().newScreen('User Authentication');
ray('Login attempt for user: admin');
// Clear the current screen
ray().clearScreen();
// Clear all screens (current and previous)
ray().clearAll();
```
--------------------------------
### Hiding Output and App Window with Ray
Source: https://github.com/permafrost-dev/node-ray/blob/main/README.md
Make output collapse immediately in Ray using `ray().hide()`. Programmatically hide the entire Ray application window with `ray().hideApp()`.
```javascript
ray().hide();
ray().hideApp();
```
--------------------------------
### Browser Configuration for Node Ray
Source: https://github.com/permafrost-dev/node-ray/blob/main/README.md
Demonstrates how to configure `node-ray` within a browser environment using a bundler like webpack. It involves importing the `Ray` class from `node-ray/web` and using `useDefaultSettings` to set host and port.
```javascript
import { Ray, ray } from 'node-ray/web';
// set several settings at once:
Ray.useDefaultSettings({
host: '192.168.1.20',
port: 23517
});
// or set individual settings only:
Ray.useDefaultSettings({ port: 23517 });
// use ray() normally:
ray().html('hello world');
```
--------------------------------
### Manage Ray Screens
Source: https://github.com/permafrost-dev/node-ray/blob/main/docs/usage.md
Create new screens for organizing Ray output or clear existing screens. `newScreen()` can optionally take a name for the screen. `clearScreen()` removes the current screen, and `clearAll()` removes all screens.
```javascript
ray().newScreen();
ray().newScreen('my new screen');
ray().clearScreen();
ray().clearAll();
```
--------------------------------
### Display Data as Formatted Tables with Syntax Highlighting - JavaScript
Source: https://context7.com/permafrost-dev/node-ray/llms.txt
The `table()` method displays arrays and objects as formatted tables with syntax highlighting. It supports simple arrays, objects, mixed content, and complex nested structures, optionally with a label.
```javascript
import { ray } from 'node-ray';
// Display an array as a table
ray().table(['Apple', 'Banana', 'Cherry']);
// Display an object as a table
ray().table({
name: 'John Doe',
email: 'john@example.com',
age: 30,
active: true
});
// Display mixed content with a label
ray().table([
'string value',
42,
{ nested: 'object' },
[1, 2, 3],
true,
null
], 'Mixed Data Table');
// Complex nested objects
ray().table({
user: { name: 'Alice', role: 'admin' },
settings: { theme: 'dark', notifications: true }
}, 'Configuration');
```
--------------------------------
### Control Ray App Visibility
Source: https://github.com/permafrost-dev/node-ray/blob/main/docs/usage.md
Programmatically show or hide the Ray application window. Use `showApp()` to make it visible and `hideApp()` to conceal it.
```javascript
ray().showApp();
ray().hideApp();
```
--------------------------------
### Display Stack Trace with trace()
Source: https://context7.com/permafrost-dev/node-ray/llms.txt
Outputs a complete stack trace of the current execution point to the Ray application. This is invaluable for understanding the call hierarchy leading to a specific part of the code.
```javascript
import { ray } from 'node-ray';
function level3() {
ray().trace(); // Shows full call stack
}
function level2() {
level3();
}
function level1() {
level2();
}
level1(); // trace() shows: level3 -> level2 -> level1 -> ...
```
--------------------------------
### Handling Errors with error() and exception() in Node.js
Source: https://context7.com/permafrost-dev/node-ray/llms.txt
Display error and exception information, including stack traces, within the Ray client. The `error()` method is for general errors, while `exception()` is specifically for caught exceptions, providing richer context with optional metadata.
```javascript
import { ray } from 'node-ray';
// Display error information (automatically colored red)
ray().error(new Error('Something went wrong'));
// Display exception with stack trace (async)
try {
throw new Error('Database connection failed');
} catch (err) {
await ray().exception(err);
}
// Exception with metadata
try {
await fetchUserData(userId);
} catch (err) {
await ray().exception(err, {
userId: userId,
endpoint: '/api/users',
timestamp: new Date().toISOString()
});
}
```
--------------------------------
### Browser Bundled Usage (JavaScript)
Source: https://context7.com/permafrost-dev/node-ray/llms.txt
Integrates node-ray into bundled JavaScript projects (e.g., Webpack, Vite) for browser environments. Requires importing the ray function from 'node-ray/web'. Configuration for the Ray instance can be set using Ray.useDefaultSettings.
```javascript
// For webpack/vite bundled projects
import { ray } from 'node-ray/web';
// Configure for browser
import { Ray } from 'node-ray/web';
Ray.useDefaultSettings({ host: '192.168.1.100', port: 23517 });
ray('Bundled browser debug');
```
--------------------------------
### Date Display - date()
Source: https://context7.com/permafrost-dev/node-ray/llms.txt
Display formatted date information including timezone and timestamp, with options for styling.
```APIDOC
## Date Display - date()
### Description
Display formatted date information including timezone and timestamp, with options for styling.
### Method
`ray().date(date: Date)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```javascript
import { ray } from 'node-ray';
// Display current date
ray().date(new Date());
// Display specific date
ray().date(new Date('2024-06-15T14:30:00Z'));
// Date with other styling
ray().date(new Date()).label('Transaction Time').green();
```
### Response
#### Success Response (200)
None (method logs date information to Ray)
#### Response Example
None
```
--------------------------------
### Chaining Payloads in Node Ray
Source: https://github.com/permafrost-dev/node-ray/blob/main/README.md
Illustrates how to chain multiple `node-ray` payloads together using the `chain()` method. This is useful for sending related debugging information in a single call, especially in asynchronous operations.
```javascript
ray().chain((ray) => {
ray.text('first payload')
.blue()
.small()
.label('test');
});
```
--------------------------------
### Browser Standalone Slim Script Tag
Source: https://github.com/permafrost-dev/node-ray/blob/main/docs/available-environments.md
Include the slim version of node-ray via a CDN script tag if axios is already included in your project. This version omits axios to reduce bundle size.
```html
```
--------------------------------
### Display and Format Dates with Ray
Source: https://github.com/permafrost-dev/node-ray/blob/main/docs/usage.md
Log date information in a formatted table. The `date()` method accepts a `Date` object and an optional format string using day.js syntax.
```javascript
ray().date(new Date(), 'YYYY-MM-DD hh:mm');
```
--------------------------------
### Browser Standalone Usage (HTML)
Source: https://context7.com/permafrost-dev/node-ray/llms.txt
Includes node-ray in browser environments using CDN links. The standalone version makes ray() globally available. The slim version requires axios to be included separately.
```html
```
--------------------------------
### Log Events with event()
Source: https://context7.com/permafrost-dev/node-ray/llms.txt
Logs events to Ray, optionally with associated data. Events can be simple strings or complex objects, useful for tracking application occurrences.
```javascript
import { ray } from 'node-ray';
// Log an event
ray().event('user.login', [{ userId: 123, timestamp: Date.now() }]);
// Event without data
ray().event('cache.cleared');
// Event with complex data
ray().event('order.created', [{
orderId: 'ORD-001',
items: ['Product A', 'Product B'],
total: 99.99
}]);
```
--------------------------------
### Error Handling - error(), exception()
Source: https://context7.com/permafrost-dev/node-ray/llms.txt
Display error and exception information with stack traces in Ray. Errors are automatically colored red.
```APIDOC
## Error Handling - error(), exception()
### Description
Display error and exception information with stack traces in Ray. Errors are automatically colored red.
### Method
`ray().error(error: Error)`
`ray().exception(error: Error, meta?: object)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```javascript
import { ray } from 'node-ray';
// Display error information (automatically colored red)
ray().error(new Error('Something went wrong'));
// Display exception with stack trace (async)
try {
throw new Error('Database connection failed');
} catch (err) {
await ray().exception(err);
}
// Exception with metadata
try {
await fetchUserData(userId);
} catch (err) {
await ray().exception(err, {
userId: userId,
endpoint: '/api/users',
timestamp: new Date().toISOString()
});
}
```
### Response
#### Success Response (200)
None (methods log error/exception data to Ray)
#### Response Example
None
```
--------------------------------
### Import ray for NodeJS environments
Source: https://github.com/permafrost-dev/node-ray/blob/main/README.md
Demonstrates the standard ESM import for the `ray` function when using node-ray in a NodeJS environment. This is the default import method and does not require specific pathing.
```javascript
import { ray } from 'node-ray';
```
--------------------------------
### Enable/Disable - enable(), disable(), enabled(), disabled()
Source: https://context7.com/permafrost-dev/node-ray/llms.txt
Control whether Ray sends payloads at runtime. Check the current state or toggle sending on/off.
```APIDOC
## Enable/Disable - enable(), disable(), enabled(), disabled()
### Description
Control whether Ray sends payloads at runtime. Check the current state or toggle sending on/off.
### Method
`ray().enable()`
`ray().disable()`
`ray().enabled(): boolean`
`ray().disabled(): boolean`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```javascript
import { ray } from 'node-ray';
// Check current state
console.log(ray().enabled()); // true
console.log(ray().disabled()); // false
// Disable sending to Ray
ray('This is sent');
ray().disable();
ray('This is NOT sent');
// Re-enable sending
ray().enable();
ray('This is sent again');
// Conditional based on environment
if (process.env.NODE_ENV === 'development') {
ray().enable();
} else {
ray().disable();
}
```
### Response
#### Success Response (200)
None (methods control internal state or return boolean)
#### Response Example
None
```
--------------------------------
### Displaying Formatted Dates with date() in Node.js
Source: https://context7.com/permafrost-dev/node-ray/llms.txt
Display formatted date information, including timezone and timestamp, using the `date()` method. This allows for clear visualization of date-related data within the Ray client, with options for custom labels and styling.
```javascript
import { ray } from 'node-ray';
// Display current date
ray().date(new Date());
// Display specific date
ray().date(new Date('2024-06-15T14:30:00Z'));
// Date with other styling
ray().date(new Date()).label('Transaction Time').green();
```
--------------------------------
### Display File Contents with file() (Node.js)
Source: https://context7.com/permafrost-dev/node-ray/llms.txt
Displays the content of a specified file directly within the Ray application. This feature is exclusive to Node.js environments and is useful for inspecting configuration or log files.
```javascript
import { ray } from 'node-ray';
// Display file contents
ray().file('/path/to/config.json');
// Display log file
ray().file('/var/log/app.log');
// Chain with styling
ray().file('./package.json').label('Package Config');
```
--------------------------------
### Send Custom Payloads with sendCustom()
Source: https://context7.com/permafrost-dev/node-ray/llms.txt
Allows sending custom data payloads with an optional label to Ray. This is useful for debugging specific, non-standard data structures or messages.
```javascript
import { ray } from 'node-ray';
// Send custom content
ray().sendCustom('Custom debug message', 'Custom Label');
// Custom with complex content
ray().sendCustom(JSON.stringify({ custom: 'data' }), 'API Debug');
// Custom without label
ray().sendCustom('Simple custom message');
```
--------------------------------
### Laravel Mix/Vite Integration (JavaScript)
Source: https://context7.com/permafrost-dev/node-ray/llms.txt
Integrates node-ray into Laravel projects using Mix or Vite by importing the ray function and assigning it to the window object. This makes ray() globally accessible within the frontend code.
```javascript
// resources/js/bootstrap.js
import { ray } from 'node-ray/web';
window.ray = ray;
// Now use ray() anywhere in your frontend code
ray('Laravel frontend debug');
ray().table({ view: 'dashboard', user: currentUser });
```
--------------------------------
### NodeJS ESM Import
Source: https://github.com/permafrost-dev/node-ray/blob/main/docs/available-environments.md
Import the node-ray package for use in a NodeJS environment using ES module syntax. This is the default and recommended method for NodeJS.
```javascript
import { ray } from 'node-ray';
```
--------------------------------
### Conditionally Show Items with Ray
Source: https://github.com/permafrost-dev/node-ray/blob/main/docs/usage.md
Control the visibility of Ray output based on conditions. Use `showIf()` or `showWhen()` with a boolean value or a callback function that returns a boolean.
```javascript
ray('will be shown').showIf(() => true);
ray('will be shown').showWhen(true);
ray('will not be shown').showIf(false);
ray('will not be shown').showWhen(() => false);
```
--------------------------------
### Send XML Data to Ray with Syntax Highlighting and Formatting - JavaScript
Source: https://context7.com/permafrost-dev/node-ray/llms.txt
The `xml()` method sends XML data to Ray, providing syntax highlighting and automatic formatting for improved readability. It can handle both simple and complex XML structures.
```javascript
import { ray } from 'node-ray';
// Display XML with syntax highlighting
ray().xml('Johnjohn@example.com');
// More complex XML
ray().xml(`
localhost5432myapp3600
`);
```
--------------------------------
### Miscellaneous Utilities: separator(), hide(), remove(), pass(), confetti(), die()
Source: https://context7.com/permafrost-dev/node-ray/llms.txt
Provides various utility methods for enhancing debug output management. These include adding visual separators, hiding payloads, removing entries, passing values through, triggering confetti animations, and halting execution (Node.js only).
```javascript
import { ray } from 'node-ray';
// Add a visual separator
ray().separator();
// Hide a payload (collapsed by default)
ray('Hidden details').hide();
// Remove a specific ray entry
const entry = ray('Temporary');
entry.remove();
// Pass through - display and return value
const result = ray().pass(computeValue()); // Displays and returns the value
// Celebrate with confetti
ray().confetti();
// Die - halt execution (Node.js only)
if (criticalError) {
ray('Fatal error').die('Process terminated');
}
```
--------------------------------
### Displaying Errors and Exceptions with Ray
Source: https://github.com/permafrost-dev/node-ray/blob/main/README.md
Display information about errors or exceptions using `ray().error()` or `ray().exception()`. The `exception()` method provides extended information and stack traces asynchronously.
```javascript
ray().error(myError);
ray().exception(myException);
```
--------------------------------
### Import ray for Browser Bundles (webpack/vite)
Source: https://github.com/permafrost-dev/node-ray/blob/main/README.md
Shows how to import the `ray` function when bundling scripts for browser environments using tools like webpack or vite. This import uses the `/web` export to ensure compatibility.
```javascript
import { ray } from 'node-ray/web';
```
--------------------------------
### Define and Use Custom Macros with macro()
Source: https://context7.com/permafrost-dev/node-ray/llms.txt
Enables the creation of custom, reusable debugging methods (macros) that can be added to the Ray class. Macros must be defined using regular functions, not arrow functions.
```javascript
import { ray } from 'node-ray';
// Define a macro (must use regular function, not arrow function)
ray().macro('debug', function(label, data) {
return this.table(data).label(label).blue();
});
// Use the macro
ray().debug('User Data', { name: 'John', role: 'admin' });
// Another macro example
ray().macro('success', function(message) {
return this.text(message).green().large();
});
ray().success('Operation completed!');
```
--------------------------------
### Browser Bundle ESM Import
Source: https://github.com/permafrost-dev/node-ray/blob/main/docs/available-environments.md
Import the '/web' variant of node-ray when bundling scripts for a browser environment, such as with webpack. This ensures compatibility with browser environments.
```javascript
import { ray } from 'node-ray/web';
```
--------------------------------
### Send JSON Data to Ray with Syntax Highlighting - JavaScript
Source: https://context7.com/permafrost-dev/node-ray/llms.txt
The `json()` and `toJson()` methods send JSON data to Ray with syntax highlighting. `json()` is used for JSON strings, while `toJson()` converts JavaScript objects to JSON before displaying.
```javascript
import { ray } from 'node-ray';
// Display a JSON string with syntax highlighting
ray().json('{"name": "John", "age": 30, "active": true}');
// Convert an object to JSON and display it
ray().toJson({
user: 'admin',
permissions: ['read', 'write', 'delete'],
metadata: { created: '2024-01-01' }
});
// Multiple JSON payloads
ray().json('{"a": 1}', '{"b": 2}');
```
--------------------------------
### Add Custom Methods to Ray with Macros
Source: https://github.com/permafrost-dev/node-ray/blob/main/docs/usage.md
Extend the Ray functionality by adding custom methods using `macro()`. Ensure the provided function is not an arrow function.
```javascript
// make sure the function isn't an arrow function!
ray().macro('uppercase', function(str) {
return str.toUpperCase();
});
ray().uppercase('this is uppercase text');
```
--------------------------------
### Include node-ray Standalone Slim Browser Bundle
Source: https://github.com/permafrost-dev/node-ray/blob/main/README.md
This snippet shows how to include the slim standalone browser bundle of node-ray. This version omits axios, making it suitable for projects that already include axios.
```html
```
--------------------------------
### Browser Standalone Script Tag
Source: https://github.com/permafrost-dev/node-ray/blob/main/docs/available-environments.md
Include node-ray directly in a webpage using a script tag from a CDN. The standalone version includes all necessary libraries, including axios.
```html
```
--------------------------------
### Limiting and Sending Once with limit() and once() in Node.js
Source: https://context7.com/permafrost-dev/node-ray/llms.txt
Control the number of payloads sent from loops or repeated code sections using `limit()` and `once()`. `limit(n)` restricts payloads to the first `n` occurrences, while `once()` ensures a payload is sent only a single time, which is useful for avoiding redundant logging.
```javascript
import { ray } from 'node-ray';
// Only send 5 payloads from this loop
for (let i = 0; i < 1000; i++) {
(await ray().limit(5)).send(`Processing item ${i}`);
}
// Only first 5 iterations are sent to Ray
// Send payload only once (useful in loops)
for (const item of items) {
await ray().once(item); // Only first item is sent
processItem(item);
}
// once() without arguments
for (let i = 0; i < 100; i++) {
(await ray().once()).text('This appears only once');
doSomething();
}
```
--------------------------------
### Control Text Size with small() and large()
Source: https://context7.com/permafrost-dev/node-ray/llms.txt
Adjust the text size of debug output in Ray using the `small()` and `large()` methods. This is useful for emphasizing important information or de-emphasizing less critical details.
```javascript
import { ray } from 'node-ray';
// Small text for less important info
ray('Debug details').small();
// Normal sized text (default)
ray('Regular message');
// Large text for important info
ray('IMPORTANT: Check this value').large();
// Chain with other methods
ray('Critical Error').large().red();
```
--------------------------------
### Displaying File Contents with Ray (NodeJS)
Source: https://github.com/permafrost-dev/node-ray/blob/main/README.md
Display the contents of a file directly in Ray using `ray().file()` in NodeJS environments. Ensure the file path is correct.
```javascript
ray().file('path/to/your/file.txt');
```
--------------------------------
### Conditional Payload Display with if(), showIf(), showWhen() in Node.js
Source: https://context7.com/permafrost-dev/node-ray/llms.txt
Conditionally send payloads to Ray based on boolean values or callback functions using `showIf()`, `showWhen()`, and `if()`. This allows for dynamic debugging, showing information only when specific conditions are met, such as user roles or debug flags.
```javascript
import { ray } from 'node-ray';
// Conditional with boolean
ray('Debug info').showIf(process.env.DEBUG === 'true');
ray('Verbose output').showWhen(false);
// Conditional with callback
ray('Admin only').showIf(() => user.role === 'admin');
ray('Active users').showWhen(() => users.length > 0);
// if() with callback parameter
ray().if(isProduction, (r) => {
r.text('Production environment detected').orange();
});
// Chained conditionals
ray('Test results')
.if(allTestsPassed, r => r.green())
.if(!allTestsPassed, r => r.red());
// Control subsequent payloads
ray().if(shouldDebug).text('This only shows if shouldDebug is true');
```
--------------------------------
### Displaying Images in Ray
Source: https://github.com/permafrost-dev/node-ray/blob/main/README.md
Display an image in Ray by providing its URL to the `ray().image()` function.
```javascript
ray().image('https://example.com/image.png');
```
--------------------------------
### Limit and Once - limit(), once()
Source: https://context7.com/permafrost-dev/node-ray/llms.txt
Control the number of payloads sent from loops or repeated code sections. Limit the frequency of messages.
```APIDOC
## Limit and Once - limit(), once()
### Description
Control the number of payloads sent from loops or repeated code sections. Limit the frequency of messages.
### Method
`ray().limit(count: number): Ray`
`ray().once(payload?: any): Ray`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```javascript
import { ray } from 'node-ray';
// Only send 5 payloads from this loop
for (let i = 0; i < 1000; i++) {
(await ray().limit(5)).send(`Processing item ${i}`);
}
// Only first 5 iterations are sent to Ray
// Send payload only once (useful in loops)
for (const item of items) {
await ray().once(item); // Only first item is sent
processItem(item);
}
// once() without arguments
for (let i = 0; i < 100; i++) {
(await ray().once()).text('This appears only once');
doSomething();
}
```
### Response
#### Success Response (200)
None (methods control payload sending)
#### Response Example
None
```
--------------------------------
### Sending HTML to Ray
Source: https://github.com/permafrost-dev/node-ray/blob/main/README.md
Send raw HTML strings to Ray for rendering using `ray().html()`. For displaying syntax-highlighted HTML code, use `ray().htmlMarkup()`.
```javascript
ray().html('
Hello World
');
ray().htmlMarkup('
Content
');
```
--------------------------------
### Display Images in Ray from URLs or Local Paths - JavaScript
Source: https://context7.com/permafrost-dev/node-ray/llms.txt
The `image()` method displays images within Ray. It supports image URLs and, in Node.js environments, local file paths. The method can be chained with other Ray methods like color and label.
```javascript
import { ray } from 'node-ray';
// Display image from URL
ray().image('https://placekitten.com/200/300');
// Display local image (Node.js only)
ray().image('/path/to/local/image.png');
// Chain with other methods
ray().image('https://example.com/chart.png').blue().label('Sales Chart');
```
--------------------------------
### Display Data as a Table with Ray
Source: https://github.com/permafrost-dev/node-ray/blob/main/docs/usage.md
Format arrays of items into a readable table within Ray. Complex data types within the array are pretty-printed and highlighted.
```javascript
ray().table(['hello world', true, [1, 2, 3], {name: 'John', age: 32}]);
```
--------------------------------
### Send Desktop Notifications with notify()
Source: https://context7.com/permafrost-dev/node-ray/llms.txt
Sends desktop notifications using the Ray desktop app. This function can be used to notify users about events like build completions or deployments. It can optionally include other debug data.
```javascript
import { ray } from 'node-ray';
// Send a notification
ray().notify('Build completed successfully!');
// Notification with other debug data
ray('Deployment finished').notify('Deployment Complete');
```
--------------------------------
### Adding Labels to Ray Payloads
Source: https://github.com/permafrost-dev/node-ray/blob/main/README.md
Add a descriptive text label to your Ray payloads using `ray().label()` for better organization and identification.
```javascript
ray('some data').label('important info');
```
--------------------------------
### Displaying Events with Ray
Source: https://github.com/permafrost-dev/node-ray/blob/main/README.md
Log events with an optional name and data payload using `ray().event()`. This is useful for tracking specific occurrences in your application.
```javascript
ray().event('userLoggedIn', { userId: 123 });
```
--------------------------------
### Performance Measurement - measure(), stopTime()
Source: https://context7.com/permafrost-dev/node-ray/llms.txt
Measure execution time and track performance of code blocks using named or anonymous stopwatches.
```APIDOC
## Performance Measurement - measure(), stopTime()
### Description
Measure execution time and track performance of code blocks using named or anonymous stopwatches.
### Method
`ray().measure(name?: string)`
`ray().stopTime(name?: string)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```javascript
import { ray } from 'node-ray';
// Measure a closure
ray().measure(() => {
// Expensive operation
for (let i = 0; i < 1000000; i++) {
Math.sqrt(i);
}
});
// Measure time between calls
ray().measure(); // Start timing
await someAsyncOperation();
ray().measure(); // Shows time since last measure()
await anotherAsyncOperation();
ray().measure(); // Shows time since previous measure()
// Named stopwatches
ray().measure('database-query');
await db.query('SELECT * FROM users');
ray().measure('database-query'); // Shows elapsed time
// Stop and remove a named stopwatch
ray().stopTime('database-query');
// Stop all stopwatches
ray().stopTime();
```
### Response
#### Success Response (200)
None (methods log performance data to Ray)
#### Response Example
None
```
--------------------------------
### Clearing Ray Screens
Source: https://github.com/permafrost-dev/node-ray/blob/main/README.md
Clear the current Ray screen with `clearScreen()` or clear all previous screens including the current one with `clearAll()`.
```javascript
ray().clearScreen();
ray().clearAll();
```
--------------------------------
### Displaying Formatted Dates with Ray
Source: https://github.com/permafrost-dev/node-ray/blob/main/README.md
Display a formatted date, its timezone, and timestamp using `ray().date()`. The `format` parameter allows for custom date string representation.
```javascript
ray().date(new Date(), 'Y-m-d H:i:s');
```
--------------------------------
### Counting Code Executions with Ray
Source: https://github.com/permafrost-dev/node-ray/blob/main/README.md
Track how many times a specific piece of code is executed using `ray().count()`. An optional name can be provided for clarity when counting multiple sections.
```javascript
ray().count('myCounter');
```
--------------------------------
### Display Rendered HTML Content
Source: https://context7.com/permafrost-dev/node-ray/llms.txt
Send HTML content to Ray for rendered display using the `html()` method. This is ideal for visualizing formatted output, custom UI elements, or complex data structures within the Ray application.
```javascript
import { ray } from 'node-ray';
// Send simple HTML
ray().html('Bold text');
// Send complex HTML with styling
ray().html(`
User Profile
Name: John Doe
Status: Active
`);
// HTML with colors
ray().html('Emphasized warning').orange();
```
--------------------------------
### Display Notifications with Ray
Source: https://github.com/permafrost-dev/node-ray/blob/main/docs/usage.md
Send a simple notification message to the Ray app. Use the `notify()` method with the desired message string.
```javascript
ray().notify('This is my notification');
```
--------------------------------
### Apply Colors to Debug Output
Source: https://context7.com/permafrost-dev/node-ray/llms.txt
Use color methods like `green()`, `red()`, `blue()`, `orange()`, `purple()`, and `gray()` to visually categorize debug output in the Ray application. Colors can be chained with other methods.
```javascript
import { ray } from 'node-ray';
// Apply individual colors
ray('Success message').green();
ray('Warning message').orange();
ray('Error message').red();
ray('Info message').blue();
ray('Debug message').purple();
ray('Muted message').gray();
// Chain with color method
ray('Critical error detected').red().large();
// Use dynamic color
ray('Dynamic color').color('purple');
```
--------------------------------
### Conditional Display - if(), showIf(), showWhen()
Source: https://context7.com/permafrost-dev/node-ray/llms.txt
Conditionally send payloads based on boolean values or callbacks. Control whether data is sent to Ray.
```APIDOC
## Conditional Display - if(), showIf(), showWhen()
### Description
Conditionally send payloads based on boolean values or callbacks. Control whether data is sent to Ray.
### Method
`payload.showIf(condition: boolean | (() => boolean))`
`payload.showWhen(condition: boolean | (() => boolean))`
`ray().if(condition: boolean | (() => boolean), callback: (r: Ray) => void)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```javascript
import { ray } from 'node-ray';
// Conditional with boolean
ray('Debug info').showIf(process.env.DEBUG === 'true');
ray('Verbose output').showWhen(false);
// Conditional with callback
ray('Admin only').showIf(() => user.role === 'admin');
ray('Active users').showWhen(() => users.length > 0);
// if() with callback parameter
ray().if(isProduction, (r) => {
r.text('Production environment detected').orange();
});
// Chained conditionals
ray('Test results')
.if(allTestsPassed, r => r.green())
.if(!allTestsPassed, r => r.red());
// Control subsequent payloads
ray().if(shouldDebug).text('This only shows if shouldDebug is true');
```
### Response
#### Success Response (200)
None (methods conditionally send data to Ray)
#### Response Example
None
```
--------------------------------
### Include node-ray Standalone Browser Bundle
Source: https://github.com/permafrost-dev/node-ray/blob/main/README.md
This snippet illustrates how to include the standalone browser bundle of node-ray using a script tag. This version includes axios and is suitable for direct use in web pages.
```html
```
--------------------------------
### Displaying Caller Information with Ray
Source: https://github.com/permafrost-dev/node-ray/blob/main/README.md
The `ray().caller()` function, when used asynchronously, displays the calling class and method. This is useful for understanding the execution context of your code.
```javascript
ray().caller();
```
--------------------------------
### Chaining Multiple Payloads with chain() in Node.js
Source: https://context7.com/permafrost-dev/node-ray/llms.txt
Send multiple chained payloads together in a single request using the `chain()` method. This is particularly useful in asynchronous contexts for grouping related debugging information into one Ray payload, improving organization and clarity.
```javascript
import { ray } from 'node-ray';
// Chain multiple methods together
ray().chain((r) => {
r.text('Server Status')
.blue()
.large()
.label('Status');
});
// Complex chains
ray().chain((r) => {
r.html('
Debug Report
')
.table({ uptime: '24h', memory: '512MB' })
.green()
.label('System');
});
```
--------------------------------
### Chaining Ray Payloads
Source: https://github.com/permafrost-dev/node-ray/blob/main/README.md
Chain multiple Ray payloads together to send them all at once. The `chain()` method accepts a callback function that receives a `Ray` instance for building the chained payload.
```javascript
ray().chain((ray) => {
// Build chained payloads here
});
```
--------------------------------
### Chaining Payloads - chain()
Source: https://context7.com/permafrost-dev/node-ray/llms.txt
Send multiple chained payloads together in a single request. Useful in async contexts for grouping related debug information.
```APIDOC
## Chaining Payloads - chain()
### Description
Send multiple chained payloads together in a single request. Useful in async contexts for grouping related debug information.
### Method
`ray().chain(callback: (r: Ray) => void)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```javascript
import { ray } from 'node-ray';
// Chain multiple methods together
ray().chain((r) => {
r.text('Server Status')
.blue()
.large()
.label('Status');
});
// Complex chains
ray().chain((r) => {
r.html('
Debug Report
')
.table({ uptime: '24h', memory: '512MB' })
.green()
.label('System');
});
```
### Response
#### Success Response (200)
None (method sends chained payloads to Ray)
#### Response Example
None
```
--------------------------------
### Intercepting Console Logs with Ray
Source: https://github.com/permafrost-dev/node-ray/blob/main/README.md
Access the `ConsoleInterceptor` via `ray().interceptor()` and enable it with `.enable()` to display `console.log()` calls within Ray.
```javascript
ray().interceptor().enable();
```
--------------------------------
### Display Caller Information with caller()
Source: https://context7.com/permafrost-dev/node-ray/llms.txt
Displays information about the function and file location from which the `caller()` method was invoked. This helps in tracing the origin of debug logs.
```javascript
import { ray } from 'node-ray';
function processOrder(order) {
ray().caller(); // Shows: processOrder at file.js:line
// process order...
}
async function debugFunction() {
await ray().caller(); // Shows caller information
}
```
--------------------------------
### Outputting Colored Data with Ray
Source: https://github.com/permafrost-dev/node-ray/blob/main/README.md
Customize the output color of data sent to Ray using chaining. Available colors include `green`, `orange`, `red`, `blue`, and `gray`.
```javascript
ray().blue();
```
--------------------------------
### Control Text Size in Ray Output
Source: https://github.com/permafrost-dev/node-ray/blob/main/docs/usage.md
Adjust the display size of text sent to Ray. Options include `small()`, default (normal), and `large()`. Chain the size method after the data.
```javascript
ray('small').small();
ray('regular');
ray('large').large();
```
--------------------------------
### Basic Usage of ray() in JavaScript
Source: https://context7.com/permafrost-dev/node-ray/llms.txt
The `ray()` function is the primary method for sending debug data to the Ray application. It accepts multiple arguments of any data type, including strings, objects, arrays, and booleans.
```javascript
import { ray } from 'node-ray';
// Send a simple string
ray('Hello, World!');
// Send multiple arguments
ray('User data:', { name: 'John', age: 30 }, [1, 2, 3]);
// Send an object
ray({ status: 'active', count: 42 });
// Send arrays and nested data
ray(['item1', 'item2'], { nested: { deep: { value: true } } });
```
--------------------------------
### Controlling Ray Payloads with enable(), disable(), enabled(), disabled() in Node.js
Source: https://context7.com/permafrost-dev/node-ray/llms.txt
Control whether Ray sends payloads at runtime using `enable()` and `disable()`. The `enabled()` and `disabled()` methods allow checking the current state. This is useful for toggling debugging output based on environment variables or application state.
```javascript
import { ray } from 'node-ray';
// Check current state
console.log(ray().enabled()); // true
console.log(ray().disabled()); // false
// Disable sending to Ray
ray('This is sent');
ray().disable();
ray('This is NOT sent');
// Re-enable sending
ray().enable();
ray('This is sent again');
// Conditional based on environment
if (process.env.NODE_ENV === 'development') {
ray().enable();
} else {
ray().disable();
}
```
--------------------------------
### Display Error Information with Ray
Source: https://github.com/permafrost-dev/node-ray/blob/main/docs/usage.md
Log detailed information about an `Error` object using the `error()` method. This provides context and stack trace for debugging.
```javascript
ray().error(new Error('my error message'));
```
--------------------------------
### Add Text Labels to Payloads for Better Organization - JavaScript
Source: https://context7.com/permafrost-dev/node-ray/llms.txt
The `label()` method allows you to attach a text label to any payload sent to Ray. This helps in organizing and identifying different pieces of debug information, especially when multiple items are displayed.
```javascript
import { ray } from 'node-ray';
// Add a label to a payload
ray('User logged in').label('Auth');
// Combine with colors
ray({ status: 'error', code: 500 }).label('API Response').red();
// Label on table
ray().table({ x: 10, y: 20 }).label('Coordinates');
```
--------------------------------
### Triggering Confetti Animation in Ray
Source: https://github.com/permafrost-dev/node-ray/blob/main/README.md
Add a celebratory touch to your debugging output by triggering a confetti animation using `ray().confetti()`.
```javascript
ray().confetti();
```
--------------------------------
### Apply Colors to Ray Output
Source: https://github.com/permafrost-dev/node-ray/blob/main/docs/usage.md
Colorize your Ray output using predefined color names. Available colors include green, orange, red, blue, purple, and gray. Chain the color method after the data.
```javascript
ray('this is green').green();
ray('this is purple').purple();
```
--------------------------------
### Display Raw Text Preserving Whitespace and Special Characters - JavaScript
Source: https://context7.com/permafrost-dev/node-ray/llms.txt
The `text()` method displays raw text in Ray, ensuring that whitespace is preserved and special characters are not interpreted as HTML. This is useful for displaying logs or plain text content.
```javascript
import { ray } from 'node-ray';
// Display plain text
ray().text('Plain text without HTML interpretation');
// Preserve whitespace formatting
ray().text(`
Line 1
Indented line 2
Line 3
`);
// Text with special characters (not interpreted as HTML)
ray().text('');
```