R/config.R

Defines functions resolve_brand_palette read_brand_yml show_config validate_config_file init_config lifecycle_timeout is_timeout_ms check_logical_settings validate_config merge_config_deep resolve_installer_license is_named_list collect_unknown_config_keys config_schema map_logging_config read_config find_config default_config

Documented in check_logical_settings collect_unknown_config_keys config_schema default_config find_config init_config is_named_list is_timeout_ms lifecycle_timeout map_logging_config merge_config_deep read_brand_yml read_config resolve_brand_palette resolve_installer_license show_config validate_config validate_config_file

#' Configuration file name
#' @keywords internal
CONFIG_FILENAME <- "_shinyelectron.yml"

#' Get default configuration values
#'
#' Returns the default configuration used when no config file exists
#' or for values not specified in the config file.
#'
#' @return List of default configuration values
#' @keywords internal
default_config <- function() {
  list(
    app = list(
      name = NULL,
      slug = NULL,
      version = SHINYELECTRON_DEFAULTS$app_version,
      description = NULL,
      author = NULL,
      homepage = NULL,
      copyright = NULL,
      log_dir = SHINYELECTRON_DEFAULTS$logging$log_dir,
      log_level = SHINYELECTRON_DEFAULTS$logging$log_level
    ),
    build = list(
      type = NULL,
      runtime_strategy = NULL,
      platforms = NULL,
      architectures = NULL
    ),
    window = list(
      width = SHINYELECTRON_DEFAULTS$window_width,
      height = SHINYELECTRON_DEFAULTS$window_height
    ),
    server = list(
      port = SHINYELECTRON_DEFAULTS$server_port
    ),
    icons = list(
      mac = NULL,
      win = NULL,
      linux = NULL
    ),
    nodejs = list(
      version = NULL
    ),
    dependencies = SHINYELECTRON_DEFAULTS$dependencies,
    container = SHINYELECTRON_DEFAULTS$container,
    # New feature configurations
    splash = SHINYELECTRON_DEFAULTS$splash,
    tray = SHINYELECTRON_DEFAULTS$tray,
    menu = SHINYELECTRON_DEFAULTS$menu,
    updates = SHINYELECTRON_DEFAULTS$updates,
    preloader = SHINYELECTRON_DEFAULTS$preloader,
    signing = SHINYELECTRON_DEFAULTS$signing,
    lifecycle = SHINYELECTRON_DEFAULTS$lifecycle,
    installer = SHINYELECTRON_DEFAULTS$installer
  )
}

#' Find configuration file
#'
#' Searches for _shinyelectron.yml in the given directory.
#'
#' @param appdir Character path to app directory
#' @return Character path to config file, or NULL if not found
#' @keywords internal
find_config <- function(appdir) {
  config_path <- fs::path(appdir, CONFIG_FILENAME)

  if (fs::file_exists(config_path)) {
    return(config_path)
  }

  NULL
}

#' Read configuration file
#'
#' Reads and parses _shinyelectron.yml from the app directory.
#' If the file doesn't exist, returns default configuration.
#'
#' @param appdir Character path to app directory
#' @return List of configuration values (merged with defaults)
#' @keywords internal
read_config <- function(appdir) {
  config_path <- find_config(appdir)

  if (is.null(config_path)) {
    return(default_config())
  }

  # Only the YAML parse itself is treated leniently (a genuinely unreadable
  # file falls back to defaults). validate_config() errors -- e.g. a legacy
  # app type combined with a conflicting runtime strategy -- are allowed to
  # surface with their specific, actionable message instead of being masked
  # as "Failed to parse" and silently replaced with defaults.
  config <- tryCatch(
    yaml::read_yaml(config_path),
    error = function(e) {
      cli::cli_warn(c(
        "Failed to parse configuration file: {.path {config_path}}",
        "i" = "Error: {conditionMessage(e)}",
        "i" = "Using default configuration"
      ))
      NULL
    }
  )
  if (is.null(config)) {
    return(default_config())
  }

  # Map logging: onto app.log_* on the raw YAML, before the merge fills in
  # defaults, so that only values written in the file count as set.
  config <- map_logging_config(config)

  unknown_keys <- collect_unknown_config_keys(config)
  if (length(unknown_keys) > 0) {
    cli::cli_warn(c(
      "Unknown configuration {cli::qty(unknown_keys)}key{?s} in {.file {CONFIG_FILENAME}}: {.val {unknown_keys}}",
      "i" = "Unknown keys are ignored. Check their spelling and nesting against {.url https://r-pkg.thecoatlessprofessor.com/shinyelectron/articles/configuration.html}."
    ), class = "shinyelectron_unknown_config_key", keys = unknown_keys)
  }

  merged <- merge_config_deep(default_config(), config)
  validate_config(merged)
}

