# Command Line Interface Source: https://docs.nativedesktop.com/native-desktop/getting-started/cli The **Native Desktop CLI** is the primary developer tool for creating, running, and building Native Desktop projects. It is a cross-platform command-line utility that supports macOS, Windows, and Linux. * Built with TypeScript for consistency and portability. * Can be installed globally with a single command. * Provides commands for project creation, execution, and packaging. For details on available commands, usage examples, and advanced workflows, refer to the following sections. # Core Frontend Library Source: https://docs.nativedesktop.com/native-desktop/getting-started/core The **Native Desktop Core** library is designed for integration with modern frontend frameworks such as **Next.js** and **Vue**. It enables seamless communication between your **web frontend** and the **Native Desktop desktop application**. * Written in **TypeScript** for strong typing and developer-friendly APIs. * Provides built-in methods to interact with the Native Desktop runtime and native environment. * Compatible with SSR frameworks and supports modular imports. For detailed function references, available types, usage examples, and advanced workflows, see the following sections. # Native Desktop Framework Source: https://docs.nativedesktop.com/native-desktop/getting-started/framework The **Native Desktop Framework** is the core of the Native Desktop ecosystem, built on top of **ElectronJS**. It provides a performance-optimized, secure, and developer-friendly foundation for building desktop applications. * Fully configurable using a single **JSON5 configuration file**. * Designed for **performance**, **security**, and **ease of use**. * Supports an **extensible plugin system** for advanced customization and integration. For more information on integrations, plugin development, and advanced configuration, refer to the following sections. # React Components Source: https://docs.nativedesktop.com/native-desktop/getting-started/react **Native Desktop React** is a custom component library designed for use with frontend applications. It provides reusable UI components that integrate seamlessly with the Native Desktop environment. * Includes a configurable **TitleBar** component that can be styled to match your application's design. * Built with **React** and **TypeScript** for consistency and strong typing. * Compatible with frameworks such as **Next.js** and supports theming and customization. For details on available components, styling options, and usage examples, refer to the following sections. # Installation Guide Source: https://docs.nativedesktop.com/native-desktop/installation Complete guide to installing and configuring Native Desktop packages ## Overview Native Desktop packages are distributed as private packages on GitHub via Polar.sh. When you purchase a Native Desktop license, you gain access to the private repository containing all packages based on your plan. ## Available Packages The Native Desktop ecosystem includes the following packages: | Package | Description | npm Package Name | | ---------- | --------------------------------------------- | ------------------------ | | **CLI** | Command-line interface for project management | `@native-desktop/cli` | | **Config** | Configuration management utilities | `@native-desktop/config` | | **Core** | Core Native Desktop functionality | `@native-desktop/core` | | **React** | React integration for Native Desktop | `@native-desktop/react` | | **App** | Application runtime and utilities | `@native-desktop/app` | All packages are scoped under `@native-desktop` and hosted on GitHub Packages. You will receive read-only access to these packages after purchasing a license. ## Prerequisites Before installing Native Desktop packages, ensure you have: * **Node.js** version 16 or higher * **npm** version 7 or higher (or **yarn** 1.22+) * A **GitHub account** * A **Native Desktop license** (purchased via Polar.sh) * Access to the Native Desktop private repository ## Step 1: Purchase a License 1. Visit [Polar.sh Native Desktop](https://nativedesktop.com) (or your purchase portal) 2. Select a plan that fits your needs 3. Complete the purchase process 4. You will receive an email with repository access instructions Repository access is granted automatically upon purchase. If you don't receive access within a few minutes, contact support. ## Step 2: Create a GitHub Personal Access Token To install packages from GitHub Packages, you need to create a personal access token (classic) with the appropriate permissions. ### Creating the Token 1. Go to [GitHub Settings → Developer settings → Personal access tokens → Tokens (classic)](https://github.com/settings/tokens) 2. Click **Generate new token** → **Generate new token (classic)** 3. Configure the token: * **Note**: `Native Desktop Packages` (or any descriptive name) * **Expiration**: Choose an expiration period (90 days recommended) * **Scopes**: Select the following: * ✅ `read:packages` - Required to download packages 4. Click **Generate token** 5. **Copy the token immediately** - You won't be able to see it again! Treat your personal access token like a password. Never commit it to version control or share it publicly. ### Example Token Permissions ```text theme={null} Scopes: ✅ read:packages - Download packages from GitHub Package Registry ``` Store your token securely in a password manager. You'll need it for authentication. ## Step 3: Configure npm Authentication You need to configure npm to authenticate with GitHub Packages using your personal access token. ### Option A: User-Level Configuration (Recommended) Configure authentication globally in your user `.npmrc` file: ```shellscript theme={null} # Edit or create ~/.npmrc nano ~/.npmrc ``` Add the following lines, replacing `YOUR_GITHUB_TOKEN` with your personal access token: ```text theme={null} @native-desktop:registry=https://npm.pkg.github.com //npm.pkg.github.com/:_authToken=YOUR_GITHUB_TOKEN ``` The `~/.npmrc` file is located at: * **macOS/Linux**: `~/.npmrc` * **Windows**: `C:\Users\YourUsername\.npmrc` ### Option B: Project-Level Configuration For project-specific configuration, create an `.npmrc` file in your project root: ```shellscript theme={null} # In your project directory touch .npmrc ``` Add the following content: ```text theme={null} @native-desktop:registry=https://npm.pkg.github.com //npm.pkg.github.com/:_authToken=${GITHUB_TOKEN} ``` Then set the `GITHUB_TOKEN` environment variable: ```shellscript theme={null} # macOS/Linux export GITHUB_TOKEN=your_personal_access_token # Windows (Command Prompt) set GITHUB_TOKEN=your_personal_access_token # Windows (PowerShell) $env:GITHUB_TOKEN="your_personal_access_token" ``` If using project-level configuration, **`never commit .npmrc with your token`** to version control. Add it to `.gitignore`: ```text theme={null} .npmrc ``` ### Option C: Using npm login (Alternative) You can also authenticate using the `npm login` command: ```shellscript theme={null} npm login --scope=@native-desktop --auth-type=legacy --registry=https://npm.pkg.github.com ``` When prompted: * **Username**: Your GitHub username * **Password**: Your personal access token (not your GitHub password!) * **Email**: Your public email address ## Step 4: Install Packages Once authentication is configured, you can install Native Desktop packages. ### Installing the CLI Globally ```shellscript theme={null} # Install latest version npm install -g @native-desktop/cli # Install specific version npm install -g @native-desktop/cli@1.0.0 ``` ### Installing Packages in a Project Add packages to your `package.json`: ```json theme={null} { "name": "my-native-desktop-app", "version": "1.0.0", "dependencies": { "@native-desktop/core": "^1.0.0", "@native-desktop/react": "^1.0.0", "@native-desktop/app": "^1.0.0" }, "devDependencies": { "@native-desktop/cli": "^1.0.0", "@native-desktop/config": "^1.0.0" } } ``` Then install: ```shellscript theme={null} npm install ``` ### Installing Individual Packages ```shellscript theme={null} # Install core package npm install @native-desktop/core # Install React integration npm install @native-desktop/react # Install app utilities npm install @native-desktop/app # Install config utilities npm install @native-desktop/config ``` ## Step 5: Verify Installation Verify that packages are installed correctly: ```shellscript theme={null} # Check CLI installation native-desktop --version # List installed Native Desktop packages npm list @native-desktop/cli npm list @native-desktop/core npm list @native-desktop/react ``` You should see version information for each installed package. ## Complete Setup Example Here's a complete example of setting up a new Native Desktop project: ```shellscript theme={null} # 1. Configure authentication echo "@native-desktop:registry=https://npm.pkg.github.com" >> ~/.npmrc echo "//npm.pkg.github.com/:_authToken=YOUR_TOKEN" >> ~/.npmrc # 2. Install CLI globally npm install -g @native-desktop/cli # 3. Create new project mkdir my-app && cd my-app native-desktop create # 4. Project packages are auto-configured in package.json npm install # 5. Start developing native-desktop run ``` ## Troubleshooting **Error**: `npm ERR! 401 Unauthorized - GET https://npm.pkg.github.com/@native-desktop/cli` **Solutions**: * Verify your personal access token is correct and not expired * Ensure the token has `read:packages` scope * Check that `.npmrc` is configured correctly * Confirm you have access to the Native Desktop repository ```shellscript theme={null} # Test authentication npm whoami --registry=https://npm.pkg.github.com ``` **Error**: `npm ERR! 404 Not Found - GET https://npm.pkg.github.com/@native-desktop/cli` **Solutions**: * Verify you have purchased a license and received repository access * Check the package name is correct (all lowercase, with scope) * Ensure `.npmrc` includes the registry configuration * Contact support if access issues persist **Error**: Authentication fails after some time **Solution**: Your personal access token may have expired. Create a new token: 1. Go to GitHub Settings → Personal access tokens 2. Delete the old token 3. Create a new token with `read:packages` scope 4. Update your `.npmrc` file with the new token **Error**: Cannot find `.npmrc` file **Solution**: Create the file manually: ```shellscript theme={null} # macOS/Linux touch ~/.npmrc nano ~/.npmrc # Windows notepad %USERPROFILE%\.npmrc ``` **Error**: `EACCES: permission denied` **Solution**: This usually happens with global installations. Try: ```shellscript theme={null} # macOS/Linux - use sudo (not recommended for security) sudo npm install -g @native-desktop/cli # Better: Configure npm to use a different directory mkdir ~/.npm-global npm config set prefix '~/.npm-global' export PATH=~/.npm-global/bin:$PATH ``` **Error**: Purchased license but still cannot access packages **Solution**: * Wait a few minutes for access to be granted * Check your GitHub account's email matches the purchase email * Verify you're logged into the correct GitHub account * Contact Native Desktop support with your purchase details ## Security Best Practices Never commit your personal access token to version control. Use environment variables or secure secret management. Set token expiration to 90 days or less and rotate regularly for better security. Only grant `read:packages` scope - never use tokens with broader permissions. Use environment variables for tokens in CI/CD and project configurations. ## CI/CD Configuration ### GitHub Actions ```yaml theme={null} name: Build on: [push] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Setup Node.js uses: actions/setup-node@v3 with: node-version: '18' registry-url: 'https://npm.pkg.github.com' scope: '@native-desktop' - name: Install dependencies run: npm install env: NODE_AUTH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - name: Build run: npm run build ``` ### GitLab CI ```yaml theme={null} build: image: node:18 before_script: - echo "@native-desktop:registry=https://npm.pkg.github.com" >> .npmrc - echo "//npm.pkg.github.com/:_authToken=${GITHUB_TOKEN}" >> .npmrc script: - npm install - npm run build ``` ### Environment Variables For CI/CD, set these environment variables: * `GITHUB_TOKEN`: Your personal access token * `NODE_AUTH_TOKEN`: Alias for GitHub token (some CI systems) ## Updating Packages ### Update All Packages ```shellscript theme={null} # Check for updates npm outdated @native-desktop/* # Update all Native Desktop packages npm update @native-desktop/cli @native-desktop/core @native-desktop/react # Update CLI globally npm update -g @native-desktop/cli ``` ### Update to Specific Version ```shellscript theme={null} # Update to specific version npm install @native-desktop/cli@1.2.0 # Update CLI globally to specific version npm install -g @native-desktop/cli@1.2.0 ``` ## Uninstalling ### Uninstall Global Packages ```shellscript theme={null} npm uninstall -g @native-desktop/cli ``` ### Uninstall Project Packages ```shellscript theme={null} npm uninstall @native-desktop/core @native-desktop/react @native-desktop/app ``` # Introduction Source: https://docs.nativedesktop.com/native-desktop/introduction **Native Desktop** is a **cross-platform framework** built on top of **Electron** to help developers build and distribute **production-ready native desktop applications** with **minimal engineering effort**. Explore the source code, contribute to projects, and check out updates on our official GitHub repository. Visit our official website to learn more about Native Desktop, its features, and how it can help you manage your workflow efficiently. # Quick Start Source: https://docs.nativedesktop.com/native-desktop/quick-start Get started with Native Desktop in minutes - create your first desktop application. ## Build Your First Desktop App in 5 Minutes This guide will walk you through creating your first Native Desktop application from scratch. By the end, you'll have a working desktop app built and running on your machine. ## Prerequisites Checklist Before you begin, make sure you have: * ✅ **Node.js 18+** installed ([Download](https://nodejs.org/)) * ✅ **Native Desktop license** purchased via Polar.sh * ✅ **GitHub account** with repository access * ✅ **GitHub Personal Access Token** with `read:packages` scope ## Step 1: Configure npm Authentication First, configure npm to access Native Desktop packages from GitHub: ```shellscript theme={null} # Create or edit ~/.npmrc echo "@native-desktop:registry=https://npm.pkg.github.com" >> ~/.npmrc echo "//npm.pkg.github.com/:_authToken=YOUR_GITHUB_TOKEN" >> ~/.npmrc ``` Replace `YOUR_GITHUB_TOKEN` with your actual GitHub personal access token! ## Step 2: Install the CLI Install the Native Desktop CLI globally: ```shellscript theme={null} npm install -g @native-desktop/cli ``` Verify the installation: ```shellscript theme={null} native-desktop --version ``` You should see the version number (e.g., `0.0.6`). ## Step 3: Create Your Project Create a new directory and initialize your project: ```shellscript theme={null} # Create project directory mkdir my-first-app # Navigate into the directory cd my-first-app # Create the project native-desktop create ``` The CLI will prompt you for project details. Here's an example setup: ```shellscript theme={null} ✔ Select the project type: Manual Project ✔ Enter a name for your project: My First App ✔ Enter the initial version of your project: 1.0.0 ✔ Enter the package identifier: my-first-app ✔ Enter a brief description of your project: My first Native Desktop application ✔ Enter the author name: Your Name ✔ Enter your project's domain URL: https://example.com ``` Choose "Manual Project" for a complete setup with all development tools configured. The CLI will automatically: * Create the project structure * Generate configuration files * Install all dependencies ## Step 4: Run Your App Start your application in development mode: ```shellscript theme={null} native-desktop run ``` 🎉 Your app window should open! You now have a running Native Desktop application. The app runs with hot-reload enabled - any changes you make to your code will automatically refresh the app. ### Making Changes Try editing your source code: 1. Open `src/index.ts` in your code editor 2. Make some changes 3. Save the file 4. Watch your app automatically reload! Press `Ctrl+C` in the terminal to stop the app when you're done testing. ## Step 5: Build Your App When you're ready to create a distributable version, build your app: ```shellscript theme={null} # Build a DMG installer native-desktop build --target dmg # Or build an APP bundle native-desktop build --target app # Or build a PKG installer native-desktop build --target pkg ``` ```shellscript theme={null} # Build a portable EXE native-desktop build --target exe # Or build an MSI installer native-desktop build --target msi ``` Your built application will be in the `bin/` directory: ```shellscript theme={null} ls bin/ ``` ## Step 6: Sign Your App (Optional but Recommended) For production distribution, sign your application: ```shellscript theme={null} # Sign with Developer ID native-desktop sign bin/My-First-App.dmg \ --platform mac \ --identity "Developer ID Application: Your Name (TEAMID)" # Sign with notarization (recommended for distribution) native-desktop sign bin/My-First-App.dmg \ --platform mac \ --identity "Developer ID Application: Your Name (TEAMID)" \ --apple-id "your.email@example.com" \ --apple-id-password "xxxx-xxxx-xxxx-xxxx" \ --team-id "TEAMID" ``` You need an Apple Developer ID certificate. ```shellscript theme={null} # Sign with certificate file native-desktop sign bin/My-First-App.exe \ --platform windows \ --cert-file "path/to/certificate.pfx" \ --cert-password "your-cert-password" ``` You need a code signing certificate. [Learn more](/sign#windows-signing) Code signing is optional for development but **required** for distribution to prevent security warnings. ## Complete Workflow Example Here's the complete workflow from start to finish: ```shellscript theme={null} # 1. Setup authentication (one-time) echo "@native-desktop:registry=https://npm.pkg.github.com" >> ~/.npmrc echo "//npm.pkg.github.com/:_authToken=YOUR_TOKEN" >> ~/.npmrc # 2. Install CLI (one-time) npm install -g @native-desktop/cli # 3. Create project mkdir my-first-app && cd my-first-app native-desktop create # 4. Run in development native-desktop run # 5. Build for production (in a new terminal) native-desktop build --target dmg # 6. Sign the app native-desktop sign bin/My-First-App.dmg --platform mac --identity "Developer ID" # 7. Your app is ready in bin/ ls -lh bin/ ``` ## What's Next? Congratulations! You've created your first Native Desktop application. ## Development Workflow For day-to-day development, follow this workflow: ### 1. Start Development ```shellscript theme={null} # Run your app native-desktop run ``` ### 2. Write Code Edit your files in `src/` - the app will automatically reload with your changes. ### 3. Check Code Quality ```shellscript theme={null} # Lint your code native-desktop lint # Format your code native-desktop fmt # Check TypeScript types native-desktop types ``` ### 4. Build & Test ```shellscript theme={null} # Build the app native-desktop build --target dmg # Test the built app open bin/My-App.dmg ``` ## Common Issues **Problem**: `npm ERR! 401 Unauthorized` **Solution**: Your GitHub token is missing or invalid. 1. Check your `.npmrc` file has the correct token 2. Verify the token has `read:packages` scope 3. Ensure you have repository access See [Installation Guide](/installation) for details. **Problem**: `NativeDesktop can only create new projects in an empty folder` **Solution**: The `create` command requires an empty directory. ```shellscript theme={null} mkdir my-new-app cd my-new-app native-desktop create ``` **Problem**: `Invalid target for platform` **Solution**: Use a target supported by your operating system: * macOS: `dmg`, `app`, `pkg` * Windows: `exe`, `msi`, `msi-wrapped` * Linux: `deb`, `rpm`, `app-image`, `flatpak`, `snap` **Problem**: Application window doesn't open **Solution**: Check the terminal for error messages and: 1. Ensure all dependencies are installed: `npm install` 2. Check for TypeScript errors: `native-desktop types` 3. Try removing node\_modules: `rm -rf node_modules && npm install` ## Quick Reference ### Essential Commands ```shellscript theme={null} # Create project native-desktop create # Run in development native-desktop run # Build for production native-desktop build --target # Sign application native-desktop sign [app-path] # Code quality native-desktop lint # Check code quality native-desktop fmt # Format code native-desktop types # Check types ``` ### Project Structure ```text theme={null} my-first-app/ ├── src/ # Your source code │ └── index.ts # Main entry point ├── bin/ # Build output (after build) ├── package.json # Dependencies ├── native-desktop.config.json5 # App configuration ├── tsconfig.json # TypeScript config └── .eslintrc.json # Linting rules ``` ## Tips for Success Choose "Manual Project" when creating for a full-featured setup with all development tools Always run `lint`, `fmt`, and `types` before building for production Always test your built application before distributing to users Code sign your apps to avoid security warnings and build user trust ## Getting Help Need assistance? We're here to help: * 📚 **Documentation**: [Native Desktop Docs](/native-desktop/introduction) * 📧 **Support**: [support@nativedesktop.com](mailto:support@nativedesktop.com) * 🐛 **Bug Reports**: GitHub Issues *** **Ready to build something amazing?** You now have everything you need to create professional desktop applications with Native Desktop. Happy coding! 🚀 # Directory Structure Source: https://docs.nativedesktop.com/native-desktop/tips/directory-structure When creating a Native Desktop application, it is recommended to follow a structured directory layout to keep your project organized and maintainable. The proposed structure is as follows: ```shellscript theme={null} . +-- assets [Directory] | +-- icons [Directory] | +-- linux.png [File] | +-- mac.icns [File] | +-- windows.ico [File] +-- html [Directory] | +-- not-allowed.html [File] | +-- offline.html [File] | +-- splash-screen.html [File] +-- src [Directory] | +-- mainPluginSample.ts [File] | +-- rendererPluginSample.ts [File] +-- .gitignore [File] +-- .prettierrc [File] +-- package.json [File] +-- native-desktop.config.json5 [File] +-- staging.native-desktop.config.json5 [File] +-- production.native-desktop.config.json5 [File] +-- eslint.config.mjs [File] +-- tsconfig.json [File] ``` ### Directory & File Description * `assets/icons`: Contains platform-specific icons for your application: * `linux.png`: Icon for Linux builds * `mac.icns`: Icon for macOS builds * `windows.ico`: Icon for Windows builds * `html`: Contains HTML pages used by the application in specific states: * `not-allowed.html`: Displayed when a page cannot be loaded or is disallowed * `offline.html`: Shown when the application is offline * `splash-screen.html`: Shown during the loading state of the application * `src`: Contains your custom Native Desktop plugin code: * `mainPluginSample.ts`: Sample main process plugin * `rendererPluginSample.ts`: Sample renderer process plugin * `.gitignore`: Specifies files and directories to exclude from version control * `.prettierrc`: Configuration for Prettier code formatting * `package.json`: Node.js project configuration and dependencies * `native-desktop.config.json5`: Default Native Desktop configuration file for development * `staging.native-desktop.config.json5`: Optional configuration for staging environment * `production.native-desktop.config.json5`: Optional configuration for production environment * `eslint.config.mjs`: ESLint configuration file for linting rules * `tsconfig.json`: TypeScript configuration file Following this structure ensures your Native Desktop project is **well-organized, scalable, and easy to maintain**, making development and deployment more efficient. # Build Project Source: https://docs.nativedesktop.com/native-desktop/user-guide/command-line-interface/build Build and package your Native Desktop application for distribution The `build` command compiles and packages your Native Desktop application into distributable formats for your target platform. This command creates production-ready binaries that can be distributed to end users. ## Prerequisites Before building your project, ensure: * Your project has been created using `native-desktop create` * All dependencies are installed (`npm install`) * Your application has been tested in development mode * You have a valid `native-desktop.config.json5` configuration file Native Desktop only allows you to build native applications for the operating system you are currently using. Cross-platform builds are not supported. ## Basic Usage To build your project, open the terminal in the **root directory** of your Native Desktop project and run: ```shellscript theme={null} native-desktop build --target ``` ### With Custom Configuration If you need to specify a custom configuration file: ```shellscript theme={null} native-desktop build --config --target ``` ## Command Options ### `--config` (Required) Path to the project configuration file. * **Type**: String * **Default**: `native-desktop.config.json5` * **Example**: `--config my-config.json5` ```shellscript theme={null} native-desktop build --config native-desktop.config.json5 --target dmg ``` ### `--target` (Required) Output format for the build. The available targets depend on your operating system. * **Type**: String * **Required**: Yes ```shellscript theme={null} native-desktop build --config native-desktop.config.json5 --target exe ``` ### `--sign` (Optional) Automatically sign the application after building. * **Type**: Boolean * **Default**: `false` ```shellscript theme={null} native-desktop build --config native-desktop.config.json5 --target dmg --sign ``` When using `--sign`, the CLI will automatically sign your application after the build completes. This requires proper signing credentials to be configured. ## Supported Target Types The available build targets vary by platform: Native Desktop supports the following targets on macOS: ### `dmg` Creates a macOS Disk Image (.dmg) file for distribution. ```shellscript theme={null} native-desktop build --target dmg ``` * **File Extension**: `.dmg` * **Distribution**: App Store and direct distribution * **User Experience**: Drag-and-drop installation * **Recommended**: ✅ Best for public distribution ### `app` Creates a macOS application bundle (.app) directory. ```shellscript theme={null} native-desktop build --target app ``` * **File Type**: Directory bundle * **Distribution**: Development and testing * **User Experience**: Raw application bundle * **Recommended**: For development only ### `pkg` Creates a macOS Installer Package (.pkg) file. ```shellscript theme={null} native-desktop build --target pkg ``` * **File Extension**: `.pkg` * **Distribution**: Enterprise and Mac App Store * **User Experience**: Guided installation wizard * **Recommended**: For enterprise distribution Native Desktop supports the following targets on Windows: ### `exe` Creates a portable Windows executable. ```shellscript theme={null} native-desktop build --target exe ``` * **File Extension**: `.exe` * **Distribution**: Portable, no installation required * **User Experience**: Single executable file * **Recommended**: ✅ Best for portable apps ### `msi` Creates a Windows Installer package. ```shellscript theme={null} native-desktop build --target msi ``` * **File Extension**: `.msi` * **Distribution**: Enterprise and standard distribution * **User Experience**: Standard Windows installation * **Recommended**: ✅ Best for enterprise deployment ### `msi-wrapped` Creates an enhanced MSI installer with additional features. ```shellscript theme={null} native-desktop build --target msi-wrapped ``` * **File Extension**: `.msi` * **Distribution**: Enhanced installer with wrapper * **User Experience**: Advanced installation options * **Recommended**: For complex installations Native Desktop supports the following targets on Linux: ### `deb` Creates a Debian package for Debian-based distributions. ```shellscript theme={null} native-desktop build --target deb ``` * **File Extension**: `.deb` * **Distribution**: Ubuntu, Debian, Linux Mint * **User Experience**: Standard package manager installation * **Recommended**: ✅ For Debian-based systems ### `rpm` Creates an RPM package for Red Hat-based distributions. ```shellscript theme={null} native-desktop build --target rpm ``` * **File Extension**: `.rpm` * **Distribution**: Fedora, Red Hat, CentOS * **User Experience**: Standard package manager installation * **Recommended**: ✅ For Red Hat-based systems ### `app-image` Creates an AppImage portable application. ```shellscript theme={null} native-desktop build --target app-image ``` * **File Extension**: `.AppImage` * **Distribution**: Universal Linux binary * **User Experience**: Single portable file * **Recommended**: ✅ For universal distribution ### `flatpak` Creates a Flatpak package. ```shellscript theme={null} native-desktop build --target flatpak ``` * **File Format**: Flatpak bundle * **Distribution**: Flatpak repositories * **User Experience**: Sandboxed application * **Recommended**: For Flatpak ecosystem ### `snap` Creates a Snap package. ```shellscript theme={null} native-desktop build --target snap ``` * **File Extension**: `.snap` * **Distribution**: Snap Store * **User Experience**: Sandboxed application * **Recommended**: For Ubuntu and Snap ecosystem ## Build Output After successful execution, the Native Desktop CLI generates build output inside a directory named `bin/` in your project root: ```text theme={null} your-project/ ├── bin/ ├── src/ ├── package.json └── native-desktop.config.json5 ``` ## Complete Examples ### Building for macOS ```shellscript theme={null} # Build DMG for distribution native-desktop build --config native-desktop.config.json5 --target dmg # Build and sign DMG native-desktop build --config native-desktop.config.json5 --target dmg --sign # Build PKG for enterprise native-desktop build --config native-desktop.config.json5 --target pkg # Build APP bundle for testing native-desktop build --config native-desktop.config.json5 --target app ``` ### Building for Windows ```shellscript theme={null} # Build portable EXE native-desktop build --config native-desktop.config.json5 --target exe # Build MSI installer native-desktop build --config native-desktop.config.json5 --target msi # Build and sign MSI native-desktop build --config native-desktop.config.json5 --target msi --sign ``` ### Building for Linux ```shellscript theme={null} # Build DEB package native-desktop build --config native-desktop.config.json5 --target deb # Build RPM package native-desktop build --config native-desktop.config.json5 --target rpm # Build AppImage native-desktop build --config native-desktop.config.json5 --target app-image # Build Flatpak native-desktop build --config native-desktop.config.json5 --target flatpak # Build Snap native-desktop build --config native-desktop.config.json5 --target snap ``` ## Build Process The build command performs the following steps: 1. **Configuration Loading**: Reads the configuration file 2. **Dependency Resolution**: Ensures all dependencies are available 3. **TypeScript Compilation**: Compiles TypeScript to JavaScript 4. **Asset Bundling**: Bundles application assets and resources 5. **Native Packaging**: Creates platform-specific package 6. **Output Generation**: Writes build artifacts to `bin/` directory 7. **Signing** (if `--sign` flag is used): Signs the application 8. **Verification**: Validates the build output ## Build Configuration The build process uses settings from your `native-desktop.config.json5` file. Key configuration options include: * Application metadata (name, version, description) * Build targets and architectures * Icon and asset paths * Platform-specific settings * Code signing configuration ## Common Issues **Error**: `Invalid target "xyz" for platform "mac". Supported targets: dmg, app, pkg` **Solution**: Use a target type that is supported on your current platform. Check the supported targets list for your OS. ```shellscript theme={null} # macOS native-desktop build --target dmg # ✅ Valid native-desktop build --target exe # ❌ Invalid on macOS ``` **Error**: `Configuration file not found` **Solution**: Ensure the configuration file exists and the path is correct. ```shellscript theme={null} # Check if file exists ls native-desktop.config.json5 # Use correct path native-desktop build --config ./native-desktop.config.json5 --target dmg ``` **Error**: `Permission denied: cannot write to bin/` **Solution**: Ensure you have write permissions in the project directory. ```shellscript theme={null} # Check permissions ls -la # Fix permissions if needed chmod 755 . ``` **Error**: `Cannot find module 'xyz'` **Solution**: Install all project dependencies before building. ```shellscript theme={null} npm install native-desktop build --target dmg ``` **Error**: `Code signing failed` **Solution**: Ensure signing credentials are properly configured. Run the `sign` command separately for more control. ```shellscript theme={null} # Build without signing native-desktop build --target dmg # Sign separately native-desktop sign bin/your-app.dmg --platform mac --identity "Developer ID" ``` ## Platform Limitations **Cross-Platform Builds**: You can only build for the operating system you are currently using. For example: * On macOS → Build macOS apps only * On Windows → Build Windows apps only * On Linux → Build Linux apps only To build for multiple platforms, you need to: 1. Use a machine running each target OS, or 2. Use cloud build services with multiple OS environments, or 3. Use virtual machines or containers for each platform ## Build Optimization ### Production Builds For production releases, consider: ```shellscript theme={null} # Build with signing enabled native-desktop build --target dmg --sign # Verify build output ls -lh bin/ # Test the built application open bin/your-app.dmg # macOS ``` ### Development Builds For testing and development: ```shellscript theme={null} # Use faster build targets native-desktop build --target app # macOS ``` ## CI/CD Integration The build command can be integrated into CI/CD pipelines: ```yaml theme={null} # Example GitHub Actions workflow - name: Build Application run: | native-desktop build --config native-desktop.config.json5 --target dmg - name: Upload Artifacts uses: actions/upload-artifact@v3 with: name: build-output path: bin/ ``` ## Best Practices Always test your application with `native-desktop run` before building for distribution Update version numbers in your config file before each production build Test built applications on clean systems to ensure all dependencies are included Always sign production builds to ensure user trust and meet platform requirements # Commands Overview Source: https://docs.nativedesktop.com/native-desktop/user-guide/command-line-interface/commands Complete reference of all Native Desktop CLI commands The Native Desktop CLI provides a comprehensive set of commands to manage your desktop application development workflow. This page provides an overview of all available commands and their primary use cases. ## Command List ### Project Management #### `create` Initialize a new Native Desktop project in an empty directory. ```shellscript theme={null} native-desktop create ``` **Use Case**: Starting a new desktop application project with proper scaffolding and configuration. **Learn More**: [Create Command Documentation](/create) *** #### `run` Run your Native Desktop application in development mode. ```shellscript theme={null} native-desktop run [project-config-file] ``` **Use Case**: Testing and developing your application with live updates during development. **Learn More**: [Run Command Documentation](/run) *** ### Build & Distribution #### `build` Build your Native Desktop project for production distribution. ```shellscript theme={null} native-desktop build --config --target [--sign] ``` **Use Case**: Creating distributable packages for end users on your target platform. **Learn More**: [Build Command Documentation](/build) *** #### `sign` Sign a built application for Windows or macOS. ```shellscript theme={null} native-desktop sign [app-path] [options] ``` **Use Case**: Code signing your application to meet platform distribution requirements and ensure user trust. **Learn More**: [Sign Command Documentation](/sign) *** ### Code Quality #### `lint` Run ESLint on your project to check for code quality issues. ```shellscript theme={null} native-desktop lint ``` **Use Case**: Identifying and fixing code style issues and potential bugs. **Learn More**: [Lint Command Documentation](/lint) *** #### `fmt` Format your source code using Prettier. ```shellscript theme={null} native-desktop fmt ``` **Use Case**: Automatically formatting code to maintain consistent style across your project. **Learn More**: [Format Command Documentation](/fmt) *** #### `types` Check TypeScript types in your project. ```shellscript theme={null} native-desktop types ``` **Use Case**: Validating TypeScript types to catch type errors before runtime. **Learn More**: [Types Command Documentation](/types) *** ## Command Workflow A typical Native Desktop development workflow follows this pattern: ```mermaid theme={null} graph LR A[Create Project] --> B[Development] B --> C[Run & Test] C --> D[Lint & Format] D --> E[Type Check] E --> F{Ready?} F -->|No| B F -->|Yes| G[Build] G --> H[Sign] H --> I[Distribute] ``` ### 1. Project Creation ```shellscript theme={null} # Create a new project native-desktop create ``` ### 2. Development Cycle ```shellscript theme={null} # Run in development mode native-desktop run # Check code quality native-desktop lint # Format code native-desktop fmt # Verify types native-desktop types ``` ### 3. Production Build ```shellscript theme={null} # Build for your platform native-desktop build --config native-desktop.config.json5 --target dmg # Sign the application native-desktop sign --platform mac --identity "Developer ID Application" ``` ## Global Options All commands support the following global options: ### `--help` / `-h` Display help information for the command. ```shellscript theme={null} native-desktop --help ``` ### `--version` / `-v` Display the CLI version number. ```shellscript theme={null} native-desktop --version ``` ## Platform-Specific Commands Some commands have platform-specific behavior: * **Build Targets**: `dmg`, `app`, `pkg` * **Signing**: Requires Apple Developer ID and certificates * **Notarization**: Supported via `sign` command with Apple ID credentials * **Build Targets**: `exe`, `msi`, `msi-wrapped` * **Signing**: Requires code signing certificate (.pfx or .p12) * **Certificate Options**: Support for file-based and SHA1-based signing * **Build Targets**: `deb`, `rpm`, `app-image`, `flatpak`, `snap` * **Signing**: Platform-specific signing mechanisms * **Distribution**: Multiple package formats for different distributions ## Configuration Files Most commands interact with the project configuration file: **Default Configuration File**: `native-desktop.config.json5` You can specify a custom configuration file using the `--config` option: ```shellscript theme={null} native-desktop build --config custom-config.json5 --target dmg ``` ## Exit Codes The Native Desktop CLI uses standard exit codes: * **0**: Command completed successfully * **1**: Command failed with an error This allows for easy integration with CI/CD pipelines and scripts. ## Error Handling When errors occur, the CLI provides detailed error messages to help diagnose issues: ```shellscript theme={null} ✖ Error: Invalid target "invalid" for platform "mac". Supported targets: dmg, app, pkg ``` Always read error messages carefully, they often include suggestions for fixing the issue. # Create Project Source: https://docs.nativedesktop.com/native-desktop/user-guide/command-line-interface/create Initialize a new Native Desktop project The `create` command initializes a new Native Desktop project with all necessary configuration files, dependencies, and project structure. This command provides an interactive setup process to customize your project. ## Prerequisites Before creating a Native Desktop project, ensure you have: * **Node.js** (version 16 or higher) * **npm** or **yarn** package manager * An **empty directory** for your project The CLI will only create projects in empty directories. If your directory contains any files or folders, the command will fail with an error. ## Basic Usage To create a new project, navigate to an empty directory and run: ```shellscript theme={null} native-desktop create ``` It is not possible to set a custom path; the recommended workflow is to create a new folder and run the CLI from there. ## Interactive Setup The `create` command launches an interactive setup wizard that guides you through the project configuration process. ### Step 1: Select Project Type The CLI first prompts you to select a project type: ```shellscript theme={null} ? Select the project type: (Use arrow keys) ❯ Empty Project Manual Project ``` #### Available Project Types Creates a new project with minimal default settings, perfect for starting from scratch. This option provides: * Basic project structure * Essential configuration files * Minimal boilerplate code * Quick setup process **Best For**: Beginners or simple applications Creates a fully customizable project with comprehensive default settings. This option includes: * Complete project structure * Advanced configuration options * Development tools setup * Extended boilerplate code **Best For**: Advanced users who want complete control and manual configuration ### Step 2: Project Configuration After selecting the project type, you'll be prompted to provide project details: #### Project Name ```shellscript theme={null} ? Enter a name for your project (e.g. "My App"): ``` * **Required**: Yes * **Min Length**: 2 characters * **Max Length**: 100 characters * **Example**: `My Awesome App` This is the human-readable name displayed to users. #### Project Version ```shellscript theme={null} ? Enter the initial version of your project (e.g. "1.0.0"): ``` * **Required**: Yes * **Default**: `1.0.0` * **Format**: Semantic versioning (MAJOR.MINOR.PATCH) * **Example**: `1.0.0`, `0.1.0`, `2.3.4` The version must follow [Semantic Versioning](https://semver.org/) format: `MAJOR.MINOR.PATCH` #### Package Identifier ```shellscript theme={null} ? Enter the package identifier (e.g. "my-app"): ``` * **Required**: Yes * **Auto-generated**: Based on project name (if not provided) * **Min Length**: 2 characters * **Max Length**: 214 characters * **Format**: Lowercase letters, numbers, and hyphens only * **Restrictions**: Cannot start or end with a hyphen * **Example**: `my-awesome-app` This identifier is used internally and in package manifests. #### Project Description ```shellscript theme={null} ? Enter a brief description of your project (e.g. "A task management app for teams"): ``` * **Required**: No * **Default**: `A NativeDesktop Application` * **Max Length**: 500 characters * **Example**: `A powerful task management application for remote teams` #### Author Information ```shellscript theme={null} ? Enter the author name (e.g. "Jane Doe "): ``` * **Required**: Yes * **Default**: `NativeDesktop` * **Max Length**: 200 characters * **Format**: Name or Name with email in angle brackets * **Example**: `John Smith ` You can include an email address in angle brackets: `Jane Doe ` #### Project URL ```shellscript theme={null} ? Enter your project's domain URL (e.g. "https://nativedesktop.com"): ``` * **Required**: Yes * **Format**: Valid HTTP or HTTPS URL * **Example**: `https://example.com` This URL is used in project metadata and application information. ## Complete Example Here's a complete example of the project creation flow: ```shellscript theme={null} $ native-desktop create ✔ Select the project type: Manual Project ✔ Enter a name for your project (e.g. "My App"): Task Manager Pro ✔ Enter the initial version of your project (e.g. "1.0.0"): 1.0.0 ✔ Enter the package identifier (e.g. "my-app"): task-manager-pro ✔ Enter a brief description of your project (e.g. "A task management app for teams"): A professional task management application with team collaboration features ✔ Enter the author name (e.g. "Jane Doe "): Jane Smith ✔ Enter your project's domain URL (e.g. "https://nativedesktop.com"): https://taskmanager.com Creating project... ✓ Created project structure ✓ Generated configuration files ✓ Installing dependencies... ✓ Project created successfully! Next steps: 1. Start development: native-desktop run 2. Build for production: native-desktop build --target dmg ``` ## Generated Project Structure After creation, your project will have the following structure: ```text theme={null} project-directory/ ├── src/ # Source code directory ├── package.json # Project dependencies and scripts ├── native-desktop.config.json5 # Native Desktop configuration ├── tsconfig.json # TypeScript configuration ├── .eslintrc.json # ESLint configuration ├── .prettierrc # Prettier configuration ├── .gitignore # Git ignore rules └── .npmrc # npm configuration ``` ### Configuration Files The `create` command generates several configuration files: The main configuration file for your Native Desktop application. Contains build settings, application metadata, and platform-specific options. TypeScript compiler configuration with recommended settings for Native Desktop projects. ESLint configuration for code quality checking with Native Desktop best practices. Prettier configuration for consistent code formatting across the project. ## Post-Creation Steps After creating your project, you can: ### 1. Install Dependencies If dependencies weren't automatically installed: ```shellscript theme={null} npm install ``` ### 2. Start Development Run your application in development mode: ```shellscript theme={null} native-desktop run ``` ### 3. Explore Configuration Review and customize the generated `native-desktop.config.json5` file to suit your needs. ### 4. Add Your Code Start building your application in the `src/` directory. ## Validation Rules The `create` command validates all inputs to ensure a valid project configuration: | Field | Validation | | ------------------ | -------------------------------------------------------------------------------- | | Project Name | Required, 2-100 characters | | Version | Must follow semantic versioning (e.g., 1.0.0) | | Package Identifier | Required, 2-214 characters, lowercase, hyphens only, no leading/trailing hyphens | | Description | Optional, max 500 characters | | Author | Required, max 200 characters, valid email format if provided | | URL | Required, valid HTTP/HTTPS URL | ## Common Issues **Error**: `NativeDesktop can only create new projects in an empty folder.` **Solution**: Ensure your directory is completely empty. Remove all files and folders, including hidden files. ```shellscript theme={null} # Create a new empty directory mkdir my-project cd my-project native-desktop create ``` **Error**: `Package identifier must contain only lowercase letters, numbers, and hyphens` **Solution**: Use only lowercase letters, numbers, and hyphens. Avoid spaces, uppercase letters, and special characters. **Valid**: `my-app-123` **Invalid**: `My App`, `my_app`, `MyApp!` **Error**: `Version must follow semantic versioning format (e.g., 1.0.0)` **Solution**: Use the semantic versioning format with three numbers separated by dots. **Valid**: `1.0.0`, `0.1.0`, `2.3.4` **Invalid**: `1.0`, `v1.0.0`, `1.0.0-beta` **Error**: `URL must start with http:// or https://` **Solution**: Provide a complete URL including the protocol. **Valid**: `https://example.com`, `http://localhost:3000` **Invalid**: `example.com`, `www.example.com` ## Best Practices Use descriptive, lowercase package identifiers with hyphens (kebab-case) Start with `1.0.0` for production-ready apps, or `0.1.0` for early development Choose "Empty Project" for learning, "Manual Project" for production apps Include a meaningful description to help other developers understand your project # Format Project Source: https://docs.nativedesktop.com/native-desktop/user-guide/command-line-interface/fmt Automatically format your code with Prettier in your Native Desktop project The `fmt` command runs Prettier on your Native Desktop project to automatically format your code, ensuring consistent style and formatting across your entire codebase. ## Prerequisites Before running the format command, ensure: * Your project has been created using `native-desktop create` * All dependencies are installed (`npm install`) * Prettier configuration exists (`.prettierrc`) ## Basic Usage To format your project, open the terminal in the **root directory** of your Native Desktop project and run: ```shellscript theme={null} native-desktop fmt ``` This command will: 1. Load Prettier configuration from `.prettierrc` 2. Scan all source files in your project 3. Automatically format files according to configured rules 4. Save the formatted files 5. Report the number of files formatted ## What Gets Formatted By default, the format command processes: * All TypeScript files (`.ts`, `.tsx`) * All JavaScript files (`.js`, `.jsx`) * JSON files (`.json`, `.json5`) * Markdown files (`.md`, `.mdx`) * CSS/SCSS files (`.css`, `.scss`) * HTML files (`.html`) * YAML files (`.yml`, `.yaml`) Files and directories specified in `.prettierignore` are automatically excluded from formatting. ## Output Examples ### Successful Format ```shellscript theme={null} $ native-desktop fmt ✓ Formatting complete ✓ 24 files formatted ✓ 0 files unchanged All files are now properly formatted ``` ### No Changes Needed ```shellscript theme={null} $ native-desktop fmt ✓ All files already formatted ✓ 0 files changed ✓ 24 files checked No formatting changes needed ``` ### With Errors ```shellscript theme={null} $ native-desktop fmt ✖ Error formatting files ✖ Syntax error in src/index.ts Please fix syntax errors before formatting ``` ## Prettier Configuration The format command uses the `.prettierrc` file generated by `native-desktop create`. Here's an example configuration: ```json theme={null} { "semi": true, "trailingComma": "all", "singleQuote": true, "printWidth": 80, "tabWidth": 2, "useTabs": false, "arrowParens": "always", "endOfLine": "lf" } ``` ## Configuration Options Common Prettier options you can customize: * **semi**: Add semicolons at the end of statements (default: `true`) * **singleQuote**: Use single quotes instead of double quotes (default: `true`) * **quoteProps**: When to quote properties in objects * **jsxSingleQuote**: Use single quotes in JSX (default: `false`) * **tabWidth**: Number of spaces per indentation level (default: `2`) * **useTabs**: Use tabs instead of spaces (default: `false`) * **printWidth**: Maximum line length (default: `80`) * **trailingComma**: Add trailing commas where valid (options: `"none"`, `"es5"`, `"all"`) * **bracketSpacing**: Print spaces between brackets in object literals (default: `true`) * **bracketSameLine**: Put `>` on the same line in JSX (default: `false`) * **arrowParens**: Include parentheses around arrow function parameters (options: `"always"`, `"avoid"`) * **endOfLine**: Line ending style (options: `"lf"`, `"crlf"`, `"cr"`, `"auto"`) * **proseWrap**: How to wrap prose in Markdown (options: `"always"`, `"never"`, `"preserve"`) ## Formatting Examples ### Before Formatting ```typescript theme={null} const myFunction=(x:number,y:number)=>{ return x+y } const obj={name:"John",age:30,city:"New York"} if(condition){ console.log("Hello") } ``` ### After Formatting ```typescript theme={null} const myFunction = (x: number, y: number) => { return x + y; }; const obj = { name: 'John', age: 30, city: 'New York' }; if (condition) { console.log('Hello'); } ``` ## Ignoring Files Create or edit `.prettierignore` to exclude files from formatting: ``` # .prettierignore node_modules/ bin/ dist/ build/ coverage/ *.min.js *.bundle.js package-lock.json ``` ## Ignoring Code Blocks You can ignore specific code blocks in your files: ```typescript theme={null} // prettier-ignore const uglyMatrix = [ 1,0,0, 0,1,0, 0,0,1 ]; // This will be formatted normally const normalArray = [1, 2, 3, 4, 5]; ``` Or ignore entire files: ```typescript theme={null} // prettier-ignore-file // This entire file won't be formatted const anything = "goes here" ``` ## Integration with Development Workflow ### Pre-Commit Hook Format code automatically before commits using Husky: ```json theme={null} { "husky": { "hooks": { "pre-commit": "native-desktop fmt" } } } ``` ### CI/CD Pipeline Check formatting in your continuous integration: ```yaml theme={null} # GitHub Actions example - name: Check Code Formatting run: | native-desktop fmt git diff --exit-code ``` ### npm Scripts Add formatting to your package.json scripts: ```json theme={null} { "scripts": { "format": "native-desktop fmt", "format:check": "prettier --check .", "precommit": "native-desktop fmt && native-desktop lint" } } ``` ## Format vs Lint Understanding the difference between `fmt` and `lint`: | Aspect | `native-desktop fmt` | `native-desktop lint` | | ------------- | ---------------------------- | ----------------------------- | | **Purpose** | Code formatting | Code quality & patterns | | **Tool** | Prettier | ESLint | | **Auto-Fix** | ✅ Yes (always) | ⚠️ Limited | | **Focus** | Style consistency | Logic & best practices | | **Concerns** | Indentation, quotes, spacing | Unused variables, type safety | | **Conflicts** | Can conflict with ESLint | Can conflict with Prettier | Use both commands together: `native-desktop fmt` for style, `native-desktop lint` for quality. ## Common Issues **Error**: `.prettierrc not found` **Solution**: Ensure the configuration file exists in your project root. ```shellscript theme={null} # Check if file exists ls -la .prettierrc # Create default configuration if missing echo '{ "semi": true, "singleQuote": true }' > .prettierrc ``` **Error**: `SyntaxError: Unexpected token` **Solution**: Fix syntax errors in your code before formatting. ```shellscript theme={null} # Check for TypeScript errors native-desktop types # Fix syntax errors, then format native-desktop fmt ``` **Error**: ESLint and Prettier disagree on formatting **Solution**: Install `eslint-config-prettier` to disable conflicting ESLint rules. ```shellscript theme={null} npm install --save-dev eslint-config-prettier ``` Update `.eslintrc.json`: ```json theme={null} { "extends": [ "eslint:recommended", "plugin:@typescript-eslint/recommended", "prettier" ] } ``` **Error**: Some files are not formatted **Solution**: Check `.prettierignore` and ensure files aren't excluded. ```shellscript theme={null} # List files that would be formatted npx prettier --list-different "src/**/*.ts" # Check ignore patterns cat .prettierignore ``` **Error**: Files appear formatted but changes aren't saved **Solution**: Check file permissions and ensure you have write access. ```shellscript theme={null} # Check file permissions ls -la src/ # Fix permissions if needed chmod u+w src/*.ts ``` ## Customizing Prettier You can customize Prettier rules in `.prettierrc`: ```json theme={null} { // Use single quotes "singleQuote": true, // Always add semicolons "semi": true, // Add trailing commas "trailingComma": "all", // 100 characters per line "printWidth": 100, // 2 spaces for indentation "tabWidth": 2, // Use spaces, not tabs "useTabs": false, // Always wrap arrow function parameters "arrowParens": "always", // Unix line endings "endOfLine": "lf", // Add space between brackets "bracketSpacing": true } ``` ## Language-Specific Overrides You can apply different rules to different file types: ```json theme={null} { "semi": true, "singleQuote": true, "overrides": [ { "files": "*.json", "options": { "printWidth": 120 } }, { "files": "*.md", "options": { "proseWrap": "always", "printWidth": 80 } }, { "files": "*.html", "options": { "printWidth": 120, "htmlWhitespaceSensitivity": "ignore" } } ] } ``` ## IDE Integration ### Visual Studio Code Install the Prettier extension: 1. Open VS Code 2. Go to Extensions (Cmd+Shift+X / Ctrl+Shift+X) 3. Search for "Prettier - Code formatter" 4. Install the official Prettier extension Configure auto-format on save: ```json theme={null} { "editor.defaultFormatter": "esbenp.prettier-vscode", "editor.formatOnSave": true, "editor.formatOnPaste": true, "[typescript]": { "editor.defaultFormatter": "esbenp.prettier-vscode" }, "[javascript]": { "editor.defaultFormatter": "esbenp.prettier-vscode" } } ``` ### WebStorm / IntelliJ IDEA Prettier is built-in. Enable it in: **Settings → Languages & Frameworks → JavaScript → Prettier** * Check "Automatic Prettier configuration" * Check "Run on save for files" ### Sublime Text Install the JsPrettier package via Package Control. ## Best Practices Run formatting regularly during development to maintain consistency. Always format code before committing to keep the repository clean. Share the same Prettier configuration across your entire team. Set up automatic formatting in your IDE and CI/CD pipeline. ## Checking Without Formatting To check if files need formatting without modifying them: ```shellscript theme={null} # Using Prettier directly npx prettier --check . # Check specific files npx prettier --check "src/**/*.ts" ``` This is useful for CI/CD pipelines where you want to verify formatting without making changes. ## Format Specific Files While the CLI command formats the entire project, you can format specific files using npx: ```shellscript theme={null} # Format specific file npx prettier --write src/index.ts # Format specific directory npx prettier --write "src/components/**/*.ts" # Format all TypeScript files npx prettier --write "**/*.ts" ``` ## Development Workflow Recommended workflow for code formatting: ```mermaid theme={null} graph LR A[Write Code] --> B[Save File] B --> C[Auto-Format on Save] C --> D[Continue Coding] D --> E[Before Commit] E --> F[native-desktop fmt] F --> G[native-desktop lint] G --> H[Commit] ``` ## Performance Tips Exclude large directories to speed up formatting. In large projects, format only modified files. Prettier caches results for faster subsequent runs. Use IDE auto-format for immediate feedback. ## Command Comparison | Command | Tool | Purpose | Changes Files | | ---------------------- | ---------- | ------------------ | ------------- | | `native-desktop fmt` | Prettier | Format code style | ✅ Yes | | `native-desktop lint` | ESLint | Check code quality | ❌ No | | `native-desktop types` | TypeScript | Check types | ❌ No | For best results, run all three commands as part of your development workflow. ## Exit Codes The format command uses standard exit codes: * **0**: Files formatted successfully * **1**: Errors occurred during formatting ```shellscript theme={null} native-desktop fmt echo $? # Check exit code ``` # CLI Introduction Source: https://docs.nativedesktop.com/native-desktop/user-guide/command-line-interface/introduction Introduction to the Native Desktop Command Line Interface The Native Desktop CLI is a powerful command-line tool that enables you to create, develop, build, and distribute native desktop applications with ease. Built on modern web technologies, it provides a streamlined workflow for desktop application development. ## Installation The Native Desktop CLI is available as a private package on GitHub. Access is granted upon purchase of a Native Desktop license. Once you have access, install the CLI globally using npm: ```shellscript theme={null} npm install -g @native-desktop/cli ``` Or install a specific version: ```shellscript theme={null} npm install -g @native-desktop/cli@1.0.0 ``` You must be authenticated with GitHub and have access to the private repository to install the package. Contact support if you've purchased a license but don't have access. ## Getting Started Once installed, you can access the CLI using the `native-desktop` command in your terminal. To see all available commands and options, run: ```shellscript theme={null} native-desktop --help ``` ## Core Features The Native Desktop CLI provides several key features to streamline your development workflow: * **Project Initialization**: Quickly scaffold new Native Desktop projects with customizable templates * **Development Server**: Run your application in development mode with hot-reload support * **Build System**: Compile and package your application for distribution across multiple platforms * **Code Quality Tools**: Built-in linting, formatting, and type-checking capabilities * **Code Signing**: Sign your applications for Windows and macOS distribution ## Available Commands The Native Desktop CLI includes the following commands: * `create` - Initialize a new Native Desktop project * `run` - Run your application in development mode * `build` - Build your application for production * `sign` - Sign your built application * `lint` - Run ESLint on your project * `fmt` - Format your code with Prettier * `types` - Check TypeScript types in your project ## Platform Support Native Desktop CLI supports development on the following operating systems: * **macOS** (darwin) * **Windows** (win32) * **Linux** You can only build applications for the operating system you are currently using. Cross-platform builds are not currently supported. ## Version Information To check your installed CLI version, use: ```shellscript theme={null} native-desktop --version ``` Or use the short alias: ```shellscript theme={null} native-desktop -v ``` ## Getting Help For any command, you can view detailed help information by appending `--help`: ```shellscript theme={null} native-desktop --help ``` For example: ```shellscript theme={null} native-desktop build --help ``` # Lint Project Source: https://docs.nativedesktop.com/native-desktop/user-guide/command-line-interface/lint Run ESLint to check code quality and style in your Native Desktop project The `lint` command runs ESLint on your Native Desktop project to identify and fix code quality issues, enforce coding standards, and catch potential bugs before they reach production. ## Prerequisites Before running the lint command, ensure: * Your project has been created using `native-desktop create` * All dependencies are installed (`npm install`) * ESLint configuration exists (`.eslintrc.json`) ## Basic Usage To lint your project, open the terminal in the **root directory** of your Native Desktop project and run: ```shellscript theme={null} native-desktop lint ``` This command will: 1. Load ESLint configuration from `.eslintrc.json` 2. Scan all source files in your project 3. Report any code quality issues, warnings, or errors 4. Exit with an appropriate status code ## What Gets Linted By default, the lint command checks: * All TypeScript files (`.ts`, `.tsx`) * All JavaScript files (`.js`, `.jsx`) * Files in the `src/` directory * Configuration files (if specified) Files and directories specified in `.eslintignore` are automatically excluded from linting. ## Output Examples ### Successful Lint (No Issues) ```shellscript theme={null} $ native-desktop lint ✓ No linting errors found All files passed ESLint checks ``` ### With Warnings ```shellscript theme={null} $ native-desktop lint ⚠ Warning: 3 warnings found src/components/Button.ts 12:5 warning 'handleClick' is defined but never used @typescript-eslint/no-unused-vars src/utils/helpers.ts 8:10 warning 'formatDate' is defined but never used @typescript-eslint/no-unused-vars 15:3 warning Unexpected console statement no-console ``` ### With Errors ```shellscript theme={null} $ native-desktop lint ✖ Error: 2 errors found src/index.ts 23:15 error 'myVariable' is not defined no-undef 45:8 error Missing semicolon semi ✖ 2 errors, 0 warnings ``` ## ESLint Configuration The lint command uses the `.eslintrc.json` file generated by `native-desktop create`. Here's an example configuration: ```json theme={null} { "parser": "@typescript-eslint/parser", "parserOptions": { "ecmaVersion": 2022, "sourceType": "module" }, "extends": [ "eslint:recommended", "plugin:@typescript-eslint/recommended" ], "rules": { "no-console": "warn", "no-unused-vars": "error", "semi": ["error", "always"], "quotes": ["error", "single"] } } ``` ## Common Linting Rules The Native Desktop CLI configures ESLint with recommended rules: * **no-unused-vars**: Disallow unused variables * **no-undef**: Disallow undeclared variables * **no-unreachable**: Disallow unreachable code * **no-constant-condition**: Disallow constant conditions * **eqeqeq**: Require `===` and `!==` * **no-eval**: Disallow `eval()` * **no-implied-eval**: Disallow implied `eval()` * **no-with**: Disallow `with` statements * **@typescript-eslint/no-explicit-any**: Warn on `any` type usage * **@typescript-eslint/no-unused-vars**: Disallow unused TypeScript variables * **@typescript-eslint/explicit-function-return-type**: Require explicit return types * **semi**: Require semicolons * **quotes**: Enforce quote style * **indent**: Enforce consistent indentation * **comma-dangle**: Require trailing commas ## Fixing Issues Automatically While the `lint` command reports issues, you can fix many of them automatically using the format command: ```shellscript theme={null} # Check for issues native-desktop lint # Fix formatting issues native-desktop fmt # Check again native-desktop lint ``` The `fmt` command (Prettier) and `lint` command (ESLint) work together. Run both for comprehensive code quality. ## Ignoring Files Create or edit `.eslintignore` to exclude files from linting: ``` # .eslintignore node_modules/ bin/ dist/ *.config.js coverage/ ``` ## Integration with Development Workflow ### Pre-Commit Hook Add linting to your pre-commit hooks using tools like Husky: ```json theme={null} { "husky": { "hooks": { "pre-commit": "native-desktop lint" } } } ``` ### CI/CD Pipeline Include linting in your continuous integration: ```yaml theme={null} # GitHub Actions example - name: Lint Code run: native-desktop lint ``` ### npm Scripts Add linting to your package.json scripts: ```json theme={null} { "scripts": { "lint": "native-desktop lint", "test": "native-desktop lint && npm run test:unit" } } ``` ## Exit Codes The lint command uses standard exit codes for CI/CD integration: * **0**: No linting errors (warnings are allowed) * **1**: Linting errors found ```shellscript theme={null} native-desktop lint echo $? # Check exit code ``` ## Common Issues **Error**: `.eslintrc.json not found` **Solution**: Ensure the configuration file exists in your project root. ```shellscript theme={null} # Check if file exists ls -la .eslintrc.json # If missing, recreate project or add configuration ``` **Error**: `Parsing error: Unexpected token` **Solution**: Ensure your TypeScript parser is configured correctly. ```json theme={null} { "parser": "@typescript-eslint/parser", "parserOptions": { "ecmaVersion": 2022, "sourceType": "module", "project": "./tsconfig.json" } } ``` **Error**: `Failed to load plugin '@typescript-eslint'` **Solution**: Install missing ESLint plugins. ```shellscript theme={null} npm install --save-dev @typescript-eslint/parser @typescript-eslint/eslint-plugin ``` **Error**: Overwhelmed by linting errors **Solution**: Fix errors gradually or adjust rules. ```json theme={null} { "rules": { "no-console": "warn", // Change from "error" to "warn" "no-unused-vars": "warn" } } ``` **Error**: Expected rule to trigger but didn't **Solution**: Verify rule configuration and ESLint version. ```shellscript theme={null} # Check ESLint version npx eslint --version # Verify rule exists npx eslint --print-config src/index.ts ``` ## Customizing Rules You can customize ESLint rules in `.eslintrc.json`: ```json theme={null} { "rules": { // Disable a rule "no-console": "off", // Set to warning "@typescript-eslint/no-explicit-any": "warn", // Set to error with options "quotes": ["error", "single", { "avoidEscape": true }], // Custom severity "semi": ["error", "always"] } } ``` ### Rule Severity Levels * **"off"** or **0**: Disable the rule * **"warn"** or **1**: Enable as warning (doesn't fail build) * **"error"** or **2**: Enable as error (fails build) ## Linting Specific Files While the CLI command lints the entire project, you can lint specific files using npx directly: ```shellscript theme={null} # Lint specific file npx eslint src/index.ts # Lint specific directory npx eslint src/components/ # Lint with fix npx eslint src/ --fix ``` ## Best Practices Run linting frequently during development to catch issues early. Keep ESLint rules consistent across your team and projects. Don't ignore warnings—they often indicate potential issues. Integrate linting into your CI/CD pipeline and pre-commit hooks. ## IDE Integration Most modern IDEs integrate with ESLint automatically: ### Visual Studio Code Install the ESLint extension: 1. Open VS Code 2. Go to Extensions (Cmd+Shift+X / Ctrl+Shift+X) 3. Search for "ESLint" 4. Install the official ESLint extension Configure auto-fix on save: ```json theme={null} { "editor.codeActionsOnSave": { "source.fixAll.eslint": true }, "eslint.validate": [ "javascript", "typescript" ] } ``` ### WebStorm / IntelliJ IDEA ESLint is built-in and enabled by default. Configure in: **Settings → Languages & Frameworks → JavaScript → Code Quality Tools → ESLint** ## Quality Metrics Track linting issues over time to improve code quality: ```shellscript theme={null} # Run lint and save output native-desktop lint > lint-report.txt # Count errors and warnings grep -c "error" lint-report.txt grep -c "warning" lint-report.txt ``` ## Command Comparison | Command | Purpose | Auto-Fix | Focus | | ---------------------- | ------------------ | -------- | --------------------- | | `native-desktop lint` | Check code quality | ❌ No | Logic, patterns, bugs | | `native-desktop fmt` | Format code style | ✅ Yes | Formatting, style | | `native-desktop types` | Check types | ❌ No | Type safety | Use all three commands together for comprehensive code quality assurance. ## Development Workflow Recommended workflow for maintaining code quality: ```mermaid theme={null} graph LR A[Write Code] --> B[native-desktop lint] B --> C{Issues Found?} C -->|Yes| D[Fix Issues] C -->|No| E[native-desktop fmt] D --> B E --> F[native-desktop types] F --> G{Type Errors?} G -->|Yes| H[Fix Types] G -->|No| I[Commit Code] H --> F ``` # Run Project Source: https://docs.nativedesktop.com/native-desktop/user-guide/command-line-interface/run Run your Native Desktop application in development mode The `run` command starts your Native Desktop application in development mode, allowing you to test and develop your application with live updates and debugging capabilities. ## Prerequisites Before running your project, ensure: * Your project has been created using `native-desktop create` * All dependencies are installed (`npm install`) * You have a valid `native-desktop.config.json5` configuration file ## Basic Usage To run your application in development mode, open the terminal in the **root directory** of your Native Desktop project and run: ```shellscript theme={null} native-desktop run ``` This command will: 1. Load your project configuration 2. Compile your TypeScript code 3. Start the application runtime 4. Launch your application window ## Command Options ### `[project-config-file]` (Optional) Path to the project configuration file. * **Type**: String (positional argument) * **Default**: `native-desktop.config.json5` * **Example**: `custom-config.json5` ```shellscript theme={null} # Use default configuration native-desktop run # Use custom configuration native-desktop run custom-config.json5 ``` ## Development Features When running in development mode, you get access to several helpful features: ### Hot Reload Your application automatically reloads when you make changes to your source code, allowing for rapid development and testing. ### Debug Console Access to developer tools and debug console for troubleshooting and inspecting your application's behavior. ### Error Messages Detailed error messages and stack traces to help identify and fix issues quickly. ### Live Testing Test your application's functionality in real-time without needing to rebuild after every change. ## Complete Examples ### Using Default Configuration ```shellscript theme={null} # Navigate to project directory cd my-native-desktop-app # Run with default config native-desktop run ``` ### Using Custom Configuration ```shellscript theme={null} # Run with development config native-desktop run native-desktop.dev.json5 # Run with staging config native-desktop run native-desktop.staging.json5 # Run with custom path native-desktop run configs/development.json5 ``` ## Development Workflow A typical development workflow looks like this: 1. **Start Development Server** ```shellscript theme={null} native-desktop run ``` 2. **Make Code Changes** * Edit your source files in the `src/` directory * Application will automatically reload 3. **Test Features** * Interact with your application * Check console for errors or logs 4. **Iterate and Refine** * Make additional changes * Test again until satisfied 5. **Run Quality Checks** ```shellscript theme={null} native-desktop lint native-desktop fmt native-desktop types ``` ## Configuration File The `run` command reads settings from your project configuration file. Here's a basic structure: ```json5 theme={null} { name: "My App", version: "1.0.0", main: "src/index.ts", window: { width: 1200, height: 800, resizable: true, title: "My Native Desktop App" }, devtools: true } ``` Development mode typically enables additional debugging features that are disabled in production builds. ## Common Use Cases ### Testing New Features ```shellscript theme={null} # Start app to test new feature native-desktop run # Make changes and test # Application auto-reloads ``` ### Debugging Issues ```shellscript theme={null} # Run with verbose logging native-desktop run # Check developer console # Inspect error messages and logs ``` ### UI/UX Development ```shellscript theme={null} # Run application native-desktop run # Adjust UI components # See changes instantly with hot reload ``` ### Integration Testing ```shellscript theme={null} # Run with test configuration native-desktop run native-desktop.test.json5 # Test integrations and APIs ``` ## Stopping the Application To stop the running application: * **Close the application window**, or * **Press `Ctrl+C`** in the terminal where the command is running ```shellscript theme={null} ^C Application stopped ``` ## Common Issues **Error**: `Configuration file not found: native-desktop.config.json5` **Solution**: Ensure the configuration file exists in your project root. ```shellscript theme={null} # Check if file exists ls native-desktop.config.json5 # If missing, specify correct path native-desktop run path/to/config.json5 ``` **Error**: `Port 3000 is already in use` **Solution**: Stop other applications using the same port or change the port in your configuration. ```shellscript theme={null} # Find process using the port lsof -i :3000 # Kill the process kill -9 ``` **Error**: `Cannot find module 'xyz'` **Solution**: Install missing dependencies. ```shellscript theme={null} # Install all dependencies npm install # Run again native-desktop run ``` **Error**: `TypeScript compilation failed` **Solution**: Fix TypeScript errors in your code. ```shellscript theme={null} # Check type errors native-desktop types # Fix errors in your code # Run again native-desktop run ``` **Error**: Application window doesn't appear **Solution**: Check terminal for error messages and verify configuration. ```shellscript theme={null} # Check for errors in terminal # Verify configuration is correct # Try running with fresh install rm -rf node_modules npm install native-desktop run ``` ## Performance Tips Periodically clean build caches if you experience slow startup times or unexpected behavior. Remove unused dependencies to improve startup time and reduce application size. TypeScript provides better development experience with type checking and IntelliSense. Keep an eye on CPU and memory usage during development to identify performance issues early. ## Development vs Production Understanding the differences between development and production modes: | Feature | Development (`run`) | Production (`build`) | | ------------ | ------------------- | -------------------- | | Hot Reload | ✅ Enabled | ❌ Disabled | | DevTools | ✅ Enabled | ❌ Disabled | | Source Maps | ✅ Enabled | ⚠️ Optional | | Minification | ❌ Disabled | ✅ Enabled | | Optimization | ❌ Minimal | ✅ Full | | Startup Time | ⚠️ Slower | ✅ Faster | | File Size | ⚠️ Larger | ✅ Smaller | Always test your application with `native-desktop build` before releasing to ensure production behavior matches your expectations. ## Keyboard Shortcuts When running in development mode, you can use keyboard shortcuts (platform-dependent): * **Reload**: `Cmd+R` (macOS) / `Ctrl+R` (Windows/Linux) * **DevTools**: `Cmd+Option+I` (macOS) / `Ctrl+Shift+I` (Windows/Linux) * **Quit**: `Cmd+Q` (macOS) / `Alt+F4` (Windows/Linux) ## Environment Variables You can use environment variables to customize the development environment: ```shellscript theme={null} # Set custom environment variables NODE_ENV=development native-desktop run # Use different API endpoints API_URL=http://localhost:8080 native-desktop run # Enable debug logging DEBUG=* native-desktop run ``` ## Multiple Configurations You can maintain multiple configuration files for different environments: ``` project/ ├── native-desktop.config.json5 # Production ├── native-desktop.dev.json5 # Development ├── native-desktop.staging.json5 # Staging └── native-desktop.test.json5 # Testing ``` Then run with the appropriate configuration: ```shellscript theme={null} native-desktop run native-desktop.dev.json5 ``` ## Best Practices Keep the development server running while coding to see changes immediately. Monitor the terminal for errors and warnings during development. Test frequently during development to catch issues early. Occasionally restart the dev server for a fresh start, especially after major changes. ## Logs and Debugging ### Viewing Logs Application logs are displayed in the terminal where you ran the command: ```shellscript theme={null} $ native-desktop run [INFO] Loading configuration... [INFO] Starting application... [INFO] Window created: 1200x800 [INFO] Application ready ``` ### Debug Mode Enable verbose logging for more detailed information: ```json5 theme={null} // native-desktop.config.json5 { debug: true, verbose: true } ``` ## Integration with Code Editors The `run` command works seamlessly with popular code editors: ### VS Code Create a launch configuration: ```json theme={null} { "type": "node", "request": "launch", "name": "Run Native Desktop", "program": "${workspaceFolder}/node_modules/@native-desktop/cli/bin/cli.js", "args": ["run"] } ``` ### WebStorm Create a Node.js run configuration pointing to the Native Desktop CLI. # Sign Project Source: https://docs.nativedesktop.com/native-desktop/user-guide/command-line-interface/sign Code sign your Native Desktop application for Windows and macOS The `sign` command allows you to digitally sign your built Native Desktop applications for Windows and macOS. Code signing is essential for ensuring user trust, preventing security warnings, and meeting platform distribution requirements. ## Prerequisites Before signing your application, ensure: * Your application has been built using `native-desktop build` * You have valid code signing certificates for your target platform * You have the necessary credentials and identities configured Code signing requires platform-specific certificates and credentials. Unsigned applications may trigger security warnings or be blocked by operating systems. ## Basic Usage To sign an application, run: ```shellscript theme={null} native-desktop sign [app-path] ``` If you don't specify an app path, the CLI will attempt to detect the application automatically from the `bin/` directory. ```shellscript theme={null} # Auto-detect application native-desktop sign # Specify application path native-desktop sign bin/my-app.dmg ``` ## Command Options ### `[app-path]` (Optional) Path to the application to sign. * **Type**: String (positional argument) * **Required**: No (auto-detected if not provided) * **Example**: `bin/MyApp.dmg`, `bin/MyApp.exe` ```shellscript theme={null} native-desktop sign bin/MyApp.dmg ``` ### `--platform` Target platform for signing. * **Type**: String * **Choices**: `windows`, `mac` * **Required**: No (auto-detected from app path) ```shellscript theme={null} native-desktop sign --platform mac ``` ### `--verbose` Enable verbose logging for detailed signing information. * **Type**: Boolean * **Default**: `false` ```shellscript theme={null} native-desktop sign --verbose ``` ## macOS Signing Signing macOS applications requires an Apple Developer certificate and optionally Apple ID credentials for notarization. ### Required Credentials * **Developer ID Application Certificate**: For signing the application * **Apple ID** (optional): For notarization * **Team ID** (optional): For notarization ### macOS Options #### `--identity` Certificate identity name or hash for signing. ```shellscript theme={null} native-desktop sign bin/MyApp.dmg --platform mac --identity "Developer ID Application: Your Name (TEAM123)" ``` * **Type**: String * **Required**: Yes (for macOS) * **Format**: Certificate name or SHA-1 hash To find your certificate identity, use: `security find-identity -v -p codesigning` #### `--apple-id` Apple ID email address for notarization. ```shellscript theme={null} native-desktop sign bin/MyApp.dmg \ --platform mac \ --identity "Developer ID Application" \ --apple-id "developer@example.com" ``` * **Type**: String * **Required**: No (required for notarization) #### `--apple-id-password` Apple ID app-specific password for notarization. ```shellscript theme={null} native-desktop sign bin/MyApp.dmg \ --platform mac \ --identity "Developer ID Application" \ --apple-id "developer@example.com" \ --apple-id-password "xxxx-xxxx-xxxx-xxxx" ``` * **Type**: String * **Required**: No (required for notarization) Generate an app-specific password at [appleid.apple.com](https://appleid.apple.com). Never use your main Apple ID password. #### `--team-id` Apple Team ID for notarization. ```shellscript theme={null} native-desktop sign bin/MyApp.dmg \ --platform mac \ --identity "Developer ID Application" \ --apple-id "developer@example.com" \ --apple-id-password "xxxx-xxxx-xxxx-xxxx" \ --team-id "TEAM123456" ``` * **Type**: String * **Required**: No (required for notarization) ### macOS Examples #### Basic Signing (No Notarization) ```shellscript theme={null} native-desktop sign bin/MyApp.dmg \ --platform mac \ --identity "Developer ID Application: Company Name (TEAMID)" ``` #### Signing with Notarization ```shellscript theme={null} native-desktop sign bin/MyApp.dmg \ --platform mac \ --identity "Developer ID Application: Company Name (TEAMID)" \ --apple-id "developer@example.com" \ --apple-id-password "xxxx-xxxx-xxxx-xxxx" \ --team-id "TEAMID" ``` #### Using Certificate Hash ```shellscript theme={null} # Find certificate hash security find-identity -v -p codesigning # Sign using hash native-desktop sign bin/MyApp.dmg \ --platform mac \ --identity "ABC123DEF456..." ``` ### macOS Notarization Notarization is an additional security step required for distribution outside the Mac App Store. It involves: 1. **Signing**: Application is signed with Developer ID 2. **Upload**: Binary is uploaded to Apple for scanning 3. **Verification**: Apple verifies the application 4. **Stapling**: Notarization ticket is attached to the application Notarization is required for macOS 10.15+ applications distributed outside the Mac App Store. ## Windows Signing Signing Windows applications requires a code signing certificate in `.pfx` or `.p12` format. ### Required Credentials * **Code Signing Certificate**: `.pfx` or `.p12` file * **Certificate Password**: Password for the certificate file ### Windows Options #### `--cert-file` Path to the certificate file (`.pfx` or `.p12`). ```shellscript theme={null} native-desktop sign bin/MyApp.exe \ --platform windows \ --cert-file "path/to/certificate.pfx" \ --cert-password "your-password" ``` * **Type**: String * **Required**: Yes (one of cert-file or certificate-sha1) #### `--cert-password` Password for the certificate file. ```shellscript theme={null} native-desktop sign bin/MyApp.exe \ --platform windows \ --cert-file "certificate.pfx" \ --cert-password "SecurePassword123" ``` * **Type**: String * **Required**: Yes (when using cert-file) Never commit certificate passwords to version control. Use environment variables or secure secret management. #### `--cert-subject-name` Certificate subject name (alternative to cert-file). ```shellscript theme={null} native-desktop sign bin/MyApp.exe \ --platform windows \ --cert-subject-name "Company Name Inc." ``` * **Type**: String * **Required**: No #### `--certificate-sha1` Certificate SHA1 hash (alternative to cert-file). ```shellscript theme={null} native-desktop sign bin/MyApp.exe \ --platform windows \ --certificate-sha1 "ABC123DEF456..." ``` * **Type**: String * **Required**: No ### Windows Examples #### Signing with Certificate File ```shellscript theme={null} native-desktop sign bin/MyApp.exe \ --platform windows \ --cert-file "certificate.pfx" \ --cert-password "MyPassword123" ``` #### Signing with Certificate Store ```shellscript theme={null} native-desktop sign bin/MyApp.exe \ --platform windows \ --cert-subject-name "Company Name Inc." ``` #### Signing with SHA1 Hash ```shellscript theme={null} native-desktop sign bin/MyApp.exe \ --platform windows \ --certificate-sha1 "1234567890ABCDEF1234567890ABCDEF12345678" ``` #### Signing MSI Installer ```shellscript theme={null} native-desktop sign bin/MyApp.msi \ --platform windows \ --cert-file "certificate.pfx" \ --cert-password "MyPassword123" \ --verbose ``` ## Automatic Signing During Build You can automatically sign your application during the build process using the `--sign` flag: ```shellscript theme={null} # macOS native-desktop build --target dmg --sign # Windows native-desktop build --target exe --sign ``` When using `--sign` with the build command, signing credentials must be configured in your `native-desktop.config.json5` file. ## Configuration File Signing You can configure signing credentials in your `native-desktop.config.json5` file: ```json theme={null} { "signing": { "mac": { "identity": "Developer ID Application: Company (TEAMID)", "appleId": "developer@example.com", "appleIdPassword": "xxxx-xxxx-xxxx-xxxx", "teamId": "TEAMID" }, "windows": { "certFile": "path/to/certificate.pfx", "certPassword": "${WINDOWS_CERT_PASSWORD}" } } } ``` Use environment variables for sensitive credentials like passwords. ## Verification After signing, verify your application: ### macOS Verification ```shellscript theme={null} # Verify signature codesign --verify --verbose bin/MyApp.app # Check notarization spctl --assess --verbose bin/MyApp.app # Display signature information codesign -dv bin/MyApp.app ``` ### Windows Verification ```shellscript theme={null} # Using signtool (Windows SDK) signtool verify /pa bin/MyApp.exe # Display signature information signtool verify /v bin/MyApp.exe ``` ## Common Issues **Error**: `Certificate identity not found` **Solution**: Ensure your Developer ID certificate is installed in Keychain. ```shellscript theme={null} # List available certificates security find-identity -v -p codesigning # Import certificate if needed security import certificate.p12 -k ~/Library/Keychains/login.keychain ``` **Error**: `Notarization failed` **Solution**: Check that all credentials are correct and the app-specific password is valid. * Verify Apple ID credentials * Ensure app-specific password is generated * Check Team ID matches your developer account * Review verbose logs with `--verbose` **Error**: `Invalid certificate password` **Solution**: Verify the certificate password is correct. ```shellscript theme={null} # Test certificate certutil -dump certificate.pfx ``` **Error**: `Certificate file not found` **Solution**: Provide the correct path to the certificate file. ```shellscript theme={null} # Use absolute path native-desktop sign bin/MyApp.exe \ --cert-file "/absolute/path/to/certificate.pfx" \ --cert-password "password" ``` **Error**: `Application path not found` **Solution**: Ensure the application has been built and the path is correct. ```shellscript theme={null} # Build first native-desktop build --target dmg # Then sign native-desktop sign bin/MyApp.dmg ``` ## Security Best Practices Never commit certificates or passwords to version control. Use environment variables or secret management tools. Use Apple app-specific passwords instead of your main Apple ID password for notarization. Store certificate files securely and restrict access to authorized personnel only. Monitor certificate expiration dates and renew before expiry to avoid distribution issues. ## Platform Requirements ### macOS * **macOS 10.13+**: Required for code signing * **Xcode Command Line Tools**: Install with `xcode-select --install` * **Apple Developer Account**: Required for Developer ID certificates * **Internet Connection**: Required for notarization ### Windows * **Windows 7+**: Supported for code signing * **signtool**: Included in Windows SDK * **Code Signing Certificate**: From trusted Certificate Authority ## CI/CD Integration ### GitHub Actions Example ```yaml theme={null} name: Build and Sign on: [push] jobs: build-mac: runs-on: macos-latest steps: - uses: actions/checkout@v3 - name: Install certificates env: CERTIFICATE_BASE64: ${{ secrets.MACOS_CERTIFICATE }} run: | echo $CERTIFICATE_BASE64 | base64 --decode > certificate.p12 security import certificate.p12 -k ~/Library/Keychains/login.keychain - name: Build and Sign env: APPLE_ID: ${{ secrets.APPLE_ID }} APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }} TEAM_ID: ${{ secrets.TEAM_ID }} run: | native-desktop build --target dmg native-desktop sign bin/MyApp.dmg \ --platform mac \ --identity "Developer ID Application" \ --apple-id "$APPLE_ID" \ --apple-id-password "$APPLE_PASSWORD" \ --team-id "$TEAM_ID" ``` # Type Checking Source: https://docs.nativedesktop.com/native-desktop/user-guide/command-line-interface/types Check TypeScript types in your Native Desktop project The `types` command runs TypeScript's type checker on your Native Desktop project to validate type safety, catch type errors, and ensure your code adheres to TypeScript's type system without emitting any output files. ## Prerequisites Before running the types command, ensure: * Your project has been created using `native-desktop create` * All dependencies are installed (`npm install`) * TypeScript configuration exists (`tsconfig.json`) * Your project uses TypeScript (`.ts` or `.tsx` files) ## Basic Usage To check TypeScript types in your project, open the terminal in the **root directory** of your Native Desktop project and run: ```shellscript theme={null} native-desktop types ``` This command will: 1. Load TypeScript configuration from `tsconfig.json` 2. Analyze all TypeScript files in your project 3. Check for type errors and inconsistencies 4. Report any type-related issues 5. Exit with an appropriate status code ## What Gets Checked By default, the types command checks: * All TypeScript files (`.ts`, `.tsx`) * Type definitions (`.d.ts` files) * Files in the `src/` directory * Files specified in `tsconfig.json` include patterns Files and directories specified in `tsconfig.json` exclude patterns are automatically skipped. ## Output Examples ### Successful Type Check (No Errors) ```shellscript theme={null} $ native-desktop types ✓ Type checking complete ✓ No type errors found All TypeScript types are valid ``` ### With Type Errors ```shellscript theme={null} $ native-desktop types ✖ Type checking failed: 3 errors found src/components/Button.tsx:15:7 Type 'string' is not assignable to type 'number'. 15 const count: number = "hello"; ~~~~~ src/utils/helpers.ts:23:16 Property 'name' does not exist on type 'User'. 23 return user.name; ~~~~ src/index.ts:45:10 Argument of type 'boolean' is not assignable to parameter of type 'string'. 45 myFunction(true); ~~~~ ✖ Found 3 type errors ``` ### With Warnings ```shellscript theme={null} $ native-desktop types ⚠ Type checking complete with warnings src/models/User.ts:12:5 'age' is declared but its value is never read. 12 age: number; ~~~ ✓ 0 errors, 1 warning ``` ## TypeScript Configuration The types command uses the `tsconfig.json` file generated by `native-desktop create`. Here's an example configuration: ```json theme={null} { "compilerOptions": { "target": "ES2022", "module": "ESNext", "lib": ["ES2022"], "moduleResolution": "node", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true, "resolveJsonModule": true, "noEmit": true, "noUnusedLocals": true, "noUnusedParameters": true, "noImplicitReturns": true, "noFallthroughCasesInSwitch": true }, "include": ["src/**/*"], "exclude": ["node_modules", "bin", "dist"] } ``` ## TypeScript Compiler Options Common compiler options that affect type checking: * **strict**: Enable all strict type-checking options * **noImplicitAny**: Error on expressions with implied `any` type * **strictNullChecks**: Enable strict null checking * **strictFunctionTypes**: Enable strict checking of function types * **strictBindCallApply**: Enable strict checking of `bind`, `call`, and `apply` * **strictPropertyInitialization**: Ensure class properties are initialized * **noUnusedLocals**: Report errors on unused local variables * **noUnusedParameters**: Report errors on unused parameters * **noImplicitReturns**: Report error when function doesn't return value * **noFallthroughCasesInSwitch**: Report errors for fallthrough cases in switch * **noUncheckedIndexedAccess**: Add `undefined` to unverified index signatures * **moduleResolution**: Specify module resolution strategy (`node`, `classic`) * **esModuleInterop**: Enable interoperability between CommonJS and ES Modules * **resolveJsonModule**: Allow importing JSON files * **allowSyntheticDefaultImports**: Allow default imports from modules with no default export * **noEmit**: Do not emit output files (only check types) * **skipLibCheck**: Skip type checking of declaration files * **forceConsistentCasingInFileNames**: Ensure consistent casing in imports * **isolatedModules**: Ensure each file can be safely transpiled ## Common Type Errors **Error**: `Type 'X' is not assignable to type 'Y'` **Cause**: You're trying to assign a value of one type to a variable of another type. **Solution**: Ensure the types match or use type assertions/conversions. ```typescript theme={null} // ❌ Error const count: number = "hello"; // ✅ Fixed const count: number = 42; ``` **Error**: `Property 'X' does not exist on type 'Y'` **Cause**: You're accessing a property that doesn't exist on the object's type. **Solution**: Add the property to the type definition or use optional chaining. ```typescript theme={null} // ❌ Error interface User { name: string; } const user: User = { name: "John" }; console.log(user.age); // ✅ Fixed interface User { name: string; age?: number; } const user: User = { name: "John" }; console.log(user.age); ``` **Error**: `Parameter 'X' implicitly has an 'any' type` **Cause**: TypeScript can't infer the type and no explicit type is provided. **Solution**: Add explicit type annotations. ```typescript theme={null} // ❌ Error function greet(name) { return `Hello, ${name}`; } // ✅ Fixed function greet(name: string): string { return `Hello, ${name}`; } ``` **Error**: `Object is possibly 'null' or 'undefined'` **Cause**: You're accessing a property on a value that might be null or undefined. **Solution**: Add null checks or use optional chaining. ```typescript theme={null} // ❌ Error function getLength(text: string | null) { return text.length; } // ✅ Fixed function getLength(text: string | null) { return text?.length ?? 0; } ``` **Error**: `Function lacks ending return statement` **Cause**: A function with a non-void return type doesn't return a value in all code paths. **Solution**: Ensure all code paths return a value. ```typescript theme={null} // ❌ Error function getValue(flag: boolean): number { if (flag) { return 42; } // Missing return for else case } // ✅ Fixed function getValue(flag: boolean): number { if (flag) { return 42; } return 0; } ``` ## Integration with Development Workflow ### Pre-Commit Hook Add type checking to your pre-commit hooks: ```json theme={null} { "husky": { "hooks": { "pre-commit": "native-desktop types && native-desktop lint" } } } ``` ### CI/CD Pipeline Include type checking in your continuous integration: ```yaml theme={null} # GitHub Actions example - name: Type Check run: native-desktop types ``` ### npm Scripts Add type checking to your package.json scripts: ```json theme={null} { "scripts": { "typecheck": "native-desktop types", "test": "native-desktop types && npm run test:unit", "validate": "native-desktop types && native-desktop lint && native-desktop fmt" } } ``` ## Exit Codes The types command uses standard exit codes for CI/CD integration: * **0**: No type errors found * **1**: Type errors found ```shellscript theme={null} native-desktop types echo $? # Check exit code ``` ## Common Issues **Error**: `Cannot find tsconfig.json` **Solution**: Ensure the configuration file exists in your project root. ```shellscript theme={null} # Check if file exists ls -la tsconfig.json # If missing, create a basic configuration npx tsc --init ``` **Error**: `Cannot find module 'xyz'` **Solution**: Install missing type definitions or dependencies. ```shellscript theme={null} # Install missing types npm install --save-dev @types/node # Or install the actual package npm install xyz ``` **Error**: Overwhelmed by type errors in a new project **Solution**: Fix errors gradually or adjust strictness settings temporarily. ```json theme={null} { "compilerOptions": { "strict": false, // Temporarily disable strict mode "noImplicitAny": false } } ``` **Error**: Conflicting type definitions **Solution**: Check for duplicate type packages or version mismatches. ```shellscript theme={null} # List installed type packages npm list @types # Remove duplicates npm uninstall @types/xyz npm install --save-dev @types/xyz@latest ``` **Error**: `JavaScript heap out of memory` **Solution**: Increase Node.js memory limit or exclude large directories. ```shellscript theme={null} # Increase memory limit NODE_OPTIONS="--max-old-space-size=4096" native-desktop types ``` Update `tsconfig.json`: ```json theme={null} { "exclude": ["node_modules", "bin", "dist", "large-folder"] } ``` ## Customizing Type Checking You can customize TypeScript's behavior in `tsconfig.json`: ```json theme={null} { "compilerOptions": { // Enable strict type checking "strict": true, // Report errors for unused variables "noUnusedLocals": true, "noUnusedParameters": true, // Require explicit return types "noImplicitReturns": true, // Check indexed access "noUncheckedIndexedAccess": true, // Skip checking of declaration files "skipLibCheck": true, // Do not emit output "noEmit": true }, "include": ["src/**/*"], "exclude": ["node_modules", "**/*.spec.ts"] } ``` ## IDE Integration Most modern IDEs provide built-in TypeScript support: ### Visual Studio Code TypeScript support is built-in. Configure in `settings.json`: ```json theme={null} { "typescript.tsdk": "node_modules/typescript/lib", "typescript.enablePromptUseWorkspaceTsdk": true, "typescript.updateImportsOnFileMove.enabled": "always", "editor.codeActionsOnSave": { "source.organizeImports": true } } ``` ### WebStorm / IntelliJ IDEA TypeScript support is built-in and enabled by default. **Settings → Languages & Frameworks → TypeScript** * Enable TypeScript Language Service * Use project's TypeScript version ## Type Checking Specific Files While the CLI command checks the entire project, you can check specific files using tsc directly: ```shellscript theme={null} # Check specific file npx tsc --noEmit src/index.ts # Check specific directory npx tsc --noEmit src/components/*.ts # Check with different config npx tsc --noEmit -p tsconfig.production.json ``` ## Watch Mode For continuous type checking during development, use TypeScript's watch mode: ```shellscript theme={null} # Run TypeScript compiler in watch mode npx tsc --noEmit --watch ``` This will continuously check types as you make changes to your code. ## Best Practices Use `"strict": true` for maximum type safety and error prevention. Add explicit type annotations, especially for function parameters and return types. Run type checking frequently during development to catch errors early. When facing many errors, fix them incrementally rather than all at once. ## Type Safety Levels Different levels of type strictness you can configure: ```json theme={null} { "compilerOptions": { "strict": false, "noImplicitAny": false, "skipLibCheck": true } } ``` Easy to start, but provides minimal type safety. ```json theme={null} { "compilerOptions": { "strict": true, "skipLibCheck": true } } ``` Good balance between safety and ease of use. ```json theme={null} { "compilerOptions": { "strict": true, "noUnusedLocals": true, "noUnusedParameters": true, "noImplicitReturns": true, "noFallthroughCasesInSwitch": true } } ``` Maximum type safety with comprehensive error checking. ## Command Comparison | Command | Purpose | Auto-Fix | Type Checking | | ---------------------- | ---------------------- | ---------- | ------------- | | `native-desktop types` | Check TypeScript types | ❌ No | ✅ Yes | | `native-desktop lint` | Check code quality | ⚠️ Limited | ❌ No | | `native-desktop fmt` | Format code style | ✅ Yes | ❌ No | Use all three commands together for comprehensive code quality: types for type safety, lint for code quality, and fmt for consistent formatting. ## Development Workflow Recommended workflow for type-safe development: ```mermaid theme={null} graph LR A[Write Code] --> B[Save File] B --> C[IDE Type Check] C --> D{Type Errors?} D -->|Yes| E[Fix Types] D -->|No| F[Continue] E --> A F --> G[Before Commit] G --> H[native-desktop types] H --> I{Pass?} I -->|No| E I -->|Yes| J[Commit] ``` ## Performance Optimization For large projects, optimize type checking performance: ```json theme={null} { "compilerOptions": { // Skip checking declaration files "skipLibCheck": true, // Use incremental compilation "incremental": true, // Specify output for incremental info "tsBuildInfoFile": ".tsbuildinfo" }, "exclude": [ "node_modules", "bin", "dist", "**/*.spec.ts" ] } ``` # Check Access Source: https://docs.nativedesktop.com/native-desktop/user-guide/core-library/check-access When using the native-desktop Core Library, it is important to **verify whether your application is running inside the native-desktop environment** or a regular web browser. The library’s features only work when the application is running inside Native Desktop. You can perform this check using the `isInNativeDesktop()` function. For example: ```typescript theme={null} import { isInNativeDesktop } from '@native-desktop/core'; const sampleFunction = () => { const inNativeDesktop = isInNativeDesktop(); if (inNativeDesktop) { // Execute Native Desktop-specific code here } } ``` Performing this check is necessary to prevent unexpected errors when the application runs in a normal browser. If you are using frameworks like Next.js, the Core Library only works on the **client side**. You must add `use client` at the top of your page. Server-side rendered pages cannot access the Native Desktop Core Library. # Core Library Source: https://docs.nativedesktop.com/native-desktop/user-guide/core-library/introduction The **Native Desktop Core Library** is a TypeScript library that allows your web application to **interact with the Native Desktop native application**. ### Installing the Core Library Installing the core library is straightforward. Simply run the following command to add the package to your project: ```shellscript theme={null} npm install @native-desktop/core ``` # IPC Commands Source: https://docs.nativedesktop.com/native-desktop/user-guide/core-library/ipc-commands The `nativeDesktopApp` API provides a set of application-level IPC commands that allow web applications to interact with native Native Desktop features such as application control, history management, and app information. * **Application-related**: Access and modify application-level details. * **Navigation-related**: Control and retrieve navigation state within the app. * **Network-related**: Manage network operations and monitor connectivity. * **Notification-related**: Send notifications to the user from the Native Desktop app. * **Window-related**: Get or set properties of the application window. These commands are available **only when the app is running inside the Native Desktop environment**. To safely use these APIs, always verify the runtime environment using `isInNativeDesktop()` from `@native-desktop/core`. # Custom IPCs `type TNativeDesktopPlugins = Record; ` Represents a key–value map of **custom plugin instances**. Each key corresponds to a plugin name registered in the Native Desktop runtime, and each value exposes the plugin’s available methods or data. You can access all available plugins through the `nativeDesktopPlugins()` function. It returns an object containing all registered plugin APIs. ```typescript theme={null} import { isInNativeDesktop, nativeDesktopPlugins } from '@native-desktop/core'; const usePlugins = async () => { if (!isInNativeDesktop()) { return; } const plugins = nativeDesktopPlugins(); if (plugins) { console.log('Available plugins:', Object.keys(plugins)); } }; ``` **Example Usage of a Custom Plugin:** Assume you have a plugin registered under the name `fileManager` that exposes methods like `openFile()` and `saveFile()`. ```typescript theme={null} if (isInNativeDesktop()) { const plugins = nativeDesktopPlugins(); const fileManager = plugins?.fileManager; if (fileManager) { const file = await fileManager.openFile('/Users/demo/Documents/sample.txt'); console.log('File content:', file.content); await fileManager.saveFile('/Users/demo/Documents/sample.txt', 'Updated content'); console.log('File saved successfully!'); } } ``` # Application-related IPCs ## `getAppUrl(): Promise` Returns the URL of the current Native Desktop application. ```typescript theme={null} if (isInNativeDesktop()) { const appUrl = await window.nativeDesktopApp.getAppUrl(); console.log('Native Desktop App URL:', appUrl); } ``` ## `quit(): void` Immediately closes the Native Desktop application. ```typescript theme={null} if (isInNativeDesktop()) { window.nativeDesktopApp.quit(); } ``` ## `restart(): void` Restarts the Native Desktop application. Useful for applying configuration or environment changes. ```typescript theme={null} if (isInNativeDesktop()) { window.nativeDesktopApp.restart(); } ``` ## `getHistory(): Promise<{ url: string; title: string; timestamp: number }[]>` Retrieves the browsing history of the current Native Desktop app window. ```typescript theme={null} if (isInNativeDesktop()) { const history = await window.nativeDesktopApp.getHistory(); console.table(history); } ``` ## `filterHistory(filters: { url?: string; title?: string }): Promise<{ url: string; title: string; timestamp: number }[]>` Filters the application history based on a specific URL or title. ```typescript theme={null} if (isInNativeDesktop()) { const filtered = await window.nativeDesktopApp.filterHistory({ title: 'Dashboard' }); console.table(filtered); } ``` ## `cleanHistory(): void` Clears all stored browsing history within the current Native Desktop application context. ```typescript theme={null} if (isInNativeDesktop()) { window.nativeDesktopApp.cleanHistory(); console.log('Native Desktop app history cleared'); } ``` # Navigation-relates IPCs ## `canGoBack(): Promise` Checks if there is a previous page in the navigation history. ```typescript theme={null} if (isInNativeDesktop()) { const canGoBack = await window.nativeDesktopNavigation.canGoBack(); console.log('Can go back?', canGoBack); } ``` ## `canGoForward(): Promise` Checks if there is a next page available in the navigation history. ```typescript theme={null} if (isInNativeDesktop()) { const canGoForward = await window.nativeDesktopNavigation.canGoForward(); console.log('Can go forward?', canGoForward); } ``` ## `goBack(): void` Navigates to the previous page in the current Native Desktop window’s history. ```typescript theme={null} if (isInNativeDesktop()) { window.nativeDesktopNavigation.goBack(); } ``` ## `goForward(): void` Navigates forward to the next page in the Native Desktop app’s navigation history. ```typescript theme={null} if (isInNativeDesktop()) { window.nativeDesktopNavigation.goForward(); } ``` ## `cloneWindow(): void` Creates a duplicate of the current Native Desktop application window, effectively cloning the app’s current state into a new window instance. ```typescript theme={null} if (isInNativeDesktop()) { window.nativeDesktopNavigation.cloneWindow(); console.log('Cloned current Native Desktop window'); } ``` # Network-related IPCs ## `getStatus(): Promise<{ online: boolean }>` Checks the current network connectivity state of the Native Desktop application. ```typescript theme={null} if (isInNativeDesktop()) { const status = await window.nativeDesktopNetwork.getStatus(); console.log('Network status:', status.online ? 'Online' : 'Offline'); } ``` ## `onStatusChange(callback: (status: { online: boolean }) => void): void` Listens for changes in the network connectivity status. The provided callback is triggered whenever the connection goes **online** or **offline**. ```typescript theme={null} if (isInNativeDesktop()) { window.nativeDesktopNetwork.onStatusChange((status) => { console.log('Network changed:', status.online ? 'Online' : 'Offline'); }); } ``` ## `speedTest(): Promise` Performs a network speed test and returns performance metrics. ```typescript theme={null} if (isInNativeDesktop()) { const result = await window.nativeDesktopNetwork.speedTest(); console.log('Speed test results:', result); } ``` # Notification-related IPCs ## `show(options: TNotificationOptions): void` Displays a native system notification. You can customize the title, body, icon, and add custom action buttons. ```typescript theme={null} if (isInNativeDesktop()) { window.nativeDesktopNotification.show({ title: 'Update Available', body: 'A new version of your app is ready to install.', icon: '/assets/update-icon.png', actions: [{ type: 'button', text: 'Restart Now' }], }); } ``` ## `setBadge(count: number): void` Sets an application badge (e.g., dock or taskbar icon counter) to indicate unread messages, notifications, or pending tasks. ```typescript theme={null} if (isInNativeDesktop()) { window.nativeDesktopNotification.setBadge(5); // shows "5" badge } ``` ## `clear(): void` Clears all active notifications and resets the badge counter. ```typescript theme={null} if (isInNativeDesktop()) { window.nativeDesktopNotification.clear(); } ``` ## `showAlert(options: TAlertOptions): Promise` Displays a modal alert dialog with customizable title, message, and buttons. ```typescript theme={null} if (isInNativeDesktop()) { await window.nativeDesktopNotification.showAlert({ type: 'info', title: 'Welcome', message: 'Your project was created successfully!', buttons: ['OK'], }); } ``` ## `showConfirm(options: TConfirmOptions): Promise` Displays a confirmation dialog with multiple buttons and returns the **index** of the button the user clicked. ```typescript theme={null} if (isInNativeDesktop()) { const choice = await window.nativeDesktopNotification.showConfirm({ title: 'Confirm Exit', message: 'Are you sure you want to quit the application?', buttons: ['Cancel', 'Quit'], }); if (choice === 1) { console.log('User confirmed quit'); } } ``` # Window-related IPCs ## `minimize(): void` Minimizes the current Native Desktop application window. ```typescript theme={null} if (isInNativeDesktop()) { window.nativeDesktopWindow.minimize(); } ``` ## `maximize(): void` Maximizes the current Native Desktop window to full size. ```typescript theme={null} if (isInNativeDesktop()) { window.nativeDesktopWindow.maximize(); } ``` ## `unmaximize(): void` Restores the Native Desktop window to its previous (non-maximized) size. ```typescript theme={null} if (isInNativeDesktop()) { window.nativeDesktopWindow.unmaximize(); } ``` ## `close(): void` Closes the current Native Desktop window. If it’s the main window, the application will likely quit. ```typescript theme={null} if (isInNativeDesktop()) { window.nativeDesktopWindow.close(); } ``` ## `toggleFullScreen(): void` Toggles the current window between fullscreen and windowed mode. ```typescript theme={null} if (isInNativeDesktop()) { window.nativeDesktopWindow.toggleFullScreen(); } ``` ## `focus(): void` Brings the current Native Desktop window to the foreground and focuses it. ```typescript theme={null} if (isInNativeDesktop()) { window.nativeDesktopWindow.focus(); } ``` ## `open(url?: string, config?: any): void` Opens a new Native Desktop window. You can optionally pass a URL and configuration object (for window options, size, etc.). ```typescript theme={null} if (isInNativeDesktop()) { window.nativeDesktopWindow.open('https://docs.nativedesktop.com', { width: 1000, height: 700, resizable: true, }); } ``` ## `getBounds(): any` Retrieves the current window’s size and position. Returns an object similar to `{ x, y, width, height }`. ```typescript theme={null} if (isInNativeDesktop()) { const bounds = window.nativeDesktopWindow.getBounds(); console.log('Current window bounds:', bounds); } ``` ## `setBounds(bounds: any): void` Sets or updates the window’s position and size. ```typescript theme={null} if (isInNativeDesktop()) { window.nativeDesktopWindow.setBounds({ width: 1200, height: 800 }); } ``` ## `isMaximized(callback: (event: any, state: boolean) => void): any` Registers a listener to detect changes in the window’s maximized state. The callback receives a `state` boolean (`true` = maximized, `false` = restored). ```typescript theme={null} if (isInNativeDesktop()) { window.nativeDesktopWindow.isMaximized((_event, state) => { console.log('Window maximized?', state); }); } ``` # Configuration File Source: https://docs.nativedesktop.com/native-desktop/user-guide/native-desktop-framework/configuration To run a Native Desktop application, you must create a configuration file in [JSON5](https://json5.org) format (not plain JSON). The default configuration file name is `native-desktop.config.json5`, and it is recommended to use this file during development. You can also create separate configuration files for different environments, for example: * `staging.native-desktop.config.json5` * `production.native-desktop.config.json5` There is **no strict naming rule** for configuration files, but it’s recommended to follow the format:`.native-desktop.config.json5` # File Structure Below is the complete structure of the **Native Desktop configuration file**. ```typescript theme={null} type TNativeDesktopConfigSchema = { environment: string; // Required name: string; // Required description: string; author: string; packageName: string; // Required version: string; domain: string; // Required icons: { mac: string[]; windows: string[]; linux: string[]; }; windowStartup: { shouldShowBeforeLoadingComplete: boolean; shouldEnableSplashScreen: boolean; }; windowSize: { height: number; width: number; minHeight: number; minWidth: number; }; windowLayout: { shouldHideTitleBar: boolean; shouldEnableFrame: boolean; shouldDisableAutoHideCursor: boolean; shouldHaveRoundCorners: boolean; shouldEnableShadows: boolean; }; windowOptions: { shouldMovable: boolean; shouldMinimizable: boolean; shouldMaximizable: boolean; shouldClosable: boolean; shouldFocusable: boolean; shouldFullscreenable: boolean; shouldRestoreState: boolean; }; windowColors: { dark: string; light: string; }; externalLinks: { shouldOpenNonAppLinksExternally: boolean; }; htmlPages: { splashScreen: string[]; offline: string[]; httpNotAllowed: string[]; }; plugins: string[][]; rendererPlugins: string[][]; development: { shouldOpenDevToolsWhenRun: boolean; }; highRisk: { shouldLoadHTTPDomains: boolean; shouldEnableWebSecurity: boolean; shouldAllowRunningInsecureContent: boolean; shouldEnableExperimentalFeatures: boolean; }; }; ``` ## Rules for Path-specific Fields These details are explained in the related sections, but they are reiterated here for clarity. In the configuration file, **all file paths must be specified as an array of strings**. For example, if you need to reference a file located at `assets/icons/mac/mac.icns`, the path should be defined as: ```json theme={null} ['assets', 'icons', 'mac', 'mac.icns'] // Path is assets/icons/mac/mac.icns ``` It is important to always use the **exact file path** in the configuration. However, for **plugins**, you must reference the **compiled JavaScript file** rather than the TypeScript source. For instance, if you create a plugin at `src/samplePlugin.ts`, it will be compiled to `runtime/samplePlugin.js` when building or running the project. In this case, the path in the configuration should be set as: ```json theme={null} [ ['runtime', 'samplePlugin.js'] // Path is runtime/samplePlugin.js ] ``` This ensures that Native Desktop loads the correct runtime files instead of the original TypeScript sources. # Configuration Fields ## Environment `environment` The `environment` field identifies the current environment for the application. Although Native Desktop runs on **Node.js** and supports the `NODE_ENV` variable, the framework itself does not use `NODE_ENV`. You can set `environment` based on your deployment target. \*\*Do not use \*\*`testing` as the environment name, as it is reserved for internal development. Setting it as `testing` may cause unexpected behavior. ## Name `name` The `name` field defines the name of your application and is also used during the build process. ## Description `description` The `description` field allows you to add a brief description of your project. ## Author `author` The `author` field specifies the author of the project, which can be an individual, a team, a company, or an organization. There is no strict format, but a recommended style is: ` ()`. ## Package Name `packageName` The `packageName` field is mainly used by the Node.js ecosystem. When defining this value, follow the standard naming conventions used in `package.json`. ## Version `version` The `version` field represents the current version of your application. It should follow **semantic versioning** with `major.minor.patch` format. Examples include `1.0.0`, `1.0.1`, or `12.9.8`. ## Domain `domain` The `domain` field specifies the starting URL of the application. When the app runs, this URL will be opened automatically. It can be either an `http` or `https` URL. ## Icons `icons` The `icon` field sets the application icon paths. You must provide separate icons for **Windows**, **Linux**, and **macOS**. Each icon path should be defined as an array of folder names ending with the icon file name. Paths should be relative to the configuration file directory. ```json theme={null} icons: { mac: ['folder', 'mac', 'icon.icns'], // Path: folder/mac/icon.icns windows: ['folder', 'windows', 'icon.ico'], // Path: folder/windows/icon.ico linux: ['folder', 'linux', 'icon.png'] // Path: Folder/linux/icon.png } ``` ## Window Startup `windowStartup` The `windowStartup` field defines how the application launches ### ` shouldShowBeforeLoadingComplete` If this is`true`, the application will not display until the page finishes loading. If `false`, the application loads immediately, which may show a blank screen briefly. It is recommended to set this to `true`. ### `shouldEnableSplashScreen` If this is `true`, a splash screen will be displayed while the page loads. You can provide a custom HTML splash screen; otherwise, the default splash screen is used. The splash screen only appears if the page loading takes noticeable time; in most cases, the page loads immediately. ## Window Size `windowSize` The `windowSize` field defines the default dimensions of the main application window: ### `height` The default height of the application window defines its initial vertical size when the app launches. The value must be greater than `0`. ### `width` The default width of the application window sets its initial horizontal size. Like height, it must also be greater than `0`. ### `minHeight` The minimum height specifies the smallest vertical size the window can be resized to. It must be greater than `0` and less than the default height. Users will not be able to resize the window below this value. ### `minWidth` The minimum width defines the smallest horizontal size the window can be resized to. It must be greater than `0` and less than the default width. Users cannot reduce the window width below this limit. ## Window Layout `windowLayout` The `windowLayout` field contains nested properties to control the main window’s appearance and behavior: ### `shouldHideTitleBar` The `shouldHideTitleBar` property, when set to `true`, hides the default OS-specific title bar from the window. This is useful when creating a custom title bar or a frameless window design. ### `shouldEnableFrame` The `shouldEnableFrame` property controls the visibility of the application frame. If set to `false`, the standard window frame is removed, allowing for a fully customized window appearance. ### `shouldDisableAutoHideCursor` The `shouldDisableAutoHideCursor` property determines cursor behavior while typing. When set to `true`, the cursor will remain visible instead of automatically hiding, which can improve usability in certain input-heavy applications. ### `shouldHaveRoundCorners` The `shouldHaveRoundCorners` property enables OS-specific rounded corners on the window when set to `true`. This provides a more modern and native look, particularly on macOS and Windows. ### `shouldEnableShadows` The `shouldEnableShadows` property adds default OS-specific shadows to the window when set to `true`. This enhances visual depth and distinguishes the application window from the background, improving overall aesthetics and user experience. ## Window Options `windowOptions` ### `shouldMovable` The `shouldMovable` property determines whether the application window can be moved by the user. When set to `true`, users can drag the window around the screen; setting it to `false` locks the window in place. ### `shouldMinimizable` The `shouldMinimizable` property controls whether the window can be minimized. If `true`, the minimize button is enabled, allowing users to send the window to the taskbar or dock. ### `shouldMaximizable` The `shouldMaximizable` property defines whether the window can be maximized to fill the screen. When set to `true`, the maximize button is active; if `false`, users cannot expand the window. ### `shouldClosable` The `shouldClosable` property determines if the window can be closed by the user. If `true`, the close button is enabled; setting it to `false` prevents accidental or manual closure of the application. ### `shouldFocusable` The `shouldFocusable` property controls whether the window can receive focus. If `true`, the window can be selected and interacted with; if `false`, it remains unfocused and ignores user input. ### `shouldFullscreenable` The `shouldFullscreenable` property specifies whether the window can enter fullscreen mode. When set to `true`, users can toggle fullscreen, providing a distraction-free experience. ### `shouldRestoreState` The `shouldRestoreState` property determines whether the window should remember its last position and size between sessions. If `true`, the application restores the previous window state on launch, enhancing user continuity. ## Window Colors `windowColors` The `windowColors` property allows you to define default colors for the application window based on the operating system’s theme. ### `dark` The `dark` field specifies the window color when the OS is in **dark mode**. This ensures that the application visually matches the user’s system theme and maintains readability and aesthetic consistency. ### `light` The `light` field defines the window color when the OS is in **light mode**. Using this color ensures that the window blends seamlessly with the system’s light theme, providing a cohesive user experience. ## External Links `externalLinks` The `externalLinks` property controls how links that lead outside the application are handled. ### `shouldOpenNonAppLinksExternally` The `shouldOpenNonAppLinksExternally` field, when set to `true`, ensures that any link not part of the Native Desktop application opens in the user’s default web browser instead of within the app window. This prevents unexpected navigation inside the application and maintains a clear separation between internal and external content. ## HTML Pages `htmlPages` The `htmlPages` property defines custom HTML pages that the application can display in specific states. Each file path should be defined as an array of folder names ending with the file name, for example: `['folder', 'sub-folder', 'splash.html']`. For each HTML page used by the application, **specific file names are recognized automatically**. If the HTML files match these names, Native Desktop will identify and use them correctly without additional configuration. The recognized files are: * `splash-screen.html`: used for the loading state of the application. * `not-allowed.html`: displayed when a requested page cannot be loaded or is not allowed. * `offline.html`: shown when the application is offline or cannot access the internet. Using these specific file names ensures that the application correctly handles different runtime states automatically. ### `splashScreen` The `splashScreen` field specifies the HTML page shown during the **loading state** of the application. These page appear while the main content is initializing, providing visual feedback to the user. ### `offline` The `offline` field defines the HTML page displayed when the application detects **no internet connection**. This allows you to show a user-friendly offline message or interface. File path follow the same array structure as other HTML pages. ### `httpNotAllowed` The `httpNotAllowed` field specifies the HTML page shown when a requested page **cannot be loaded**. This ensures users receive clear feedback when navigation fails. File path must also be defined as arrays of folder names ending with the file name. ## Plugins `plugins` The `plugins` field is a string path array that allows you to define custom plugins for your application. Each entry must point to the **compiled JavaScript file**, not the original TypeScript source. For example, if your plugin source is located at `/src/plugin.ts` and it compiles to `runtime/plugin.js`, you should set the path as: ```json theme={null} [ ['runtime'], ['plugin.js'] // Path is runtime/plugin.js ] ``` This ensures that the Native Desktop framework loads the correct runtime files for your plugins. ## Renderer Plugins `rendererPlugins` The `prendererPlugins` field is a string path array that allows you to define custom renderer plugins for your application. Each entry must point to the **compiled JavaScript file**, not the original TypeScript source. For example, if your plugin source is located at `/src/rendererPlugin.ts` and it compiles to `runtime/rendererPlugin.js`, you should set the path as: ```json theme={null} [ ['runtime'], ['rendererPlugin.js'] // Path is runtime/rendererPlugin.js ] ``` This ensures that the Native Desktop framework loads the correct runtime files for your plugins. ## Development `development` The `development` field provides options specifically for **development mode**. ### `shouldOpenDevToolsWhenRun` The `shouldOpenDevToolsWhenRun` property, when set to `true`, automatically opens the browser or Electron **developer tools** each time the application starts. This is useful for debugging, inspecting elements, and monitoring console output during development. It should generally be disabled in production builds to prevent exposing developer tools to end users. ## HighRisk `highRisk` The `highRisk` field contains settings that can impact application security and stability. These options should be used **with caution** and are generally intended for advanced scenarios or trusted environments. ### `shouldLoadHTTPDomains` The `shouldLoadHTTPDomains` property, when set to `true`, allows the application to load content over **insecure HTTP** connections. This can be useful for testing or internal sites but may expose users to security risks. ### `shouldEnableWebSecurity` The `shouldEnableWebSecurity` property controls the browser’s security policies. If set to `false`, standard web security restrictions (such as same-origin policy) are disabled, which can be useful for development but is unsafe for production. ### `shouldAllowRunningInsecureContent` The `shouldAllowRunningInsecureContent` property permits the execution of **mixed content**, such as scripts or resources loaded over HTTP within an HTTPS page. Enabling this can compromise security, so it should only be used in controlled environments. ### `shouldEnableExperimentalFeatures` The `shouldEnableExperimentalFeatures` property activates **experimental Electron / browser features** that may not be stable or fully supported. This allows testing of new APIs but may introduce unpredictable behavior in the application. # Native Desktop Framework Source: https://docs.nativedesktop.com/native-desktop/user-guide/native-desktop-framework/introduction The **Native Desktop Framework** is published on npm as the `@native-desktop/app` package. You do not need to install it manually, the **Native Desktop CLI** automatically manages all setup and operations related to this package. The framework consists of three main components: 1. **Configuration File**: Defines project structure, runtime settings, and build behavior. 2. **Plugin System**: Extends core functionality with custom logic, integrations, and runtime hooks. 3. **IPC Commands**: Inter-Process Communication (IPC) commands refer to the methods and events used to facilitate communication between the main process and renderer processes. Electron's architecture separates the application's backend logic (main process) from its user interface (renderer processes), and IPC provides the necessary mechanism for these processes to interact. These components work together to provide a flexible and maintainable environment for building Native Desktop-based desktop applications. # IPC Commands Source: https://docs.nativedesktop.com/native-desktop/user-guide/native-desktop-framework/ipc-commands In Electron, Inter-Process Communication (IPC) is crucial for enabling communication between the main process and renderer processes. This is because they operate in separate environments with different responsibilities. Native Desktop provides a set of **built-in IPC channels** for interacting with the desktop application. These IPCs allow you to get or set various aspects of the application and its environment. * `nativeDesktopVersion`: Retrieve version information of the Native Desktop framework. * `nativeDesktopApp`: Get or set application-specific details. * `nativeDesktopWindow`: Get or set properties of the application window. * `nativeDesktopNavigation`: Get or set navigation-related details within the app. * `nativeDesktopNotification`: Set notification messages and properties. * `nativeDesktopNetwork`: Set network-related configurations and behaviors. The details for each IPC are explained in the following section: # Main Plugins Source: https://docs.nativedesktop.com/native-desktop/user-guide/native-desktop-framework/main-plugins **Main plugins** allow you to customize, extend, or enhance the **main process** of the Native Desktop application. These plugins have full access to the **Electron API**, enabling you to add new capabilities or modify existing behavior. Each main plugin must follow a specific structure: ```typescript theme={null} import { App } from 'electron'; const plugin = { init: (nativeDesktopApp: App) => { // Your main process logic here }, }; export default plugin; ``` When the file follows this structure, Native Desktop will automatically **identify and inject the plugin** into the main process. There is no limit to the number of plugins you can create. **Main plugins** operate on the **backend side** of the Native Desktop application and run within the main process. They **do not have direct access to the web view**. To interact with the frontend or web view, you must create **renderer plugins**, which are specifically designed for the renderer proces Here is a sample main plugin example. In this example, a new window is created whenever the main window is initialized: ```typescript theme={null} import { BrowserWindow, App } from 'electron'; const plugin = { init: (nativeDesktopApp: App) => { nativeDesktopApp.whenReady().then(() => { const mainWindow = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true, contextIsolation: false, }, show: true, }); mainWindow.loadURL('data:text/html;charset=utf-8,' + encodeURIComponent('

