### Install Valdi CLI
Source: https://github.com/snapchat/valdi/blob/main/docs/INSTALL.md
Installs the Valdi Command Line Interface globally using npm. This is the first step to using Valdi for project development.
```bash
npm install -g @snap/valdi
```
--------------------------------
### Install and Set Up Valdi CLI (Bash)
Source: https://github.com/snapchat/valdi/blob/main/docs/docs/start-install.md
Installs the Valdi CLI globally using npm, sets up the development environment, verifies the installation with 'valdi doctor', and bootstraps a new project. It also includes commands to install platform-specific dependencies for iOS or Android.
```bash
# 1. Install the Valdi CLI
npm install -g @snap/valdi
# 2. Set up your development environment
valdi dev_setup
# 3. Verify everything works
valdi doctor
# 4. Create your first project
mkdir my_project && cd my_project
valdi bootstrap
valdi install ios # or android
```
--------------------------------
### Set Up Development Environment and Verify
Source: https://github.com/snapchat/valdi/blob/main/docs/INSTALL.md
Sets up the complete development environment, including all necessary dependencies, and then verifies the installation. This command handles automatic installation of tools like Homebrew, Bazelisk, Java JDK, Android SDK, Git LFS, and Watchman.
```bash
# Set up your development environment (installs all dependencies)
valdi dev_setup
# Verify everything is working
valdi doctor
```
--------------------------------
### Install and Setup Valdi CLI for App Development
Source: https://github.com/snapchat/valdi/blob/main/AGENTS.md
Essential bash commands for app developers to install Valdi CLI, setup development environment, bootstrap new projects, install platform-specific dependencies, and start hot reload. These commands enable rapid UI development without native recompilation.
```bash
# Install Valdi CLI (first time)
cd npm_modules/cli && npm run cli:install
# Setup development environment
valdi dev_setup
# Bootstrap a new project
mkdir my_project && cd my_project
valdi bootstrap
# Install dependencies and build
valdi install ios # or android
# Start hot reload
valdi hotreload
```
--------------------------------
### Valdi CLI Installation and Project Setup
Source: https://github.com/snapchat/valdi/blob/main/README.md
Commands for installing the Valdi CLI globally and setting up a new Valdi project. This includes installing dependencies, bootstrapping the project, and installing platform-specific builds.
```bash
# Install Valdi CLI
npm install -g @snap/valdi
# One-command setup (installs all dependencies)
valdi dev_setup
# Create your first project
mkdir my_project && cd my_project
valdi bootstrap
valdi install ios # or android
```
--------------------------------
### Install Valdi from Source (for Contributors)
Source: https://github.com/snapchat/valdi/blob/main/docs/INSTALL.md
Clones the Valdi repository and installs the CLI from source, intended for developers contributing to Valdi itself. This process involves cloning the git repository and running an npm script within the CLI module.
```bash
git clone git@github.com:Snapchat/Valdi.git
cd Valdi/npm_modules/cli/
npm run cli:install
```
--------------------------------
### Install and run the adapter for contribution
Source: https://github.com/snapchat/valdi/blob/main/compiler/companion/remotedebug-ios-webkit-adapter/README.md
Commands to install project dependencies and start the adapter locally, intended for developers contributing to the project. Assumes Node.js and npm are installed.
```shell
npm install
npm start
```
--------------------------------
### Install and Link Valdi GPT in Web Demo
Source: https://github.com/snapchat/valdi/blob/main/apps/valdi_gpt/web_demo/README.md
Installs project dependencies for the Valdi GPT web demo and links the locally built Valdi GPT npm package. The `npm link` command must be run after `npm install` because it modifies the `node_modules` folder. This ensures the web demo uses the latest version of the Valdi GPT library.
```bash
cd apps/valdi_gpt/web_demo
npm install
npm link valdi_gpt_npm
```
--------------------------------
### Bootstrap a New Valdi Project
Source: https://github.com/snapchat/valdi/blob/main/docs/INSTALL.md
Initializes a new Valdi project by creating necessary directories, source files, and configuration. This command is run after creating and navigating into a new project directory.
```bash
# Create and enter your project directory
mkdir my_project
cd my_project
# Initialize a new Valdi project
valdi bootstrap
```
--------------------------------
### Run Valdi GPT Web Demo Development Server
Source: https://github.com/snapchat/valdi/blob/main/apps/valdi_gpt/web_demo/README.md
Starts the development server for the Valdi GPT web demo from the `web_demo` directory. This command enables hot-reloading, allowing for faster development cycles. The application will be accessible at `http://localhost:3030/` in a web browser.
```bash
npm run serve
```
--------------------------------
### Valdi Component Setup and Basic Rendering
Source: https://github.com/snapchat/valdi/blob/main/docs/docs/control-flow.md
Demonstrates the basic setup of a Valdi component, including initializing variables in onCreate and performing rendering logic in onRender. It displays a simple message with the current time.
```tsx
import { Component } from 'valdi_core/src/Component';
export class GettingStartedCodelab extends Component {
private msg?: string;
onCreate() {
this.msg = 'Hello Valdi on ';
}
onRender() {
const fullMsg = this.msg + new Date().toLocaleTimeString();
;
}
}
```
--------------------------------
### Install Platform Dependencies
Source: https://github.com/snapchat/valdi/blob/main/docs/INSTALL.md
Installs platform-specific dependencies required for running the Valdi project on either iOS or Android simulators/emulators. This step is necessary after bootstrapping a new project.
```bash
# For iOS
valdi install ios
# For Android
valdi install android
```
--------------------------------
### Basic HelloWorld Component Setup (TypeScript)
Source: https://github.com/snapchat/valdi/blob/main/docs/codelabs/advanced_ui/1-setup.md
This TypeScript code defines a basic 'App' component for a Valdi application. It extends `valdi_core/src/Component`, imports necessary functions, and defines `ViewModel` and `ComponentContext` interfaces. The `onCreate` method calls `onRootComponentCreated`, and `onRender` returns a simple 'view' element. This serves as a starting point for UI development in Valdi.
```tsx
import { Component } from 'valdi_core/src/Component';
import { onRootComponentCreated } from './CppModule';
/**
* @ViewModel
* @ExportModel
*/
export interface ViewModel {}
/**
* @Context
* @ExportModel
*/
export interface ComponentContext {}
/**
* @Component
* @ExportModel
*/
export class App extends Component {
onCreate(): void {
onRootComponentCreated(this.renderer.contextId);
}
onRender(): void {
;
}
}
```
--------------------------------
### Install and Use Valdi CLI
Source: https://github.com/snapchat/valdi/blob/main/AGENTS.md
Install the Valdi command-line interface globally using npm and access CLI commands. Requires navigating to the CLI directory first.
```bash
cd npm_modules/cli
# Install the valdi command-line tool globally
npm run cli:install
# After installation, use the CLI
valdi --help
```
--------------------------------
### Install and Run Valdi CLI Commands
Source: https://github.com/snapchat/valdi/blob/main/npm_modules/cli/README.md
Install the Valdi CLI globally via npm and execute basic commands for environment setup, diagnostics, and help.
```bash
npm install -g @snap/valdi
valdi dev_setup
valdi doctor
valdi --help
```
--------------------------------
### Install Protobuf Compiler
Source: https://github.com/snapchat/valdi/blob/main/docs/docs/advanced-protobuf.md
Instructions for installing the Protobuf compiler on macOS using Homebrew and on Linux using apt. This is a prerequisite for generating Protobuf code.
```bash
brew install protobuf
```
```bash
apt install -y protobuf-compiler
```
--------------------------------
### Install Valdi Editor Extensions
Source: https://github.com/snapchat/valdi/blob/main/docs/INSTALL.md
Installs Valdi-specific extensions for VSCode or Cursor, providing features like syntax highlighting, debugging, and device logs. The extensions are installed using the editor's command-line interface.
```bash
# For VSCode
code --install-extension /path/to/valdi-vivaldi.vsix
code --install-extension /path/to/valdi-debug.vsix
# For Cursor
cursor --install-extension /path/to/valdi-vivaldi.vsix
cursor --install-extension /path/to/valdi-debug.vsix
```
--------------------------------
### Build and Test Valdi Platform
Source: https://github.com/snapchat/valdi/blob/main/AGENTS.md
Commands for platform developers contributing to the Valdi framework. Includes development environment setup, Bazel builds, test execution, and running example apps. Requires Bazel build system and follows monorepo patterns.
```bash
# Setup development environment (first time)
scripts/dev_setup.sh
# Build everything
bazel build //...
# Run all tests
bazel test //...
# Build and run example app
cd apps/helloworld
valdi install ios # or android
```
--------------------------------
### Install Valdi App for Android
Source: https://github.com/snapchat/valdi/blob/main/docs/codelabs/getting_started/2-start_coding.md
Command to build and install the 'hello_world' Valdi app on an Android device. Requires the Valdi CLI and a connected Android device or emulator.
```bash
valdi install android
```
--------------------------------
### Install Valdi App for iOS
Source: https://github.com/snapchat/valdi/blob/main/docs/codelabs/getting_started/2-start_coding.md
Command to build and install the 'hello_world' Valdi app on an iOS device. Requires the Valdi CLI and a connected iOS device or simulator.
```bash
valdi install ios
```
--------------------------------
### Install Dependencies with npm
Source: https://github.com/snapchat/valdi/blob/main/compiler/companion/README.md
Installs all the necessary project dependencies using npm. This command should be run before any other development or build commands.
```sh
npm install
```
--------------------------------
### Run Diagnostics for Troubleshooting
Source: https://github.com/snapchat/valdi/blob/main/docs/INSTALL.md
Executes a diagnostic check of the development environment to identify potential issues and provide specific fix suggestions. This is a primary troubleshooting step for Valdi setup problems.
```bash
valdi doctor
```
--------------------------------
### Build Valdi GPT Web Dependencies with Bazel
Source: https://github.com/snapchat/valdi/blob/main/apps/valdi_gpt/web_demo/README.md
Builds the necessary npm dependencies for the Valdi GPT web application using Bazel. This command compiles and packages the front-end assets and libraries required for the web demo. Ensure Bazel is installed and configured in your environment.
```bash
bazel build //apps/valdi_gpt:valdi_gpt_npm
```
--------------------------------
### Install Valdi CLI via npm
Source: https://github.com/snapchat/valdi/blob/main/docs/docs/command-line-references.md
Installs the Valdi command-line interface globally using npm. The `dev_setup` command is then used to set up the development environment.
```bash
npm install -g @snap/valdi
valdi dev_setup # Sets up your entire development environment
```
--------------------------------
### Example Valdi Benchmark Runtime Log Output
Source: https://github.com/snapchat/valdi/blob/main/valdi/src/valdi/startup_benchmark/README.md
Provides an example of runtime log output from the Valdi benchmark, showing the loading time and mode for different JS modules. This helps in diagnosing performance issues and verifying module loading behavior.
```log
[0.003: INFO] Loaded JS module coreutils/src/unicode/TextCoding in 296.2 us (load mode: js bytecode) own memory usage: 229376 total memory usage: 229376
[0.004: INFO] Loaded JS module valdi_core/src/Valdi in 242.3 us (load mode: native) own memory usage: 0 total memory usage: 0
[0.005: INFO] Loaded JS module valdi_core/src/BuildType in 84.3 us (load mode: js source) own memory usage: 0 total memory usage: 0
```
--------------------------------
### Create and Build a Valdi App
Source: https://github.com/snapchat/valdi/blob/main/npm_modules/cli/README.md
Commands to create a new Valdi project, build it, and install it on iOS or Android devices, and start the hot reload development server.
```bash
mkdir my_valdi_app
cd my_valdi_app
valdi bootstrap
valdi install ios
valdi install android
valdi hotreload
```
--------------------------------
### Installing Coreutils with Bazel
Source: https://github.com/snapchat/valdi/blob/main/docs/docs/stdlib-coreutils.md
Adds the coreutils module as a dependency in a Valdi project's BUILD.bazel file using Bazel syntax. Requires the Bazel build system and valdi_module rule. Inputs: module name and dependencies list; outputs: configured build target. No runtime limitations, but assumes Valdi environment setup.
```python
valdi_module(
name = "my_module",
deps = [
"@valdi//src/valdi_modules/src/valdi/coreutils",
],
)
```
--------------------------------
### Complete Navigation Example
Source: https://github.com/snapchat/valdi/blob/main/docs/docs/navigation.md
A complete example demonstrating the usage of NavigationRoot and NavigationPageComponent to build a simple application with navigation between pages. It includes a main App component that renders buttons to navigate to Page1 and Page2, and each page has a back button.
```tsx
export class App extends Component {
private navigationController?: NavigationController;
onRender(): void {
{$slot(navigationController => {
this.navigationController = navigationController;
{this.renderButtons()}
;
})}
;
}
private renderButtons() {
;
;
}
private handleOpenPage1 = () => {
this.navigationController?.push(Page1, {}, {});
};
private handleOpenPage2 = () => {
this.navigationController?.push(Page2, {}, {});
};
}
@NavigationPage(module)
export class Page1 extends NavigationPageComponent<{}> {
onRender() {
;
}
private handleBack = () => {
this.navigationController.pop();
};
}
@NavigationPage(module)
export class Page2 extends NavigationPageComponent<{}> {
onRender() {
;
}
private handleBack = () => {
this.navigationController.pop();
};
}
```
--------------------------------
### Install Valdi Application to Device
Source: https://github.com/snapchat/valdi/blob/main/docs/docs/command-line-references.md
Builds and installs the Valdi application onto a connected device. This command combines the build process with the deployment step.
```sh
valdi install
```
--------------------------------
### Customizing Runtime Executable and Arguments
Source: https://github.com/snapchat/valdi/blob/main/valdi/vscode_debugger/README.md
This example shows how to specify a custom runtime executable and its arguments for launching snap-node. This is useful when using alternative Node.js versions or specific runtime flags.
```json
{
"name": "Launch with Custom Runtime",
"type": "node",
"request": "launch",
"runtimeExecutable": "/usr/local/bin/node",
"runtimeArgs": [
"--inspect-brk"
],
"program": "${workspaceFolder}/src/index.js"
}
```
--------------------------------
### Configure Valdi Widgets Setup in Workspace - Python
Source: https://github.com/snapchat/valdi/blob/main/docs/docs/third-party-dependencies.md
This code snippet shows optional configuration steps after loading the setup function from the valdi_widgets repository. It loads and invokes the setup function to configure the dependency. Depends on the @valdi_widgets repository being available. No inputs; outputs configured workspace. Limitation: Specific to valdi_widgets setup.
```python
# Load the setup function from our Valdi widgets repository
load("@valdi_widgets//:setup.bzl", "setup_valdi_widgets")
# Invoke it
setup_valdi_widgets()
```
--------------------------------
### Compiling and Installing Valdi Assets
Source: https://github.com/snapchat/valdi/blob/main/docs/docs/core-images.md
Provides bash commands for common Valdi development workflows. It includes steps for synchronizing projects, building a specific module to regenerate `BUILD.bazel` files after adding resources, and installing the compiled assets for iOS or Android platforms.
```bash
# Typical valdi development path
cd /Path/To/Your/App/src/valdi/app_name/src
# Need to regenerate the BUILD.bazel files if adding in a /res folder
bazel build //src/onboarding/onboarding:onboarding
# Compile the typescript code into the native repo
valdi install ios
# or
valdi install android
```
--------------------------------
### Install Valdi Application on a Device or Emulator
Source: https://github.com/snapchat/valdi/blob/main/docs/docs/command-line-references.md
Builds and installs a Valdi application onto a connected device or emulator for Android, iOS, or macOS. Supports specifying an application target and passing additional Bazel arguments.
```shell
valdi install [--application] [--bazel_args]
```
--------------------------------
### Initialize Runtime in Objective-C
Source: https://github.com/snapchat/valdi/blob/main/docs/codelabs/shared_business_logic/ios/2-ios_hook_up_module.md
Initializes the local _runtime variable with the Valdi runtime instance obtained from valdiServices. This setup occurs during the view controller's initialization.
```objectivec
if (self = [super init]) {
...
_runtime = valdiServices.valdiRuntimeProvider.target.runtime;
}
```
--------------------------------
### Initialize Valdi runtime in Android (Kotlin)
Source: https://github.com/snapchat/valdi/blob/main/docs/docs/workflow-external-build-system.md
Kotlin code example for loading the Valdi library and initializing the Valdi runtime manager in an Android Activity.
```kotlin
import com.snap.valdi.ValdiRuntimeManager
import com.snap.valdi.support.SupportValdiRuntimeManager
import com.snap.valdi.modules.hello_world.App
class MainActivity : Activity() {
var runtimeManager: ValdiRuntimeManager? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// This needs to execute at least once
// The name of the library will match the name of
// your valdi_exported_library() target.
System.loadLibrary("hello_world_export")
// For best performance, your app should maintain a singleton
// of the Valdi runtime manager.
val runtimeManager = SupportValdiRuntimeManager.createWithSupportLibs(this.applicationContext)
this.runtimeManager = runtimeManager
setContentView(App.create(runtimeManager.mainRuntime))
}
}
```
--------------------------------
### Configure TypeScript Workspace Version
Source: https://github.com/snapchat/valdi/blob/main/docs/INSTALL.md
Manually configures VSCode/Cursor to use the project's workspace version of TypeScript. This is a crucial step for ensuring proper development environment setup and cannot be automated.
```bash
# Open Command Palette (Cmd+Shift+P or Ctrl+Shift+P)
# Select "TypeScript: Select TypeScript Version..."
# Choose "Use Workspace Version"
```
--------------------------------
### Enable Hot Reloading
Source: https://github.com/snapchat/valdi/blob/main/docs/INSTALL.md
Starts the hot reloader for Valdi applications. This feature allows developers to see changes in real-time on the simulator or emulator without a full rebuild.
```bash
valdi hotreload
```
--------------------------------
### Console Grouping and Collapsed Grouping with Valdi
Source: https://github.com/snapchat/valdi/blob/main/valdi/vscode_debugger/src/test/console/console-format-groups.txt
Demonstrates `console.group()` for creating collapsible log groups and `console.groupCollapsed()` for creating initially collapsed groups. These methods allow for organizing and structuring log output, with `groupEnd()` used to close the current group. The examples show the output for starting and ending these groups.
```javascript
console.group()
```
```javascript
console.groupCollapsed('named')
```
```javascript
console.group({ complex: true })
```
```javascript
console.groupEnd()
```
```javascript
console.groupEnd()
```
```javascript
console.groupEnd()
```
--------------------------------
### Project Synchronization
Source: https://github.com/snapchat/valdi/blob/main/docs/INSTALL.md
Updates the project configuration after changes to dependencies, localization files, or resource files. This command ensures the project's internal configuration reflects any external modifications.
```bash
valdi projectsync
```
--------------------------------
### Build and Run Valdi Benchmark with JS Source Modules
Source: https://github.com/snapchat/valdi/blob/main/valdi/src/valdi/startup_benchmark/README.md
Builds the Valdi benchmark binary for testing with JS source modules and then runs it for QuickJS, Hermes, and JSCore engines. Requires Bazel build system. Outputs performance metrics for each engine.
```sh
# Build the benchmark binary
bzl build @valdi//valdi:startup_benchmark --snap_flavor=production -c opt --//bzl/valdi:js_bytecode_format=none
# Run for QuickJS
bazel-bin/valdi/startup_benchmark --js_engine quickjs
# Run for Hermes
bazel-bin/valdi/startup_benchmark --js_engine hermes
# Run for JSCore
bazel-bin/valdi/startup_benchmark --js_engine jscore
```
--------------------------------
### Build and Run Valdi Benchmark with QuickJS Bytecode Modules
Source: https://github.com/snapchat/valdi/blob/main/valdi/src/valdi/startup_benchmark/README.md
Builds the Valdi benchmark binary configured for QuickJS bytecode and executes it using the QuickJS engine. This tests load latency for modules compiled into QuickJS bytecode. Requires Bazel.
```sh
# Build the benchmark binary
bzl build @valdi//valdi:startup_benchmark --snap_flavor=production -c opt --//bzl/valdi:js_bytecode_format=quickjs
# Run for QuickJS
bazel-bin/valdi/startup_benchmark --js_engine quickjs
```
--------------------------------
### Optimize callback handlers by storing as component properties
Source: https://github.com/snapchat/valdi/blob/main/docs/docs/performance-optimization.md
Demonstrates the performance issue with inline lambda callbacks that get recreated on every render. Shows how to properly store callback functions as component properties to maintain stable references and prevent unnecessary framework updates. The good example shows the recommended pattern.
```tsx
class MyComponent extends Component {
onRender() {
{
// Handle click
}}/>
}
}
```
```tsx
class MyComponent extends Component {
onRender() {
}
private onTap = () => {
// Handle click
}
}
```
--------------------------------
### Create Test File Structure
Source: https://github.com/snapchat/valdi/blob/main/docs/codelabs/getting_started/8-unittest.md
This snippet shows the command-line steps to create the necessary directory and an empty test file for a Valdi component. It's the initial setup for writing unit tests.
```bash
cd apps/helloworld/src/valdi/hello_world
mkdir test
touch test/GettingStartedCodelab.spec.tsx
```
--------------------------------
### Link Valdi GPT npm Package Locally
Source: https://github.com/snapchat/valdi/blob/main/apps/valdi_gpt/web_demo/README.md
Navigates to the Bazel output directory and links the built Valdi GPT npm package for local development. This makes the package available globally on your system, allowing other projects to use it. This step is crucial for integrating the Valdi GPT library into the web demo.
```bash
cd bazel-bin/apps/valdi_gpt/valdi_gpt_npm
npm link
```
--------------------------------
### Bootstrap a new Valdi Project
Source: https://github.com/snapchat/valdi/blob/main/docs/docs/command-line-references.md
Initializes a new Valdi project in the current directory, creating necessary files for building and running. Supports skipping prompts and specifying project details.
```sh
valdi bootstrap [-y --confirm-bootstrap] [-n --project-name]
```
--------------------------------
### Build and Run Valdi Benchmark with TSN Compiled Modules
Source: https://github.com/snapchat/valdi/blob/main/valdi/src/valdi/startup_benchmark/README.md
Builds the Valdi benchmark binary for modules compiled with TSN and executes it using the QuickJS TSN engine. Requires modifications to module.yaml to include all files for TSN compilation. Requires Bazel.
```sh
# Build the benchmark binary
bzl build @valdi//valdi:startup_benchmark --snap_flavor=production -c opt --//bzl/valdi:js_bytecode_format=quickjs
# Run for QuickJS with TSN
bazel-bin/valdi/startup_benchmark --js_engine quickjs_tsn
```
--------------------------------
### Enable Runtime Logging in Valdi Benchmark
Source: https://github.com/snapchat/valdi/blob/main/valdi/src/valdi/startup_benchmark/README.md
Demonstrates how to enable runtime logging for the Valdi benchmark by adding the `--@valdi//bzl/runtime_flags:enable_logging` argument during the Bazel build. This is useful for verifying module loading modes.
```sh
# Example of enabling logging during build
bzl build @valdi//valdi:startup_benchmark --snap_flavor=production -c opt --//bzl/valdi:js_bytecode_format=quickjs --@valdi//bzl/runtime_flags:enable_logging
```
--------------------------------
### HTTPClient GET Request
Source: https://github.com/snapchat/valdi/blob/main/docs/docs/stdlib-http.md
Performs an HTTP GET request to the specified path or URL with optional headers. Returns a cancelable promise that resolves with an HTTPResponse.
```APIDOC
## GET /api/data
### Description
Performs an HTTP GET request to retrieve data from a specified resource.
### Method
GET
### Endpoint
`/api/data`
### Parameters
#### Query Parameters
- **pathOrUrl** (string) - Required - The path or full URL for the GET request.
- **headers** (StringMap) - Optional - An object containing request headers.
### Request Example
```typescript
const response = await client.get('/api/data', {
'Authorization': 'Bearer token123',
'Accept': 'application/json'
});
```
### Response
#### Success Response (200)
- **headers** (StringMap) - Response headers.
- **statusCode** (number) - HTTP status code.
- **body** (Uint8Array) - Response body (optional).
#### Response Example
```json
{
"headers": {
"Content-Type": "application/json"
},
"statusCode": 200,
"body": "{\"message\": \"Success\"}"
}
```
```
--------------------------------
### Enable Startup Profiling
Source: https://github.com/snapchat/valdi/blob/main/valdi/vscode_debugger/README.md
Enables profiling immediately when the process launches. Disabled by default.
```javascript
"profileStartup": false
```
--------------------------------
### Install remotedebug-ios-webkit-adapter globally
Source: https://github.com/snapchat/valdi/blob/main/compiler/companion/remotedebug-ios-webkit-adapter/README.md
Command to install the RemoteDebug iOS WebKit Adapter globally using npm. This makes the adapter executable from the command line.
```shell
npm install remotedebug-ios-webkit-adapter -g
```
--------------------------------
### Build and Run Valdi Benchmark with Hermes Bytecode Modules
Source: https://github.com/snapchat/valdi/blob/main/valdi/src/valdi/startup_benchmark/README.md
Builds the Valdi benchmark binary for Hermes bytecode and runs it with the Hermes engine. This assesses load latency for modules compiled into Hermes bytecode. Requires Bazel.
```sh
# Build the benchmark binary
bzl build @valdi//valdi:startup_benchmark --snap_flavor=production -c opt --//bzl/valdi:js_bytecode_format=hermes
# Run for QuickJS
bazel-bin/valdi/startup_benchmark --js_engine hermes
```
--------------------------------
### Initialize HTTPClient and Perform Basic Requests
Source: https://github.com/snapchat/valdi/blob/main/docs/docs/stdlib-http.md
Demonstrates creating an HTTPClient instance with a base URL and executing GET and POST requests. Shows response handling with status codes and Uint8Array bodies, plus JSON encoding with TextEncoder for POST data.
```typescript
import { HTTPClient } from 'valdi_http/src/HTTPClient';
const client = new HTTPClient('https://api.example.com');
// GET request
const response = await client.get('/users');
console.log(response.statusCode); // 200
console.log(response.body); // Uint8Array
// POST request with body
const postData = new TextEncoder().encode(JSON.stringify({ name: 'Alice' }));
const postResponse = await client.post('/users', postData, {
'Content-Type': 'application/json'
});
```
--------------------------------
### Install ios-webkit-debug-proxy and libimobiledevice on Linux
Source: https://github.com/snapchat/valdi/blob/main/compiler/companion/remotedebug-ios-webkit-adapter/README.md
Instructions for installing required debugging proxy and libraries on Linux systems. These are prerequisites for the RemoteDebug iOS WebKit Adapter.
```shell
# Instructions for installing ios-webkit-debug-proxy and libimobiledevice on Linux
# Please refer to the official repositories for the most up-to-date commands:
# https://github.com/google/ios-webkit-debug-proxy#installation
# https://github.com/libimobiledevice/libimobiledevice
```
--------------------------------
### Configuring Environment Variables for snap-node
Source: https://github.com/snapchat/valdi/blob/main/valdi/vscode_debugger/README.md
Demonstrates how to set environment variables for a snap-node launch. This is crucial for configuring application behavior, such as database connections or API keys, during debugging sessions.
```json
{
"name": "Launch with Env Vars",
"type": "node",
"request": "launch",
"program": "${workspaceFolder}/src/index.js",
"env": {
"NODE_ENV": "development",
"PORT": "3000"
}
}
```
--------------------------------
### Kotlin ValdiViewTestRule Setup
Source: https://github.com/snapchat/valdi/blob/main/docs/codelabs/integration_with_native/android/5-android_testing.md
Sets up the test rule using ValdiViewTestRule to create a HelloWorldView component with default context and ViewModel. The rule initializes the view for testing Valdi components in an Android environment. Dependencies include ValdiViewTestRule, HelloWorldContext, HelloWorldView, and HelloWorldViewModel classes.
```kotlin
@Rule
@JvmField
val viewTestRule = ValdiViewTestRule {
val context = HelloWorldContext(
title = "Hello world",
recommendFriendsCallback = {
"success"
}
)
HelloWorldView.create(it, HelloWorldViewModel(), context)
}
```
--------------------------------
### Install Valdi CLI Locally
Source: https://github.com/snapchat/valdi/blob/main/npm_modules/cli/README.md
Installs the 'valdi' command globally or locally for development purposes. This makes the CLI accessible directly from the command line.
```sh
npm run cli:install
```
--------------------------------
### Install ios-webkit-debug-proxy using Scoop on Windows
Source: https://github.com/snapchat/valdi/blob/main/compiler/companion/remotedebug-ios-webkit-adapter/README.md
Command to install the ios-webkit-debug-proxy using the Scoop package manager on Windows. This is a necessary step for Windows users to set up the adapter.
```shell
scoop bucket add extras
scoop install ios-webkit-debug-proxy
```
--------------------------------
### Bazel Build File: Test Library Setup
Source: https://github.com/snapchat/valdi/blob/main/docs/codelabs/integration_with_native/android/5-android_testing.md
Bazel BUILD file snippet for defining an instrumentation test library. It includes necessary loads for SDK variables and build rules, specifies source files, manifest, and dependencies including Valdi core, test support libraries, and various testing frameworks like Espresso, JUnit, and AssertJ.
```bazel
load(
"//bzl:sdk_variables.bzl",
"SAMPLE_MIN_SDK_VERSION",
"SAMPLE_TARGET_SDK_VERSION",
)
load("//bzl/instrumentation:build_instrumentation_test.bzl", "instrumentation_test_library")
load("//bzl/instrumentation/spoon_instrumentation_rule:defs.bzl", "spoon_instrumentation_test")
instrumentation_test_library(
name = "valdi-playground-test-lib",
srcs = glob([
"java/**/*.java",
"java/**/*.kt",
]),
manifest = "AndroidManifest.xml",
deps = [
"//platform/valdi/core",
"//platform/valdi/test-support:lib",
"//platform/test-attribution:lib",
"//platform/test-instrumentation-support:lib",
"@valdi_modules//:hello_world",
"@test_mvn//:androidx_test_espresso_espresso_core",
"@test_mvn//:androidx_test_runner",
"@test_mvn//:junit_junit",
"@test_mvn//:org_assertj_assertj_core",
"@test_mvn//:org_hamcrest_hamcrest_core",
"@test_mvn//:org_hamcrest_hamcrest_library",
],
)
```
--------------------------------
### Start Valdi Hotreloader
Source: https://github.com/snapchat/valdi/blob/main/docs/codelabs/getting_started/2-start_coding.md
Command to start the Valdi hotreloader, which watches for changes in Valdi source code, recompiles, and updates the running application UI. It requires specifying the module to reload.
```bash
valdi hotreload --module hello_world
```
--------------------------------
### Valdi Declarative Rendering with Component Lifecycle
Source: https://github.com/snapchat/valdi/blob/main/docs/docs/start-introduction.md
Demonstrates creating a basic Valdi component using a React-like syntax for UI rendering. It utilizes `onCreate` to initialize a message and `onRender` to define the UI structure with `view` and `label` elements. Requires 'valdi_core/src/Component'.
```tsx
import { Component } from 'valdi_core/src/Component';
class HelloWorld extends Component {
private msg?: string;
onCreate() {
this.msg = 'Hello Valdi on ' + new Date().toLocaleString();
}
onRender() {
}
}
```
--------------------------------
### Execute HTTP GET Request with Headers
Source: https://github.com/snapchat/valdi/blob/main/docs/docs/stdlib-http.md
Performs an HTTP GET request with custom headers using the HTTPClient. Supports authorization tokens and content type negotiation. Returns a CancelablePromise that resolves with an HTTPResponse object.
```typescript
const response = await client.get('/api/data', {
'Authorization': 'Bearer token123',
'Accept': 'application/json'
});
```
--------------------------------
### Install debugging tools on OSX/Mac using Homebrew
Source: https://github.com/snapchat/valdi/blob/main/compiler/companion/remotedebug-ios-webkit-adapter/README.md
Commands to install and configure necessary debugging tools like usbmuxd, libimobiledevice, and ios-webkit-debug-proxy on macOS using Homebrew. This ensures proper communication with iOS devices.
```shell
brew update
brew unlink libimobiledevice ios-webkit-debug-proxy usbmuxd
brew uninstall --force libimobiledevice ios-webkit-debug-proxy usbmuxd
brew install --HEAD usbmuxd
brew install --HEAD libimobiledevice
brew install --HEAD ios-webkit-debug-proxy
```
--------------------------------
### Test HelloWorldView using Valdi Android framework
Source: https://github.com/snapchat/valdi/blob/main/docs/codelabs/integration_with_native/android/5-android_testing.md
Comprehensive Android UI test suite for HelloWorldView component using Snap's Valdi testing framework. Validates UI rendering, ViewModel integration, and user interaction flows. Depends on AndroidJUnit4, Valdi test utilities, and HelloWorldView components. Tests button visibility, dynamic title/subtitle binding, and friend recommendation callback handling.
```kotlin
package com.snap.valdi.settings.core
import androidx.test.runner.AndroidJUnit4
import com.snap.valdi.test.ValdiViewTestRule
import com.snap.playground.HelloWorldContext
import com.snap.playground.HelloWorldFriend
import com.snap.valdi.test.ValdiElementActions.click
import com.snap.valdi.test.ValdiElementAssertions.matchesAnyDescendant
import com.snap.valdi.test.ValdiElementMatchers.withAccessibilityId
import com.snap.valdi.test.ValdiElementAssertions.matches
import com.snap.valdi.test.ValdiElementMatchers.withValdiAttribute
import com.snap.valdi.test.ValdiEspresso.onValdiElement
import com.snap.playground.HelloWorldView
import com.snap.playground.HelloWorldViewModel
import org.assertj.core.api.Assertions.assertThat
import org.junit.runner.RunWith
import org.junit.Test
import org.junit.Rule
import org.junit.After
import org.junit.Before
@RunWith(AndroidJUnit4::class)
class HelloWorldTests {
@Rule
@JvmField
val viewTestRule = ValdiViewTestRule {
val context = HelloWorldContext(
title = "Hello world test",
recommendFriendsCallback = {
it(listOf(HelloWorldFriend("Steve Rogers"),
HelloWorldFriend("Tony Stark"),
HelloWorldFriend("Thor Odinson")))
"success"
}
)
HelloWorldView.create(it, HelloWorldViewModel(), context)
}
@Before
fun prepare() {
viewTestRule.waitForNextRender()
}
@After
fun tearDown() {
viewTestRule.destroyView()
}
@Test
fun dummy() {
assertThat("things").isEqualTo("things")
}
@Test
fun rendersRecommendFriendsButton() {
onValdiElement(withAccessibilityId(com.snap.valdi.modules.R.id.hello_world__recommend_friends_button))
.check(matchesAnyDescendant(withValdiAttribute("value", "Recommend friends")))
}
@Test
fun contextSetsTitle() {
onValdiElement(withAccessibilityId(com.snap.valdi.modules.R.id.hello_world__title))
.check(matches(withValdiAttribute("value", "Hello world test")))
}
@Test
fun resetSubtitleThroughViewModel() {
onValdiElement(withAccessibilityId(com.snap.valdi.modules.R.id.hello_world__subtitle))
.check(matches(withValdiAttribute("value", null)))
var helloWorldViewModel = HelloWorldViewModel()
helloWorldViewModel.subtitle = "subtitle"
viewTestRule.view.viewModel = helloWorldViewModel
viewTestRule.waitForNextRender()
onValdiElement(withAccessibilityId(com.snap.valdi.modules.R.id.hello_world__subtitle))
.check(matches(withValdiAttribute("value", "subtitle")))
viewTestRule.view.viewModel = helloWorldViewModel
helloWorldViewModel.subtitle = "new subtitle"
viewTestRule.waitForNextRender()
onValdiElement(withAccessibilityId(com.snap.valdi.modules.R.id.hello_world__subtitle))
.check(matches(withValdiAttribute("value", "new subtitle")))
}
@Test
fun recommendsFriends() {
onValdiElement(withAccessibilityId(com.snap.valdi.modules.R.id.hello_world__recommend_friends_button))
.perform(click())
viewTestRule.waitForNextRender()
onValdiElement(withAccessibilityId(com.snap.valdi.modules.R.id.hello_world__recommended_friends_container))
.check(matchesAnyDescendant(withValdiAttribute("value", "Steve Rogers")))
onValdiElement(withAccessibilityId(com.snap.valdi.modules.R.id.hello_world__recommended_friends_container))
.check(matchesAnyDescendant(withValdiAttribute("value", "Tony Stark")))
onValdiElement(withAccessibilityId(com.snap.valdi.modules.R.id.hello_world
```
--------------------------------
### Console Table Handling of Long Table Overflow
Source: https://github.com/snapchat/valdi/blob/main/valdi/vscode_debugger/src/test/console/console-api-format-string.txt
This example shows `console.table`'s behavior when the table contains a large number of columns, exceeding the display width. It truncates the columns and indicates overflow with ellipses.
```javascript
const longTableOverflow = Array(3).fill(0).map((_, rowIndex) =>
Array(20).fill(0).reduce((acc, _, colIndex) => {
acc[colIndex] = `${rowIndex}${colIndex}`;
return acc;
}, {})
);
console.table(longTableOverflow);
```
--------------------------------
### Default snap-node launch configuration
Source: https://github.com/snapchat/valdi/blob/main/valdi/vscode_debugger/README.md
This snippet shows a typical launch configuration for snap-node, specifying the program to run, working directory, and source map settings. It's a common starting point for debugging Node.js applications.
```json
{
"name": "Launch snap-node",
"type": "node",
"request": "launch",
"program": "${workspaceFolder}/src/index.js",
"cwd": "${workspaceFolder}",
"sourceMaps": true,
"outFiles": [
"${workspaceFolder}/**/*.js",
"!**/node_modules/**"
]
}
```
--------------------------------
### Console Table Handling of Trimmed Empty Columns
Source: https://github.com/snapchat/valdi/blob/main/valdi/vscode_debugger/src/test/console/console-api-format-string.txt
This example demonstrates `console.table` with data that might appear to have empty columns, but the function correctly identifies and displays the structure. It assumes the input data structure is valid.
```javascript
const trimEmptyColumn = [
{ 0: "John", 1: "Smith" },
{ 0: "Jane", 1: "Doe" },
{ 0: "Emily", 1: "Jones" }
];
console.table(trimEmptyColumn);
```
--------------------------------
### Compose Valdi Components
Source: https://github.com/snapchat/valdi/blob/main/docs/docs/start-introduction.md
This example demonstrates how to compose Valdi components by embedding one component within another. It promotes reusability and simplifies UI development by breaking down complex interfaces into smaller, focused components. Dependencies include `valdi_core/src/Component`.
```tsx
import { Component } from 'valdi_core/src/Component';
class MyOtherComponent extends Component {
onRender() {
;
;
}
}
class HelloWorld extends Component {
onRender() {
;
}
}
```
--------------------------------
### Displaying Object Array with Long Header Names in Console Table
Source: https://github.com/snapchat/valdi/blob/main/valdi/vscode_debugger/src/test/console/console-api-format-string.txt
This example demonstrates `console.table`'s behavior when object keys (headers) are longer strings. The table formatting adjusts to accommodate the provided header names.
```javascript
const peopleLongHeader = [
{ "first name": "John", "last name": "Smith" },
{ "first name": "Jane", "last name": "Doe" },
{ "first name": "Emily", "last name": "Jones" }
];
console.table(peopleLongHeader);
```
--------------------------------
### Create HelloWorldContext with recommendFriendsCallback in Kotlin
Source: https://github.com/snapchat/valdi/blob/main/docs/codelabs/integration_with_native/android/5-android_testing.md
Defines a HelloWorldContext for testing, providing a recommendFriendsCallback that supplies a list of HelloWorldFriend objects and returns a status string. Used to simulate friend recommendation data in UI tests.
```Kotlin
val context = HelloWorldContext(
title = "Hello world test",
recommendFriendsCallback = {
it(listOf(HelloWorldFriend("Steve Rogers"),
HelloWorldFriend("Tony Stark"),
HelloWorldFriend("Thor Odinson")))
"success"
}
)
```
--------------------------------
### Valdi Module Creation Command
Source: https://github.com/snapchat/valdi/blob/main/docs/docs/core-module.md
Shows the command-line tool to create a new Valdi module, which initializes the basic project structure and files. The command provides help options for specifying the module name.
```shell
$ valdi new_module --help\nvaldi new_module [module-name]
```
--------------------------------
### File System vs. PersistentStore (TypeScript)
Source: https://github.com/snapchat/valdi/blob/main/docs/docs/stdlib-filesystem.md
Compares using the direct file system API for storing application data (like user preferences) with the recommended PersistentStore API. It highlights the advantages of PersistentStore, such as being asynchronous, supporting encryption, and offering better performance.
```typescript
// ❌ Using file_system for app data
import { fs } from 'file_system/src/FileSystem';
fs.writeFileSync('user_prefs.json', JSON.stringify(prefs));
// ✅ Better: Use PersistentStore
import { PersistentStore } from 'persistence/src/PersistentStore';
const store = new PersistentStore('user_prefs');
await store.storeString('preferences', JSON.stringify(prefs));
```
--------------------------------
### FlexBox Column Layout Example
Source: https://github.com/snapchat/valdi/blob/main/docs/docs/core-flexbox.md
Illustrates a column layout using FlexBox in Valdi. This example aligns elements vertically, centers them along the main (vertical) axis, and aligns them to the right on the cross (horizontal) axis. It utilizes flexDirection='column', justifyContent='center', and alignItems='flex-end'.
```tsx
export class HelloWorld extends Component {
onRender() {
{this.onRenderItems()}
;
}
onRenderItems() {
for (let i = 0; i < 3; i++) {