#' Map the logging section onto the app section
#'
#' `_shinyelectron.yml` documents the log settings under a top-level
#' `logging:` section, while the build reads them from `app.log_dir` and
#' `app.log_level`, which the file may also set directly. This copies
#' `logging.log_dir` and `logging.log_level` into `app` on the parsed YAML,
#' before [merge_config_deep()] fills in the defaults. When both spellings set
#' a field to different values, the `logging` value wins and a warning of
#' class `shinyelectron_logging_conflict` names the field. Any other key under
#' `logging` stays in place so that [collect_unknown_config_keys()] reports it.
#' A `logging` value that is not a map, such as `logging: debug` or a list, is
#' dropped with a warning of class `shinyelectron_invalid_logging_section`.
#'
#' @param config List. User configuration parsed from the YAML file.
#' @return `config` with the `logging` fields moved into `app`.
#' @keywords internal
map_logging_config <- function(config) {
  if (!is.list(config) || is.null(config[["logging"]])) {
    return(config)
  }
  logging <- config[["logging"]]
  if (!is.list(logging) || (length(logging) > 0 && is.null(names(logging)))) {
    cli::cli_warn(c(
      "{.field logging} in {.file {CONFIG_FILENAME}} must be a map, not {.obj_type_friendly {logging}}, so it is ignored.",
      "i" = "Put each setting on its own indented line under {.field logging}, such as {.code log_level: debug}."
    ), class = "shinyelectron_invalid_logging_section")
    config[["logging"]] <- NULL
    return(config)
  }
  app <- config[["app"]]
  if (!(is.null(app) || is.list(app))) {
    return(config)
  }

  for (field in names(SHINYELECTRON_DEFAULTS$logging)) {
    value <- logging[[field]]
    logging[[field]] <- NULL
    if (is.null(value)) next
    if (!is.null(app[[field]]) && !identical(app[[field]], value)) {
      cli::cli_warn(c(
        "{.field logging.{field}} and {.field app.{field}} are both set in {.file {CONFIG_FILENAME}}.",
        "i" = "Using the {.field logging} value {.val {value}}."
      ), class = "shinyelectron_logging_conflict")
    }
    app[[field]] <- value
  }

  if (!is.null(app)) config[["app"]] <- app
  config[["logging"]] <- if (length(logging) > 0) logging
  config
}

#' Configuration keys accepted in _shinyelectron.yml
#'
#' The keys of [default_config()] plus the top-level keys that have no
#' default: the `icon` shortcut, the multi-app `apps` list and the `logging`
#' section that [map_logging_config()] maps onto `app.log_dir` and
#' `app.log_level`.
#'
#' @return Named list shaped like [default_config()].
#' @keywords internal
config_schema <- function() {
  c(default_config(), list(
    icon = NULL,
    apps = list(),
    logging = SHINYELECTRON_DEFAULTS$logging
  ))
}

#' Collect unknown configuration keys
#'
#' Compares the keys in the config file against the accepted keys
#' ([config_schema()]) and returns the dotted paths of any key that would
#' otherwise be silently ignored. It descends only where both the config
#' value and the default are named lists, the rule [merge_config_deep()] uses,
#' so a value that the merge takes whole is not inspected: free-form maps
#' (`container.volumes`, `container.env`), values whose default is a list
#' (`dependencies.r.repos`), the entries of the multi-app `apps` list and the
#' top-level `icon` shortcut.
#'
#' @param config List. User configuration parsed from the YAML file.
#' @param defaults List. Schema to compare against (defaults to the full schema).
#' @param path Character vector. Internal recursion path.
#' @return Character vector of unknown dotted key paths (possibly empty).
#' @keywords internal
collect_unknown_config_keys <- function(config, defaults = config_schema(),
                                        path = character(0)) {
  if (!is.list(config) || is.null(names(config))) {
    return(character(0))
  }
  unknown <- character(0)
  for (name in names(config)) {
    full <- c(path, name)
    if (!name %in% names(defaults)) {
      unknown <- c(unknown, paste(full, collapse = "."))
    } else if (is_named_list(config[[name]]) &&
               is_named_list(defaults[[name]])) {
      unknown <- c(unknown, collect_unknown_config_keys(config[[name]], defaults[[name]], full))
    }
  }
  unknown
}

#' Test for a map-like list
#'
#' `TRUE` for a list whose elements all have non-empty names, the shape YAML
#' gives a mapping. YAML sequences, scalars and lists with an unnamed element
#' are not map-like.
#'
#' @param x Object to test.
#' @return A single logical.
#' @keywords internal
is_named_list <- function(x) {
  is.list(x) && !is.null(names(x)) && all(nzchar(names(x)))
}

#' Resolve the Windows installer license against the app directory
#'
#' `installer.license_file` is written relative to the app directory, while
#' electron-builder runs inside the generated Electron project. Resolving the
#' path up front lets the build copy the file into the project, and stops on
#' a missing file before any runtime is downloaded.
#'
#' @param config List. The effective configuration.
#' @param appdir Character. The app directory the configuration was read from.
#' @return `config`, with `installer$license_file` made absolute when it is set.
#' @keywords internal
resolve_installer_license <- function(config, appdir) {
  license_file <- config$installer$license_file
  if (is.null(license_file)) {
    return(config)
  }
  if (!is.character(license_file) || length(license_file) != 1L ||
      is.na(license_file) || !nzchar(license_file)) {
    cli::cli_abort(c(
      "Invalid {.field installer.license_file} in config: {.val {license_file}}",
      "i" = "Must be the path to a license file, relative to the app directory",
      "i" = "Edit {.field installer.license_file} in {.file _shinyelectron.yml}"
    ))
  }

  path <- fs::path_expand(license_file)
  if (!fs::is_absolute_path(path)) {
    path <- fs::path(appdir, path)
  }
  if (!fs::is_file(path)) {
    cli::cli_abort(c(
      "License file not found: {.path {path}}",
      "i" = "{.field installer.license_file} is resolved relative to the app directory",
      "i" = "Edit {.field installer.license_file} in {.file _shinyelectron.yml}"
    ))
  }

  config$installer$license_file <- as.character(fs::path_abs(path))
  config
}

#' Deep merge two lists
#'
#' Recursively merges config into defaults, where config values override defaults.
#'
#' @param defaults List of default values
#' @param config List of config values to merge
#' @return Merged list
#' @keywords internal
merge_config_deep <- function(defaults, config) {
  if (is.null(config)) {
    return(defaults)
  }

  # Only recurse into map-like (fully named) lists, as tested by
  # is_named_list(). Unnamed YAML sequences (repos, index_urls, package lists)
  # and scalars must override the default wholesale; recursing into them would
  # iterate an empty `names()` and silently return the default, discarding the
  # user's value.
  result <- defaults

  for (name in names(config)) {
    if (name %in% names(defaults) &&
        is_named_list(defaults[[name]]) &&
        is_named_list(config[[name]])) {
      result[[name]] <- merge_config_deep(defaults[[name]], config[[name]])
    } else {
      result[[name]] <- config[[name]]
    }
  }

  result
}