Hello from Main Plugin!

This window was created by your plugin.

') ); mainWindow.webContents.openDevTools(); console.log('Window created and visible.'); }); nativeDesktopApp.on('window-all-closed', () => { if (process.platform !== 'darwin') { nativeDesktopApp.quit(); } }); }, }; export default plugin; ``` This approach allows developers to extend the core Native Desktop functionality safely and efficiently. # Renderer Plugins Source: https://docs.nativedesktop.com/native-desktop/user-guide/native-desktop-framework/renderer-plugins **Renderer plugins** are used to interact with the **web view or frontend** of your Native Desktop application. They also support **Electron APIs**, allowing you to add new functionality or modify existing behavior in the renderer process. Each renderer plugin must follow a specific structure: ```typescript theme={null} import type { IpcRenderer } from 'electron'; const plugin = { init: (nativeDesktopIpcRenderer: IpcRenderer) => { // Your renderer logic here }, }; export default plugin; ``` When a file follows this structure, Native Desktop automatically **detects and injects the plugin** into the renderer process. Here is a simple example demonstrating a console log. When the application runs, the message will appear in the web browser console: ```typescript theme={null} import type { IpcRenderer } from 'electron'; const plugin = { init: (nativeDesktopIpcRenderer: IpcRenderer) => { console.log('Renderer plugin initialized:', nativeDesktopIpcRenderer); }, }; export default plugin; ``` This structure allows developers to safely extend and customize frontend behavior while maintaining integration with Electron. # React Components Source: https://docs.nativedesktop.com/native-desktop/user-guide/react-components/introduction React components in Native Desktop are not tightly coupled with the core framework but are designed to help you **customize and enhance your application's user interface**. At the moment, the **Title Bar component** is the only available component, allowing you to create a **custom, theme-friendly title bar** that seamlessly matches your application's design and branding. # Install Package To use Native Desktop React components, first install the package using npm: ```shellscript theme={null} npm install @native-desktop/react ``` After installation, you can import and use the components in your React application: ```typescript theme={null} import { NativeDesktopTitleBar } from '@native-desktop/react'; const CustomTitleBar = () => { return ; } ``` # Title Bar Component Source: https://docs.nativedesktop.com/native-desktop/user-guide/react-components/title-bar The `NativeDesktopTitleBar` component provides a fully customizable, draggable title bar designed for **Electron-based Native Desktop applications**. It allows developers to replace the default OS title bar with a **custom React-driven UI**, giving full control over layout, styling, and interactivity. # Overview `NativeDesktopTitleBar` is a React component that renders a flexible container at the top of the application window. It supports **custom alignment**, **dynamic visibility**, and **drag regions** that integrate with Electron’s window controls (e.g., drag, maximize, unmaximize). It does **not rely on any external CSS files**, all styles are inline and customizable via props. ## Key Features * **Draggable region** support using `WebkitAppRegion` for Electron windows. * **Fully customizable layout** via `contentAlignment`, padding, height, and inline styles. * **Composable components array**, render any React elements (buttons, titles, icons, menus, etc.) inside the title bar. * **Visibility control** for both the entire title bar and individual components. * **Double-click maximize/unmaximize** behavior, mimicking native window behavior. ## Usage Example ```typescript theme={null} import { NativeDesktopTitleBar, ContentAlignment } from '@native-desktop/react'; import { MyWindowControls } from './MyWindowControls'; import { AppLogo } from './AppLogo'; export const MyAppTitleBar = () => ( , isDragable: false, }, { id: 'right', component: , isDragable: false, }, ]} /> ); ``` # Titlebar Component ## Props | Prop | Type | Default | Description | | :----------------- | :------------------ | :-------------- | :------------------------------------------------------------------- | | `id` | `string` | — | Optional ID for the title bar. | | `components` | `TComponent[]` | `[]` | Array of components (React elements) to render inside the title bar. | | `contentAlignment` | `TContentAlignment` | `SPACE_BETWEEN` | Determines how components are aligned within the container. | | `height` | `number` | `32` | Height of the title bar in pixels. | | `inlinePadding` | `number` | `8` | Horizontal padding (left and right). | | `blockPadding` | `number` | `0` | Vertical padding (top and bottom). | | `className` | `string` | `''` | Optional custom class name. | | `style` | `CSSProperties` | `{}` | Inline style overrides for the container. | | `isDragable` | `boolean` | `true` | Enables dragging of the entire title bar area. | | `isVisible` | `boolean` | `true` | Controls visibility of the entire title bar. | ## Component Types Each component object inside the `components` array defines what to render and how it behaves. | Field | Type | Default | Description | | | :----------- | :-------------- | :------------ | :------------------------------------------------- | ------------------------------------------------------- | | `id` | \`string | number\` | — | Optional unique identifier. | | `component` | \`ReactNode | JSX.Element\` | — | The React element to render (e.g., icon, button, text). | | `className` | `string` | — | Optional class name for the wrapper div. | | | `style` | `CSSProperties` | `{}` | Inline style for the wrapper div. | | | `isDragable` | `boolean` | `true` | Whether this component region should be draggable. | | | `isVisible` | `boolean` | `true` | Controls visibility of this specific component. | | ## Content Alignment Options The `contentAlignment` prop controls horizontal positioning of child components. | Alignment | CSS Equivalent | Description | | :-------------- | :-------------- | :------------------------------------------------------- | | `LEFT` | `flex-start` | Align items to the left. | | `RIGHT` | `flex-end` | Align items to the right. | | `CENTER` | `center` | Center all items horizontally. | | `SPACE_BETWEEN` | `space-between` | Evenly distribute items, first at start and last at end. | | `SPACE_AROUND` | `space-around` | Even spacing around all items. | | `SPACE_EVENLY` | `space-evenly` | Equal spacing between and around all items. | # Notes * The title bar is rendered as a **fixed element** positioned at the top of the viewport. * The container has a default background color of **red** — intended for debugging. You should override it using the `style` prop. * For best results, combine with Electron’s frameless window mode. # Developer Notes ## Design Philosophy * The component is **style-agnostic**, no CSS or theme dependency. * Built for **Electron environments only**, where frameless windows require custom drag and control logic. * Uses **flexbox layout** for predictable alignment and composability. ## Drag Region Behavior * Setting `WebkitAppRegion: drag` makes an area draggable by Native Desktop. * **MacOS and Windows handle drag regions slightly differently**: * On **macOS**, buttons near the top-left may interfere with draggable areas; ensure custom buttons are within `no-drag` zones. * On **Windows**, draggable areas may overlap invisible hitboxes if padding or overlapping elements are misaligned. Always mark interactive elements (buttons, menus) as `isDragable: false`. ## Window Events * Double-clicking toggles maximize/unmaximize via `window.nativeDesktopWindow`. * Developers can disable this behavior by removing or replacing the event listener. ## Performance & Rendering * The component uses **inline styles** to avoid runtime stylesheet loading. * Recommended for small, lightweight render trees (\<10 child components). * Since it’s fixed-positioned, it won’t reflow with other layout changes. ## Accessibility * The component itself doesn’t handle focus, keyboard navigation, or ARIA roles yet. * If accessibility is a priority, wrap internal components (like buttons or menus) with proper roles and keyboard handlers.