R/run.R

Defines functions run_electron_app

Documented in run_electron_app

#' Run Electron Application for Testing
#'
#' Launches a previously exported Electron application for testing and debugging
#' without building distributable packages. Pass the `electron-app` directory
#' from a prior `export()` call.
#'
#' @param app_dir Character string. Path to the Electron application directory
#'   (the `electron-app` subdirectory from `export()`).
#' @param port Integer. Port number for the development server. Default is 3000.
#' @param open_devtools Logical. Whether to open Chromium DevTools automatically. Default is TRUE.
#' @param verbose Logical. Whether to display detailed progress information. Default is TRUE.
#' @param update_version Character string or `NULL`. A version such as
#'   `"2.0.0"` runs the app against a local update feed offering that version,
#'   so the update check can be tried without publishing a release. The app
#'   must have been exported with auto-updates on (see [enable_auto_updates()])
#'   by this version of shinyelectron. Download is expected to fail, because
#'   the feed holds no installer. On macOS only the startup notice shows the
#'   result, so the app must check on startup (`check_on_startup`, the
#'   default), since Help > About has no Check for Updates there. Default is
#'   `NULL`, a normal run.
#'
#' @return Invisibly returns the completed `processx::run()` result list
#'   (with `status`, `stdout`, and `stderr`) after Electron exits, or `NULL`
#'   if the run is interrupted. Note that this call blocks until the Electron
#'   window is closed.
#'
#' @section Details:
#' This function starts the Electron application for testing, which:
#' \itemize{
#'   \item Opens the application in an Electron window
#'   \item Optionally opens Chromium DevTools for debugging
#'   \item Does NOT build distributable packages (use `export(build = TRUE)` for that)
#'   \item With `update_version`, serves a local update feed on `127.0.0.1` and
#'     writes `dev-app-update.yml` into `app_dir` for the run, then stops the
#'     feed and removes the file when the run ends, even after an error or
#'     Ctrl+C
#' }
#'
#' @examplesIf interactive()
#' # Run a previously exported Electron app in development mode
#' run_electron_app("path/to/electron/app")
#'
#' # Run with custom port and no dev tools
#' run_electron_app(
#'   app_dir = "path/to/app",
#'   port = 8080,
#'   open_devtools = FALSE
#' )
#'
#' # Try the update check against a local feed offering version 2.0.0
#' run_electron_app("path/to/electron/app", update_version = "2.0.0")
#'
#' @export
run_electron_app <- function(app_dir, port = 3000, open_devtools = TRUE, verbose = TRUE,
                             update_version = NULL) {

  # Validate inputs
  validate_directory_exists(app_dir, "Electron application directory")
  validate_electron_project(app_dir)
  validate_port(port)
  if (!is.null(update_version)) {
    check_update_version(update_version)
  }

  if (verbose) {
    cli::cli_h1("Running Electron application in development mode")
    cli::cli_alert_info("App directory: {.path {app_dir}}")
    cli::cli_alert_info("Port: {.val {port}}")
    cli::cli_alert_info("Developer tools: {.val {if(open_devtools) 'enabled' else 'disabled'}}")
  }

  # Validate npm/node availability
  validate_node_npm()

  # Check if package.json exists and has necessary scripts
  package_json_path <- fs::path(app_dir, "package.json")
  if (!fs::file_exists(package_json_path)) {
    cli::cli_abort(c(
      "No {.file package.json} found in {.path {app_dir}}",
      "i" = "Run {.code export()} first to build the Electron project"
    ))
  }

  package_json <- jsonlite::fromJSON(package_json_path, simplifyVector = FALSE)
  if (is.null(package_json$scripts$electron)) {
    cli::cli_abort(c(
      "No {.val electron} script in {.file {package_json_path}}",
      "i" = "Add one under {.field scripts}: {.code \"electron\": \"electron .\"}",
      "i" = "Or re-run {.code export()} to regenerate {.file package.json}"
    ))
  }
  if (!is.null(update_version)) {
    check_updates_exported(package_json, app_dir)
  }

  # Set environment variables
  old_env <- set_dev_environment(port, open_devtools)
  on.exit(restore_environment(old_env), add = TRUE)

  if (is.null(update_version)) {
    # A run that could not clean up may have left its feed config behind.
    remove_dev_update_config(app_dir)
  } else {
    # The teardown is registered first, so an error or Ctrl+C while the feed
    # starts still undoes what was set up. `feed` holds the server's process,
    # which ends the server if collected, so it stays here until the run ends.
    feed <- NULL
    on.exit(stop_update_feed(feed), add = TRUE)
    feed <- start_update_feed(app_dir, update_version, package_json$name)
    if (verbose) {
      cli::cli_alert_info("Offering version {.val {update_version}} from a local update feed at {.url {feed$server$url}}")
    }
  }

  if (verbose) {
    cli::cli_alert_info("Starting Electron application...")
    cli::cli_alert_info("Press Ctrl+C to stop the application")
  }

  # Only the run itself is wrapped, so the exit-status check below produces its
  # own clean error rather than being re-wrapped by this handler.
  result <- tryCatch(
    processx::run(
      command = get_npm_command(),
      args = c("run", "electron"),
      env = nodejs_subprocess_env(),
      wd = app_dir,
      echo = verbose,
      echo_cmd = verbose,
      spinner = verbose,
      error_on_status = FALSE
    ),
    interrupt = function(int) {
      if (verbose) {
        cli::cli_alert_info("Stopping Electron application...")
      }
      NULL
    },
    error = function(e) {
      cli::cli_abort(c(
        "Failed to run Electron application",
        "x" = "Error: {conditionMessage(e)}"
      ), parent = e)
    }
  )

  # NULL means the run was interrupted (Ctrl+C).
  if (is.null(result)) {
    return(invisible(NULL))
  }

  if (result$status != 0) {
    cli::cli_abort(c(
      "Failed to start Electron application",
      "x" = "Exit code: {result$status}",
      "i" = "stderr: {result$stderr}"
    ))
  }

  if (verbose) {
    cli::cli_alert_success("Electron application started successfully")
  }

  invisible(result)
}

Try the shinyelectron package in your browser

Any scripts or data that you put into this service are public.

shinyelectron documentation built on Dec. 3, 2026, 9:07 a.m.