#' Validate configuration values
#'
#' Checks configuration values and warns about invalid entries. The Windows
#' installer flags are read with [config_flag()]: a quoted `"true"` or
#' `"false"` is used with a warning, but any other invalid value aborts, as
#' does `installer.allow_to_change_installation_directory: true` without
#' `installer.one_click: false`, because falling back to a default would
#' build a different installer than the one requested. The other settings
#' that take only true or false abort on anything else, a quoted value
#' included (see [check_logical_settings()]).
#'
#' @param config List of configuration values
#' @return List of validated configuration
#' @keywords internal
validate_config <- function(config) {
  # Use centralized constants
  valid_types <- SHINYELECTRON_DEFAULTS$valid_app_types
  valid_platforms <- SHINYELECTRON_DEFAULTS$valid_platforms
  valid_arch <- SHINYELECTRON_DEFAULTS$valid_architectures

  # Stop on a true/false setting that holds anything else, before the checks
  # below read one of them.
  check_logical_settings(config)

  # Normalize legacy build.type values first (emits deprecation warning).
  if (!is.null(config$build$type) &&
      config$build$type %in% c("r-shinylive", "py-shinylive")) {
    legacy_normalized <- normalize_app_type_arg(
      config$build$type, config$build$runtime_strategy
    )
    config$build$type <- legacy_normalized$app_type
    config$build$runtime_strategy <- config$build$runtime_strategy %||% legacy_normalized$runtime_strategy
  }

  # Validate build type against the canonical set.
  if (!is.null(config$build$type) && !config$build$type %in% valid_types) {
    cli::cli_warn(c(
      "Invalid build type in config: {.val {config$build$type}}",
      "i" = "Valid types: {.val {valid_types}}",
      "i" = "Falling back to autodetection"
    ))
    config$build$type <- NULL
  }

  # Validate runtime strategy against the canonical set. An invalid value in
  # the config file warns and falls back to the default rather than aborting
  # the build later (an explicit runtime_strategy = argument is still strict).
  valid_strategies <- SHINYELECTRON_DEFAULTS$valid_runtime_strategies
  if (!is.null(config$build$runtime_strategy) &&
      !config$build$runtime_strategy %in% valid_strategies) {
    cli::cli_warn(c(
      "Invalid runtime_strategy in config: {.val {config$build$runtime_strategy}}",
      "i" = "Valid strategies: {.val {valid_strategies}}",
      "i" = "Falling back to {.val shinylive}"
    ))
    config$build$runtime_strategy <- NULL
  }

  # Validate platforms and architectures, the targets export() builds for.
  # Invalid entries are dropped with a warning and the rest kept once each,
  # as a character vector. A list with nothing left counts as unset, so
  # export() builds for the current platform or architecture rather than for
  # none.
  targets <- list(
    platforms = list(valid = valid_platforms, what = "platform"),
    architectures = list(valid = valid_arch, what = "architecture")
  )
  for (key in names(targets)) {
    values <- config$build[[key]]
    if (is.null(values)) next
    valid <- targets[[key]]$valid
    what <- targets[[key]]$what
    ok <- values %in% valid
    if (!all(ok)) {
      cli::cli_warn(c(
        "Invalid {what}(s) in config: {.val {values[!ok]}}",
        "i" = "Valid {what}s: {.val {valid}}",
        "i" = if (!any(ok)) "Falling back to the current {what}"
      ))
    }
    values <- unique(as.character(unlist(values[ok], use.names = FALSE)))
    config$build[[key]] <- if (length(values) > 0) values
  }

  # Validate window dimensions using centralized defaults
  default_width <- SHINYELECTRON_DEFAULTS$window_width
  default_height <- SHINYELECTRON_DEFAULTS$window_height

  if (!is.null(config$window$width) && (
      !is.numeric(config$window$width) ||
      length(config$window$width) != 1 ||
      config$window$width < 100
  )) {
    cli::cli_warn(c(
      "Invalid {.field window.width} in config: {.val {config$window$width}}",
      "i" = "Must be a single number >= 100; using default: {.val {default_width}}",
      "i" = "Edit {.field window.width} in {.file _shinyelectron.yml}"
    ))
    config$window$width <- default_width
  }
  if (!is.null(config$window$height) && (
      !is.numeric(config$window$height) ||
      length(config$window$height) != 1 ||
      config$window$height < 100
  )) {
    cli::cli_warn(c(
      "Invalid {.field window.height} in config: {.val {config$window$height}}",
      "i" = "Must be a single number >= 100; using default: {.val {default_height}}",
      "i" = "Edit {.field window.height} in {.file _shinyelectron.yml}"
    ))
    config$window$height <- default_height
  }

  # Validate port using centralized default
  default_port <- SHINYELECTRON_DEFAULTS$server_port
  if (!is.null(config$server$port)) {
    if (!is.numeric(config$server$port) || length(config$server$port) != 1 ||
        config$server$port < 1 || config$server$port > 65535) {
      cli::cli_warn(c(
        "Invalid {.field server.port} in config: {.val {config$server$port}}",
        "i" = "Must be a single integer between 1 and 65535; using default: {.val {default_port}}",
        "i" = "Edit {.field server.port} in {.file _shinyelectron.yml}"
      ))
      config$server$port <- default_port
    }
  }

  # Validate splash settings
  if (!is.null(config$splash)) {
    if (!is.null(config$splash$duration) && (!is.numeric(config$splash$duration) || config$splash$duration < 0)) {
      cli::cli_warn(c(
        "Invalid {.field splash.duration} in config: {.val {config$splash$duration}}",
        "i" = "Must be a non-negative number (milliseconds); using default: {.val {SHINYELECTRON_DEFAULTS$splash$duration}}"
      ))
      config$splash$duration <- SHINYELECTRON_DEFAULTS$splash$duration
    }
  }

  # Validate updates provider
  if (!is.null(config$updates) && !is.null(config$updates$provider)) {
    valid_providers <- c("github", "s3", "generic")
    if (!config$updates$provider %in% valid_providers) {
      cli::cli_warn(c(
        "Invalid updates provider: {.val {config$updates$provider}}",
        "i" = "Valid providers: {.val {valid_providers}}"
      ))
      config$updates$provider <- "github"
    }
  }

  # The generic address and the unsupported S3 provider matter only while
  # updates are on.
  check_update_settings(config)

  # Validate menu template
  if (!is.null(config$menu) && !is.null(config$menu$template)) {
    valid_templates <- c("default", "minimal")
    if (!config$menu$template %in% valid_templates) {
      cli::cli_warn(c(
        "Invalid menu template: {.val {config$menu$template}}",
        "i" = "Valid templates: {.val {valid_templates}}"
      ))
      config$menu$template <- "default"
    }
  }

  # Validate preloader style
  if (!is.null(config$preloader) && !is.null(config$preloader$style)) {
    valid_styles <- c("spinner", "bar", "dots")
    if (!config$preloader$style %in% valid_styles) {
      cli::cli_warn(c(
        "Invalid preloader style: {.val {config$preloader$style}}",
        "i" = "Valid styles: {.val {valid_styles}}"
      ))
      config$preloader$style <- "spinner"
    }
  }

  # Validate container engine against the canonical set. An invalid value in
  # the config file warns and falls back to the default rather than aborting
  # the build later (mirrors the runtime_strategy check above).
  valid_engines <- SHINYELECTRON_DEFAULTS$valid_container_engines
  if (!is.null(config$container) && !is.null(config$container$engine) &&
      !config$container$engine %in% valid_engines) {
    cli::cli_warn(c(
      "Invalid container engine in config: {.val {config$container$engine}}",
      "i" = "Valid engines: {.val {valid_engines}}",
      "i" = "Falling back to the default engine ({.val {SHINYELECTRON_DEFAULTS$container$engine}})"
    ))
    config$container$engine <- NULL
  }

  # Validate lifecycle timeouts. Both are milliseconds, and shutdown_timeout
  # is written into main.js as a JavaScript literal, so a value such as "10s"
  # would stop the app from launching.
  for (key in c("startup_timeout", "shutdown_timeout")) {
    value <- config$lifecycle[[key]]
    if (!is.null(value) && !is_timeout_ms(value)) {
      default_value <- SHINYELECTRON_DEFAULTS$lifecycle[[key]]
      cli::cli_warn(c(
        "Invalid {.field lifecycle.{key}} in config: {.val {value}}",
        "i" = "Must be a whole number of milliseconds between 1000 and 2147483647; using default: {.val {default_value}}",
        "i" = "Edit {.field lifecycle.{key}} in {.file _shinyelectron.yml}"
      ))
      config$lifecycle[[key]] <- default_value
    }
  }

  # Validate dependencies version strings: r, python, electron.
  # Each must be a single character string (e.g. "4.5.1" or "latest") or NULL.
  for (rt in c("r", "python", "electron")) {
    ver <- config$dependencies[[rt]]$version
    if (!is.null(ver) && (!is.character(ver) || length(ver) != 1L)) {
      cli::cli_warn(c(
        "Invalid {.field dependencies.{rt}.version} in config: {.val {ver}}",
        "i" = "Must be a single character string (e.g. {.val \"4.5.1\"}) or {.val \"latest\"}",
        "i" = "Dropping to {.val NULL}"
      ))
      config$dependencies[[rt]]$version <- NULL
    }
  }

  # Normalize dependencies.r.prune to a logical here, so a quoted "true" or
  # "false" warns once when the file is read and later lookups see TRUE or
  # FALSE. Unlike the checks above, any other value aborts rather than falling
  # back to the default, because guessing could remove files the user meant
  # to keep.
  if (!is.null(config$dependencies$r$prune)) {
    config$dependencies$r$prune <- resolve_r_prune(config)
  }

  # Validate dependencies$system_packages: must be a character vector or NULL.
  sp <- config$dependencies$system_packages
  if (!is.null(sp) && !is.character(sp)) {
    cli::cli_warn(c(
      "Invalid {.field dependencies.system_packages} in config",
      "i" = "Must be a character vector of package names (e.g. {.val c(\"libfoo-dev\")})",
      "i" = "Dropping to {.val NULL}"
    ))
    config$dependencies$system_packages <- NULL
  }

  # Read the Windows installer flags with config_flag(): a quoted "true" or
  # "false" becomes the logical with a warning, and any other value aborts.
  # Storing the logicals means build_nsis_config() and the check below never
  # see a string (isTRUE("true") is FALSE, which would silently turn a
  # one-click installer into the wizard), and the warning fires once per read.
  for (key in c("one_click", "allow_to_change_installation_directory",
                "per_machine")) {
    flag <- config_flag(config$installer[[key]], paste0("installer.", key))
    if (!is.null(flag)) {
      config$installer[[key]] <- flag
    }
  }

  # electron-builder only lets the wizard installer change the installation
  # directory, and it rejects the combination only while building the Windows
  # installer, after the runtime download. An unset one_click means one-click.
  if (isTRUE(config$installer$allow_to_change_installation_directory) &&
      !isFALSE(config$installer$one_click)) {
    cli::cli_abort(c(
      "{.field installer.allow_to_change_installation_directory} requires {.field installer.one_click} to be {.code false}",
      "i" = "Only the wizard installer can ask where to install the app",
      "i" = "Set {.field installer.one_click} to {.code false} in {.file _shinyelectron.yml}, or remove {.field installer.allow_to_change_installation_directory}"
    ))
  }

  # YAML reads an unquoted name or slug such as 2048 as a number; read a
  # single number as text. export() checks both values before it builds.
  for (key in c("name", "slug")) {
    value <- config$app[[key]]
    if (is.numeric(value) && length(value) == 1L && !is.na(value)) {
      config$app[[key]] <- format(value, scientific = FALSE, trim = TRUE, digits = 15)
    }
  }

  # Validate the app metadata that fills package.json and the About dialog.
  for (key in c("description", "copyright")) {
    value <- config$app[[key]]
    if (!is.null(value) && !(is.character(value) && length(value) == 1L)) {
      cli::cli_warn(c(
        "Invalid {.field app.{key}} in config",
        "i" = "Must be a single string; ignoring it",
        "i" = "Edit {.field app.{key}} in {.file _shinyelectron.yml}"
      ))
      config$app[[key]] <- NULL
    }
  }

  # app.author is an npm person string or a map. A malformed value is
  # dropped; normalize_app_author() explains why.
  if (!is.null(config$app$author) && is.null(normalize_app_author(config$app$author))) {
    config$app$author <- NULL
  }

  # The About dialog opens app.homepage in the browser, so it must be a web
  # URL. A blank value counts as unset.
  homepage <- config$app$homepage
  homepage_blank <- is.character(homepage) && length(homepage) == 1L &&
    (is.na(homepage) || !nzchar(trimws(homepage)))
  if (!is.null(homepage) && !homepage_blank && !is_http_url(homepage)) {
    cli::cli_abort(c(
      "Invalid {.field app.homepage} in config: it must start with {.val http://} or {.val https://}",
      "x" = if (is.character(homepage) && length(homepage) == 1L) "Found {.val {homepage}}",
      "i" = "Edit {.field app.homepage} in {.file _shinyelectron.yml}"
    ), class = "shinyelectron_invalid_homepage")
  }

  config
}

