Nothing
# Render main.js through the package's own template pipeline and let Node
# parse it, covering the template sections that auto-updates and the system
# tray switch on and off.
render_main_js <- function(config, is_multi_app = FALSE, env = parent.frame()) {
out <- withr::local_tempdir(.local_envir = env)
vars <- generate_template_variables(
app_name = "Test App", app_slug = "test-app", app_type = "r-shiny",
runtime_strategy = "system", icon = NULL, backend_module = "native-r.js",
brand = NULL, config = config, is_multi_app = is_multi_app,
apps_manifest = if (is_multi_app) list(list(id = "a", name = "A")) else NULL
)
render_shared_templates(out, vars, is_multi_app)
file.path(out, "main.js")
}
node_check <- function(path) {
processx::run(Sys.which("node"), c("--check", path), error_on_status = FALSE)
}
test_that("rendered main.js parses with auto-updates enabled and disabled", {
skip_on_cran()
skip_if_not(nzchar(Sys.which("node")), "Node.js not available")
for (updates in c(TRUE, FALSE)) {
for (tray in c(TRUE, FALSE)) {
cfg <- default_config()
cfg$updates$enabled <- updates
cfg$tray$enabled <- tray
cfg$tray$close_to_tray <- tray
main_js <- render_main_js(cfg, is_multi_app = tray)
label <- sprintf("updates = %s, tray and multi-app = %s", updates, tray)
res <- node_check(main_js)
expect_equal(res$status, 0, info = paste(label, res$stderr))
main <- paste(readLines(main_js), collapse = "\n")
if (updates) {
expect_match(main, "cancelId: 1", fixed = TRUE, info = label)
expect_match(main, "setTimeout(resolve, 10000)", fixed = TRUE, info = label)
} else {
expect_no_match(main, "autoUpdater", fixed = TRUE, info = label)
}
}
}
})
test_that("an unvalidated shutdown_timeout still renders a parseable main.js", {
skip_on_cran()
skip_if_not(nzchar(Sys.which("node")), "Node.js not available")
cfg <- default_config()
cfg$updates$enabled <- TRUE
cfg$lifecycle$shutdown_timeout <- "10s"
main_js <- render_main_js(cfg)
res <- node_check(main_js)
expect_equal(res$status, 0, info = res$stderr)
expect_no_match(paste(readLines(main_js), collapse = "\n"), "10s", fixed = TRUE)
})
test_that("the update notice logs a failure to show", {
skip_on_cran()
cfg <- default_config()
cfg$updates$enabled <- TRUE
main <- paste(readLines(render_main_js(cfg)), collapse = "\n")
expect_match(main, "notification.on('failed'", fixed = TRUE)
})
test_that("the rendered shell routes navigation through the guard", {
skip_on_cran()
for (multi in c(TRUE, FALSE)) {
main <- paste(readLines(render_main_js(default_config(), is_multi_app = multi)),
collapse = "\n")
for (wiring in c("require('./backends/shell-guard')", "setWindowOpenHandler(",
"'will-navigate'", "'will-redirect'", "'will-frame-navigate'",
"'did-create-window'", "guardContents(mainWindow.webContents)")) {
expect_match(main, wiring, fixed = TRUE, info = wiring)
}
}
})
test_that("the rendered shell loads its own pages by the address it recognizes", {
skip_on_cran()
for (multi in c(TRUE, FALSE)) {
main <- paste(readLines(render_main_js(default_config(), is_multi_app = multi)),
collapse = "\n")
label <- paste("multi-app =", multi)
expect_no_match(main, "mainWindow.loadFile(", fixed = TRUE, info = label)
# Once in loadApp() and once in loadShellPage().
expect_equal(lengths(regmatches(main, gregexpr("mainWindow.loadURL(", main, fixed = TRUE))), 2L,
info = label)
}
})
test_that("the rendered shell checks who sends a control action", {
skip_on_cran()
main_js <- render_main_js(default_config())
main <- paste(readLines(main_js), collapse = "\n")
expect_match(main, "guard.isTrustedSender(", fixed = TRUE)
expect_match(main, "guard\\.isTrustedSender\\([^)]*process\\.platform === 'win32'\\)")
preload <- paste(readLines(file.path(dirname(main_js), "preload.js")), collapse = "\n")
expect_match(preload, "location.protocol === 'file:'", fixed = TRUE)
})
test_that("the preload hands readings to the shell's own pages only", {
skip_on_cran()
skip_if_not(nzchar(Sys.which("node")), "Node.js not available")
preload <- file.path(dirname(render_main_js(default_config())), "preload.js")
# Load the preload under Node with a stand-in for electron, as a page at the
# given protocol would, and report what it exposed and subscribed to.
runner <- withr::local_tempfile(fileext = ".js", lines = c(
"const Module = require('module');",
"const seen = { exposed: [], channels: [] };",
"const electron = {",
" contextBridge: { exposeInMainWorld: (name, api) => {",
" seen.exposed.push(name);",
" if (name === 'usage') {",
" seen.members = Object.keys(api);",
" api.onReading((...args) => { seen.received = args; });",
" }",
" } },",
" ipcRenderer: { on: (channel, handler) => {",
" seen.channels.push(channel);",
" handler({ marker: 'ipc-event' }, { marker: 'view' });",
" }, send: () => {} }",
"};",
"const load = Module._load;",
"Module._load = function (request, ...rest) {",
" return request === 'electron' ? electron : load.call(this, request, ...rest);",
"};",
"globalThis.location = { protocol: process.argv[3] };",
"require(process.argv[2]);",
"process.stdout.write(JSON.stringify(seen));"
))
seen <- function(protocol) {
jsonlite::fromJSON(processx::run("node", c(runner, preload, protocol))$stdout)
}
expect_length(seen("http:")$exposed, 0)
file_page <- seen("file:")
expect_setequal(file_page$exposed, c("lifecycle", "usage"))
expect_equal(file_page$channels, "usage-reading")
expect_equal(file_page$members, "onReading")
expect_equal(file_page$received$marker, "view")
})
test_that("the rendered shell grants permissions by the page the window shows", {
skip_on_cran()
for (multi in c(TRUE, FALSE)) {
main <- paste(readLines(render_main_js(default_config(), is_multi_app = multi)),
collapse = "\n")
for (wiring in c("setPermissionRequestHandler(", "setPermissionCheckHandler(",
"guardSession(mainWindow.webContents.session)",
"externalUrl: details.externalURL")) {
expect_match(main, wiring, fixed = TRUE, info = wiring)
}
}
})
test_that("the rendered shell takes the single-instance lock and focuses the first copy", {
skip_on_cran()
for (tray in c(TRUE, FALSE)) {
cfg <- default_config()
cfg$tray$enabled <- tray
main_js <- render_main_js(cfg)
main <- paste(readLines(main_js), collapse = "\n")
for (wiring in c("app.requestSingleInstanceLock()", "'second-instance'")) {
expect_match(main, wiring, fixed = TRUE, info = paste(wiring, "tray =", tray))
}
if (nzchar(Sys.which("node"))) {
res <- node_check(main_js)
expect_equal(res$status, 0, info = res$stderr)
}
}
})
test_that("the uncaught exception handler stops the servers before exiting", {
skip_on_cran()
main <- paste(readLines(render_main_js(default_config())), collapse = "\n")
stop_at <- regexpr("stopAll([currentBackend, sharedShinyliveServer])", main, fixed = TRUE)
exit_at <- regexpr("process.exit(1)", main, fixed = TRUE)
expect_gt(stop_at, 0)
expect_gt(exit_at, stop_at)
})
test_that("a crashed window shows the error screen", {
skip_on_cran()
main_js <- render_main_js(default_config())
main <- paste(readLines(main_js), collapse = "\n")
for (wiring in c("guard.shouldShowWindowCrash(", "phase: 'window_crashed'")) {
expect_match(main, wiring, fixed = TRUE, info = wiring)
}
# The third argument says whether the error screen itself was loading.
expect_match(main, "guard\\.shouldShowWindowCrash\\([^,()]+,[^,()]+,[^,()]+\\)")
lifecycle <- paste(readLines(file.path(dirname(main_js), "lifecycle.html")), collapse = "\n")
expect_match(lifecycle, "case 'window_crashed':", fixed = TRUE)
})
test_that("a suite goes back to the launcher through one function", {
skip_on_cran()
for (template in c("default", "minimal")) {
cfg <- default_config()
cfg$menu$template <- template
main <- paste(readLines(render_main_js(cfg, is_multi_app = TRUE)), collapse = "\n")
label <- paste("menu template =", template)
expect_match(main, "label: 'Back to Launcher',[^}]*click: \\(\\) => backToLauncher\\(\\)",
info = label)
expect_match(main, "actionType === 'back_to_launcher') {\n backToLauncher();",
fixed = TRUE, info = label)
# The function, the menu item and the action, and nothing else.
expect_equal(lengths(regmatches(main, gregexpr("backToLauncher()", main, fixed = TRUE))), 3L,
info = label)
}
})
test_that("Help offers Resource Usage right after View Logs in both templates", {
skip_on_cran()
for (template in c("default", "minimal")) for (multi in c(TRUE, FALSE)) {
cfg <- default_config()
cfg$menu$template <- template
main_js <- render_main_js(cfg, is_multi_app = multi)
main <- paste(readLines(main_js), collapse = "\n")
label <- paste("template =", template, "multi-app =", multi)
expect_match(main, paste0("shell\\.openPath\\(logDir\\);\\s*\\}\\s*\\},\\s*\\{\\s*id: 'resource-usage',",
"\\s*label: 'Resource Usage',\\s*click: \\(\\) => showUsageWindow\\(\\)"), info = label)
expect_equal(lengths(regmatches(main, gregexpr("id: 'resource-usage'", main, fixed = TRUE))), 1L,
info = label)
if (nzchar(Sys.which("node"))) expect_equal(node_check(main_js)$status, 0, info = label)
}
cfg <- default_config()
cfg$menu$enabled <- FALSE
if (nzchar(Sys.which("node"))) expect_equal(node_check(render_main_js(cfg))$status, 0)
})
test_that("the usage window is a shell page that samples only while open", {
skip_on_cran()
main <- paste(readLines(render_main_js(default_config())), collapse = "\n")
for (wiring in c("require('./backends/resource-usage')",
"['lifecycle.html', 'launcher.html', 'usage.html'].map(shellPageUrl)",
".loadURL(shellPageUrl('usage.html'))", "guardContents(win.webContents)",
"once('did-finish-load', () => sampler.start())",
"usage.shellReading(app.getAppMetrics(), own === pagePid(mainWindow) ? null : own)",
"currentServer: () => (appsManifest && !lastSelectedAppId ? null : currentBackend)",
"win.webContents.send('usage-reading', view)",
"win.webContents.on('render-process-gone'")) {
expect_match(main, wiring, fixed = TRUE, info = wiring)
}
# The App window row leaves out the usage window's own page, and looking up
# a page's process cannot throw, even for a window that is gone.
expect_match(main, "readShell: \\(\\) => \\{\\s*const own = pagePid\\(win\\);")
expect_match(main, paste0("function pagePid\\(w\\) \\{\\s*try \\{\\s*",
"if \\(!w \\|\\| w\\.isDestroyed\\(\\) \\|\\| w\\.webContents\\.isDestroyed\\(\\)\\) return null;\\s*",
"return w\\.webContents\\.getOSProcessId\\(\\);\\s*",
"\\} catch \\{\\s*return null;\\s*\\}"))
expect_match(main, "win\\.on\\('closed', \\(\\) => \\{[^}]*sampler\\.stop\\(\\)")
expect_match(main, "mainWindow\\.on\\('closed', \\(\\) => \\{[^}]*usageWindow\\.close\\(\\)")
# A window whose setup threw part-way is not kept for the next click.
expect_match(main, "function showUsageWindow\\(\\) \\{\\s*let win = null;\\s*try \\{")
expect_match(main, paste0("\\} catch \\(err\\) \\{\\s*log\\('error', 'Could not open Resource Usage:'[^}]*",
"if \\(win && !win\\.isDestroyed\\(\\)\\) win\\.destroy\\(\\);\\s*",
"if \\(usageWindow === win\\) usageWindow = null;\\s*\\}"))
})
test_that("the shell reads a development update feed only when unpackaged", {
skip_on_cran()
cfg <- default_config()
cfg$updates$enabled <- TRUE
main <- paste(readLines(render_main_js(cfg)), collapse = "\n")
expect_match(main, paste0(
"if (!app.isPackaged && fs.existsSync(path.join(app.getAppPath(), 'dev-app-update.yml'))) {\n",
" autoUpdater.forceDevUpdateConfig = true;\n",
" }"), fixed = TRUE)
expect_length(gregexpr("forceDevUpdateConfig", main, fixed = TRUE)[[1]], 1L)
cfg$updates$enabled <- FALSE
expect_no_match(paste(readLines(render_main_js(cfg)), collapse = "\n"),
"dev-app-update.yml", fixed = TRUE)
})
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.