Nothing
#' Export Shiny Application as Electron Desktop Application
#'
#' Main entry point function that wraps the conversion, building, and optionally
#' running of a Shiny application as an Electron desktop application.
#'
#' @param appdir Character string. Path to the directory containing the Shiny application.
#' @param destdir Character string. Path to the destination directory where the Electron app will be created.
#' @param app_name Character string. Display name of the application. If NULL,
#' uses `app.name` from `_shinyelectron.yml`, then the name of the app
#' directory. Unless `app.slug` is set, this argument also gives the app's
#' slug, its identity for installed copies and updates; without it the slug
#' comes from the name of the app directory, never from `app.name`.
#' @param app_type Character string or NULL. Language of the Shiny app:
#' `"r-shiny"` or `"py-shiny"`. If NULL (default), the type is autodetected
#' from files in `appdir`. The legacy values `"r-shinylive"` and
#' `"py-shinylive"` are accepted with a deprecation warning and translate
#' to the canonical language plus `runtime_strategy = "shinylive"`.
#' @param runtime_strategy Character string or NULL. How R or Python reaches
#' the end user: `"shinylive"`, `"bundled"`, `"system"`, `"auto-download"`,
#' or `"container"`. Default `"shinylive"` when neither argument nor config
#' sets one.
#' @param sign Logical. Whether to enable code signing for the built application.
#' When TRUE, electron-builder will attempt to sign the app using credentials
#' from environment variables or the config file. Default is FALSE.
#' @param platform Character vector. Target platforms: "win", "mac", "linux".
#' If NULL, uses `build.platforms` from `_shinyelectron.yml`, then the
#' current platform. macOS apps build only on macOS, so a `"mac"` target
#' stops the export on Windows and Linux unless `build = FALSE`.
#' @param arch Character vector. Target architectures: "x64", "arm64". If
#' NULL, uses `build.architectures` from `_shinyelectron.yml`, then the
#' current architecture. Each of `platform` and `arch` replaces only its
#' own list, so `platform = "win"` still builds for every architecture in
#' `build.architectures`.
#' @param icon Character string. Path to application icon file, absolute or
#' relative to the working directory. A PNG (1024x1024 or larger) or an
#' `.icns` file serves every platform; an `.ico` file serves Windows only.
#' Overrides `icon` and `icons` in `_shinyelectron.yml`, whose paths are
#' relative to `appdir`.
#' @param overwrite Logical. Whether to overwrite existing output directory. Default is FALSE.
#' @param build Logical. Whether to build distributable packages. Default is TRUE.
#' @param run_after Logical. Whether to run the application in development mode after export. Default is FALSE.
#' @param open_after Logical. Whether to open the generated project directory after export. Default is FALSE.
#' @param verbose Logical. Whether to display detailed progress information. Default is TRUE.
#'
#' @return List containing paths to the converted app and built Electron app (if built).
#'
#' @section Details:
#' This is the main function of the package that orchestrates the entire process:
#' \itemize{
#' \item Validates the input Shiny application
#' \item Converts the Shiny app to the specified format (shinylive by default)
#' \item Sets up the Electron project structure
#' \item Optionally builds distributable packages
#' \item Optionally runs the application for testing
#' }
#'
#' @section Supported Combinations:
#' Two languages, five delivery strategies.
#' \itemize{
#' \item `r-shiny` or `py-shiny` plus `runtime_strategy = "shinylive"`: app compiles to WebAssembly and runs inside the Electron window with no runtime on disk.
#' \item `r-shiny` or `py-shiny` plus `"auto-download"`, `"bundled"`, `"system"`, or `"container"`: app runs against a real R or Python process supplied by the chosen strategy.
#' }
#'
#' @examplesIf interactive()
#' # Simplest call: app_type autodetects, runtime_strategy defaults to shinylive
#' export(
#' appdir = "path/to/shiny/app",
#' destdir = "path/to/electron/output"
#' )
#'
#' # Run against a real R process instead of shinylive
#' export(
#' appdir = "path/to/shiny/app",
#' destdir = "path/to/output",
#' runtime_strategy = "bundled"
#' )
#'
#' # Pin language explicitly when autodetection is ambiguous
#' export(
#' appdir = "path/to/shiny/app",
#' destdir = "path/to/output",
#' app_type = "r-shiny",
#' runtime_strategy = "system"
#' )
#'
#' @export
export <- function(appdir, destdir, app_name = NULL, app_type = NULL,
runtime_strategy = NULL, sign = FALSE,
platform = NULL, arch = NULL, icon = NULL,
overwrite = FALSE, build = TRUE, run_after = FALSE,
open_after = FALSE, verbose = TRUE) {
# Expand ~ in paths before passing to external tools (Python, npm, etc.)
appdir <- path.expand(appdir)
destdir <- path.expand(destdir)
# Validate inputs
validate_directory_exists(appdir, "Application directory")
# Normalize legacy app_type values (r-shinylive / py-shinylive)
normalized <- normalize_app_type_arg(app_type, runtime_strategy)
app_type <- normalized$app_type
runtime_strategy <- normalized$runtime_strategy
# Read config file (or get defaults) -- must happen before structure
# validation so multi-app mode can be detected early
config <- read_config(appdir)
# File paths in the config are relative to the app directory (the suite
# root for a multi-app suite), whatever the working directory. Resolve them
# before anything uses them, and drop a missing splash image, tray icon or
# launcher icon with a warning so the build falls back to its default.
config <- resolve_config_paths(config, appdir)
config <- drop_missing_config_files(config, base_dir = appdir)
# installer.license_file is relative to the app directory, but
# electron-builder runs in the generated project. Resolve it now so the
# build can copy it there and a missing file fails before any work starts.
config <- resolve_installer_license(config, appdir)
# App display name: explicit argument > config app.name > directory name
# (mirrors export_multi_app(), so app.name is honored for single apps too).
# The slug below still comes from the argument or the directory only.
app_name_arg <- app_name
name_from_config <- is.null(app_name) && !is.null(config$app$name)
app_name <- app_name %||% config$app$name %||% app_dir_name(appdir)
validate_app_name(app_name, field = if (name_from_config) "app.name" else "app_name")
# Target platforms and architectures: function arg > config
# build.platforms and build.architectures > the build machine. The icon,
# signing and installer text checks below and the build itself all use
# them, for single apps and suites alike. A macOS target stops a build on
# another system now, since electron-builder would fail there without
# stopping the export.
targets <- resolve_build_targets(platform, arch, config)
if (build) check_build_host(targets$platform, targets$from_config)
# Resolve the icon: function arg > config `icon:` > the `icons:` entry for
# the first target platform. Wiring the YAML keys here makes them effective
# for both single and multi-app builds. The argument stays relative to the
# working directory, like any path argument. A configured icon that does not
# exist stops the export now, as a missing argument does in validate_icon().
# The build gives that one icon to every target platform, so the `icons:`
# entries of the others go unused, with a warning.
if (is.null(icon)) {
icon <- check_config_icon(config, targets$platform[1], base_dir = appdir)
check_unused_icons(config, targets$platform)
}
# Resolve signing before the multi-app branch so suites honor
# `signing: sign: true`. The function arg can force signing on and the
# config can enable it; there is no way to force signing off via the arg.
sign <- sign || isTRUE(config$signing$sign)
if (sign && build) {
for (p in targets$platform) {
validate_signing_config(config, platform = p, sign = sign)
}
if ("win" %in% targets$platform) {
check_config_certificate(config, base_dir = appdir)
}
}
# A one-entry `apps:` block is not a suite. Reject it explicitly rather than
# silently falling through to the single-app path, which ignores the declared
# per-app config and usually aborts later with a confusing autodetect error.
if (!is.null(config$apps) && length(config$apps) == 1) {
cli::cli_abort(c(
"An {.field apps:} suite needs at least 2 apps, but only 1 was declared.",
"i" = "Remove the {.field apps:} block to build the single app directly.",
"x" = "Found 1 app entry: {.val {config$apps[[1]]$id %||% config$apps[[1]]$name}}"
), class = "shinyelectron_one_app_suite")
}
# Settle the slug, the app's identity, here where the app directory is
# known, and check it before any conversion or runtime download;
# process_templates() takes it from the config. It comes from app.slug,
# else the app_name argument, else the directory name, as in earlier
# releases, so editing app.name never changes an installed app's identity.
slug_pinned <- !is.null(config$app$slug)
config$app$slug <- resolve_app_slug(config, app_name_arg, appdir)
if (build) check_app_slug(config$app$slug)
# The Windows installer cannot hold a $ in the app's name or metadata; stop
# a Windows build here, before any conversion or runtime download.
check_installer_text(app_name, config,
windows = build && "win" %in% targets$platform)
# Detect multi-app mode (skip single-app structure validation). The suite
# gets the platform and arch arguments as given and resolves the same
# targets from the same config, so its errors can name the settings.
if (is_multi_app(config)) {
return(export_multi_app(appdir, destdir, config,
app_name = app_name,
runtime_strategy = runtime_strategy,
sign = sign, platform = platform, arch = arch,
icon = icon, overwrite = overwrite, build = build,
run_after = run_after, open_after = open_after,
verbose = verbose, slug_pinned = slug_pinned))
}
# Resolve app_type: function arg > config (normalized) > autodetect
if (is.null(app_type)) {
cfg_type <- config$build$type
if (!is.null(cfg_type) && nzchar(cfg_type)) {
cfg_normalized <- normalize_app_type_arg(cfg_type, runtime_strategy)
app_type <- cfg_normalized$app_type
runtime_strategy <- runtime_strategy %||% cfg_normalized$runtime_strategy
}
}
if (is.null(app_type)) {
app_type <- detect_app_type(appdir)
}
validate_app_type(app_type)
# Validate app structure based on language
if (app_type == "r-shiny") {
validate_shiny_app_structure(appdir)
} else if (app_type == "py-shiny") {
validate_python_app_structure(appdir)
}
# Validate icon file if provided
if (!is.null(icon)) {
validate_icon(icon, targets$platform)
}
# Resolve runtime strategy: function param > config file > shinylive default
runtime_strategy <- runtime_strategy %||% config$build$runtime_strategy %||% "shinylive"
validate_runtime_strategy(runtime_strategy)
# A bundled or auto-download build takes one target. build_electron_app()
# stops on more, but only after the app is copied and its dependencies
# resolved, so check here first.
if (build) {
check_single_target(runtime_strategy, targets$platform, targets$arch,
from_config = targets$from_config)
warn_if_electron_unsupported(config)
}
# Local R packages only go into a bundled R library. Resolve them against
# the app directory, then check and read them before anything is copied or
# downloaded. The config then holds what was read, for the later steps.
local_packages <- resolve_local_packages(
config$dependencies$r$local_packages,
base_dir = appdir,
bundled_r = runtime_strategy == "bundled" && grepl("^r-", app_type)
)
if (length(local_packages) > 0) {
config$dependencies$r$local_packages <- local_packages
}
# Without dependencies.r.version, an R app that embeds, downloads or runs R
# in a container uses the newest portable R for the first target platform.
# Look it up once here; the later steps read it from the config.
if (grepl("^r-", app_type) &&
runtime_strategy %in% c("bundled", "auto-download", "container")) {
config$dependencies$r$version <- resolve_runtime_version(
"r", config, platform = targets$platform[1]
)
}
# Validate runtime requirements for the system strategy. R/Python are an
# end-user requirement (the bundle does not need them), so a missing runtime
# on the build machine is a warning, mirroring the container-engine check.
if (runtime_strategy == "system") {
tryCatch({
if (app_type == "r-shiny") {
validate_r_available()
} else if (app_type == "py-shiny") {
validate_python_available()
}
}, error = function(e) {
cli::cli_warn(c(
"Runtime not available on build machine (the end user will need it)",
"i" = conditionMessage(e)
))
})
}
if (runtime_strategy == "container") {
engine <- tryCatch(
validate_container_available(config$container$engine),
error = function(e) {
cli::cli_warn(c(
"Container engine not available on build machine (end user will need it)",
"i" = e$message
))
config$container$engine %||% "docker"
}
)
if (verbose) {
cli::cli_alert_info("Container engine: {.val {engine}}")
}
}
if (verbose) {
cli::cli_h1("Exporting Shiny application to Electron")
alert_app_identity("Application", app_name, config$app$slug, slug_pinned)
cli::cli_alert_info("Type: {.val {app_type}}")
cli::cli_alert_info("Runtime: {.val {runtime_strategy}}")
cli::cli_alert_info("Source: {.path {appdir}}")
cli::cli_alert_info("Destination: {.path {destdir}}")
if (sign) {
cli::cli_alert_info("Code signing: {.val enabled}")
} else {
cli::cli_alert_info("Code signing: {.val disabled} (unsigned build)")
}
}
# Resolve the app's dependencies before the destination is touched, so a
# package that cannot be installed stops the export with any earlier build
# still in place. Shinylive apps manage their own packages.
dependencies <- if (runtime_strategy != "shinylive") {
resolve_app_dependencies(appdir, app_type, runtime_strategy, config)
}
# Create destination directory
if (fs::dir_exists(destdir)) {
if (!overwrite) {
cli::cli_abort(c(
"Destination directory already exists: {.path {destdir}}",
"i" = "Use {.code overwrite = TRUE} to overwrite existing directory"
))
} else {
if (verbose) cli::cli_alert_warning("Overwriting existing directory: {.path {destdir}}")
assert_safe_to_overwrite(destdir)
unlink(destdir, recursive = TRUE)
}
}
fs::dir_create(destdir, recurse = TRUE)
# Track that this call created/owns destdir so a failed export can clean up
# the partial output instead of forcing the user to pass overwrite = TRUE.
created_destdir <- TRUE
result <- list()
result <- tryCatch({
# Step 1: Convert or stage application files
if (runtime_strategy == "shinylive") {
converted_app_dir <- convert_app_to_shinylive(
appdir, destdir, app_type, verbose = verbose
)
result$converted_app <- converted_app_dir
} else {
prep <- prepare_native_app_files(
appdir, destdir, app_type, runtime_strategy,
targets$platform, targets$arch, config, verbose = verbose,
dependencies = dependencies
)
converted_app_dir <- prep$converted_app
result$converted_app <- prep$converted_app
if (!is.null(prep$dependencies)) result$dependencies <- prep$dependencies
}
# Step 2: Build Electron application if requested
if (build) {
if (verbose) cli::cli_alert_info("Building Electron application...")
electron_dir <- fs::path(destdir, "electron-app")
built_app_dir <- without_repeated_update_url_warning(build_electron_app(
app_dir = converted_app_dir,
output_dir = electron_dir,
app_name = app_name,
app_type = app_type,
runtime_strategy = runtime_strategy,
sign = sign,
platform = targets$platform,
arch = targets$arch,
icon = icon,
config = config,
overwrite = TRUE,
verbose = verbose
))
result$electron_app <- built_app_dir
}
result
}, error = function(e) {
# Remove only the partial output this call created, so a retry does not
# require overwrite = TRUE.
if (isTRUE(created_destdir) && fs::dir_exists(destdir)) {
unlink(destdir, recursive = TRUE)
}
cli::cli_abort(c(
"Failed to export Shiny application",
"x" = "Error: {e$message}"
), parent = e)
})
# The build output is committed past this point. Post-build actions must
# never delete it, so they run OUTSIDE the cleanup tryCatch above.
if (verbose) {
cli::cli_alert_success("Successfully exported Shiny application to Electron!")
cli::cli_alert_info("Output directory: {.path {destdir}}")
if (build) {
cli::cli_alert_info("Electron app: {.path {result$electron_app}}")
if (fs::dir_exists(fs::path(result$electron_app, "dist"))) {
cli::cli_alert_info("Distributables: {.path {fs::path(result$electron_app, 'dist')}}")
}
}
}
# Run in dev mode if requested. A non-zero Electron exit must not destroy the
# successful build, so failures warn rather than abort.
if (run_after && build) {
if (verbose) cli::cli_alert_info("Starting application in development mode...")
tryCatch(
run_electron_app(app_dir = result$electron_app, verbose = verbose),
error = function(e) cli::cli_warn(c(
"The application exited with an error (the build output was kept).",
"i" = conditionMessage(e)
))
)
}
if (open_after) {
if (verbose) cli::cli_alert_info("Opening output directory...")
tryCatch(
utils::browseURL(destdir),
error = function(e) cli::cli_warn(c(
"Could not open the output directory (the build output was kept).",
"i" = conditionMessage(e)
))
)
}
result
}
Any scripts or data that you put into this service are public.
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.