#' Settings that take only true or false
#'
#' The dotted names of the settings [check_logical_settings()] checks. The
#' Windows installer flags and `dependencies.r.prune` take only true or false
#' as well, but are left out: [config_flag()] reads those, with its own rules.
#'
#' @keywords internal
LOGICAL_SETTINGS <- c(
  "splash.enabled",
  "tray.enabled",
  "tray.minimize_to_tray",
  "tray.close_to_tray",
  "menu.enabled",
  "menu.show_dev_tools",
  "updates.enabled",
  "updates.check_on_startup",
  "updates.auto_download",
  "updates.auto_install",
  "updates.github.private",
  "container.pull_on_start",
  "dependencies.auto_detect",
  "signing.sign",
  "signing.mac.notarize",
  "signing.linux.gpg_sign",
  "lifecycle.show_phase_details",
  "lifecycle.error_show_logs",
  "lifecycle.prompt_before_install",
  "lifecycle.prompt_runtime_version"
)

#' Check the settings that take only true or false
#'
#' Stops when one of the [LOGICAL_SETTINGS] holds anything but a single
#' `TRUE` or `FALSE`: a string, a number, `NA`, a vector longer than one, or a
#' list. A quoted `"yes"` or `"false"` is not read as the value it spells,
#' because the build reads these settings in more than one way: a template
#' renders a section for any non-empty string, while `isTRUE()` is false for
#' one, so a quoted value could turn on only part of a feature. A setting that
#' is absent is fine.
#'
#' @param config List of configuration values.
#' @return `config`, invisibly. Aborts with class
#'   `shinyelectron_invalid_logical_setting`.
#' @keywords internal
check_logical_settings <- function(config) {
  for (field in LOGICAL_SETTINGS) {
    keys <- strsplit(field, ".", fixed = TRUE)[[1]]
    value <- config
    for (key in keys) {
      value <- if (is.list(value)) value[[key]]
    }
    if (is.null(value) || isTRUE(value) || isFALSE(value)) next

    is_single <- is.atomic(value) && length(value) == 1L && !is.na(value)
    what <- if (is_single && is.character(value)) {
      cli::format_inline("the string {.val {value}}")
    } else if (is_single && is.numeric(value)) {
      cli::format_inline("the number {.val {value}}")
    } else {
      cli::format_inline("{.obj_type_friendly {value}}")
    }
    # A quoted value that spells true or false needs only its quotes removed.
    word <- if (is_single && is.character(value)) {
      switch(tolower(trimws(value)),
        "true" = , "yes" = , "on" = "true",
        "false" = , "no" = , "off" = "false"
      )
    }
    name <- keys[length(keys)]
    cli::cli_abort(c(
      "{.field {field}} must be {.code true} or {.code false}, not {what}.",
      "i" = if (is.null(word)) {
        "Write {.code {name}: true} or {.code {name}: false}, or leave the setting out."
      } else {
        "Write it without quotes: {.code {name}: {word}}."
      }
    ), class = "shinyelectron_invalid_logical_setting")
  }
  invisible(config)
}

#' Check a lifecycle timeout value
#'
#' @param x Value to check.
#' @return `TRUE` if `x` is a single whole number of milliseconds between
#'   1000 and 2147483647 (the largest R integer), otherwise `FALSE`.
#' @keywords internal
is_timeout_ms <- function(x) {
  is.numeric(x) && length(x) == 1L && !is.na(x) &&
    x >= 1000 && x <= .Machine$integer.max && x == round(x)
}

#' Look up a lifecycle timeout for the generated app
#'
#' @param config List. Effective configuration.
#' @param key Character. `"startup_timeout"` or `"shutdown_timeout"`.
#' @return Integer milliseconds: the configured value, or the default when it
#'   is missing or invalid (for example a config that skipped
#'   [validate_config()]).
#' @keywords internal
lifecycle_timeout <- function(config, key) {
  value <- config$lifecycle[[key]]
  if (is_timeout_ms(value)) as.integer(value) else SHINYELECTRON_DEFAULTS$lifecycle[[key]]
}

#' Initialize configuration file
#'
#' Creates a template _shinyelectron.yml file in the specified directory.
#'
#' @param appdir Character path to app directory
#' @param app_name Character application name. If NULL, derived from directory name.
#' @param overwrite Logical whether to overwrite existing config. Default FALSE.
#' @param verbose Logical whether to show progress. Default TRUE.
#'
#' @return Invisibly returns the path to the created config file.
#'
#' @seealso [wizard()] for an interactive configuration generator;
#'   [show_config()] to display the merged effective configuration.
#'
#' @examples
#' # Create a config for a temporary app
#' app <- file.path(tempdir(), "init-config-demo")
#' dir.create(app, showWarnings = FALSE)
#' writeLines("library(shiny)", file.path(app, "app.R"))
#' init_config(app, app_name = "My App")
#'
#' @export
init_config <- function(appdir, app_name = NULL, overwrite = FALSE, verbose = TRUE) {
  validate_directory_exists(appdir, "Application directory")

  config_path <- fs::path(appdir, CONFIG_FILENAME)

  if (fs::file_exists(config_path) && !overwrite) {
    cli::cli_abort(c(
      "Configuration file already exists: {.path {config_path}}",
      "i" = "Use {.code overwrite = TRUE} to replace it"
    ))
  }

  # Derive app name from directory if not provided
  if (is.null(app_name)) {
    app_name <- app_dir_name(appdir)
  }

  # Escape app_name for a YAML double-quoted scalar.
  # Backslashes must be escaped first (\\ -> \\\\), then double-quotes (" -> \").
  app_name_safe <- gsub("\\", "\\\\", app_name, fixed = TRUE)
  app_name_safe <- gsub('"', '\\"', app_name_safe, fixed = TRUE)

  # Write the slug out, so the app keeps its identity when the name changes.
  # As export() does without an app_name argument, it comes from the
  # directory name; app_name only sets the display name.
  slug <- resolve_app_slug(list(), NULL, appdir)

  # The slug of the config being replaced: its app.slug or, without one,
  # the directory's, which export() used for it.
  old_slug <- NULL
  if (fs::file_exists(config_path)) {
    old <- tryCatch(yaml::read_yaml(config_path), error = function(e) NULL)
    old_slug <- if (!is.null(old$app$slug)) {
      as.character(old$app$slug)[1]
    } else {
      slug_or_null(app_dir_name(appdir))
    }
  }

  slug_line <- if (is.null(slug)) {
    '# slug: null             # Set a lowercase ASCII slug such as "my-app"'
  } else {
    paste0('slug: "', slug, '"')
  }

  # Template content with all configuration sections
  template <- '# shinyelectron configuration file
# Documentation: https://r-pkg.thecoatlessprofessor.com/shinyelectron/

app:
  name: "{{{app_name}}}"
  # The slug is the app identity: package name, app ID, user data folder,
  # and installer file names. Keep it once the app has shipped, even if
  # the name changes.
  {{{slug_line}}}
  version: "1.0.0"
  # Uncomment to describe the app in Help > About and the installer metadata
  # description: null        # null = "<slug> - Shiny Electron App"
  # author: null             # "Name <email> (url)", or a map of name, email, url
  # homepage: null           # http:// or https:// URL for a Visit Website button
  # copyright: null          # e.g. "Copyright 2026 Example Inc."

# Uncomment to configure logging (app.log_dir and app.log_level also work)
# logging:
#   log_dir: null            # null = default log directory
#   log_level: "info"        # "debug", "info", "warn", "error"

build:
  # type is autodetected from files in the app directory (app.R, ui.R/server.R, or app.py).
  # Uncomment to pin explicitly: "r-shiny" or "py-shiny".
  # type: "r-shiny"
  # runtime_strategy controls how R or Python reaches the end user.
  # Default is "shinylive" (in-browser WebAssembly, no runtime on disk).
  # Other options: "bundled", "system", "auto-download", "container".
  # runtime_strategy: "shinylive"
  # Uncomment to specify target platforms and architectures (default: those
  # of the machine running export()). macOS builds need a Mac, and the
  # bundled and auto-download strategies take one platform and one
  # architecture.
  # platforms:
  #   - mac
  #   - win
  #   - linux
  # architectures:
  #   - x64
  #   - arm64

window:
  width: 1200
  height: 800

server:
  port: 3838

# Uncomment to specify custom icons (platform-specific).
# File paths in this file are relative to the directory that holds it.
# icons:
#   mac: "icons/icon.icns"
#   win: "icons/icon.ico"
#   linux: "icons/icon.png"

nodejs:
  # Version to install (null = latest LTS)
  version: null

# Dependency configuration
# Controls R and Python package dependencies, the bundled Electron version, and container system packages.
# dependencies:
#   auto_detect: true        # Automatically detect dependencies
#   extra_packages: []       # Additional packages to include
#   r:
#     # null or "latest" = newest portable R (built-in version when offline);
#     # "4.5.1" = the same R on every build
#     version: null
#     packages: []           # Extra R packages
#     repos:
#       - "https://cloud.r-project.org"
#     lib_path: null         # null = R default, "app-local", or custom path
#     prune: true            # Bundled only: remove package tests, R manuals and news
#     local_packages: []     # Bundled R only: package source folders or .tar.gz files, relative to this file
#   python:
#     # null = the maintained latest pin; "latest" = always newest; "3.12.0" = exact pin
#     version: null
#     packages: []           # Extra Python packages
#     index_urls:
#       - "https://pypi.org/simple"
#   electron:
#     # null = maintained pin; "latest" = newest; "45.5.0" = exact. Sets the
#     # Electron runtime bundled in the desktop app.
#     version: null
#   # system_packages: list of apt package names (container strategy only)
#   # system_packages:
#   #   - libssl-dev
#   #   - libcurl4-openssl-dev

# Container configuration (used when runtime_strategy is "container")
# container:
#   engine: "docker"         # "docker" or "podman"
#   image: null              # Docker image to use (null = auto-select)
#   tag: "latest"
#   pull_on_start: true      # Pull latest image when app starts
#   volumes:                 # Host-to-container volume map (not a list)
#     "/host/path": "/container/path"
#   env:                     # Environment variable map (not a list)
#     KEY: "value"

# Splash screen configuration
# Shown briefly while the runtime starts up
# splash:
#   enabled: true
#   duration: 1500          # Minimum display time in ms before transitioning out
#   background: null        # null = inherit from _brand.yml; or hex/CSS colour
#   image: null             # Path to a PNG logo, relative to this file (up to 128 px square)
#   text: "Loading..."
#   text_color: "#333333"

# System tray configuration
# Enables minimize/close to tray and tray menu
# tray:
#   enabled: false
#   minimize_to_tray: true
#   close_to_tray: false
#   tooltip: null           # Uses app name if null
#   icon: null              # Path relative to this file; null uses the app icon

# Application menu configuration
# menu:
#   enabled: true
#   template: "default"     # "default" or "minimal"
#   show_dev_tools: false
#   help_url: null

# Auto-update configuration
# Enables automatic app updates via GitHub Releases or any static HTTP server
# updates:
#   enabled: false
#   provider: "github"      # "github" or "generic" (S3 is planned)
#   check_on_startup: true
#   auto_download: false
#   auto_install: false
#   github:
#     owner: null           # GitHub username/organization
#     repo: null            # Repository name
#     private: false
#   generic:
#     url: null             # https:// folder holding latest.yml and the installers

# Preloader configuration
# Shown after the splash, while the runtime emits status events
# preloader:
#   style: "spinner"        # "spinner", "bar", or "dots"
#   message: "Loading application..."
#   background: null        # null = inherit from _brand.yml; or hex/CSS colour

## Code Signing
## Set sign to true for distribution builds.
## macOS requires an Apple Developer account ($99/year) for code signing
## and notarization. Without it, Gatekeeper will block the app.
## Secrets are provided via environment variables:
##   APPLE_ID, APPLE_APP_SPECIFIC_PASSWORD, APPLE_TEAM_ID (macOS)
##   CSC_LINK, CSC_KEY_PASSWORD (macOS/Windows certificate)
##   GPG_KEY (Linux)
# signing:
#   sign: false
#   mac:
#     identity: null            # "Developer ID Application: Your Name (TEAMID)"
#     team_id: null             # Apple Team ID
#     notarize: false           # Notarize for Gatekeeper
#   win:
#     certificate_file: null    # Path to .pfx certificate, relative to this file
#   linux:
#     gpg_sign: false           # GPG-sign AppImage

## Installer Branding
## Customize the installer appearance and behavior.
# installer:
#   app_id: null                  # null = "com.shinyelectron.<slug>"
#   license_file: null            # Windows installer license page; path relative to the app dir
#   one_click: true               # Windows: true = silent install, false = wizard
#   # true adds a page for choosing the install directory; requires one_click: false
#   allow_to_change_installation_directory: null
#   # true = install for all users (admin prompt on every update). Unset or
#   # false: the one-click installer installs per user; the wizard lets the user choose.
#   per_machine: null

## Lifecycle UI
## Controls the startup, loading, error, and shutdown experience.
# lifecycle:
#   show_phase_details: true
#   error_show_logs: true
#   startup_timeout: 180000       # ms to wait for the R, Python, or container server to start
#   shutdown_timeout: 10000       # ms to wait for the server to stop when quitting
#   custom_splash_html: null
#   custom_error_html: null
#   prompt_before_install: false  # true = ask before installing packages
#   prompt_runtime_version: false # true = ask which R/Python version to use
'

  content <- whisker::whisker.render(
    template, list(app_name = app_name_safe, slug_line = slug_line)
  )
  writeLines(content, config_path)

  if (!is.null(old_slug) && !is.null(slug) && !identical(old_slug, slug)) {
    cli::cli_warn(c(
      "The new configuration gives the app the slug {.val {slug}}; the one it replaced gave {.val {old_slug}}.",
      "i" = "Copies installed from builds with the old slug will not update to builds with the new one. To keep them updating, set {.code slug: \"{old_slug}\"} in {.path {config_path}}."
    ), class = "shinyelectron_config_slug_changed")
  }

  if (verbose) {
    cli::cli_alert_success("Created configuration file: {.path {config_path}}")
    cli::cli_alert_info("Edit this file to customize your Electron app settings")
    if (is.null(slug)) alert_missing_slug()
  }

  validate_config_file(config_path)

  invisible(config_path)
}

#' Validate a configuration file
#'
#' Checks a _shinyelectron.yml file for common issues and warns about them.
#'
#' @param config_path Character string. Path to the config file.
#' @return Invisible TRUE if valid, with warnings for issues.
#' @keywords internal
validate_config_file <- function(config_path) {
  if (!file.exists(config_path)) return(invisible(TRUE))

  config <- tryCatch(
    yaml::read_yaml(config_path),
    error = function(e) {
      cli::cli_warn(c(
        "Config file is not valid YAML",
        "x" = "Error: {e$message}",
        "i" = "Check for indentation issues or special characters"
      ))
      return(NULL)
    }
  )

  if (is.null(config)) return(invisible(FALSE))

  # Check for common mistakes. Legacy app_type values are accepted with a
  # deprecation warning; the normaliser emits its own message so we skip the
  # "unknown app type" warning for them here.
  if (!is.null(config$build$type)) {
    valid_types <- SHINYELECTRON_DEFAULTS$valid_app_types
    legacy_types <- c("r-shinylive", "py-shinylive")
    if (config$build$type %in% legacy_types) {
      normalize_app_type_arg(config$build$type, config$build$runtime_strategy)
    } else if (!config$build$type %in% valid_types) {
      cli::cli_warn("Unknown app type {.val {config$build$type}} in config. Valid types: {.val {valid_types}}")
    }
  }

  if (!is.null(config$build$runtime_strategy)) {
    valid_strategies <- SHINYELECTRON_DEFAULTS$valid_runtime_strategies
    if (!config$build$runtime_strategy %in% valid_strategies) {
      cli::cli_warn("Unknown runtime strategy {.val {config$build$runtime_strategy}}. Valid: {.val {valid_strategies}}")
    }
  }

  if (!is.null(config$server$port)) {
    port <- config$server$port
    if (!is.numeric(port) || port < 1 || port > 65535) {
      cli::cli_warn("Invalid port {.val {port}}. Must be between 1 and 65535")
    }
  }

  if (!is.null(config$container$engine)) {
    valid_engines <- SHINYELECTRON_DEFAULTS$valid_container_engines
    if (!config$container$engine %in% valid_engines) {
      cli::cli_warn("Unknown container engine {.val {config$container$engine}}. Valid: {.val {valid_engines}}")
    }
  }

  invisible(TRUE)
}

#' Show Effective Configuration
#'
#' Pretty-prints the merged effective configuration (params + config file + defaults)
#' for a shinyelectron app directory. Useful for debugging and verifying settings.
#'
#' @param appdir Character path to the app directory.
#' @return Invisibly returns the merged configuration list.
#'
#' @examples
#' # Show the merged configuration for a bundled example app
#' show_config(example_app("r"))
#'
#' @export
show_config <- function(appdir = ".") {
  validate_directory_exists(appdir, "Application directory")

  config_path <- find_config(appdir)
  config <- read_config(appdir)

  cli::cli_h1("shinyelectron Configuration")

  if (!is.null(config_path)) {
    cli::cli_alert_info("Config file: {.path {config_path}}")
  } else {
    cli::cli_alert_warning("No config file found, showing defaults only")
  }

  cat("\n")

  # App section. The slug follows the same rules as export() without an
  # app_name argument: app.slug, else the directory name.
  app_name <- config$app$name %||% app_dir_name(appdir)
  slug <- resolve_app_slug(config, NULL, appdir)
  cli::cli_h2("Application")
  cli::cli_bullets(c(
    "*" = "Name: {.val {app_name}}",
    "*" = "Version: {.val {config$app$version %||% '1.0.0'}}",
    "*" = "Slug: {.val {slug %||% '(none; set app.slug)'}}"
  ))

  # Build section
  cli::cli_h2("Build")
  cli::cli_bullets(c(
    "*" = "Type: {.val {config$build$type %||% '(autodetect)'}}",
    "*" = "Runtime strategy: {.val {config$build$runtime_strategy %||% 'shinylive'}}",
    "*" = "Platforms: {.val {config$build$platforms %||% detect_current_platform()}}",
    "*" = "Architectures: {.val {config$build$architectures %||% detect_current_arch()}}"
  ))

  # Window section
  cli::cli_h2("Window")
  cli::cli_bullets(c(
    "*" = "Size: {config$window$width %||% 1200}x{config$window$height %||% 800}",
    "*" = "Port: {config$server$port %||% 3838}"
  ))

  # Features section
  cli::cli_h2("Features")
  cli::cli_bullets(c(
    "*" = "Tray: {.val {isTRUE(config$tray$enabled)}}",
    "*" = "Menu: {.val {config$menu$enabled %||% TRUE}}",
    "*" = "Auto-updates: {.val {isTRUE(config$updates$enabled)}}",
    "*" = "Code signing: {.val {isTRUE(config$signing$sign)}}"
  ))

  # Lifecycle section
  lifecycle <- config$lifecycle %||% SHINYELECTRON_DEFAULTS$lifecycle
  cli::cli_h2("Lifecycle")
  cli::cli_bullets(c(
    "*" = "Prompt before install: {.val {isTRUE(lifecycle$prompt_before_install)}}",
    "*" = "Prompt runtime version: {.val {isTRUE(lifecycle$prompt_runtime_version)}}",
    "*" = "Custom splash: {.val {!is.null(lifecycle$custom_splash_html)}}"
  ))

  invisible(config)
}

#' Read _brand.yml file
#'
#' Reads a _brand.yml file from the app directory for visual customization.
#' Follows the Posit brand.yml specification.
#'
#' @param appdir Character string. Path to the app directory.
#' @return List with brand settings, or NULL if no file found.
#' @keywords internal
read_brand_yml <- function(appdir) {
  brand_file <- file.path(appdir, "_brand.yml")
  if (!file.exists(brand_file)) return(NULL)
  tryCatch(
    resolve_brand_palette(yaml::read_yaml(brand_file)),
    error = function(e) {
      cli::cli_warn(c(
        "Failed to parse {.file {brand_file}}",
        "x" = "{e$message}",
        "i" = "Check YAML syntax and indentation",
        "i" = "Using default branding"
      ))
      NULL
    }
  )
}

#' Resolve Posit brand.yml palette references
#'
#' In a brand.yml `color` block the semantic roles (`primary`, `background`,
#' `foreground`, ...) may either hold a colour directly or name an entry in
#' `color.palette`. shinyelectron reads these roles verbatim for the Electron
#' shell, so a reference such as `primary: plum` must be resolved to its palette
#' value before use. Roles that already hold a literal colour are left untouched.
#'
#' @param brand List or NULL. Parsed `_brand.yml` contents.
#' @return The brand list with `color` roles resolved against `color.palette`.
#' @keywords internal
resolve_brand_palette <- function(brand) {
  palette <- brand$color$palette
  if (is.null(brand$color) || is.null(palette)) return(brand)
  for (role in setdiff(names(brand$color), "palette")) {
    val <- brand$color[[role]]
    if (is.character(val) && length(val) == 1L && val %in% names(palette)) {
      brand$color[[role]] <- palette[[val]]
    }
  }
  brand
}

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.