mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-30 02:07:10 +01:00
Merge main into fix/scriptcheck-linear-work
This commit is contained in:
commit
967f83c442
82 files changed
+5257
-294
No files matched your search
@@ -1468,11 +1468,11 @@ fn install(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// A heavy plug-in is installed once a person agrees.
|
||||
if plugin.manifest().budget == Budget::Heavy && !allow_heavy {
|
||||
let (minutes, times) = vectorcraft_plugins::heavy_terms();
|
||||
let name = permissions::display_text(&plugin.manifest().name, permissions::MAX_SHOWN_NAME);
|
||||
return Err(bad(
|
||||
C,
|
||||
format!(
|
||||
"“{}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants",
|
||||
plugin.manifest().name
|
||||
"“{name}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants"
|
||||
),
|
||||
));
|
||||
}
|
||||
@@ -1615,6 +1615,10 @@ fn inspect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if !refused.is_empty() {
|
||||
v["refusedCommands"] = json!(refused);
|
||||
}
|
||||
let translations = &plugin.manifest().translations;
|
||||
if !translations.is_empty() {
|
||||
v["translations"] = serde_json::to_value(translations).unwrap_or(Value::Null);
|
||||
}
|
||||
v
|
||||
})
|
||||
}
|
||||
@@ -2447,7 +2451,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Inspect Plug-in",
|
||||
[],
|
||||
None,
|
||||
"{path: a .wasm file or a .vcplugin manifest (desktop) | dataBase64: the module or a JavaScript plug-in's JSON, name?: the file name shown as its source (with dataBase64)} validate a plug-in without installing it, running none of its code → the plugin.list entry it would have, plus needsApproval: bool (true when it lists permissions no person has granted this very module, its bytes included: it then needs a person's approval, see plugin.install) and needsReplace: bool (true when it would take the place of another module with its id: plugin.install then needs replace: true), unknownCommands?: [id] (commandAllowlist ids no command has) and refusedCommands?: [id] (commandAllowlist ids no plug-in may call: plugin.install refuses the module)",
|
||||
"{path: a .wasm file or a .vcplugin manifest (desktop) | dataBase64: the module or a JavaScript plug-in's JSON, name?: the file name shown as its source (with dataBase64)} validate a plug-in without installing it, running none of its code → the plugin.list entry it would have, plus needsApproval: bool (true when it lists permissions no person has granted this very module, its bytes included: it then needs a person's approval, see plugin.install) and needsReplace: bool (true when it would take the place of another module with its id: plugin.install then needs replace: true), unknownCommands?: [id] (commandAllowlist ids no command has), refusedCommands?: [id] (commandAllowlist ids no plug-in may call: plugin.install refuses the module) and translations?: {language: {name?, params?, groups?, commands?}} (the manifest's translations as declared, when it gives any)",
|
||||
always,
|
||||
inspect
|
||||
),
|
||||
|
||||
@@ -18,7 +18,7 @@ use crate::script;
|
||||
pub const EXTS: &[&str] = &["jsx", "jsxinc", "jsxbin"];
|
||||
|
||||
/// The extensions of the scripts `script.run` takes as a file, in any case.
|
||||
pub const RUN_EXTS: &[&str] = &["js", "jsx"];
|
||||
pub const RUN_EXTS: &[&str] = &["js", "mjs", "jsx"];
|
||||
|
||||
/// Does `path` name a file `script.run` takes?
|
||||
pub fn runs(path: &str) -> bool {
|
||||
@@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Run Script",
|
||||
[],
|
||||
None,
|
||||
"{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), actions?: [{set, name, steps: [{command, params?, step?: the step's place in the action, a whole number from 1 (default its place in the list)}]}] (the actions app.doScript(action, set, dialogs?) plays, matched by their exact names; a command.batch step gives its own steps; at most 4096 actions, 10000 steps an action, 100000 steps in all and 16 MiB as JSON; in the app, the Actions panel's actions with their included steps, which a caller's list replaces), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handlers without closing the dialog, addEventListener and removeEventListener take click, change, changing and show (show on the dialog only; at most 256 listeners a window or control; the other documented event
Line truncated
|
||||
"{path?: a script file (.js, .mjs or .jsx) | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), module?: true or false (default true for a path ending in .mjs, false otherwise; true runs the file or source as a .mjs file runs, as a module, and a source run this way imports no files), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), actions?: [{set, name, steps: [{command, params?, step?: the step's place in the action, a whole number from 1 (default its place in the list)}]}] (the actions app.doScript(action, set, dialogs?) plays, matched by their exact names; a command.batch step gives its own steps; at most 4096 actions, 10000 steps an action, 100000 steps in all and 16 MiB as JSON; in the app, the Actions panel's actions with their included steps, which a caller's list replaces), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handler
Line truncated
|
||||
always,
|
||||
run
|
||||
),
|
||||
@@ -86,7 +86,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"List Installed Scripts",
|
||||
[],
|
||||
None,
|
||||
"{} list the .js and .jsx files of the Scripts folder next to the settings, which File › Scripts lists, each subfolder as a submenu, in menu order; only names are read, never a script's text; links, hidden files, names starting with a dot and folders without a script are left out. VectorCraft's own limits: 2048 folder entries looked at, 512 scripts, 128 subfolders, 4 levels of subfolders, names of 255 bytes, labels of 128 characters, 250 ms → {folder: the Scripts folder's path | null (a session without one, and the web), scripts: [{path, label: the file name without its extension (the whole file name when another row of its folder has that label), folders: [the labels of the subfolders it is in]}], truncated: a limit was reached or a subfolder could not be read, unreadable: the folder is there and could not be read, or is a link}",
|
||||
"{} list the .js, .mjs and .jsx files of the Scripts folder next to the settings, which File › Scripts lists, each subfolder as a submenu, in menu order; only names are read, never a script's text; links, hidden files, names starting with a dot and folders without a script are left out. VectorCraft's own limits: 2048 folder entries looked at, 512 scripts, 128 subfolders, 4 levels of subfolders, names of 255 bytes, labels of 128 characters, 250 ms → {folder: the Scripts folder's path | null (a session without one, and the web), scripts: [{path, label: the file name without its extension (the whole file name when another row of its folder has that label), folders: [the labels of the subfolders it is in]}], truncated: a limit was reached or a subfolder could not be read, unreadable: the folder is there and could not be read, or is a link}",
|
||||
always,
|
||||
list_installed
|
||||
),
|
||||
@@ -198,6 +198,7 @@ fn prepare(s: &Session, p: &Value) -> Result<script::Request> {
|
||||
let actions = script::actions::parse(p.get("actions")).map_err(param)?;
|
||||
let fuel = max_fuel(p)?;
|
||||
let installed = switch_or(p, "installed", false, "script.run")?;
|
||||
let module = switch_or(p, "module", script::include::module_script(path), "script.run")?;
|
||||
let mut checked_real = None;
|
||||
let text = match (path, source) {
|
||||
(Some(""), None) => return Err(param("`path` is empty")),
|
||||
@@ -213,7 +214,7 @@ fn prepare(s: &Session, p: &Value) -> Result<script::Request> {
|
||||
return Err(EngineError::Other(COMPILED.to_string()));
|
||||
}
|
||||
if !runs(path) {
|
||||
return Err(param("`path` must name a .js or .jsx file"));
|
||||
return Err(param("`path` must name a .js, .mjs or .jsx file"));
|
||||
}
|
||||
// One byte more than a script may have shows that the file is too large.
|
||||
let bytes = super::fileio::read_file_head(path, script::MAX_SOURCE_BYTES + 1)?;
|
||||
@@ -242,6 +243,7 @@ fn prepare(s: &Session, p: &Value) -> Result<script::Request> {
|
||||
fuel,
|
||||
locale,
|
||||
answers,
|
||||
module,
|
||||
actions,
|
||||
})
|
||||
}
|
||||
@@ -444,6 +446,7 @@ impl Session {
|
||||
fuel,
|
||||
locale,
|
||||
answers: vec![],
|
||||
module: script::include::module_script(path.to_str()),
|
||||
actions: vec![],
|
||||
};
|
||||
let runs = self.script_runs;
|
||||
|
||||
@@ -715,6 +715,15 @@ impl ScriptScope {
|
||||
|
||||
/// The real path of the file at `path` and its first `max` bytes, at most.
|
||||
pub(crate) fn read(&self, path: &Path, max: usize) -> Result<(PathBuf, Vec<u8>), ScriptRead> {
|
||||
match self.read_unless(path, max, |_| false)? {
|
||||
(real, Some(bytes)) => Ok((real, bytes)),
|
||||
(_, None) => Err(ScriptRead::Failed("the file was not read".to_string())),
|
||||
}
|
||||
}
|
||||
|
||||
/// [`ScriptScope::read`], except that a file whose real path `known` accepts is not opened:
|
||||
/// → its real path and no bytes.
|
||||
pub(crate) fn read_unless(&self, path: &Path, max: usize, known: impl Fn(&Path) -> bool) -> Result<(PathBuf, Option<Vec<u8>>), ScriptRead> {
|
||||
use std::io::Read;
|
||||
if self.is_empty() || Self::refused_by_name(path) || check_read(&path.to_string_lossy()).is_err() {
|
||||
return Err(ScriptRead::Refused);
|
||||
@@ -730,6 +739,9 @@ impl ScriptScope {
|
||||
if !self.allows(&real) {
|
||||
return Err(ScriptRead::Refused);
|
||||
}
|
||||
if known(&real) {
|
||||
return Ok((real, None));
|
||||
}
|
||||
let file = std::fs::File::open(&real).map_err(|e| ScriptRead::Failed(e.to_string()))?;
|
||||
let meta = file.metadata().map_err(|e| ScriptRead::Failed(e.to_string()))?;
|
||||
if !meta.is_file() {
|
||||
@@ -747,7 +759,7 @@ impl ScriptScope {
|
||||
if std::fs::canonicalize(path).ok().as_ref() != Some(&real) {
|
||||
return Err(ScriptRead::Refused);
|
||||
}
|
||||
Ok((real, bytes))
|
||||
Ok((real, Some(bytes)))
|
||||
}
|
||||
|
||||
/// The first granted folder, as people read it (`None` for a script given as text).
|
||||
@@ -966,6 +978,21 @@ mod tests {
|
||||
p.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
/// A file the caller already has is not opened: its size is not checked and no byte is read.
|
||||
#[test]
|
||||
fn a_known_script_file_is_not_read_again() {
|
||||
let (base, _) = folders("known");
|
||||
std::fs::write(base.join("in/big.js"), "x".repeat(64)).unwrap();
|
||||
let scope = ScriptScope::of_folder(&base.join("in"));
|
||||
let path = base.join("in/big.js");
|
||||
assert_eq!(scope.read(&path, 16).map(|(_, b)| b.len()), Err(ScriptRead::TooLarge));
|
||||
let real = std::fs::canonicalize(&path).unwrap();
|
||||
assert_eq!(scope.read_unless(&path, 16, |r| r == real), Ok((real.clone(), None)));
|
||||
assert_eq!(scope.read_unless(&path, 64, |_| false).map(|(_, b)| b.map(|b| b.len())), Ok(Some(64)));
|
||||
assert_eq!(scope.read_unless(&base.join("outside/secret.svg"), 64, |_| true), Err(ScriptRead::Refused));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// The roots both grant: the deeper of two nested roots, nothing for roots apart, and a kind
|
||||
/// only one grants is not granted.
|
||||
#[test]
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! The Scripts folder: the `.js` and `.jsx` files File › Scripts lists, with each subfolder as a
|
||||
//! The Scripts folder: the `.js`, `.mjs` and `.jsx` files File › Scripts lists, with each subfolder as a
|
||||
//! submenu ([`list`]), and the read of one of them when it is chosen ([`read`]).
|
||||
//!
|
||||
//! A listing reads names and file types only, never a script's text. It follows no link: a symbolic
|
||||
@@ -279,7 +279,7 @@ pub(super) fn plain(path: &Path, folder: bool, shown: bool) -> bool {
|
||||
.is_ok_and(|m| !m.file_type().is_symlink() && (if folder { m.is_dir() } else { m.is_file() }) && !(shown && hidden_meta(&m)))
|
||||
}
|
||||
|
||||
/// Is `path` a script a listing of `root` can hold now: a `.js` or `.jsx` file at most
|
||||
/// Is `path` a script a listing of `root` can hold now: a `.js`, `.mjs` or `.jsx` file at most
|
||||
/// [`MAX_DEPTH`] folders below `root`, where `root`, each folder on the way and the file are there
|
||||
/// and none is a link, and neither the file nor a folder below `root` is marked hidden or system?
|
||||
pub fn holds(root: &Path, path: &Path) -> bool {
|
||||
|
||||
@@ -37,11 +37,21 @@
|
||||
//!
|
||||
//! The expanded source keeps a [`SourceMap`], so an error is reported at the line and column of
|
||||
//! the file it is in.
|
||||
//!
|
||||
//! A `.mjs` script is a module ([`module_script`]): it has no preprocessor lines, and the modules
|
||||
//! it imports are read by [`Files::module`]. A specifier is a path relative to the importing
|
||||
//! module's file, starting with `./` or `../` and naming a `.mjs` or `.js` file; a bare name, a URL
|
||||
//! and any other form are a `SyntaxError`. Its `..` names are taken off by name, and one that would
|
||||
//! lead above the script's folder is refused. Modules are read through the same [`ScriptScope`],
|
||||
//! so a link that leads out of the script's folder is refused as well. Module files count against
|
||||
//! the same limits as included files, and the paths of one file (two spellings, a link, or names
|
||||
//! that differ only in letter case on Windows) give one module.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_js::{DirectiveName, Options};
|
||||
use vectorcraft_js::{DirectiveName, LoadError, Options};
|
||||
|
||||
use crate::file_access::{ScriptRead, ScriptScope};
|
||||
|
||||
@@ -219,13 +229,65 @@ pub(crate) struct Files {
|
||||
frames: Vec<Frame>,
|
||||
/// The run reads ECMAScript 2015 ([`es2015_script`]): its files are parsed that way.
|
||||
es2015: bool,
|
||||
/// The modules a module run has read, by key ([`module_key`]): the names of the folders each
|
||||
/// is in, below the script's folder.
|
||||
module_dirs: HashMap<String, Vec<String>>,
|
||||
/// The key of each module path read, below the script's folder.
|
||||
module_paths: HashMap<String, String>,
|
||||
/// The key [`Files::module_entry`] gave the script, in a module run.
|
||||
entry_key: Option<String>,
|
||||
}
|
||||
|
||||
/// A script at `path` runs with [`vectorcraft_js::Options::es2015`] when its file name ends in
|
||||
/// `.js` (in any letter case); a `.jsx` script, any other file and a script given as text run as
|
||||
/// ECMAScript 5.1 with the ExtendScript extensions.
|
||||
/// `.js` or `.mjs` (in any letter case); a `.jsx` script, any other file and a script given as text
|
||||
/// run as ECMAScript 5.1 with the ExtendScript extensions.
|
||||
pub(crate) fn es2015_script(path: Option<&str>) -> bool {
|
||||
path.and_then(|p| Path::new(p).extension()).is_some_and(|e| e.eq_ignore_ascii_case("js"))
|
||||
path.and_then(|p| Path::new(p).extension()).is_some_and(|e| e.eq_ignore_ascii_case("js") || e.eq_ignore_ascii_case("mjs"))
|
||||
}
|
||||
|
||||
/// A script at `path` runs as a module when its file name ends in `.mjs` (in any letter case).
|
||||
pub(crate) fn module_script(path: Option<&str>) -> bool {
|
||||
path.and_then(|p| Path::new(p).extension()).is_some_and(|e| e.eq_ignore_ascii_case("mjs"))
|
||||
}
|
||||
|
||||
/// What names the file at the real path `real` among a run's modules: on Unix its device and file
|
||||
/// number, so two paths to one file give one module; elsewhere its real path, which on Windows
|
||||
/// spells each name in the letter case the folder stores it in, so two spellings of one file in a
|
||||
/// folder that ignores case give one module and two files in a folder that does not stay two.
|
||||
fn module_key(real: &Path) -> String {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
if let Ok(m) = std::fs::metadata(real) {
|
||||
return format!("{}:{}", m.dev(), m.ino());
|
||||
}
|
||||
}
|
||||
display(real).to_string()
|
||||
}
|
||||
|
||||
/// The names of the folders from `root` down to `dir`, both real paths, or `None` when `dir` is
|
||||
/// not `root` or below it, or has a name that is not Unicode.
|
||||
fn names_below(root: &Path, dir: &Path) -> Option<Vec<String>> {
|
||||
dir.strip_prefix(root).ok()?.components().map(|c| c.as_os_str().to_str().map(str::to_string)).collect()
|
||||
}
|
||||
|
||||
/// The names of a module specifier's path: one that starts with `./` or `../`, uses `/` between
|
||||
/// names and names a `.mjs` or `.js` file. A specifier in any other form is a syntax error.
|
||||
fn specifier_names(specifier: &str) -> Result<Vec<&str>, LoadError> {
|
||||
let wrong = |why: &str| Err(LoadError::Syntax(format!("module specifier '{specifier}' {why}")));
|
||||
if !(specifier.starts_with("./") || specifier.starts_with("../")) {
|
||||
return wrong("must start with './' or '../'");
|
||||
}
|
||||
if specifier.chars().any(|c| matches!(c, '\\' | ':' | '\0') || c.is_control()) {
|
||||
return wrong("must not contain \\, : or control characters");
|
||||
}
|
||||
let names: Vec<&str> = specifier.split('/').collect();
|
||||
let file = names.last().copied().unwrap_or_default();
|
||||
let ext = Path::new(file).extension().and_then(|e| e.to_str()).unwrap_or_default();
|
||||
if !(ext.eq_ignore_ascii_case("mjs") || ext.eq_ignore_ascii_case("js")) {
|
||||
return wrong("must name a .mjs or .js file");
|
||||
}
|
||||
Ok(names)
|
||||
}
|
||||
|
||||
/// The output being built: its UTF-16 text, the line it is on, the units since that line began,
|
||||
@@ -321,9 +383,91 @@ impl Files {
|
||||
levels: 0,
|
||||
frames: vec![Frame { shown: Arc::from(path.unwrap_or_default()), dir }],
|
||||
es2015: es2015_script(path),
|
||||
module_dirs: HashMap::new(),
|
||||
module_paths: HashMap::new(),
|
||||
entry_key: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Makes the run's files read ECMAScript 2015, as a module run given as text does.
|
||||
pub(crate) fn read_es2015(&mut self) {
|
||||
self.es2015 = true;
|
||||
}
|
||||
|
||||
/// The module `text`, the script's own, as a source of one file. → its key and the source.
|
||||
pub(crate) fn module_entry(&mut self, text: &str) -> Result<(String, Expanded), Failure> {
|
||||
self.bytes = self.bytes.saturating_add(text.len());
|
||||
let shown = self.frames.first().map(|f| f.shown.clone()).unwrap_or_else(|| Arc::from(""));
|
||||
let key = self.chain.first().map(|real| module_key(real)).unwrap_or_default();
|
||||
self.module_dirs.insert(key.clone(), Vec::new());
|
||||
self.entry_key = Some(key.clone());
|
||||
let map = SourceMap { files: vec![shown], segments: vec![Segment { out_line: 1, file: 0, line: 1, shift: 0 }] };
|
||||
Ok((key, Expanded { source: text.to_string(), map, name: None, strict: None, engine: None }))
|
||||
}
|
||||
|
||||
/// The module `specifier` names for the module `referrer` (a key [`Files::module_entry`] or
|
||||
/// this function gave). → the module's key, with its text and source map the first time the
|
||||
/// run reads it.
|
||||
pub(crate) fn module(&mut self, referrer: &str, specifier: &str) -> Result<(String, Option<(String, SourceMap)>), LoadError> {
|
||||
let names = specifier_names(specifier)?;
|
||||
let mut path = self.module_dirs.get(referrer).cloned().ok_or_else(|| LoadError::Other(format!("module not found: '{referrer}'")))?;
|
||||
for name in names {
|
||||
match name {
|
||||
"" | "." => {}
|
||||
".." => {
|
||||
if path.pop().is_none() {
|
||||
return Err(LoadError::Other(format!("module path leads out of the script's folder: '{specifier}'")));
|
||||
}
|
||||
}
|
||||
name => path.push(name.to_string()),
|
||||
}
|
||||
}
|
||||
let relative = path.join("/");
|
||||
if let Some(key) = self.module_paths.get(&relative) {
|
||||
return Ok((key.clone(), None));
|
||||
}
|
||||
let root =
|
||||
self.frames.first().and_then(|f| f.dir.clone()).ok_or_else(|| LoadError::Other(format!("script file read refused: {specifier}")))?;
|
||||
self.probes += 1;
|
||||
if self.probes > MAX_PROBES {
|
||||
return Err(LoadError::Range(format!("module search limit ({MAX_PROBES} paths) reached")));
|
||||
}
|
||||
let candidate = path.iter().fold(root.clone(), |p, name| p.join(name));
|
||||
// Another path to a module already read gives that module: the file is not read again, and
|
||||
// its text is not counted again.
|
||||
let loaded = &self.module_dirs;
|
||||
let read = self.scope.read_unless(&candidate, crate::script::MAX_SOURCE_BYTES, |real| loaded.contains_key(&module_key(real)));
|
||||
let (real, bytes) = match read {
|
||||
Ok(found) => found,
|
||||
Err(ScriptRead::Missing) => return Err(LoadError::Other(format!("module file not found: {specifier}"))),
|
||||
Err(ScriptRead::Refused) => return Err(LoadError::Other(format!("script file read refused: {specifier}"))),
|
||||
Err(ScriptRead::TooLarge) => return Err(LoadError::Range(format!("script file is too large: {specifier}"))),
|
||||
Err(ScriptRead::Failed(e)) => return Err(LoadError::Other(format!("cannot read script file {specifier}: {e}"))),
|
||||
};
|
||||
let key = module_key(&real);
|
||||
let Some(bytes) = bytes else {
|
||||
self.module_paths.insert(relative, key.clone());
|
||||
return Ok((key, None));
|
||||
};
|
||||
if self.bytes.saturating_add(bytes.len()) > MAX_TOTAL_BYTES {
|
||||
return Err(LoadError::Range("script source limit reached (32 MiB)".to_string()));
|
||||
}
|
||||
if self.files >= MAX_FILES {
|
||||
return Err(LoadError::Range(format!("module file limit ({MAX_FILES}) reached")));
|
||||
}
|
||||
let text = decode(&bytes, specifier).map_err(LoadError::Other)?;
|
||||
self.bytes += bytes.len();
|
||||
self.files += 1;
|
||||
self.module_paths.insert(relative, key.clone());
|
||||
// The module's relative imports start from the folder the file is in, whichever path to it
|
||||
// was read first; the path as written stands in when that folder is not below the script's.
|
||||
path.pop();
|
||||
let dir = folder_of(&real).and_then(|d| names_below(&root, &d)).unwrap_or(path);
|
||||
self.module_dirs.insert(key.clone(), dir);
|
||||
let map = SourceMap { files: vec![display(&real)], segments: vec![Segment { out_line: 1, file: 0, line: 1, shift: 0 }] };
|
||||
Ok((key, Some((text, map))))
|
||||
}
|
||||
|
||||
/// The options a file of this run is parsed with, preprocessor lines aside.
|
||||
pub(crate) fn options(&self) -> Options {
|
||||
Options { max_source_units: MAX_TOTAL_BYTES, es2015: self.es2015, e4x: true, ..Options::default() }
|
||||
@@ -362,12 +506,26 @@ impl Files {
|
||||
self.expand(shown, dir, text, true)
|
||||
}
|
||||
|
||||
/// The file `path` names for `$.evalFile`, relative to the file being run now, read and with its
|
||||
/// preprocessor lines read. It becomes the file being run until [`Files::end_eval`].
|
||||
pub(crate) fn eval_file(&mut self, path: &str) -> Result<Expanded, Failure> {
|
||||
/// The folder of the module `key` ([`Files::module`] gave it), from the script's folder.
|
||||
pub(crate) fn module_dir(&self, key: &str) -> Option<PathBuf> {
|
||||
let names = self.module_dirs.get(key)?;
|
||||
let root = self.frames.first().and_then(|f| f.dir.clone())?;
|
||||
Some(names.iter().fold(root, |p, name| p.join(name)))
|
||||
}
|
||||
|
||||
/// The script's folder when the run is a module run ([`Files::module_entry`] read the script),
|
||||
/// or `None` for a script run.
|
||||
pub(crate) fn entry_module_dir(&self) -> Option<PathBuf> {
|
||||
self.module_dir(self.entry_key.as_deref()?)
|
||||
}
|
||||
|
||||
/// The file `path` names for `$.evalFile`, relative to the file being run now, or to the folder
|
||||
/// `module_dir` when a module's code calls it, read and with its preprocessor lines read. It
|
||||
/// becomes the file being run until [`Files::end_eval`].
|
||||
pub(crate) fn eval_file(&mut self, path: &str, module_dir: Option<PathBuf>) -> Result<Expanded, Failure> {
|
||||
let current = self.frames.last().map(|f| f.shown.clone()).unwrap_or_else(|| Arc::from(""));
|
||||
let fail = |kind, message: String| Failure { kind, message, index: 0, file: current.clone(), line: 0, column: 0 };
|
||||
let dir = self.frames.last().and_then(|f| f.dir.clone());
|
||||
let dir = module_dir.or_else(|| self.frames.last().and_then(|f| f.dir.clone()));
|
||||
let (real, bytes) = self.open(path, dir.as_deref(), false).map_err(|(kind, message)| fail(kind, message))?;
|
||||
let text = self.admit(&real, bytes, path).map_err(|(kind, message)| fail(kind, message))?;
|
||||
let shown = display(&real);
|
||||
|
||||
@@ -66,7 +66,8 @@ use std::sync::Arc;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_js::{
|
||||
Data, DataLimits, HostError, HostFunction, HostItem, Interrupt, LimitKind, Limits, Options, Progress, Realm, RunError, RunErrorKind,
|
||||
Data, DataLimits, HostError, HostFunction, HostItem, Interrupt, LimitKind, Limits, LoadError, LoadedModule, ModuleLimits, Options, Progress,
|
||||
Realm, RunError, RunErrorKind,
|
||||
};
|
||||
|
||||
use crate::{
|
||||
@@ -207,6 +208,8 @@ pub(crate) struct Request {
|
||||
pub locale: String,
|
||||
/// The answers to the dialogs of a run with nobody to ask, in order.
|
||||
pub answers: Vec<DialogAnswer>,
|
||||
/// The script runs as an ECMAScript 2015 module, as a `.mjs` file does ([`include::module_script`]).
|
||||
pub module: bool,
|
||||
/// The actions `app.doScript` can play.
|
||||
pub actions: Vec<actions::Playable>,
|
||||
}
|
||||
@@ -784,6 +787,9 @@ struct Host {
|
||||
script_map: RefCell<include::SourceMap>,
|
||||
/// The same for each source `$.evalFile` gave, in order.
|
||||
eval_maps: RefCell<Vec<include::SourceMap>>,
|
||||
/// The module key ([`include::Files::module`]) of each of [`Host::eval_maps`] that is a
|
||||
/// module's, by its index there.
|
||||
module_maps: RefCell<HashMap<usize, String>>,
|
||||
/// The file, line and column of each error `$.evalFile` raised for a file it could not run, in
|
||||
/// order: the error's mark ([`HostError::Marked`]) is its index.
|
||||
eval_failures: RefCell<Vec<(Arc<str>, u32, u32)>>,
|
||||
@@ -979,6 +985,22 @@ impl Host {
|
||||
}
|
||||
}
|
||||
|
||||
/// The folder of the module whose source has `tag`, when it is a module of a module run: the
|
||||
/// script itself or a module it imported (not a file `$.evalFile` gave, or code from another
|
||||
/// run).
|
||||
fn module_dir_at(&self, tag: u32) -> Option<std::path::PathBuf> {
|
||||
let script = self.script_tag.get();
|
||||
if tag == vectorcraft_js::UNKNOWN_SOURCE || script == vectorcraft_js::UNKNOWN_SOURCE {
|
||||
return None;
|
||||
}
|
||||
let n = tag.checked_sub(script)?;
|
||||
if n == 0 {
|
||||
return self.files.borrow().entry_module_dir();
|
||||
}
|
||||
let key = self.module_maps.borrow().get(&(n as usize - 1)).cloned()?;
|
||||
self.files.borrow().module_dir(&key)
|
||||
}
|
||||
|
||||
/// Adds a line to the run's console and, during a slice, to the session's.
|
||||
fn line(&self, entry: console::Entry, cut: bool) {
|
||||
let line = console::ConsoleLine { run: self.run, name: self.name.clone(), entry };
|
||||
@@ -1596,6 +1618,7 @@ fn dollar_object(link: &Link, info: dollar::RunInfo, localization: &Rc<vectorcra
|
||||
}
|
||||
}),
|
||||
strict_writes: Rc::new(move || current(&strict).ok().and_then(|h| h.eval_strict.get())),
|
||||
site: true,
|
||||
}
|
||||
};
|
||||
let mut items = vec![
|
||||
@@ -1610,9 +1633,17 @@ fn dollar_object(link: &Link, info: dollar::RunInfo, localization: &Rc<vectorcra
|
||||
}
|
||||
|
||||
/// `$.evalFile(path[, timeout])`: the source of the file `path` names, relative to the file being
|
||||
/// run, with its preprocessor lines read, which the interpreter then runs. `timeout`, in
|
||||
/// milliseconds, is taken and not waited on: the file is read at once.
|
||||
fn eval_file(host: &Host, args: Vec<Data>) -> std::result::Result<Data, HostError> {
|
||||
/// run (for a call in a module the script imported, that module's file), with its preprocessor
|
||||
/// lines read, which the interpreter then runs. `timeout`, in milliseconds, is taken and not
|
||||
/// waited on: the file is read at once. `args` starts with the call's place, as
|
||||
/// [`HostItem::Evaluator`] gives it with `site`.
|
||||
fn eval_file(host: &Host, mut args: Vec<Data>) -> std::result::Result<Data, HostError> {
|
||||
let tag = match args.first() {
|
||||
Some(Data::Number(n)) if args.len() >= 3 => *n as u32,
|
||||
_ => vectorcraft_js::UNKNOWN_SOURCE,
|
||||
};
|
||||
args.drain(..3.min(args.len()));
|
||||
let module_dir = host.module_dir_at(tag);
|
||||
let Some(Data::String(path)) = args.first().filter(|p| !matches!(p, Data::String(s) if s.is_empty())) else {
|
||||
return Err(HostError::Type(EVAL_NO_PATH.to_string()));
|
||||
};
|
||||
@@ -1626,7 +1657,7 @@ fn eval_file(host: &Host, args: Vec<Data>) -> std::result::Result<Data, HostErro
|
||||
return Err(HostError::Type(EVAL_ARGUMENTS.to_string()));
|
||||
}
|
||||
host.charge_call(path.len() as u64 + 2)?;
|
||||
let expanded = host.files.borrow_mut().eval_file(path).map_err(|f| {
|
||||
let expanded = host.files.borrow_mut().eval_file(path, module_dir).map_err(|f| {
|
||||
let message = if f.line > 0 { format!("{}:{}:{}: {}", f.file, f.line, f.column, f.message) } else { f.message };
|
||||
let error = match f.kind {
|
||||
include::FailKind::Limit => HostError::Abort(message),
|
||||
@@ -1736,6 +1767,22 @@ fn explained(e: &RunError) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// The module `specifier` names for the module `referrer` of the run of `host`, read through the
|
||||
/// run's files. Its source map is kept with the maps of the sources the run evaluates, in the order
|
||||
/// the modules are read, which is the order of their sources' tags.
|
||||
fn load_module(host: &Host, referrer: &str, specifier: &str) -> std::result::Result<LoadedModule, LoadError> {
|
||||
let (key, read) = host.files.borrow_mut().module(referrer, specifier)?;
|
||||
let source = read.map(|(text, map)| {
|
||||
let mut maps = host.eval_maps.borrow_mut();
|
||||
host.module_maps.borrow_mut().insert(maps.len(), key.clone());
|
||||
maps.push(map);
|
||||
drop(maps);
|
||||
host.disk.borrow_mut().saw_code(&text.encode_utf16().collect::<Vec<u16>>());
|
||||
text
|
||||
});
|
||||
Ok(LoadedModule { key, source })
|
||||
}
|
||||
|
||||
/// The error of a run that stopped in its preprocessor lines (`f`), as the realm gives its own.
|
||||
fn preprocessor_error(f: include::Failure) -> (RunError, Option<Arc<str>>) {
|
||||
let (kind, message) = match f.kind {
|
||||
@@ -2153,7 +2200,19 @@ impl Session {
|
||||
self.script_stop.clear();
|
||||
self.script_report = None;
|
||||
let mut files = include::Files::new(request.file.as_deref(), request.checked_real, include::Files::jsinclude_env());
|
||||
let expanded = files.expand_script(&request.source);
|
||||
if request.module {
|
||||
files.read_es2015();
|
||||
}
|
||||
// A module (a `.mjs` file, or a script run with `module`) has no preprocessor lines;
|
||||
// `module_key` names it among the modules it imports.
|
||||
let (expanded, module_key) = if request.module {
|
||||
match files.module_entry(&request.source) {
|
||||
Ok((key, expanded)) => (Ok(expanded), Some(key)),
|
||||
Err(f) => (Err(f), None),
|
||||
}
|
||||
} else {
|
||||
(files.expand_script(&request.source), None)
|
||||
};
|
||||
let name = match &expanded {
|
||||
Ok(include::Expanded { name: Some(name), .. }) if !request.name_given => name.clone(),
|
||||
_ => request.name,
|
||||
@@ -2184,9 +2243,8 @@ impl Session {
|
||||
// from its first run, and they act for the run that calls them.
|
||||
let fresh = realm.is_none();
|
||||
// A `.js` script reads ECMAScript 2015; `eval`, `Function`, includes and `$.evalFile` read
|
||||
// code the way the script does. Its realm has `Promise`: a kept realm gets it at the first
|
||||
// `.js` run that names it, and keeps it as it keeps its globals.
|
||||
let es2015 = include::es2015_script(request.file.as_deref());
|
||||
// code the way the script does. Its realm has `Promise`; a kept realm retains it.
|
||||
let es2015 = request.module || include::es2015_script(request.file.as_deref());
|
||||
let options = Options { max_source_units: include::MAX_TOTAL_BYTES.saturating_mul(2), es2015, e4x: true, ..Options::default() };
|
||||
let strict = options.strict;
|
||||
// A kept engine reads each run's code the way that run's script does.
|
||||
@@ -2255,6 +2313,7 @@ impl Session {
|
||||
files: RefCell::new(files),
|
||||
script_map: RefCell::default(),
|
||||
eval_maps: RefCell::default(),
|
||||
module_maps: RefCell::default(),
|
||||
eval_failures: RefCell::default(),
|
||||
script_tag: Cell::new(vectorcraft_js::UNKNOWN_SOURCE),
|
||||
report_name: Arc::from(name.as_str()),
|
||||
@@ -2319,7 +2378,13 @@ impl Session {
|
||||
.and_then(|()| if fresh { dom::install(&mut realm, &link) } else { Ok(()) })
|
||||
.and_then(|()| if fresh { files::install(&mut realm, &link) } else { realm.reset_folder_current() })
|
||||
.and_then(|()| {
|
||||
let r = realm.start(&expanded.source);
|
||||
let r = match &module_key {
|
||||
None => realm.start(&expanded.source),
|
||||
Some(key) => {
|
||||
let limits = ModuleLimits { modules: include::MAX_FILES + 1, depth: include::MAX_DEPTH };
|
||||
realm.start_module(key, &expanded.source, limits, &mut |referrer, specifier| load_module(&host, referrer, specifier))
|
||||
}
|
||||
};
|
||||
// Source that does not compile defines no code, so its map is not kept.
|
||||
if !matches!(&r, Err(e) if e.kind == RunErrorKind::Syntax) {
|
||||
host.script_tag.set(realm.script_tag());
|
||||
|
||||
@@ -184,6 +184,7 @@ mod script_engines;
|
||||
mod script_folder;
|
||||
mod script_include;
|
||||
mod script_io;
|
||||
mod script_modules;
|
||||
mod script_run;
|
||||
mod script_scriptui;
|
||||
mod script_styles;
|
||||
|
||||
@@ -3195,6 +3195,19 @@ fn a_heavy_filter_installs_once_the_user_agrees() {
|
||||
assert!(install(&mut s, DESATURATE).get("budget").is_none());
|
||||
}
|
||||
|
||||
/// The refusal of a heavy filter names it as prompts show text: a right-to-left override in its
|
||||
/// name is escaped, so it can't reorder the message around it.
|
||||
#[test]
|
||||
fn a_heavy_filter_refusal_escapes_its_name() {
|
||||
let mut s = session();
|
||||
// The override as a JSON escape in the manifest.
|
||||
let rlo = format!("\\u{:04X}", 0x202E);
|
||||
let manifest = format!(r#"{{"id":"test.engine.heavy.name","name":"Route{rlo}txt.exe","version":"1","kind":"filter","budget":"heavy"}}"#);
|
||||
let module = wat::parse_str(tpl::spinning(&manifest, 1, r#"{"objects":[]}"#)).unwrap();
|
||||
let e = s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&module)})).unwrap_err().to_string();
|
||||
assert!(e.contains("“Route\\u{202E}txt.exe” asks for a heavy budget"), "{e}");
|
||||
}
|
||||
|
||||
/// A module that carries its manifest in a `vc_manifest` custom section is inspected and installed
|
||||
/// without any of its code running: its start function traps and its `vc_manifest` export loops.
|
||||
#[test]
|
||||
|
||||
@@ -376,6 +376,7 @@ fn an_installed_run_reads_its_includes_in_the_folder_its_read_found() {
|
||||
fuel: script::DEFAULT_FUEL,
|
||||
locale: "en_US".into(),
|
||||
answers: Vec::new(),
|
||||
module: false,
|
||||
actions: Vec::new(),
|
||||
};
|
||||
s.script_start(request).unwrap();
|
||||
|
||||
@@ -0,0 +1,315 @@
|
||||
//! `.mjs` scripts: modules, the modules they import from the script's folder, the refusals of
|
||||
//! specifiers and paths, the run's limits, and errors at the file they are in.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::*;
|
||||
|
||||
/// A fresh folder for test `name`, with a `main` folder inside it for the script.
|
||||
fn folder(name: &str) -> PathBuf {
|
||||
let base = std::env::temp_dir().join(format!("vc-script-modules-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
std::fs::create_dir_all(base.join("main")).unwrap();
|
||||
base
|
||||
}
|
||||
|
||||
fn write(path: &Path, text: &str) {
|
||||
if let Some(dir) = path.parent() {
|
||||
std::fs::create_dir_all(dir).unwrap();
|
||||
}
|
||||
std::fs::write(path, text).unwrap();
|
||||
}
|
||||
|
||||
/// Runs `main/<file>` in `base`, with the text `text`.
|
||||
fn run_file(base: &Path, file: &str, text: &str) -> (Result<Value>, Session) {
|
||||
let main = base.join("main").join(file);
|
||||
write(&main, text);
|
||||
let mut s = Session::new();
|
||||
let r = s.execute("script.run", &json!({"path": main.to_string_lossy()}));
|
||||
(r, s)
|
||||
}
|
||||
|
||||
fn run(base: &Path, text: &str) -> Result<Value> {
|
||||
run_file(base, "main.mjs", text).0
|
||||
}
|
||||
|
||||
/// The report of the run of `main/main.mjs` that failed.
|
||||
fn failed(base: &Path, text: &str) -> Value {
|
||||
let (r, s) = run_file(base, "main.mjs", text);
|
||||
assert!(r.is_err(), "the run failed: {r:?}");
|
||||
s.script_report().unwrap().clone()
|
||||
}
|
||||
|
||||
fn message(report: &Value) -> &str {
|
||||
report["message"].as_str().unwrap_or_default()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_module_imports_from_its_folder_and_below() {
|
||||
let base = folder("imports");
|
||||
write(&base.join("main/lib/count.mjs"), "export let n = 0;\nexport function inc() { n++; }\nexport default 'lib';");
|
||||
write(
|
||||
&base.join("main/lib/use.mjs"),
|
||||
"import { inc } from './count.mjs';\nimport name from '../lib/count.mjs';\nexport const used = name;\ninc();",
|
||||
);
|
||||
let text = "import { n, inc } from './lib/count.mjs';\nimport { used } from './lib/use.mjs';\ninc();\nvc.log([n, used, this === undefined, /main\\.mjs$/.test($.fileName)]);";
|
||||
let r = run(&base, text).unwrap();
|
||||
// count.mjs ran once: use.mjs and the script share its binding.
|
||||
assert_eq!(r["log"], json!([[2, "lib", true, true]]));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_module_two_modules_import_each_other() {
|
||||
let base = folder("cycle");
|
||||
write(&base.join("main/a.mjs"), "import { b } from './b.mjs';\nexport function a() { return 'a' + b(); }");
|
||||
write(&base.join("main/b.mjs"), "import { a } from './a.mjs';\nexport function b() { return 'b'; }\nexport const viaA = () => a();");
|
||||
let r = run(&base, "import { a } from './a.mjs';\nimport { viaA } from './b.mjs';\nvc.log([a(), viaA()]);").unwrap();
|
||||
assert_eq!(r["log"], json!([["ab", "ab"]]));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_module_path_above_the_script_folder_is_refused() {
|
||||
let base = folder("above");
|
||||
write(&base.join("outside.mjs"), "export var leaked = 1;");
|
||||
let report = failed(&base, "vc.log(1);\nimport { leaked } from '../outside.mjs';");
|
||||
assert!(message(&report).contains("module path leads out of the script's folder: '../outside.mjs'"), "{report}");
|
||||
assert_eq!((report["line"].as_u64(), report["log"].clone()), (Some(2), json!([])), "{report}");
|
||||
// `..` names that stay inside are read by name.
|
||||
write(&base.join("main/sub/x.mjs"), "export var x = 'x';");
|
||||
let r = run(&base, "import { x } from './sub/../sub/./x.mjs';\nvc.log(x);").unwrap();
|
||||
assert_eq!(r["log"], json!(["x"]));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_module_missing_file_is_named() {
|
||||
let base = folder("missing");
|
||||
write(&base.join("main/a.mjs"), "import './nope.mjs';");
|
||||
let report = failed(&base, "import './a.mjs';");
|
||||
assert!(message(&report).contains("module file not found: ./nope.mjs"), "{report}");
|
||||
assert!(report["file"].as_str().unwrap().ends_with("a.mjs"), "{report}");
|
||||
assert_eq!(report["line"], 1);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_module_specifiers_other_than_relative_paths_are_syntax_errors() {
|
||||
let base = folder("specifiers");
|
||||
// The specifier as the script writes it, as the error names it, and why it is refused.
|
||||
for (written, shown, why) in [
|
||||
("lib", "lib", "must start with './' or '../'"),
|
||||
("lib/x.mjs", "lib/x.mjs", "must start with './' or '../'"),
|
||||
("https://example.com/x.mjs", "https://example.com/x.mjs", "must start with './' or '../'"),
|
||||
("/abs/x.mjs", "/abs/x.mjs", "must start with './' or '../'"),
|
||||
("./C:x.mjs", "./C:x.mjs", "must not contain"),
|
||||
("./a\\u005cb.mjs", "./a\\b.mjs", "must not contain"),
|
||||
("./x.txt", "./x.txt", "must name a .mjs or .js file"),
|
||||
("./x", "./x", "must name a .mjs or .js file"),
|
||||
] {
|
||||
let report = failed(&base, &format!("import '{written}';"));
|
||||
let expected = format!("SyntaxError: module specifier '{shown}' {why}");
|
||||
assert!(message(&report).starts_with(&expected), "{written}: {report}");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_module_errors_are_at_the_file_they_are_in() {
|
||||
let base = folder("errors");
|
||||
write(&base.join("main/bad.mjs"), "export var a = 1;\nexport var = 2;");
|
||||
let report = failed(&base, "import { a } from './bad.mjs';");
|
||||
assert_eq!(report["kind"], "syntax", "{report}");
|
||||
assert!(report["file"].as_str().unwrap().ends_with("bad.mjs"), "{report}");
|
||||
assert_eq!(report["line"], 2);
|
||||
write(&base.join("main/thrower.mjs"), "export var a = 1;\n\nthrow new Error('from thrower');");
|
||||
let report = failed(&base, "import { a } from './thrower.mjs';\nvc.log(a);");
|
||||
assert!(report["file"].as_str().unwrap().ends_with("thrower.mjs"), "{report}");
|
||||
assert_eq!((report["line"].as_u64(), report["log"].clone()), (Some(3), json!([])), "{report}");
|
||||
let report = failed(&base, "import { b } from './thrower.mjs';");
|
||||
assert!(message(&report).contains("the module './thrower.mjs' has no export named 'b'"), "{report}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_module_preprocessor_lines_and_scripts_differ_by_extension() {
|
||||
let base = folder("kinds");
|
||||
write(&base.join("main/lib.jsxinc"), "var included = 1;");
|
||||
// A module has no preprocessor lines.
|
||||
let report = failed(&base, "#include \"lib.jsxinc\"\n");
|
||||
assert_eq!(report["kind"], "syntax", "{report}");
|
||||
// A .js or .jsx script does not read import or export.
|
||||
for file in ["main.js", "main.jsx"] {
|
||||
let (r, s) = run_file(&base, file, "import { a } from './a.mjs';");
|
||||
assert!(r.is_err(), "{file}");
|
||||
assert_eq!(s.script_report().unwrap()["kind"], "syntax", "{file}");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_module_files_count_against_the_include_limits() {
|
||||
let base = folder("limits");
|
||||
for i in 0..70 {
|
||||
write(&base.join(format!("main/m{i}.mjs")), &format!("import './m{}.mjs';", i + 1));
|
||||
}
|
||||
let report = failed(&base, "import './m0.mjs';");
|
||||
assert!(message(&report).contains("limit"), "{report}");
|
||||
assert_eq!(report["log"], json!([]));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_module_paths_of_one_file_give_one_module() {
|
||||
let base = folder("same");
|
||||
write(&base.join("main/once.mjs"), "vc.log('ran');\nexport var v = 1;");
|
||||
let mut text = "import { v } from './once.mjs';\nimport { v as w } from './sub/../once.mjs';\n".to_string();
|
||||
// Windows file names ignore letter case.
|
||||
if cfg!(windows) {
|
||||
text.push_str("import { v as u } from './ONCE.mjs';\n");
|
||||
}
|
||||
let r = run(&base, &text).unwrap();
|
||||
assert_eq!(r["log"], json!(["ran"]));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// Makes `link` lead to the folder `target`: a junction on Windows, a symbolic link elsewhere.
|
||||
/// `false` when the system does not allow it here.
|
||||
fn link_folder(target: &Path, link: &Path) -> bool {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let made = std::process::Command::new("cmd").args(["/C", "mklink", "/J"]).arg(link).arg(target).output().is_ok_and(|o| o.status.success());
|
||||
made && std::fs::canonicalize(link).ok() == std::fs::canonicalize(target).ok()
|
||||
}
|
||||
#[cfg(unix)]
|
||||
{
|
||||
std::os::unix::fs::symlink(target, link).is_ok()
|
||||
}
|
||||
#[cfg(not(any(unix, windows)))]
|
||||
{
|
||||
let _ = (target, link);
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_module_link_out_of_the_folder_is_refused() {
|
||||
let base = folder("link");
|
||||
write(&base.join("outside/x.mjs"), "export var leaked = 1;");
|
||||
if !link_folder(&base.join("outside"), &base.join("main").join("away")) {
|
||||
eprintln!("skipped: a folder link can't be made here");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
return;
|
||||
}
|
||||
let report = failed(&base, "import { leaked } from './away/x.mjs';\nvc.log(leaked);");
|
||||
assert!(message(&report).contains("script file read refused: ./away/x.mjs"), "{report}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_module_is_listed_and_taken_by_path() {
|
||||
assert!(cmd::scripts::runs("tool.MJS"));
|
||||
let base = folder("text");
|
||||
let root = base.join("Scripts");
|
||||
write(&root.join("tool.mjs"), "export var a = 1;");
|
||||
let mut s = Session::new();
|
||||
s.attach_scripts_dir(root.clone());
|
||||
let listed = s.execute("script.listInstalled", &json!({})).unwrap();
|
||||
assert_eq!(listed["scripts"], json!([{"path": root.join("tool.mjs").to_string_lossy(), "label": "tool", "folders": []}]));
|
||||
// A script given as text is not a module, whatever its name.
|
||||
let mut s = Session::new();
|
||||
let r = s.execute("script.run", &json!({"source": "export var a = 1;", "name": "t.mjs"}));
|
||||
assert!(r.is_err());
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_module_is_chosen_by_the_module_param() {
|
||||
let mut s = Session::new();
|
||||
let r = s.execute("script.run", &json!({"source": "export var a = 1;\nvc.log([a, this === undefined]);", "module": true})).unwrap();
|
||||
assert_eq!(r["log"], json!([[1, true]]));
|
||||
// A source run as a module imports no files.
|
||||
let r = s.execute("script.run", &json!({"source": "import { b } from './b.mjs';", "module": true}));
|
||||
assert!(r.is_err());
|
||||
assert!(message(s.script_report().unwrap()).contains("./b.mjs"), "{:?}", s.script_report());
|
||||
let r = s.execute("script.run", &json!({"source": "export var a = 1;", "module": "yes"}));
|
||||
assert!(matches!(r, Err(EngineError::BadParams { .. })), "{r:?}");
|
||||
// `module: false` runs a .mjs file as a script, where `export` is a syntax error.
|
||||
let base = folder("param");
|
||||
let main = base.join("main").join("main.mjs");
|
||||
write(&main, "export var a = 1;");
|
||||
let r = s.execute("script.run", &json!({"path": main.to_string_lossy(), "module": false}));
|
||||
assert!(r.is_err());
|
||||
assert_eq!(s.script_report().unwrap()["kind"], "syntax");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_module_read_again_through_another_path_is_not_counted_again() {
|
||||
let base = folder("budget");
|
||||
// 7 MiB, under the 8 MiB a file may have; five reads of it would pass the 32 MiB of a run.
|
||||
let big = format!("export var v = 1;\n//{}", "x".repeat(7 * 1024 * 1024));
|
||||
write(&base.join("main/lib/big.mjs"), &big);
|
||||
let mut text = String::new();
|
||||
for i in 0..5 {
|
||||
if !link_folder(&base.join("main/lib"), &base.join(format!("main/l{i}"))) {
|
||||
eprintln!("skipped: a folder link can't be made here");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
return;
|
||||
}
|
||||
text.push_str(&format!("import {{ v as v{i} }} from './l{i}/big.mjs';\n"));
|
||||
}
|
||||
text.push_str("vc.log(v0 + v4);");
|
||||
let r = run(&base, &text);
|
||||
assert_eq!(r.map(|r| r["log"].clone()).ok(), Some(json!([2])));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_module_imports_are_read_from_the_folder_the_file_is_in() {
|
||||
let base = folder("realdir");
|
||||
write(&base.join("main/real/user.mjs"), "import { d } from './dep.mjs';\nexport const got = d;");
|
||||
write(&base.join("main/real/dep.mjs"), "export const d = 'real';");
|
||||
write(&base.join("main/other/dep.mjs"), "export const d = 'other';");
|
||||
#[cfg(unix)]
|
||||
let linked = std::os::unix::fs::symlink(base.join("main/real/user.mjs"), base.join("main/other/user.mjs")).is_ok();
|
||||
#[cfg(windows)]
|
||||
let linked = std::os::windows::fs::symlink_file(base.join("main/real/user.mjs"), base.join("main/other/user.mjs")).is_ok();
|
||||
#[cfg(not(any(unix, windows)))]
|
||||
let linked = false;
|
||||
if !linked {
|
||||
eprintln!("skipped: a file link can't be made here");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
return;
|
||||
}
|
||||
let r = run(&base, "import { got } from './other/user.mjs';\nvc.log(got);").unwrap();
|
||||
assert_eq!(r["log"], json!(["real"]));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_module_eval_file_reads_beside_the_module_that_calls_it() {
|
||||
let base = folder("evalfile");
|
||||
write(&base.join("main/helper.jsx"), "'top'");
|
||||
write(&base.join("main/sub/helper.jsx"), "'sub'");
|
||||
write(&base.join("main/sub/m.mjs"), "export const got = $.evalFile('helper.jsx');");
|
||||
let r = run(&base, "import { got } from './sub/m.mjs';\nvc.log([got, $.evalFile('helper.jsx')]);").unwrap();
|
||||
assert_eq!(r["log"], json!([["sub", "top"]]));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_module_function_of_the_script_reads_beside_the_script_when_another_file_calls_it() {
|
||||
let base = folder("evalfile-entry");
|
||||
write(&base.join("main/helper.jsx"), "'top'");
|
||||
write(&base.join("main/sub/helper.jsx"), "'sub'");
|
||||
// The file in `sub` calls the script's function while it is the file being run.
|
||||
write(&base.join("main/sub/caller.jsx"), "$.global.load()");
|
||||
let text = "$.global.load = function () { return $.evalFile('helper.jsx'); };\nvc.log($.evalFile('sub/caller.jsx'));";
|
||||
let r = run(&base, text).unwrap();
|
||||
assert_eq!(r["log"], json!(["top"]));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
@@ -118,7 +118,7 @@ fn a_script_refused_before_it_runs_has_not_started() {
|
||||
let r = result(&mut session(), &json!({"path": "notes.txt", "maxFuel": FUEL, "answers": []}));
|
||||
assert_eq!(r["started"], false);
|
||||
assert_eq!(r["ok"], false);
|
||||
assert!(r["message"].as_str().unwrap().contains(".js or .jsx"), "{r}");
|
||||
assert!(r["message"].as_str().unwrap().contains(".js, .mjs or .jsx"), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -619,6 +619,62 @@ pub struct Program {
|
||||
pub(crate) supers: crate::parser::SuperRules,
|
||||
}
|
||||
|
||||
/// The name an import takes from the module it names, or an export from a module it re-exports.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum ImportName {
|
||||
/// The export of this name (`default` for a default import).
|
||||
Name(String),
|
||||
/// The module's namespace object (`* as ns`).
|
||||
Namespace,
|
||||
}
|
||||
|
||||
/// A module a module imports or re-exports from: the specifier as written and where it stands.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ModuleRequest {
|
||||
/// The specifier as text, with each unpaired surrogate written as U+FFFD.
|
||||
pub specifier: String,
|
||||
/// The specifier's string value, code unit for code unit (ECMA-262 2015 section 15.2.1.16,
|
||||
/// ModuleRequests). It may hold an unpaired surrogate, which no host path can name.
|
||||
pub units: Vec<u16>,
|
||||
pub span: Span,
|
||||
}
|
||||
|
||||
/// One name an import declaration binds (ECMA-262 2015 section 15.2.1.16, ImportEntry).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ImportEntry {
|
||||
/// The index of the module in [`ModuleInfo::requests`].
|
||||
pub request: usize,
|
||||
pub import: ImportName,
|
||||
/// The name bound in the importing module.
|
||||
pub local: Name,
|
||||
}
|
||||
|
||||
/// One name a module exports (ExportEntry).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum ExportEntry {
|
||||
/// `export_name` is the module's own binding `local` (`*default*` for a default export of an
|
||||
/// expression or an anonymous function).
|
||||
Local { export_name: String, local: String, span: Span },
|
||||
/// `export_name` is the export `import` of the module `request` (`export { a as b } from`,
|
||||
/// `export * as ns from`, or an exported import).
|
||||
Indirect { export_name: String, request: usize, import: ImportName, span: Span },
|
||||
/// Every export of the module `request` but `default` (`export * from`).
|
||||
Star { request: usize, span: Span },
|
||||
}
|
||||
|
||||
/// What a module imports and exports, read by [`crate::parse_module`].
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct ModuleInfo {
|
||||
/// The modules it names, each specifier once, in the order they first appear.
|
||||
pub requests: Vec<ModuleRequest>,
|
||||
pub imports: Vec<ImportEntry>,
|
||||
pub exports: Vec<ExportEntry>,
|
||||
}
|
||||
|
||||
/// The binding name of a default export that has no name of its own (ECMA-262 2015 section
|
||||
/// 15.2.3.5); no identifier can name it.
|
||||
pub const DEFAULT_BINDING: &str = "*default*";
|
||||
|
||||
impl Program {
|
||||
/// The line and column (both from 1, the column in UTF-16 code units) of a source offset.
|
||||
pub fn line_column(&self, offset: u32) -> (u32, u32) {
|
||||
|
||||
@@ -591,7 +591,7 @@ fn object_value_of(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> Js
|
||||
fn has_own_property(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
let k = interp.to_prop_key(&arg(args, 0))?;
|
||||
let o = interp.to_object(&this)?;
|
||||
Ok(Value::Bool(interp.get_own_pk(o, &k)?.is_some() || interp.is_host_member_pk(o, &k)?))
|
||||
Ok(Value::Bool(interp.own_pk(o, &k)?.is_some() || interp.is_host_member_pk(o, &k)?))
|
||||
}
|
||||
|
||||
fn is_prototype_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
@@ -610,7 +610,7 @@ fn is_prototype_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) ->
|
||||
fn property_is_enumerable(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
let k = interp.to_prop_key(&arg(args, 0))?;
|
||||
let o = interp.to_object(&this)?;
|
||||
Ok(Value::Bool(interp.get_own_pk(o, &k)?.is_some_and(|p| p.enumerable()) || interp.is_host_member_pk(o, &k)?))
|
||||
Ok(Value::Bool(interp.own_pk(o, &k)?.is_some_and(|p| p.enumerable()) || interp.is_host_member_pk(o, &k)?))
|
||||
}
|
||||
|
||||
// ---- Function ----
|
||||
|
||||
@@ -139,7 +139,7 @@ fn get_own_property_descriptor(interp: &mut Interp, _: Value, args: &[Value], _:
|
||||
let o = interp.to_object(&arg(args, 0))?;
|
||||
interp.rooted(&[Value::Object(o)], |interp| {
|
||||
let k = interp.to_prop_key(&arg(args, 1))?;
|
||||
match interp.get_own_pk(o, &k)? {
|
||||
match interp.own_pk(o, &k)? {
|
||||
Some(p) => from_prop(interp, &p),
|
||||
None => Ok(Value::Undefined),
|
||||
}
|
||||
@@ -282,7 +282,7 @@ fn locked(interp: &mut Interp, v: &Value, frozen: bool) -> JsResult<Value> {
|
||||
let o = *o;
|
||||
for k in own_prop_keys(interp, o)? {
|
||||
interp.use_fuel()?;
|
||||
let Some(prop) = interp.get_own_pk(o, &k)? else { continue };
|
||||
let Some(prop) = interp.own_pk(o, &k)? else { continue };
|
||||
if prop.configurable() || (frozen && matches!(prop, Prop::Data { flags, .. } if flags & WRITABLE != 0)) {
|
||||
return Ok(Value::Bool(false));
|
||||
}
|
||||
@@ -311,7 +311,7 @@ fn keys(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Valu
|
||||
let mut names = Vec::new();
|
||||
for k in interp.own_keys(o)? {
|
||||
interp.use_fuel()?;
|
||||
if interp.get_own_property(o, &k)?.is_some_and(|p| p.enumerable()) {
|
||||
if interp.own_property(o, &k)?.is_some_and(|p| p.enumerable()) {
|
||||
names.push(k);
|
||||
}
|
||||
}
|
||||
|
||||
+67
-23
@@ -98,6 +98,8 @@ struct FnCompiler<'a> {
|
||||
recursion: u32,
|
||||
/// The code was read with [`crate::Options::es2015`]: blocks have scopes of their own.
|
||||
es2015: bool,
|
||||
/// The code is a module's ([`compile_module`]), which has no completion value.
|
||||
module: bool,
|
||||
scopes: Vec<BlockScope>,
|
||||
templates: Vec<Template>,
|
||||
uses_this: bool,
|
||||
@@ -156,6 +158,7 @@ impl<'a> FnCompiler<'a> {
|
||||
uses_arguments: false,
|
||||
recursion,
|
||||
es2015: false,
|
||||
module: false,
|
||||
scopes: Vec::new(),
|
||||
templates: Vec::new(),
|
||||
uses_this: false,
|
||||
@@ -169,6 +172,12 @@ impl<'a> FnCompiler<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Script and eval code keep the value of the last expression statement as their
|
||||
/// completion value; function and module code do not.
|
||||
fn keeps_completion(&self) -> bool {
|
||||
self.kind != CodeKind::Function && !self.module
|
||||
}
|
||||
|
||||
// ---- emitting ----
|
||||
|
||||
fn emit(&mut self, op: Op) {
|
||||
@@ -270,8 +279,10 @@ impl<'a> FnCompiler<'a> {
|
||||
let mut seen = HashSet::new();
|
||||
// The `let` and `const` names and the block functions of each statement list and loop the
|
||||
// walk enters, with the index of the one around it; the body's are first, and its
|
||||
// functions are var-scoped.
|
||||
let mut scopes: Vec<(Option<usize>, HashSet<Key>, HashSet<Key>)> = vec![(None, self.lexical_names(body), HashSet::new())];
|
||||
// functions are var-scoped. Only Annex B's block functions read them, so without
|
||||
// [`crate::Options::es2015`] none is collected.
|
||||
let top = if self.es2015 { self.lexical_names(body) } else { HashSet::new() };
|
||||
let mut scopes: Vec<(Option<usize>, HashSet<Key>, HashSet<Key>)> = vec![(None, top, HashSet::new())];
|
||||
let mut work: Vec<(StmtId, bool, usize)> = body.iter().rev().map(|&s| (s, false, 0)).collect();
|
||||
let mut add_var = |out: &mut Hoisted, k: Key| {
|
||||
if seen.insert(k.clone()) {
|
||||
@@ -306,7 +317,7 @@ impl<'a> FnCompiler<'a> {
|
||||
}
|
||||
}
|
||||
Stmt::Block(list) => {
|
||||
let s = enter(self.lexical_names(list), self.block_function_names(list));
|
||||
let s = if inner { enter(self.lexical_names(list), self.block_function_names(list)) } else { scope };
|
||||
work.extend(list.iter().rev().map(|&st| (st, nested || inner, s)));
|
||||
}
|
||||
Stmt::If { consequent, alternate, .. } => {
|
||||
@@ -314,7 +325,7 @@ impl<'a> FnCompiler<'a> {
|
||||
// (Annex B.3.4).
|
||||
for &branch in alternate.iter().chain(std::iter::once(consequent)) {
|
||||
let alone = matches!(self.ast.stmt(branch), Some(Stmt::FunctionDecl(_)));
|
||||
let s = if alone { enter(HashSet::new(), HashSet::new()) } else { scope };
|
||||
let s = if alone && inner { enter(HashSet::new(), HashSet::new()) } else { scope };
|
||||
work.push((branch, nested || inner, s));
|
||||
}
|
||||
}
|
||||
@@ -347,30 +358,38 @@ impl<'a> FnCompiler<'a> {
|
||||
work.push((*body, nested || inner, s));
|
||||
}
|
||||
Stmt::Switch { cases, .. } => {
|
||||
let names = cases.iter().flat_map(|c| self.lexical_names(&c.body)).collect();
|
||||
let funcs = cases.iter().flat_map(|c| self.block_function_names(&c.body)).collect();
|
||||
let s = enter(names, funcs);
|
||||
let s = if inner {
|
||||
let names = cases.iter().flat_map(|c| self.lexical_names(&c.body)).collect();
|
||||
let funcs = cases.iter().flat_map(|c| self.block_function_names(&c.body)).collect();
|
||||
enter(names, funcs)
|
||||
} else {
|
||||
scope
|
||||
};
|
||||
for case in cases.iter().rev() {
|
||||
work.extend(case.body.iter().rev().map(|&st| (st, nested || inner, s)));
|
||||
}
|
||||
}
|
||||
Stmt::Try { block, handler, finalizer } => {
|
||||
if let Some(f) = finalizer {
|
||||
let s = enter(self.lexical_names(f), self.block_function_names(f));
|
||||
let s = if inner { enter(self.lexical_names(f), self.block_function_names(f)) } else { scope };
|
||||
work.extend(f.iter().rev().map(|&st| (st, nested || inner, s)));
|
||||
}
|
||||
if let Some(h) = handler {
|
||||
// A `var` cannot redeclare a destructured catch parameter's names
|
||||
// (ECMA-262 11th edition section B.3.5), so a block function of that name
|
||||
// in the body is not also made a `var` (section B.3.3).
|
||||
let mut names = self.lexical_names(&h.body);
|
||||
if matches!(h.param, Binding::Pattern(_)) {
|
||||
names.extend(self.bound_keys(&h.param));
|
||||
}
|
||||
let s = enter(names, self.block_function_names(&h.body));
|
||||
let s = if inner {
|
||||
// A `var` cannot redeclare a destructured catch parameter's names
|
||||
// (ECMA-262 11th edition section B.3.5), so a block function of that
|
||||
// name in the body is not also made a `var` (section B.3.3).
|
||||
let mut names = self.lexical_names(&h.body);
|
||||
if matches!(h.param, Binding::Pattern(_)) {
|
||||
names.extend(self.bound_keys(&h.param));
|
||||
}
|
||||
enter(names, self.block_function_names(&h.body))
|
||||
} else {
|
||||
scope
|
||||
};
|
||||
work.extend(h.body.iter().rev().map(|&st| (st, nested || inner, s)));
|
||||
}
|
||||
let s = enter(self.lexical_names(block), self.block_function_names(block));
|
||||
let s = if inner { enter(self.lexical_names(block), self.block_function_names(block)) } else { scope };
|
||||
work.extend(block.iter().rev().map(|&st| (st, nested || inner, s)));
|
||||
}
|
||||
Stmt::Expr(_)
|
||||
@@ -493,7 +512,10 @@ impl<'a> FnCompiler<'a> {
|
||||
fn lexical_decls(&mut self, decls: &[VarDecl]) -> CResult<()> {
|
||||
for d in decls {
|
||||
match (d.init, &d.target) {
|
||||
(Some(init), Binding::Name(name)) => self.named_expr(init, &name.name)?,
|
||||
(Some(init), Binding::Name(name)) => {
|
||||
let public_name = if name.name == crate::ast::DEFAULT_BINDING { "default" } else { &name.name };
|
||||
self.named_expr(init, public_name)?;
|
||||
}
|
||||
(Some(init), Binding::Pattern(_)) => self.expr(init)?,
|
||||
(None, Binding::Name(_)) => self.emit(Op::Undefined),
|
||||
(None, Binding::Pattern(_)) => return internal("a destructuring declaration without an initializer"),
|
||||
@@ -552,7 +574,7 @@ impl<'a> FnCompiler<'a> {
|
||||
Stmt::Empty | Stmt::Debugger => Ok(()),
|
||||
Stmt::Expr(e) => {
|
||||
self.expr(*e)?;
|
||||
self.emit(if self.kind == CodeKind::Function { Op::Pop } else { Op::SetCompletion });
|
||||
self.emit(if self.keeps_completion() { Op::SetCompletion } else { Op::Pop });
|
||||
Ok(())
|
||||
}
|
||||
Stmt::Block(list) => self.block(list),
|
||||
@@ -1016,8 +1038,12 @@ impl<'a> FnCompiler<'a> {
|
||||
let Some(Stmt::Switch { discriminant, cases }) = self.ast.stmt(id) else { return internal("not a switch") };
|
||||
self.statement_completion_start();
|
||||
self.expr(*discriminant)?;
|
||||
let all: Vec<StmtId> = cases.iter().flat_map(|c| c.body.iter().copied()).collect();
|
||||
let scope = self.list_scope(&all, true)?;
|
||||
let scope = if self.es2015 {
|
||||
let all: Vec<StmtId> = cases.iter().flat_map(|c| c.body.iter().copied()).collect();
|
||||
self.list_scope(&all, true)?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(scope) = scope {
|
||||
self.emit(Op::PushBlock(scope));
|
||||
self.env_depth += 1;
|
||||
@@ -1247,7 +1273,7 @@ impl<'a> FnCompiler<'a> {
|
||||
self.bind(fin_entry);
|
||||
// In script and eval code the finally block keeps the completion value of the try or
|
||||
// catch block when it ends normally (ECMA-262 5.1 section 12.14).
|
||||
let keeps_completion = self.kind != CodeKind::Function;
|
||||
let keeps_completion = self.keeps_completion();
|
||||
if keeps_completion {
|
||||
self.emit(Op::GetCompletion);
|
||||
}
|
||||
@@ -2519,7 +2545,10 @@ pub(crate) fn compile_function(
|
||||
class_ctor: f.is_class_constructor(),
|
||||
derived: f.kind == FunctionKind::DerivedConstructor,
|
||||
pattern_names,
|
||||
own_name: es2015.then(|| key_of(f.name.as_ref().map_or("", |n| n.name.as_str()))),
|
||||
own_name: es2015.then(|| {
|
||||
let name = f.name.as_ref().map_or("", |n| n.name.as_str());
|
||||
key_of(if f.kind == FunctionKind::Declaration && name == crate::ast::DEFAULT_BINDING { "default" } else { name })
|
||||
}),
|
||||
method: (f.home && !f.is_class_constructor())
|
||||
|| (es2015 && matches!(f.kind, FunctionKind::Method | FunctionKind::Getter | FunctionKind::Setter)),
|
||||
};
|
||||
@@ -2539,6 +2568,21 @@ pub(crate) fn compile_program(program: &crate::Program, source: &Rc<Source>, kin
|
||||
c.finish(hoisted, Meta { span: (0, end), top_scope, ..Meta::default() })
|
||||
}
|
||||
|
||||
/// Compiles a module's statements ([`crate::parse_module`]): strict code that runs in an
|
||||
/// environment of its own, as strict eval code does, and returns `undefined`.
|
||||
pub(crate) fn compile_module(program: &crate::Program, source: &Rc<Source>) -> CResult<Rc<Code>> {
|
||||
let mut c = FnCompiler::new(&program.ast, source, CodeKind::Eval, true, 0);
|
||||
c.es2015 = true;
|
||||
c.module = true;
|
||||
let hoisted = c.hoist(&program.body, &[])?;
|
||||
let top_scope = c.list_scope(&program.body, false)?;
|
||||
c.stmts(&program.body)?;
|
||||
c.emit(Op::Undefined);
|
||||
c.emit(Op::Return);
|
||||
let end = u32::try_from(source.text.len()).unwrap_or(u32::MAX);
|
||||
c.finish(hoisted, Meta { span: (0, end), top_scope, ..Meta::default() })
|
||||
}
|
||||
|
||||
/// The function of a `Function` constructor's source, `(function anonymous(…) {…})`: the program
|
||||
/// must be that one parenthesized function expression and nothing else. The name `anonymous` is
|
||||
/// not bound inside the function (section 15.3.2.1).
|
||||
|
||||
@@ -119,8 +119,16 @@ fn redeclarations_and_bad_declarations_are_syntax_errors() {
|
||||
syntax("'use strict'; { function f() {} function f() {} }");
|
||||
syntax("for (let x = 1 in {}) {}");
|
||||
syntax("if (1) let x = 1;");
|
||||
// No statement starts with `let [`, in a statement list or in the body of an `if` or a loop.
|
||||
for body in ["if (true) let[0];", "if (false) ; else let[0];", "while (false) let[0];", "for (;false;) let[0];", "lbl: let[0];"] {
|
||||
syntax(&format!("var let = [1]; {body}"));
|
||||
}
|
||||
// Outside strict mode code `let` is still a name where no declaration can start.
|
||||
truth("var let = 3; let === 3");
|
||||
truth("var let = [1]; var r; if (true) (let[0]); if (true) r = let[0]; r === 1");
|
||||
truth("var let = [2]; if (true) let\n; let.length === 1");
|
||||
// ECMAScript 5.1 reads it as a property read.
|
||||
assert_eq!(Realm::new().run("var let = [1]; if (true) let[0];"), Ok(JsValue::Number(1.0)));
|
||||
truth("{ function f() { return 1; } function f() { return 2; } } f() === 2");
|
||||
// A labeled function in a block declares its name in the block.
|
||||
syntax("{ let f; label: function f() {} }");
|
||||
@@ -202,7 +210,7 @@ fn global_lexical_bindings_stay_across_runs_and_cannot_be_redeclared() {
|
||||
assert!(matches!(&var, Err(RunError { kind: RunErrorKind::Thrown, message, .. }) if message.starts_with("SyntaxError")), "{var:?}");
|
||||
assert_eq!(realm.run("kept"), Ok(JsValue::Number(5.0)));
|
||||
let restricted = realm.run("let undefined = 1;");
|
||||
assert!(restricted.is_err(), "{restricted:?}");
|
||||
assert!(is_thrown(&restricted, "SyntaxError"), "{restricted:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -388,8 +396,14 @@ fn a_global_var_stops_a_later_let_even_on_a_configurable_property() {
|
||||
assert_eq!(realm.run("let z = 3; z"), Ok(JsValue::Number(3.0)));
|
||||
// Deleting the property itself, not through the global environment, keeps the record
|
||||
// (ECMA-262 2015 sections 12.5.3.2 and 8.1.1.4.7).
|
||||
// Deleting the global object's property, not the variable, leaves the name declared
|
||||
// (ECMA-262 2015 section 8.1.1.4.7 runs only for `delete w`).
|
||||
assert_eq!(realm.run("(0, eval)('var w = 1'); delete this.w"), Ok(JsValue::Bool(true)));
|
||||
assert!(is_thrown(&realm.run("let w = 4;"), "SyntaxError"));
|
||||
let after_property = realm.run("let w = 4; w");
|
||||
assert!(is_thrown(&after_property, "SyntaxError"), "{after_property:?}");
|
||||
assert_eq!(realm.run("(0, eval)('var v = 1'); with (this) delete v"), Ok(JsValue::Bool(true)));
|
||||
let after_with = realm.run("let v = 4; v");
|
||||
assert!(is_thrown(&after_with, "SyntaxError"), "{after_with:?}");
|
||||
assert_eq!(realm.run("(0, eval)('var u = 1'); with (this) { delete u; }"), Ok(JsValue::Bool(true)));
|
||||
assert!(is_thrown(&realm.run("let u = 5;"), "SyntaxError"));
|
||||
// Deleting a name the global object only inherits deletes no variable.
|
||||
@@ -525,6 +539,17 @@ fn arrow_functions_cannot_be_constructed() {
|
||||
truth("((a, b) => 0).length === 2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_arrow_functions_length_is_configurable_and_read_only() {
|
||||
truth(
|
||||
"var d = Object.getOwnPropertyDescriptor((a) => a, 'length'); \
|
||||
d.configurable && !d.writable && !d.enumerable && d.value === 1",
|
||||
);
|
||||
truth("var f = (a, b) => 0; delete f.length && !f.hasOwnProperty('length')");
|
||||
// In ECMAScript 2015 code the other functions' `length` is configurable too (section 19.2.4.1).
|
||||
truth("var d = Object.getOwnPropertyDescriptor(function (a) {}, 'length'); d.configurable && !d.writable && !d.enumerable");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_arrow_functions_are_syntax_errors() {
|
||||
syntax("var f = x\n=> x;");
|
||||
|
||||
@@ -305,6 +305,8 @@ impl Interp {
|
||||
completion,
|
||||
boundary,
|
||||
generator: Some(generator),
|
||||
chained: false,
|
||||
pending_module: false,
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
+54
-3
@@ -199,7 +199,7 @@ pub(crate) enum Func {
|
||||
Pausable { f: crate::interp::PausableFn, name: &'static str },
|
||||
Host { f: Rc<HostFn>, name: Rc<str> },
|
||||
Data { f: DataFn, name: Rc<str>, read: crate::host::ArgRead },
|
||||
Eval { f: DataFn, end: Rc<dyn Fn()>, strict_writes: Rc<dyn Fn() -> Option<bool>>, name: Rc<str> },
|
||||
Eval { f: DataFn, end: Rc<dyn Fn()>, strict_writes: Rc<dyn Fn() -> Option<bool>>, name: Rc<str>, site: bool },
|
||||
Bound { target: ObjId, this: Value, args: Rc<[Value]> },
|
||||
}
|
||||
|
||||
@@ -272,6 +272,9 @@ pub(crate) enum Class {
|
||||
Xmp(Box<crate::xmp::Meta>),
|
||||
/// An object the `XMPFile` constructor made ([`crate::xmp_classes`]).
|
||||
XmpFile(Box<PropMap<Value>>),
|
||||
/// A module namespace object (ECMA-262 2015 section 9.4.6): its own properties are the
|
||||
/// module's exports, read live from the bindings they name.
|
||||
ModuleNamespace(Box<ModuleExports>),
|
||||
/// An object of a class a host defined ([`crate::host_classes`]).
|
||||
Host(crate::host_classes::HostObj),
|
||||
/// A `UnitValue` object and its measurement ([`crate::unit_value`]).
|
||||
@@ -598,6 +601,8 @@ impl Class {
|
||||
Class::String(_) => "String",
|
||||
Class::RegExp(_) => "RegExp",
|
||||
Class::Date(_) => "Date",
|
||||
// The value of a namespace object's @@toStringTag (ECMA-262 2015 section 26.3.1).
|
||||
Class::ModuleNamespace(_) => "Module",
|
||||
Class::UnitValue(_) => "UnitValue",
|
||||
Class::Map(_) => "Map",
|
||||
Class::Set(_) => "Set",
|
||||
@@ -644,17 +649,49 @@ pub(crate) struct Binding {
|
||||
/// A `let` or `const` binding, or a function declared in a block: a `var` that eval code
|
||||
/// declares cannot take its name.
|
||||
pub(crate) lexical: bool,
|
||||
/// A module's import of another module's binding (ECMA-262 2015 section 8.1.1.5.5,
|
||||
/// CreateImportBinding): reading it reads the binding of that name in that environment, and
|
||||
/// writing it is a `TypeError`. `value` is unused.
|
||||
pub(crate) import: Option<(EnvId, Key)>,
|
||||
}
|
||||
|
||||
impl Binding {
|
||||
/// An initialized binding.
|
||||
pub(crate) fn new(value: Value, mutable: bool, deletable: bool) -> Self {
|
||||
Self { value, mutable, deletable, uninitialized: false, constant: false, lexical: false }
|
||||
Self { value, mutable, deletable, uninitialized: false, constant: false, lexical: false, import: None }
|
||||
}
|
||||
|
||||
/// A `let` (or with `constant`, a `const`) binding not yet initialized.
|
||||
pub(crate) fn lexical(constant: bool) -> Self {
|
||||
Self { value: Value::Undefined, mutable: !constant, deletable: false, uninitialized: true, constant, lexical: true }
|
||||
Self { value: Value::Undefined, mutable: !constant, deletable: false, uninitialized: true, constant, lexical: true, import: None }
|
||||
}
|
||||
|
||||
/// An import of the binding `name` of the environment `env`.
|
||||
pub(crate) fn import(env: EnvId, name: Key) -> Self {
|
||||
Self {
|
||||
value: Value::Undefined,
|
||||
mutable: false,
|
||||
deletable: false,
|
||||
uninitialized: false,
|
||||
constant: true,
|
||||
lexical: true,
|
||||
import: Some((env, name)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A module namespace object's exports (ECMA-262 2015 section 9.4.6): each exported name, in
|
||||
/// code unit order, with the environment and name of the binding it reads, or `None` for an export
|
||||
/// whose value is fixed (another module's namespace object), kept in the object's own property.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(crate) struct ModuleExports {
|
||||
pub(crate) bindings: Vec<(Key, Option<(EnvId, Key)>)>,
|
||||
}
|
||||
|
||||
impl ModuleExports {
|
||||
/// The binding the export `name` reads, when it reads one.
|
||||
pub(crate) fn binding(&self, name: &[u16]) -> Option<&(EnvId, Key)> {
|
||||
self.bindings.binary_search_by(|(k, _)| (**k).cmp(name)).ok().and_then(|i| self.bindings.get(i)).and_then(|(_, b)| b.as_ref())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1103,6 +1140,16 @@ fn trace_object(o: &Object, work: &mut Vec<u32>, strings: &mut StringSizes) -> u
|
||||
work.push(map.env.0);
|
||||
extra = ARG_NAME_BYTES * map.names.len();
|
||||
}
|
||||
Class::ModuleNamespace(exports) => {
|
||||
for (k, b) in &exports.bindings {
|
||||
strings.add_key(k);
|
||||
if let Some((env, name)) = b {
|
||||
work.push(env.0);
|
||||
strings.add_key(name);
|
||||
}
|
||||
}
|
||||
extra = PROP_BYTES * exports.bindings.len();
|
||||
}
|
||||
Class::String(s) => strings.add(s),
|
||||
Class::RegExp(re) => {
|
||||
if strings.seen.insert(Rc::as_ptr(re) as *const () as usize) {
|
||||
@@ -1233,6 +1280,10 @@ fn trace_env(e: &Env, work: &mut Vec<u32>, strings: &mut StringSizes) -> usize {
|
||||
for (k, b) in bindings.iter() {
|
||||
strings.add_key(k);
|
||||
mark_value(&b.value, work, strings);
|
||||
if let Some((env, name)) = &b.import {
|
||||
work.push(env.0);
|
||||
strings.add_key(name);
|
||||
}
|
||||
}
|
||||
ENV_BYTES + PROP_BYTES * bindings.len()
|
||||
}
|
||||
|
||||
+14
-5
@@ -160,11 +160,14 @@ pub enum HostItem {
|
||||
/// that is not a string is the call's result. `end` is called when the source has run,
|
||||
/// normally or not. Each source given has the next tag of [`crate::Realm::error_source`],
|
||||
/// from 1. `strict_writes`, called after `source`, gives [`crate::Realm::set_strict_writes`]
|
||||
/// for that source alone; with `None` it takes the calling code's.
|
||||
/// for that source alone; with `None` it takes the calling code's. With `site`, `source` is
|
||||
/// given the [`CallSite`] of the code that calls it first, as the three numbers its source
|
||||
/// tag, line and column, and the arguments after them.
|
||||
Evaluator {
|
||||
source: HostFunction,
|
||||
end: Rc<dyn Fn()>,
|
||||
strict_writes: Rc<dyn Fn() -> Option<bool>>,
|
||||
site: bool,
|
||||
},
|
||||
/// A read-only property that reads the interpreter's own state.
|
||||
Script(ScriptItem),
|
||||
@@ -466,7 +469,8 @@ impl Interp {
|
||||
/// source it gives as global code, as an indirect `eval` does, giving that code's completion
|
||||
/// value. A result that is not a string is given to the script as it is. `end` is called once
|
||||
/// the source has run, normally or not. `strict_writes` gives the source's
|
||||
/// [`crate::bytecode::Source::strict_writes`], or `None` for the calling code's.
|
||||
/// [`crate::bytecode::Source::strict_writes`], or `None` for the calling code's. With `site`,
|
||||
/// `f` is given the calling code's [`CallSite`] before the arguments.
|
||||
pub(crate) fn call_evaluator(
|
||||
&mut self,
|
||||
f: &crate::heap::DataFn,
|
||||
@@ -474,8 +478,13 @@ impl Interp {
|
||||
strict_writes: &Rc<dyn Fn() -> Option<bool>>,
|
||||
name: &Rc<str>,
|
||||
args: &[Value],
|
||||
site: bool,
|
||||
) -> JsResult<Value> {
|
||||
let data = self.read_args(name, None, args, &ArgRead::Data)?;
|
||||
let caller = site.then(|| self.call_site());
|
||||
let mut data = self.read_args(name, None, args, &ArgRead::Data)?;
|
||||
if let Some(caller) = caller {
|
||||
data.splice(0..0, site_data(caller));
|
||||
}
|
||||
let source = match f(data) {
|
||||
Ok(Data::String(source)) => source,
|
||||
Ok(d) => return self.write_data(d, 0, false),
|
||||
@@ -689,9 +698,9 @@ impl Interp {
|
||||
HostItem::Converted(list, f) => {
|
||||
Prop::Data { value: Value::Object(self.host_function(f, &full, ArgRead::Each(list.into()))), flags: ENUMERABLE }
|
||||
}
|
||||
HostItem::Evaluator { source, end, strict_writes } => {
|
||||
HostItem::Evaluator { source, end, strict_writes, site } => {
|
||||
let proto = self.intrinsics.function_proto;
|
||||
let func = Func::Eval { f: source, end, strict_writes, name: full.into() };
|
||||
let func = Func::Eval { f: source, end, strict_writes, name: full.into(), site };
|
||||
let f = self.heap.alloc_object(Object::new(Class::Function(func), Some(proto)));
|
||||
Prop::Data { value: Value::Object(f), flags: ENUMERABLE }
|
||||
}
|
||||
|
||||
@@ -433,7 +433,7 @@ fn a_site_getter_is_told_where_the_code_that_reads_it_is() {
|
||||
Ok(Data::Number(f64::from(s.line)))
|
||||
});
|
||||
let source: HostFunction = Rc::new(|_| Ok(Data::String("\n\nfunction inEval() { return host.site; }".into())));
|
||||
let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None) };
|
||||
let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None), site: false };
|
||||
r.define_host_object("host", vec![("site".into(), HostItem::SiteGetter(site)), ("load".into(), load)]).unwrap();
|
||||
r.run("function early() {\n return host.site;\n}\nhost.load();").unwrap();
|
||||
let first = r.script_tag();
|
||||
@@ -455,6 +455,31 @@ fn a_site_getter_is_told_where_the_code_that_reads_it_is() {
|
||||
assert_eq!(seen.borrow().first().map(|s| s.source), Some(r.script_tag()));
|
||||
}
|
||||
|
||||
/// An evaluator made with `site` is given the place of the code that calls it before its
|
||||
/// arguments; one made without it is given only the arguments.
|
||||
#[test]
|
||||
fn an_evaluator_with_site_is_told_where_it_is_called() {
|
||||
let mut r = realm(10_000_000);
|
||||
let given: Rc<RefCell<Vec<Vec<Data>>>> = Rc::default();
|
||||
let evaluator = |site: bool| {
|
||||
let log = given.clone();
|
||||
let source: HostFunction = Rc::new(move |a| {
|
||||
log.borrow_mut().push(a);
|
||||
Ok(Data::String("1".into()))
|
||||
});
|
||||
HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None), site }
|
||||
};
|
||||
r.define_host_object("host", vec![("at".into(), evaluator(true)), ("plain".into(), evaluator(false))]).unwrap();
|
||||
r.run("\n\n host.at('x');\nhost.plain('y');").unwrap();
|
||||
let tag = f64::from(r.script_tag());
|
||||
let given = given.borrow();
|
||||
assert_eq!(given.len(), 2, "{given:?}");
|
||||
assert_eq!(given[0].len(), 4, "{given:?}");
|
||||
assert_eq!((&given[0][..2], &given[0][3]), (&[Data::Number(tag), Data::Number(3.0)][..], &Data::String("x".into())), "{given:?}");
|
||||
assert!(matches!(given[0][2], Data::Number(c) if c >= 1.0), "{given:?}");
|
||||
assert_eq!(given[1], vec![Data::String("y".into())]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_text_function_takes_each_argument_as_string_gives_it() {
|
||||
let mut r = realm(1_000_000);
|
||||
@@ -978,7 +1003,7 @@ fn a_converted_function_reads_each_argument_as_its_list_says() {
|
||||
fn error_sources_count_from_the_last_script_and_code_from_an_earlier_one_is_unknown() {
|
||||
let mut r = realm(10_000_000);
|
||||
let source: HostFunction = Rc::new(|_| Ok(Data::String("\nthrow new Error('in eval')".into())));
|
||||
let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None) };
|
||||
let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None), site: false };
|
||||
r.define_host_object("host", vec![("load".into(), load)]).unwrap();
|
||||
r.run("function late() { throw new Error('late'); }").unwrap();
|
||||
assert!(r.run("host.load()").is_err());
|
||||
@@ -1000,7 +1025,7 @@ fn the_code_observer_sees_every_source_evaluated_at_run_time() {
|
||||
let s = seen.clone();
|
||||
r.observe_code(move |units| s.borrow_mut().push(String::from_utf16_lossy(units)));
|
||||
let source: HostFunction = Rc::new(|_| Ok(Data::String("40 + 2".into())));
|
||||
let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None) };
|
||||
let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None), site: false };
|
||||
r.define_host_object("host", vec![("load".into(), load)]).unwrap();
|
||||
let out = r.run("function f() { return eval('1 + 1'); } f() + (0, eval)('2') + Function('a', 'return a')(3) + host.load()").unwrap();
|
||||
assert_eq!(out, JsValue::Number(49.0));
|
||||
@@ -1015,7 +1040,7 @@ fn the_code_observer_sees_every_source_evaluated_at_run_time() {
|
||||
fn error_tags_stay_the_same_from_run_to_run_and_are_never_shared() {
|
||||
let mut r = realm(10_000_000);
|
||||
let source: HostFunction = Rc::new(|_| Ok(Data::String("function inEval() { throw new Error('in eval'); }".into())));
|
||||
let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None) };
|
||||
let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None), site: false };
|
||||
r.define_host_object("host", vec![("load".into(), load)]).unwrap();
|
||||
assert_eq!(r.script_tag(), UNKNOWN_SOURCE, "no script yet");
|
||||
r.run("function late() { throw new Error('late'); }\nhost.load(); host.load();").unwrap();
|
||||
@@ -1048,7 +1073,7 @@ fn an_evaluators_source_takes_fuel_before_it_is_parsed() {
|
||||
let ends = Rc::new(Cell::new(0));
|
||||
let ended = ends.clone();
|
||||
let source: HostFunction = Rc::new(|_| Ok(Data::String(format!("{}7", " ".repeat(1 << 17)))));
|
||||
let item = HostItem::Evaluator { source, end: Rc::new(move || ended.set(ended.get() + 1)), strict_writes: Rc::new(|| None) };
|
||||
let item = HostItem::Evaluator { source, end: Rc::new(move || ended.set(ended.get() + 1)), strict_writes: Rc::new(|| None), site: false };
|
||||
let mut r = realm(10_000);
|
||||
r.define_host_object("host", vec![("evaluate".into(), item)]).unwrap();
|
||||
let e = r.run("host.evaluate()").unwrap_err();
|
||||
@@ -1069,7 +1094,7 @@ fn an_evaluators_whole_source_must_fit_in_the_heap_before_it_is_parsed() {
|
||||
// The source does not parse, so a parse would throw a syntax error instead.
|
||||
let n = (1 << 17) + 1;
|
||||
let source: HostFunction = Rc::new(move |_| Ok(Data::String(format!("{}(", " ".repeat(n - 1)))));
|
||||
let item = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None) };
|
||||
let item = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None), site: false };
|
||||
let mut r = realm(1_000_000);
|
||||
r.define_host_object("host", vec![("evaluate".into(), item)]).unwrap();
|
||||
r.interp().collect_for_room();
|
||||
|
||||
+296
-18
@@ -26,8 +26,8 @@ use crate::ast::BinaryOp;
|
||||
use crate::bytecode::{Code, CodeKind, NamePrefix, Op, Source};
|
||||
use crate::compiler::{CompileFail, compile_program};
|
||||
use crate::heap::{
|
||||
ArgMap, Binding, CONFIGURABLE, Class, ENUMERABLE, ENV_BYTES, Env, EnvId, ForIn, Func, HIDDEN, Heap, Key, NativeKind, OBJECT_BYTES, OPEN, ObjId,
|
||||
Object, PROP_BYTES, Prop, PropMap, ROPE_BYTES, Roots, WRITABLE, code_bytes, key, string_bytes,
|
||||
ArgMap, Binding, CONFIGURABLE, Class, ENUMERABLE, ENV_BYTES, Env, EnvId, ForIn, Func, HIDDEN, Heap, Key, ModuleExports, NativeKind, OBJECT_BYTES,
|
||||
OPEN, ObjId, Object, PROP_BYTES, Prop, PropMap, ROPE_BYTES, Roots, WRITABLE, code_bytes, key, string_bytes,
|
||||
};
|
||||
use crate::parser::SuperRules;
|
||||
use crate::string_builtins::flat_charged;
|
||||
@@ -231,6 +231,11 @@ pub(crate) struct Frame {
|
||||
pub(crate) boundary: bool,
|
||||
/// The generator object whose body this frame runs, once [`Op::GeneratorStart`] has made it.
|
||||
pub(crate) generator: Option<ObjId>,
|
||||
/// The frame runs a module that another module of the same run waits under (ECMA-262 2015
|
||||
/// section 15.2.1.16.5): its completion value is dropped when it returns, and an exception
|
||||
/// that leaves it ends the run at the boundary frame without stopping in the frames between.
|
||||
pub(crate) chained: bool,
|
||||
pub(crate) pending_module: bool,
|
||||
}
|
||||
|
||||
/// Where the exception being thrown was raised: the code and the instruction.
|
||||
@@ -275,6 +280,7 @@ pub(crate) struct Interp {
|
||||
pub(crate) heap: Heap,
|
||||
pub(crate) stack: Vec<Value>,
|
||||
pub(crate) frames: Vec<Frame>,
|
||||
pending_module_frames: usize,
|
||||
/// Values native code holds while it may run JavaScript.
|
||||
pub(crate) temp_roots: Vec<Value>,
|
||||
/// Environments native code is still building.
|
||||
@@ -637,6 +643,7 @@ impl Interp {
|
||||
heap,
|
||||
stack: Vec::new(),
|
||||
frames: Vec::new(),
|
||||
pending_module_frames: 0,
|
||||
temp_roots: Vec::new(),
|
||||
temp_envs: Vec::new(),
|
||||
temp_codes: Vec::new(),
|
||||
@@ -1032,7 +1039,11 @@ impl Interp {
|
||||
self.push(v)?;
|
||||
return Ok(None);
|
||||
}
|
||||
if self.frames.last().is_some_and(|frame| frame.pending_module) {
|
||||
self.pending_module_frames -= 1;
|
||||
}
|
||||
let frame = self.frame_mut()?;
|
||||
frame.pending_module = false;
|
||||
let Some(&op) = frame.code.ops.get(frame.pc) else { return internal("ran past the end of the code") };
|
||||
frame.pc += 1;
|
||||
match op {
|
||||
@@ -1101,10 +1112,14 @@ impl Interp {
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let Some(frame) = self.frames.pop() else { return Err(Abrupt::Throw(v)) };
|
||||
let Some(frame) = self.pop_frame() else { return Err(Abrupt::Throw(v)) };
|
||||
self.stack.truncate(frame.base);
|
||||
self.end_generator(frame.generator);
|
||||
if frame.boundary {
|
||||
if frame.chained {
|
||||
// The modules under it have not started, so no handler of theirs takes it.
|
||||
self.abort_to_boundary();
|
||||
}
|
||||
if frame.boundary || frame.chained {
|
||||
self.passing = v.clone();
|
||||
return Err(Abrupt::Throw(v));
|
||||
}
|
||||
@@ -1114,11 +1129,24 @@ impl Interp {
|
||||
/// Each running frame of script code, outermost first: its code, the index of its next
|
||||
/// instruction, and whether it runs a function (not global or eval code).
|
||||
pub(crate) fn script_frames(&self) -> impl Iterator<Item = (&Rc<Code>, usize, bool)> {
|
||||
self.frames.iter().map(|f| (&f.code, f.pc, f.callee.is_some()))
|
||||
self.frames.iter().filter(|f| !f.pending_module).map(|f| (&f.code, f.pc, f.callee.is_some()))
|
||||
}
|
||||
|
||||
pub(crate) fn clear_frames(&mut self) {
|
||||
self.frames.clear();
|
||||
self.pending_module_frames = 0;
|
||||
}
|
||||
|
||||
fn pop_frame(&mut self) -> Option<Frame> {
|
||||
let frame = self.frames.pop()?;
|
||||
if frame.pending_module {
|
||||
self.pending_module_frames -= 1;
|
||||
}
|
||||
Some(frame)
|
||||
}
|
||||
|
||||
fn abort_to_boundary(&mut self) {
|
||||
while let Some(frame) = self.frames.pop() {
|
||||
while let Some(frame) = self.pop_frame() {
|
||||
self.stack.truncate(frame.base);
|
||||
self.end_generator(frame.generator);
|
||||
if frame.boundary {
|
||||
@@ -1148,7 +1176,7 @@ impl Interp {
|
||||
Some(_) => crate::builtins::iterator::iter_result(self, v, true)?,
|
||||
None => v,
|
||||
};
|
||||
let Some(frame) = self.frames.pop() else { return internal("return without a frame") };
|
||||
let Some(frame) = self.pop_frame() else { return internal("return without a frame") };
|
||||
self.stack.truncate(frame.base);
|
||||
self.end_generator(frame.generator);
|
||||
// A `return` in a finally block leaves the block, and the value takes its exception's slot.
|
||||
@@ -1160,6 +1188,9 @@ impl Interp {
|
||||
if frame.boundary {
|
||||
return Ok(Some(v));
|
||||
}
|
||||
if frame.chained {
|
||||
return Ok(None);
|
||||
}
|
||||
self.push(v)?;
|
||||
Ok(None)
|
||||
}
|
||||
@@ -1490,6 +1521,15 @@ impl Interp {
|
||||
matches!(self.heap.env(env), Some(Env::Decl { bindings, .. }) if bindings.get(name).is_some_and(|b| b.uninitialized))
|
||||
}
|
||||
|
||||
/// The binding the binding `name` of the declarative environment `env` imports, when it is a
|
||||
/// module's import.
|
||||
fn import_of(&self, env: EnvId, name: &[u16]) -> Option<(EnvId, Key)> {
|
||||
match self.heap.env(env) {
|
||||
Some(Env::Decl { bindings, .. }) => bindings.get(name).and_then(|b| b.import.clone()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn not_initialized(&mut self, name: &[u16]) -> Abrupt {
|
||||
let ident = String::from_utf16_lossy(name);
|
||||
self.throw(ErrorType::Reference, &format!("{ident} is used before it is initialized"))
|
||||
@@ -1502,6 +1542,14 @@ impl Interp {
|
||||
|
||||
/// GetValue of a reference whose base was resolved earlier (section 8.7.1).
|
||||
fn get_resolved(&mut self, r: Resolved, name: &Key) -> JsResult<(Value, Value)> {
|
||||
if let Resolved::Decl(e) = r
|
||||
&& let Some((target, target_name)) = self.import_of(e, name)
|
||||
{
|
||||
if self.uninitialized(target, &target_name) {
|
||||
return Err(self.not_initialized(name));
|
||||
}
|
||||
return Ok((self.binding_value(target, &target_name)?, Value::Undefined));
|
||||
}
|
||||
match r {
|
||||
Resolved::Decl(e) if self.uninitialized(e, name) => Err(self.not_initialized(name)),
|
||||
Resolved::Decl(e) => Ok((self.binding_value(e, name)?, Value::Undefined)),
|
||||
@@ -1521,6 +1569,12 @@ impl Interp {
|
||||
/// PutValue of a reference whose base was resolved earlier (section 8.7.2).
|
||||
fn set_resolved(&mut self, r: Resolved, name: &Key, v: Value) -> JsResult<()> {
|
||||
let strict = self.strict();
|
||||
if let Resolved::Decl(e) = r
|
||||
&& self.import_of(e, name).is_some()
|
||||
{
|
||||
let ident = String::from_utf16_lossy(name);
|
||||
return Err(self.type_error(&format!("assignment to the import '{ident}'")));
|
||||
}
|
||||
match r {
|
||||
Resolved::Decl(e) if self.uninitialized(e, name) => Err(self.not_initialized(name)),
|
||||
Resolved::Decl(e) if matches!(self.heap.env(e), Some(Env::Decl { bindings, .. }) if bindings.get(name).is_some_and(|b| b.constant)) => {
|
||||
@@ -1726,18 +1780,59 @@ impl Interp {
|
||||
return Ok(crate::builtins::binary::element(self, view, n).map(|v| Prop::Data { value: Value::Number(v), flags: OPEN }));
|
||||
}
|
||||
}
|
||||
Class::ModuleNamespace(exports) => {
|
||||
if let Some((env, name)) = exports.binding(k)
|
||||
&& let Some(Prop::Data { flags, .. }) = o.props.get(k)
|
||||
{
|
||||
return Ok(Some(Prop::Data { value: self.binding_value(*env, name)?, flags: *flags }));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Ok(o.props.get(k).cloned())
|
||||
}
|
||||
|
||||
/// [[GetOwnProperty]] as a script reaches it (`hasOwnProperty`, `Object.keys` and the like):
|
||||
/// [`Self::get_own_property`], except that an export of a module namespace object read before
|
||||
/// its module initialized it is a `ReferenceError` (ECMA-262 2015 section 9.4.6.5).
|
||||
pub(crate) fn own_property(&mut self, id: ObjId, k: &[u16]) -> JsResult<Option<Prop>> {
|
||||
self.check_namespace_export(id, k)?;
|
||||
self.get_own_property(id, k)
|
||||
}
|
||||
|
||||
/// [`Self::own_property`] for a name or a Symbol: [`Self::get_own_pk`], with the same
|
||||
/// `ReferenceError` for a namespace export read before its module initialized it.
|
||||
pub(crate) fn own_pk(&mut self, id: ObjId, k: &PropKey) -> JsResult<Option<Prop>> {
|
||||
if let PropKey::Str(name) = k {
|
||||
self.check_namespace_export(id, name)?;
|
||||
}
|
||||
self.get_own_pk(id, k)
|
||||
}
|
||||
|
||||
/// A `ReferenceError` when `k` is an export of the module namespace object `id` that its module
|
||||
/// has not initialized yet.
|
||||
fn check_namespace_export(&mut self, id: ObjId, k: &[u16]) -> JsResult<()> {
|
||||
if let Some(Class::ModuleNamespace(exports)) = self.heap.object(id).map(|o| &o.class)
|
||||
&& let Some((env, name)) = exports.binding(k)
|
||||
&& self.uninitialized(*env, name)
|
||||
{
|
||||
return Err(self.not_initialized(k));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// [[GetProperty]]: the property found on the object or its prototype chain.
|
||||
pub(crate) fn find_property(&self, id: ObjId, k: &[u16]) -> JsResult<Option<Prop>> {
|
||||
Ok(self.find_property_on(id, k)?.map(|(_, p)| p))
|
||||
}
|
||||
|
||||
/// [`Self::find_property`], with the object on the prototype chain that has the property.
|
||||
fn find_property_on(&self, id: ObjId, k: &[u16]) -> JsResult<Option<(ObjId, Prop)>> {
|
||||
let mut cur = Some(id);
|
||||
let mut steps = 0usize;
|
||||
while let Some(o) = cur {
|
||||
if let Some(p) = self.get_own_property(o, k)? {
|
||||
return Ok(Some(p));
|
||||
return Ok(Some((o, p)));
|
||||
}
|
||||
// A typed array's prototypes are not searched for a numeric name (section 9.4.5.4).
|
||||
if crate::builtins::binary::typed_key(self, o, k).is_some() {
|
||||
@@ -1764,7 +1859,14 @@ impl Interp {
|
||||
{
|
||||
return self.host_index(&f, start, crate::Data::Number(f64::from(i)), false);
|
||||
}
|
||||
match self.find_property(start, k)? {
|
||||
let found = self.find_property_on(start, k)?;
|
||||
// A module's export read before the module ran is in its temporal dead zone (ECMA-262
|
||||
// 2015 section 9.4.6.8), whether the read starts at the namespace object or reaches it
|
||||
// through a prototype chain.
|
||||
if let Some((holder, _)) = &found {
|
||||
self.check_namespace_export(*holder, k)?;
|
||||
}
|
||||
match found.map(|(_, p)| p) {
|
||||
// A name the object and its prototypes lack is the indexer's answer too.
|
||||
None => match self.host_indexer(start)? {
|
||||
Some(f) => self.host_index(&f, start, Self::indexer_key(k), false),
|
||||
@@ -1780,7 +1882,11 @@ impl Interp {
|
||||
/// class: a name the object and its prototypes lack is `undefined`. For names the engine looks
|
||||
/// up itself, such as `toJSON`, which a collection's indexer would answer with an error.
|
||||
pub(crate) fn get_property_only(&mut self, start: ObjId, k: &[u16], receiver: &Value) -> JsResult<Value> {
|
||||
match self.find_property(start, k)? {
|
||||
let found = self.find_property_on(start, k)?;
|
||||
if let Some((holder, _)) = &found {
|
||||
self.check_namespace_export(*holder, k)?;
|
||||
}
|
||||
match found.map(|(_, p)| p) {
|
||||
None | Some(Prop::Accessor { get: None, .. }) => Ok(Value::Undefined),
|
||||
Some(Prop::Data { value, .. }) => Ok(value),
|
||||
Some(Prop::Accessor { get: Some(g), .. }) => self.call(&Value::Object(g), receiver, &[]),
|
||||
@@ -1892,10 +1998,26 @@ impl Interp {
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
Class::ModuleNamespace(_) => self.define_namespace_export(id, &k, desc, throw),
|
||||
_ => self.define_ordinary(id, k, desc, throw),
|
||||
}
|
||||
}
|
||||
|
||||
/// A module namespace object's [[DefineOwnProperty]] (ECMA-262 2020 section 9.4.6.5): only a
|
||||
/// descriptor that leaves an export as it is (enumerable, writable, not configurable, its
|
||||
/// current value) succeeds.
|
||||
fn define_namespace_export(&mut self, id: ObjId, k: &[u16], desc: &Desc, throw: bool) -> JsResult<bool> {
|
||||
let Some(Prop::Data { value, .. }) = self.own_property(id, k)? else {
|
||||
return self.reject_bool(throw, k, "a module namespace object is not extensible");
|
||||
};
|
||||
let unchanged = desc.configurable != Some(true)
|
||||
&& desc.enumerable != Some(false)
|
||||
&& !desc.is_accessor()
|
||||
&& desc.writable != Some(false)
|
||||
&& desc.value.as_ref().is_none_or(|v| same_value(v, &value));
|
||||
if unchanged { Ok(true) } else { self.reject_bool(throw, k, "a module namespace object is read-only") }
|
||||
}
|
||||
|
||||
pub(crate) fn reject_bool(&mut self, throw: bool, k: &[u16], why: &str) -> JsResult<bool> {
|
||||
if throw {
|
||||
let key = String::from_utf16_lossy(k);
|
||||
@@ -2068,6 +2190,10 @@ impl Interp {
|
||||
if let Some(n) = crate::builtins::binary::typed_key(self, id, &k) {
|
||||
return crate::builtins::binary::set_element(self, id, n, &v);
|
||||
}
|
||||
// A module namespace object takes no writes (ECMA-262 2015 section 9.4.6.9).
|
||||
if matches!(self.object(id)?.class, Class::ModuleNamespace(_)) {
|
||||
return self.reject(throw, &k, "a module namespace object is read-only");
|
||||
}
|
||||
match self.get_own_property(id, &k)? {
|
||||
Some(Prop::Data { flags, .. }) => {
|
||||
if flags & WRITABLE == 0 {
|
||||
@@ -2079,8 +2205,25 @@ impl Interp {
|
||||
Some(Prop::Accessor { set: None, .. }) => return self.reject(throw, &k, "it has only a getter"),
|
||||
None => {}
|
||||
}
|
||||
let proto = self.object(id)?.proto;
|
||||
let inherited = proto.map(|p| self.find_property(p, &k)).transpose()?.flatten();
|
||||
let mut inherited = None;
|
||||
let mut cur = self.object(id)?.proto;
|
||||
let mut steps = 0usize;
|
||||
while let Some(o) = cur {
|
||||
// A write that reaches a module namespace object on the prototype chain is refused
|
||||
// there too: its [[Set]] returns false for every key.
|
||||
if matches!(self.object(o)?.class, Class::ModuleNamespace(_)) {
|
||||
return self.reject(throw, &k, "a module namespace object is read-only");
|
||||
}
|
||||
if let Some(p) = self.get_own_property(o, &k)? {
|
||||
inherited = Some(p);
|
||||
break;
|
||||
}
|
||||
cur = self.object(o)?.proto;
|
||||
steps += 1;
|
||||
if steps > 1_000_000 {
|
||||
return internal("prototype chain too long");
|
||||
}
|
||||
}
|
||||
match inherited {
|
||||
Some(Prop::Accessor { set: Some(s), .. }) => return self.call(&Value::Object(s), &Value::Object(id), &[v]).map(drop),
|
||||
Some(Prop::Accessor { set: None, .. }) => return self.reject(throw, &k, "it has only a getter"),
|
||||
@@ -2953,6 +3096,8 @@ impl Interp {
|
||||
// listed or their bytes reserved must not free it.
|
||||
let saved = self.temp_roots.len();
|
||||
self.temp_roots.push(Value::Object(o));
|
||||
// Listing a namespace object's exports does not read them (ECMA-262 2015 section
|
||||
// 9.4.6.11, [[Enumerate]]), so an export still in its temporal dead zone is listed.
|
||||
let keys = self.enumerable_keys(o).and_then(|keys| {
|
||||
let bytes = keys.iter().map(|k| string_bytes(k.len())).sum::<usize>();
|
||||
self.reserve_heap(bytes)?;
|
||||
@@ -3067,8 +3212,8 @@ impl Interp {
|
||||
// keeps itself reachable.
|
||||
return Ok(Prepared::Done(self.call_data(&f, &name, &this, &args, &read)?));
|
||||
}
|
||||
Func::Eval { f, end, strict_writes, name } => {
|
||||
return Ok(Prepared::Done(self.call_evaluator(&f, &end, &strict_writes, &name, &args)?));
|
||||
Func::Eval { f, end, strict_writes, name, site } => {
|
||||
return Ok(Prepared::Done(self.call_evaluator(&f, &end, &strict_writes, &name, &args, site)?));
|
||||
}
|
||||
Func::Host { f: host, .. } => {
|
||||
let js_args: Vec<crate::JsValue> = args.iter().map(|v| self.to_js_value(v)).collect();
|
||||
@@ -3157,9 +3302,7 @@ impl Interp {
|
||||
/// the stack.
|
||||
pub(crate) fn enter_function(&mut self, entry: Entry, construct: Option<ObjId>, boundary: bool) -> JsResult<()> {
|
||||
let Entry { callee, code, env, this, args, new_target } = entry;
|
||||
if self.frames.len() >= self.limits.frames {
|
||||
return Err(Abrupt::Limit(LimitKind::Frames));
|
||||
}
|
||||
self.check_frame_room()?;
|
||||
let params = code.params.iter().chain(&code.pattern_names).fold(0usize, |total, p| total.saturating_add(binding_bytes(p.len())));
|
||||
// An arrow function reads the `arguments` object of the function around it.
|
||||
let arguments = if code.uses_arguments && !code.arrow { arguments_bytes(args.len()) } else { 0 };
|
||||
@@ -3220,6 +3363,8 @@ impl Interp {
|
||||
completion: Value::Undefined,
|
||||
boundary,
|
||||
generator: None,
|
||||
chained: false,
|
||||
pending_module: false,
|
||||
});
|
||||
Ok(())
|
||||
};
|
||||
@@ -3563,6 +3708,22 @@ impl Interp {
|
||||
})
|
||||
}
|
||||
|
||||
/// Parses and compiles a module's source ([`crate::parse_module`]), counting it against the
|
||||
/// source limit, with [`Self::source_tag`] as its source's tag.
|
||||
pub(crate) fn compile_module_source(&mut self, units: &[u16]) -> Result<(Rc<Code>, crate::ModuleInfo), CompileError> {
|
||||
self.source_units = self.source_units.saturating_add(units.len());
|
||||
let remaining = self.options.max_source_units.saturating_sub(self.source_units.saturating_sub(units.len()));
|
||||
let options = Options { max_source_units: remaining, ..self.options.clone() };
|
||||
let (program, info) = crate::parse_module_utf16(units, &options).map_err(CompileError::Syntax)?;
|
||||
let writes = self.writes_mode();
|
||||
let source = Rc::new(Source { lines: program.lines.clone(), text: units.into(), tag: self.source_tag, strict_writes: writes });
|
||||
let code = crate::compiler::compile_module(&program, &source).map_err(|e| match e {
|
||||
CompileFail::Syntax(s) => CompileError::Syntax(s),
|
||||
CompileFail::Internal(m) => CompileError::Internal(m),
|
||||
})?;
|
||||
Ok((code, info))
|
||||
}
|
||||
|
||||
/// Turns a compile failure inside a running script into what it throws.
|
||||
pub(crate) fn compile_error_to_abrupt(&mut self, e: CompileError) -> Abrupt {
|
||||
match e {
|
||||
@@ -3751,7 +3912,7 @@ impl Interp {
|
||||
|
||||
/// A [`LimitKind::Frames`] error when no other frame fits under the frame limit.
|
||||
fn check_frame_room(&self) -> JsResult<()> {
|
||||
if self.frames.len() >= self.limits.frames {
|
||||
if self.frames.len() - self.pending_module_frames >= self.limits.frames {
|
||||
return Err(Abrupt::Limit(LimitKind::Frames));
|
||||
}
|
||||
Ok(())
|
||||
@@ -3777,10 +3938,127 @@ impl Interp {
|
||||
completion: Value::Undefined,
|
||||
boundary,
|
||||
generator: None,
|
||||
chained: false,
|
||||
pending_module: false,
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Declaration binding instantiation for a module's code (ECMA-262 2015 section 15.2.1.16.4,
|
||||
/// ModuleDeclarationInstantiation, its imports aside): a new environment inside the global
|
||||
/// scope holds its variables and functions, and one inside that its `let` and `const` names,
|
||||
/// uninitialized. → the environment it runs in and the outer one. Both stay in the temporary
|
||||
/// roots for the caller to remove.
|
||||
pub(crate) fn instantiate_module(&mut self, code: &Rc<Code>) -> JsResult<(EnvId, EnvId)> {
|
||||
// The code itself was counted when the module was loaded ([`Self::hold_module_code`]).
|
||||
self.reserve_heap(declaration_bytes(code).saturating_add(ENV_BYTES))?;
|
||||
let scope = self.global_lex;
|
||||
let env = self.heap.alloc_env(Env::Decl { bindings: PropMap::default(), outer: Some(scope) });
|
||||
self.temp_envs.push(env);
|
||||
let lex = self.instantiate_global(code, env, env, true)?;
|
||||
self.temp_envs.push(lex);
|
||||
Ok((lex, env))
|
||||
}
|
||||
|
||||
/// Adds `binding` (an import) to the module environment `env`, which must not have `name`.
|
||||
pub(crate) fn add_import(&mut self, env: EnvId, name: Key, binding: Binding) -> JsResult<()> {
|
||||
self.use_fuel()?;
|
||||
// The binding's value (a namespace object) stays reachable while room is made.
|
||||
self.temp_roots.push(binding.value.clone());
|
||||
let reserved = self.reserve_heap(binding_bytes(name.len()));
|
||||
self.temp_roots.pop();
|
||||
reserved?;
|
||||
self.env_insert(env, name, binding)
|
||||
}
|
||||
|
||||
/// The environment that holds `name` of a module whose code runs in `lex` inside `env`.
|
||||
pub(crate) fn module_binding(&self, lex: EnvId, env: EnvId, name: &[u16]) -> Option<EnvId> {
|
||||
[lex, env].into_iter().find(|e| matches!(self.heap.env(*e), Some(Env::Decl { bindings, .. }) if bindings.contains(name)))
|
||||
}
|
||||
|
||||
/// A module namespace object for the exports `exports`, each `(name, binding)` with the
|
||||
/// binding it reads or, for `None`, the value `fixed` gives. The names must be in code unit
|
||||
/// order and distinct.
|
||||
pub(crate) fn module_namespace(&mut self, exports: Vec<(Key, Option<(EnvId, Key)>)>, fixed: &[(Key, Value)]) -> JsResult<ObjId> {
|
||||
let names = exports.iter().map(|(name, _)| string_bytes(name.len())).sum::<usize>();
|
||||
let bindings = PROP_BYTES.saturating_mul(exports.len());
|
||||
let tag = self.well_known(|symbols| &symbols.to_string_tag);
|
||||
let tagged = if tag.is_some() { PROP_BYTES.saturating_add(string_bytes(6)) } else { 0 };
|
||||
let extra = bindings.saturating_add(names).saturating_add(tagged);
|
||||
self.reserve_heap(OBJECT_BYTES.saturating_add(bindings).saturating_add(extra))?;
|
||||
let mut object = Object::new(Class::ModuleNamespace(Box::default()), None);
|
||||
if let Some(tag) = tag {
|
||||
object.syms.get_or_insert_with(Default::default).insert(tag, Prop::Data { value: Value::str("Module"), flags: 0 });
|
||||
}
|
||||
object.extensible = false;
|
||||
for (name, _) in &exports {
|
||||
self.use_fuel()?;
|
||||
let value = fixed.iter().find(|(k, _)| k == name).map_or(Value::Undefined, |(_, v)| v.clone());
|
||||
object.props.insert(name.clone(), Prop::Data { value, flags: WRITABLE | ENUMERABLE });
|
||||
}
|
||||
object.class = Class::ModuleNamespace(Box::new(ModuleExports { bindings: exports }));
|
||||
let namespace = self.heap.alloc_object(object);
|
||||
self.heap.bytes = self.heap.bytes.saturating_add(extra);
|
||||
Ok(namespace)
|
||||
}
|
||||
|
||||
/// Pushes the frames of a run of modules: `modules` in the order they run, each with its code,
|
||||
/// the environment it runs in and the outer one. The last is the boundary frame, pushed first;
|
||||
/// each of the others is pushed above the one that runs after it, so the first to run is on
|
||||
/// top.
|
||||
pub(crate) fn push_module_frames(&mut self, modules: &[(Rc<Code>, EnvId, EnvId)]) -> JsResult<()> {
|
||||
for (i, (code, env, var_env)) in modules.iter().enumerate().rev() {
|
||||
let last = i + 1 == modules.len();
|
||||
self.push_code_frame(code.clone(), *env, *var_env, Value::Undefined, last)?;
|
||||
if let Some(frame) = self.frames.last_mut() {
|
||||
frame.chained = !last;
|
||||
frame.pending_module = true;
|
||||
}
|
||||
self.pending_module_frames += 1;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Ends module linking: drops the temporary roots from `mark` on.
|
||||
pub(crate) fn drop_temp_envs(&mut self, mark: usize) {
|
||||
self.temp_envs.truncate(mark);
|
||||
}
|
||||
|
||||
pub(crate) fn temp_envs_mark(&self) -> usize {
|
||||
self.temp_envs.len()
|
||||
}
|
||||
|
||||
/// Counts a loaded module's code against the heap once, when the module is loaded, and keeps
|
||||
/// it reachable until [`Self::drop_temp_codes`] drops it, so a collection while later modules
|
||||
/// load counts it too.
|
||||
pub(crate) fn hold_module_code(&mut self, code: &Rc<Code>) -> JsResult<()> {
|
||||
self.charge_code(code, 0)?;
|
||||
self.temp_codes.push(code.clone());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn temp_codes_mark(&self) -> usize {
|
||||
self.temp_codes.len()
|
||||
}
|
||||
|
||||
/// Ends module linking: drops the modules' code held from `mark` on.
|
||||
pub(crate) fn drop_temp_codes(&mut self, mark: usize) {
|
||||
self.temp_codes.truncate(mark);
|
||||
}
|
||||
|
||||
/// Keeps `v` reachable until [`Self::drop_temp_roots`] drops it.
|
||||
pub(crate) fn hold(&mut self, v: Value) {
|
||||
self.temp_roots.push(v);
|
||||
}
|
||||
|
||||
pub(crate) fn temp_roots_mark(&self) -> usize {
|
||||
self.temp_roots.len()
|
||||
}
|
||||
|
||||
pub(crate) fn drop_temp_roots(&mut self, mark: usize) {
|
||||
self.temp_roots.truncate(mark);
|
||||
}
|
||||
|
||||
/// Declaration binding instantiation for global and eval code (section 10.5). The caller has
|
||||
/// reserved [`declaration_bytes`] of `code`; each declaration takes a unit of fuel.
|
||||
///
|
||||
|
||||
+46
-4
@@ -63,7 +63,17 @@
|
||||
//! closes its iterator. In a realm made without the option and later given it with
|
||||
//! [`Realm::set_es2015`], which has no `Symbol.iterator`, they walk arrays and `arguments` objects
|
||||
//! by index and strings by code point, and throw a `TypeError` for other values.
|
||||
//! Object rest properties (`{ a, ...rest }`) and modules stay syntax errors.
|
||||
//! Object rest properties (`{ a, ...rest }`) stay syntax errors, and so do `import` and `export`
|
||||
//! in a script.
|
||||
//!
|
||||
//! [`parse_module`] reads a module (section 15.2): strict mode code with those forms and `import`
|
||||
//! and `export` declarations at its top. [`Realm::start_module`] and [`Realm::run_module`] run a
|
||||
//! module and the modules it imports, which the host gives through a [`ModuleLoader`]: each module
|
||||
//! once, after the modules it imports, with each import reading the exporting module's binding. In
|
||||
//! a cycle of imports, a module is marked as visited before the modules it imports are, so it does
|
||||
//! not wait for a module that is still waiting for its own imports, and reading a binding of that
|
||||
//! module before it is initialized throws a `ReferenceError`.
|
||||
//! Dynamic `import()` is a syntax error.
|
||||
//!
|
||||
//! With [`Options::es2015`], the parser and the realm also have generators (ECMA-262 11th edition,
|
||||
//! sections 14.4 and 25.4): `function*` declarations and expressions, `*name() {…}` methods in
|
||||
@@ -129,6 +139,7 @@ mod host_classes;
|
||||
mod interp;
|
||||
mod iteration;
|
||||
mod lexer;
|
||||
mod module;
|
||||
mod number;
|
||||
mod number_builtins;
|
||||
mod parser;
|
||||
@@ -151,15 +162,16 @@ mod xmp_classes;
|
||||
mod xpath;
|
||||
|
||||
pub use ast::{
|
||||
AssignOp, Ast, BinaryOp, Binding, CatchClause, ClassDef, ClassElement, ClassKey, Expr, ExprId, ForInTarget, ForInit, Function, FunctionId,
|
||||
FunctionKind, LexKind, LogicalOp, MethodKind, Name, Program, Property, PropertyKey, PropertyValue, Stmt, StmtId, SwitchCase, TemplatePiece,
|
||||
UnaryOp, UpdateOp, VarDecl, XmlNamePart, XmlPart, XmlQualifier,
|
||||
AssignOp, Ast, BinaryOp, Binding, CatchClause, ClassDef, ClassElement, ClassKey, DEFAULT_BINDING, ExportEntry, Expr, ExprId, ForInTarget,
|
||||
ForInit, Function, FunctionId, FunctionKind, ImportEntry, ImportName, LexKind, LogicalOp, MethodKind, ModuleInfo, ModuleRequest, Name, Program,
|
||||
Property, PropertyKey, PropertyValue, Stmt, StmtId, SwitchCase, TemplatePiece, UnaryOp, UpdateOp, VarDecl, XmlNamePart, XmlPart, XmlQualifier,
|
||||
};
|
||||
pub use builtins::extensions::Localization;
|
||||
pub use error::{SyntaxError, TOO_DEEP, TOO_LONG};
|
||||
pub use host::{Arg, CallSite, Data, DataLimits, HostError, HostFunction, HostItem, ScriptItem, SiteFunction};
|
||||
pub use host_classes::{ArgInfo, FILE_REF_KEY, HOST_REF_KEY, HostClass, HostMember, MemberInfo, file_ref_path, host_ref, host_ref_parts};
|
||||
pub use lexer::{Goal, Lexer};
|
||||
pub use module::{LoadError, LoadedModule, ModuleLimits, ModuleLoader};
|
||||
pub use number::to_string as number_to_string;
|
||||
pub use realm::{
|
||||
Interrupt, JsValue, LimitKind, Limits, MAX_UNBROKEN_FUEL, Progress, Realm, Rejection, RunError, RunErrorKind, SourceLocator, UNKNOWN_SOURCE,
|
||||
@@ -222,6 +234,34 @@ pub fn parse_utf16(source: &[u16], options: &Options) -> Result<Program, SyntaxE
|
||||
parser::Parser::new(source, options, false)?.parse_program().map(|(program, _)| program)
|
||||
}
|
||||
|
||||
/// Parses `source` as a module (ECMA-262 2015 section 15.2): strict mode code with
|
||||
/// [`Options::es2015`]'s forms, `import` and `export` declarations at its top, and no preprocessor
|
||||
/// lines, whatever `options` says about those three. Gives its statements and what it imports and
|
||||
/// exports.
|
||||
pub fn parse_module(source: &str, options: &Options) -> Result<(Program, ModuleInfo), SyntaxError> {
|
||||
let units = to_utf16(source, options)?;
|
||||
parse_module_utf16(&units, options)
|
||||
}
|
||||
|
||||
/// Parses `source`, in UTF-16 code units, as a module ([`parse_module`]).
|
||||
pub fn parse_module_utf16(source: &[u16], options: &Options) -> Result<(Program, ModuleInfo), SyntaxError> {
|
||||
check_length(source.len(), options)?;
|
||||
parser::Parser::new(source, &module_options(options), false)?.parse_module().map(|(program, info, _)| (program, info))
|
||||
}
|
||||
|
||||
/// The tokens of `source` as [`tokenize`] gives them, with `source` read as a module
|
||||
/// ([`parse_module`]). The source must be a valid module.
|
||||
pub fn tokenize_module(source: &str, options: &Options) -> Result<Vec<Token>, SyntaxError> {
|
||||
let units = to_utf16(source, options)?;
|
||||
check_length(units.len(), options)?;
|
||||
parser::Parser::new(&units, &module_options(options), true)?.parse_module().map(|(_, _, tokens)| tokens)
|
||||
}
|
||||
|
||||
/// `options` as a module is read with them.
|
||||
pub(crate) fn module_options(options: &Options) -> Options {
|
||||
Options { strict: true, es2015: true, preprocessor_lines: false, ..options.clone() }
|
||||
}
|
||||
|
||||
/// [`parse_utf16`] for code a direct `eval` runs, which may use `super` and `new.target` as the
|
||||
/// code that calls it may (ECMA-262 2015 section 18.2.1.1).
|
||||
pub(crate) fn parse_utf16_with_supers(source: &[u16], options: &Options, rules: parser::SuperRules) -> Result<Program, SyntaxError> {
|
||||
@@ -324,6 +364,8 @@ mod host_tests;
|
||||
#[cfg(test)]
|
||||
mod interp_tests;
|
||||
#[cfg(test)]
|
||||
mod module_tests;
|
||||
#[cfg(test)]
|
||||
mod promise_tests;
|
||||
#[cfg(test)]
|
||||
mod reflect_tests;
|
||||
|
||||
@@ -0,0 +1,553 @@
|
||||
//! Running modules (ECMA-262 2015 section 15.2.1): loading a module and the modules it imports,
|
||||
//! linking their imports to the bindings their exports name, and readying them to run, each once,
|
||||
//! the modules a module imports before it.
|
||||
//!
|
||||
//! The host maps each specifier to a module ([`ModuleLoader`], the role of section 15.2.1.17,
|
||||
//! HostResolveImportedModule): it gives a key that names the module, and its source the first time
|
||||
//! it gives that key. Every module is parsed and compiled before any runs, and every import is
|
||||
//! linked before any runs, so a syntax error, a missing or ambiguous export, or a module the host
|
||||
//! cannot give ends the run before any of its code runs. The run's [`ModuleLimits`] bound how many
|
||||
//! modules it loads and how deep its imports go; parsing takes fuel for each code unit, and each
|
||||
//! binding made in linking takes a unit.
|
||||
//!
|
||||
//! An import reads the exporting module's binding itself, so it sees each later assignment, and a
|
||||
//! read before that binding is initialized (a module that imports one that imports it back) is a
|
||||
//! `ReferenceError`. A module namespace object (`import * as ns`) is not extensible, has no
|
||||
//! prototype, takes no writes and has the module's export names, in code unit order, as its
|
||||
//! properties. `export *` passes on every name but `default`; a name two `export *` give from
|
||||
//! different bindings is left out of a namespace and is a `SyntaxError` to import.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::rc::Rc;
|
||||
|
||||
use crate::ast::{ExportEntry, ImportName, ModuleInfo};
|
||||
use crate::bytecode::Code;
|
||||
use crate::heap::{Binding, Env, EnvId, ObjId, Prop, key};
|
||||
use crate::interp::{Abrupt, CompileError, ErrorType, Interp};
|
||||
use crate::value::Value;
|
||||
|
||||
/// What the host gives for a module a run imports.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct LoadedModule {
|
||||
/// What names the module: two specifiers that give one key import one module, which runs once.
|
||||
pub key: String,
|
||||
/// The module's source, given the first time the host gives its key in a run. `None` for a key
|
||||
/// the host gave before in the same run.
|
||||
pub source: Option<String>,
|
||||
}
|
||||
|
||||
/// Why the host cannot give a module, which ends the run before any module runs: the error the
|
||||
/// `import` raises, with its message.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum LoadError {
|
||||
/// A specifier the host does not read: a `SyntaxError`.
|
||||
Syntax(String),
|
||||
/// A limit of the host's: a `RangeError`.
|
||||
Range(String),
|
||||
/// A module that is missing, refused or unreadable: an `Error`.
|
||||
Other(String),
|
||||
}
|
||||
|
||||
/// The host's map from a specifier to a module: called with the key of the importing module and
|
||||
/// the specifier as written.
|
||||
pub type ModuleLoader<'a> = dyn FnMut(&str, &str) -> Result<LoadedModule, LoadError> + 'a;
|
||||
|
||||
/// Bounds on the modules of one run.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct ModuleLimits {
|
||||
/// The most modules a run loads, the first included.
|
||||
pub modules: usize,
|
||||
/// The most imports from the first module to any other, along the shortest chain.
|
||||
pub depth: usize,
|
||||
}
|
||||
|
||||
impl Default for ModuleLimits {
|
||||
fn default() -> Self {
|
||||
Self { modules: 64, depth: 16 }
|
||||
}
|
||||
}
|
||||
|
||||
/// The most modules a run loads, whatever its limits say: [`resolve_export`] and
|
||||
/// [`exported_names`] recurse once for each module at most.
|
||||
const MAX_MODULES: usize = 1024;
|
||||
/// The most `(module, name)` pairs one export's resolution visits.
|
||||
const MAX_RESOLVE_STEPS: usize = 1024;
|
||||
|
||||
#[derive(Default)]
|
||||
struct ResolveSeen {
|
||||
pairs: HashSet<ResolveKey>,
|
||||
count: usize,
|
||||
}
|
||||
|
||||
struct ResolveKey {
|
||||
module: usize,
|
||||
name: String,
|
||||
}
|
||||
|
||||
impl PartialEq for ResolveKey {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
#[cfg(test)]
|
||||
RESOLVE_MEMBERSHIP_CHECKS.with(|count| count.set(count.get() + 1));
|
||||
self.module == other.module && self.name == other.name
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for ResolveKey {}
|
||||
|
||||
impl std::hash::Hash for ResolveKey {
|
||||
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
|
||||
std::hash::Hash::hash(&(self.module, &self.name), state);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
pub(crate) static RESOLVED_STAR_EDGES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
pub(crate) static RESOLVE_CALLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
pub(crate) static RESOLVE_MEMBERSHIP_CHECKS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// A loaded module.
|
||||
struct Record {
|
||||
key: String,
|
||||
info: ModuleInfo,
|
||||
code: Rc<Code>,
|
||||
tag: u32,
|
||||
/// The module each of `info.requests` names, by index.
|
||||
requested: Vec<usize>,
|
||||
/// The environment its code runs in and the outer one, once instantiated.
|
||||
envs: Option<(EnvId, EnvId)>,
|
||||
namespace: Option<ObjId>,
|
||||
/// Each name the module exports itself or re-exports by name, with its entry in
|
||||
/// `info.exports`.
|
||||
explicit: HashMap<String, usize>,
|
||||
/// Each `export *` request, replaced by distinct canonical targets after loading, in order.
|
||||
stars: Vec<usize>,
|
||||
}
|
||||
|
||||
/// Why a module run could not start.
|
||||
pub(crate) enum LinkFail {
|
||||
/// A module does not parse; `tag` is its source's.
|
||||
Syntax { tag: u32, error: crate::SyntaxError },
|
||||
/// An exception, raised at `line` and `column` of the module whose source has `tag`.
|
||||
At { tag: u32, line: u32, column: u32, abrupt: Abrupt },
|
||||
/// A limit or an internal error, not at any place.
|
||||
Run(Abrupt),
|
||||
}
|
||||
|
||||
/// Where an export resolves to (ResolvedBinding).
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
enum Resolution {
|
||||
/// The binding `name` of module `module`.
|
||||
Binding { module: usize, name: String },
|
||||
/// The namespace object of module `module` (`export * as ns from`).
|
||||
Namespace(usize),
|
||||
}
|
||||
|
||||
/// An export that two `export *` declarations give from different places.
|
||||
struct Ambiguous;
|
||||
|
||||
/// The modules of a run, loaded and linked.
|
||||
struct Graph<'a, 'l> {
|
||||
interp: &'a mut Interp,
|
||||
records: Vec<Record>,
|
||||
by_key: HashMap<String, usize>,
|
||||
load: &'a mut ModuleLoader<'l>,
|
||||
}
|
||||
|
||||
/// Loads the module `key` with `source` and every module it imports, instantiates and links them,
|
||||
/// and gives them in the order they run, each with its code, the environment it runs in and the
|
||||
/// outer one. The first module's source has tag `entry_tag`; each module loaded after it takes
|
||||
/// the next tag. The environments stay in the interpreter's temporary roots for the caller to
|
||||
/// remove once their frames are pushed.
|
||||
pub(crate) fn link(
|
||||
interp: &mut Interp,
|
||||
key_name: &str,
|
||||
source: &str,
|
||||
entry_tag: u32,
|
||||
limits: ModuleLimits,
|
||||
load: &mut ModuleLoader<'_>,
|
||||
) -> Result<Vec<(Rc<Code>, EnvId, EnvId)>, LinkFail> {
|
||||
let mut graph = Graph { interp, records: Vec::new(), by_key: HashMap::new(), load };
|
||||
if limits.modules == 0 {
|
||||
return Err(graph.fail_at(0, 0, ErrorType::Range, "module limit (0) reached"));
|
||||
}
|
||||
graph.add(key_name.to_string(), source, entry_tag)?;
|
||||
graph.load_imports(limits)?;
|
||||
graph.instantiate()?;
|
||||
graph.link_imports()?;
|
||||
Ok(graph.evaluation_order())
|
||||
}
|
||||
|
||||
impl Graph<'_, '_> {
|
||||
/// Parses and compiles a module's source under `tag`.
|
||||
fn add(&mut self, key_name: String, source: &str, tag: u32) -> Result<usize, LinkFail> {
|
||||
let interp = &mut *self.interp;
|
||||
let minimum_units = source.len().div_ceil(3);
|
||||
if u64::try_from(minimum_units).unwrap_or(u64::MAX) > interp.fuel {
|
||||
interp.prepare_source(minimum_units).map_err(LinkFail::Run)?;
|
||||
}
|
||||
interp.prepare_source(0).map_err(LinkFail::Run)?;
|
||||
interp.prepare_source(source.encode_utf16().count()).map_err(LinkFail::Run)?;
|
||||
let saved = std::mem::replace(&mut interp.source_tag, tag);
|
||||
let compiled = interp.encode_source(source).and_then(|units| interp.compile_module_source(&units));
|
||||
interp.source_tag = saved;
|
||||
let (code, info) = match compiled {
|
||||
Ok(c) => c,
|
||||
Err(CompileError::Syntax(error)) => return Err(LinkFail::Syntax { tag, error }),
|
||||
Err(CompileError::Internal(m)) => return Err(LinkFail::Run(Abrupt::Internal(m))),
|
||||
};
|
||||
// The record keeps the code from here on, so the heap counts it from here on.
|
||||
self.interp.hold_module_code(&code).map_err(LinkFail::Run)?;
|
||||
let mut explicit = HashMap::new();
|
||||
let mut stars = Vec::new();
|
||||
for (i, e) in info.exports.iter().enumerate() {
|
||||
match e {
|
||||
ExportEntry::Local { export_name, .. } | ExportEntry::Indirect { export_name, .. } => {
|
||||
explicit.entry(export_name.clone()).or_insert(i);
|
||||
}
|
||||
ExportEntry::Star { request, .. } => stars.push(*request),
|
||||
}
|
||||
}
|
||||
self.records.push(Record { key: key_name.clone(), info, code, tag, requested: Vec::new(), envs: None, namespace: None, explicit, stars });
|
||||
let index = self.records.len() - 1;
|
||||
self.by_key.insert(key_name, index);
|
||||
Ok(index)
|
||||
}
|
||||
|
||||
/// An exception of type `t` with `message`, at the source offset `offset` of module `m`.
|
||||
fn fail_at(&mut self, m: usize, offset: u32, t: ErrorType, message: &str) -> LinkFail {
|
||||
let (tag, (line, column)) = match self.records.get(m) {
|
||||
Some(r) => (r.tag, r.code.source.lines.line_column(offset)),
|
||||
None => (crate::realm::UNKNOWN_SOURCE, (0, 0)),
|
||||
};
|
||||
LinkFail::At { tag, line, column, abrupt: self.interp.throw(t, message) }
|
||||
}
|
||||
|
||||
/// Loads the modules each loaded module imports, breadth first, so a module's depth is the
|
||||
/// length of the shortest chain of imports to it.
|
||||
fn load_imports(&mut self, limits: ModuleLimits) -> Result<(), LinkFail> {
|
||||
let max_modules = limits.modules.min(MAX_MODULES);
|
||||
let mut depths = vec![0usize];
|
||||
let mut i = 0;
|
||||
while i < self.records.len() {
|
||||
let requests: Vec<(String, bool, u32)> = self.records[i]
|
||||
.info
|
||||
.requests
|
||||
.iter()
|
||||
.map(|r| (r.specifier.clone(), char::decode_utf16(r.units.iter().copied()).all(|c| c.is_ok()), r.span.start))
|
||||
.collect();
|
||||
let depth = depths.get(i).copied().unwrap_or(0);
|
||||
for (specifier, text, offset) in requests {
|
||||
self.interp.use_fuel().map_err(LinkFail::Run)?;
|
||||
// The host maps text to modules, and a specifier with an unpaired surrogate is not
|
||||
// text, so it is refused here, as a host refuses a specifier it does not read.
|
||||
if !text {
|
||||
let message = format!("module specifier '{specifier}' is not valid text: it has an unpaired surrogate");
|
||||
return Err(self.fail_at(i, offset, ErrorType::Syntax, &message));
|
||||
}
|
||||
let referrer = self.records[i].key.clone();
|
||||
let loaded = match (self.load)(&referrer, &specifier) {
|
||||
Ok(loaded) => loaded,
|
||||
Err(LoadError::Syntax(why)) => return Err(self.fail_at(i, offset, ErrorType::Syntax, &why)),
|
||||
Err(LoadError::Range(why)) => return Err(self.fail_at(i, offset, ErrorType::Range, &why)),
|
||||
Err(LoadError::Other(why)) => return Err(self.fail_at(i, offset, ErrorType::Error, &why)),
|
||||
};
|
||||
let target = match (self.by_key.get(&loaded.key), loaded.source) {
|
||||
(Some(&j), _) => j,
|
||||
(None, None) => {
|
||||
let message = format!("the module '{specifier}' was given without its source");
|
||||
return Err(self.fail_at(i, offset, ErrorType::Error, &message));
|
||||
}
|
||||
(None, Some(source)) => {
|
||||
if depth >= limits.depth {
|
||||
let message = format!("import depth limit ({}) reached at '{specifier}'", limits.depth);
|
||||
return Err(self.fail_at(i, offset, ErrorType::Range, &message));
|
||||
}
|
||||
if self.records.len() >= max_modules {
|
||||
let message = format!("module limit ({max_modules}) reached at '{specifier}'");
|
||||
return Err(self.fail_at(i, offset, ErrorType::Range, &message));
|
||||
}
|
||||
let tag = crate::realm::next_tag(self.records.last().map_or(0, |r| r.tag));
|
||||
self.interp.evaluated = tag;
|
||||
depths.push(depth + 1);
|
||||
self.add(loaded.key, &source, tag)?
|
||||
}
|
||||
};
|
||||
self.records[i].requested.push(target);
|
||||
}
|
||||
let mut seen_targets = HashSet::new();
|
||||
let targets: Vec<usize> = self.records[i]
|
||||
.stars
|
||||
.iter()
|
||||
.filter_map(|&request| self.records[i].requested.get(request).copied())
|
||||
.filter(|target| seen_targets.insert(*target))
|
||||
.collect();
|
||||
self.records[i].stars = targets;
|
||||
i += 1;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Makes each module's environments, with its variables, functions and `let` and `const`
|
||||
/// names.
|
||||
fn instantiate(&mut self) -> Result<(), LinkFail> {
|
||||
for i in 0..self.records.len() {
|
||||
let code = self.records[i].code.clone();
|
||||
let envs = self.interp.instantiate_module(&code).map_err(LinkFail::Run)?;
|
||||
self.records[i].envs = Some(envs);
|
||||
for import in &self.records[i].info.imports {
|
||||
if matches!(&import.import, ImportName::Namespace) {
|
||||
self.interp.add_import(envs.1, key(&import.local.name), Binding::lexical(true)).map_err(LinkFail::Run)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The module the request `request` of module `m` names.
|
||||
fn target(&self, m: usize, request: usize) -> Option<usize> {
|
||||
self.records.get(m).and_then(|r| r.requested.get(request)).copied()
|
||||
}
|
||||
|
||||
/// The specifier of request `request` of module `m`, as written.
|
||||
fn specifier(&self, m: usize, request: usize) -> String {
|
||||
self.records.get(m).and_then(|r| r.info.requests.get(request)).map(|r| r.specifier.clone()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// ResolveExport (section 15.2.1.16.3): where the export `name` of module `m` comes from,
|
||||
/// `None` when the module has no such export (or only through a cycle).
|
||||
fn resolve_export(&mut self, m: usize, name: &str, seen: &mut ResolveSeen) -> Result<Result<Option<Resolution>, Ambiguous>, LinkFail> {
|
||||
#[cfg(test)]
|
||||
RESOLVE_CALLS.with(|count| count.set(count.get() + 1));
|
||||
let visit = ResolveKey { module: m, name: name.to_string() };
|
||||
if seen.pairs.contains(&visit) {
|
||||
return Ok(Ok(None));
|
||||
}
|
||||
if seen.count >= MAX_RESOLVE_STEPS {
|
||||
let message = format!("export resolution limit ({MAX_RESOLVE_STEPS} steps) reached for '{name}'");
|
||||
return Err(LinkFail::Run(self.interp.throw(ErrorType::Range, &message)));
|
||||
}
|
||||
self.interp.use_fuel().map_err(LinkFail::Run)?;
|
||||
seen.pairs.insert(visit);
|
||||
seen.count += 1;
|
||||
let Some(record) = self.records.get(m) else { return Ok(Ok(None)) };
|
||||
// The module's own export of the name, looked up in its index, comes before any `export *`.
|
||||
let explicit = record.explicit.get(name).and_then(|&i| record.info.exports.get(i));
|
||||
match explicit {
|
||||
Some(ExportEntry::Local { local, .. }) => return Ok(Ok(Some(Resolution::Binding { module: m, name: local.clone() }))),
|
||||
Some(ExportEntry::Indirect { request, import, .. }) => {
|
||||
let (request, import) = (*request, import.clone());
|
||||
let Some(t) = self.target(m, request) else { return Ok(Ok(None)) };
|
||||
return match import {
|
||||
ImportName::Namespace => Ok(Ok(Some(Resolution::Namespace(t)))),
|
||||
ImportName::Name(n) => self.resolve_export(t, &n, seen),
|
||||
};
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if name == "default" {
|
||||
return Ok(Ok(None));
|
||||
}
|
||||
let mut star = None;
|
||||
let stars = record.stars.clone();
|
||||
for t in stars {
|
||||
#[cfg(test)]
|
||||
RESOLVED_STAR_EDGES.with(|count| count.set(count.get() + 1));
|
||||
self.interp.use_fuel().map_err(LinkFail::Run)?;
|
||||
match self.resolve_export(t, name, seen)? {
|
||||
Err(Ambiguous) => return Ok(Err(Ambiguous)),
|
||||
Ok(None) => {}
|
||||
Ok(Some(r)) => match &star {
|
||||
None => star = Some(r),
|
||||
Some(s) if *s == r => {}
|
||||
Some(_) => return Ok(Err(Ambiguous)),
|
||||
},
|
||||
}
|
||||
}
|
||||
Ok(Ok(star))
|
||||
}
|
||||
|
||||
/// GetExportedNames (section 15.2.1.16.2): the names module `m` exports, those of its
|
||||
/// `export *` modules but `default` included, each once.
|
||||
fn exported_names(
|
||||
&mut self,
|
||||
m: usize,
|
||||
star: bool,
|
||||
visited: &mut Vec<usize>,
|
||||
names: &mut Vec<String>,
|
||||
seen: &mut HashSet<String>,
|
||||
) -> Result<(), LinkFail> {
|
||||
if visited.contains(&m) {
|
||||
return Ok(());
|
||||
}
|
||||
visited.push(m);
|
||||
let count = self.records.get(m).map_or(0, |r| r.info.exports.len());
|
||||
for i in 0..count {
|
||||
self.interp.use_fuel().map_err(LinkFail::Run)?;
|
||||
let Some(e) = self.records.get(m).and_then(|r| r.info.exports.get(i)) else { break };
|
||||
match e {
|
||||
ExportEntry::Local { export_name, .. } | ExportEntry::Indirect { export_name, .. } => {
|
||||
if !(star && export_name == "default") && !seen.contains(export_name) {
|
||||
seen.insert(export_name.clone());
|
||||
names.push(export_name.clone());
|
||||
}
|
||||
}
|
||||
ExportEntry::Star { request, .. } => {
|
||||
if let Some(t) = self.target(m, *request) {
|
||||
self.exported_names(t, true, visited, names, seen)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The environment and name of the binding `name` of module `m`.
|
||||
fn binding_of(&self, m: usize, name: &str) -> Option<(EnvId, crate::heap::Key)> {
|
||||
let (lex, env) = self.records.get(m)?.envs?;
|
||||
let k = key(name);
|
||||
self.interp.module_binding(lex, env, &k).map(|e| (e, k))
|
||||
}
|
||||
|
||||
/// GetModuleNamespace (section 15.2.1.18): module `m`'s namespace object, made the first time.
|
||||
fn namespace(&mut self, m: usize) -> Result<ObjId, LinkFail> {
|
||||
if let Some(ns) = self.records.get(m).and_then(|r| r.namespace) {
|
||||
return Ok(ns);
|
||||
}
|
||||
let mut names = Vec::new();
|
||||
self.exported_names(m, false, &mut Vec::new(), &mut names, &mut HashSet::new())?;
|
||||
let mut resolved = Vec::new();
|
||||
for name in names {
|
||||
if let Ok(Some(r)) = self.resolve_export(m, &name, &mut ResolveSeen::default())? {
|
||||
resolved.push((key(&name), r));
|
||||
}
|
||||
}
|
||||
resolved.sort_by(|(a, _), (b, _)| a.cmp(b));
|
||||
let mut exports = Vec::new();
|
||||
let mut later = Vec::new();
|
||||
for (k, r) in resolved {
|
||||
match r {
|
||||
Resolution::Binding { module, name } => match self.binding_of(module, &name) {
|
||||
Some(b) => exports.push((k, Some(b))),
|
||||
None => return Err(LinkFail::Run(Abrupt::Internal(format!("module binding '{name}' not found")))),
|
||||
},
|
||||
Resolution::Namespace(module) => {
|
||||
exports.push((k.clone(), None));
|
||||
later.push((k, module));
|
||||
}
|
||||
}
|
||||
}
|
||||
let ns = self.interp.module_namespace(exports, &[]).map_err(LinkFail::Run)?;
|
||||
self.interp.hold(Value::Object(ns));
|
||||
if let Some(r) = self.records.get_mut(m) {
|
||||
r.namespace = Some(ns);
|
||||
}
|
||||
// A namespace that holds another is made first, so two that hold each other end.
|
||||
for (k, module) in later {
|
||||
let inner = self.namespace(module)?;
|
||||
let flags = crate::heap::WRITABLE | crate::heap::ENUMERABLE;
|
||||
self.interp.define(ns, k, Prop::Data { value: Value::Object(inner), flags }).map_err(LinkFail::Run)?;
|
||||
}
|
||||
Ok(ns)
|
||||
}
|
||||
|
||||
/// Binds each module's imports (section 15.2.1.16.4, steps 9 and 12), after checking that
|
||||
/// each re-export resolves.
|
||||
fn link_imports(&mut self) -> Result<(), LinkFail> {
|
||||
for m in 0..self.records.len() {
|
||||
let exports = self.records[m].info.exports.clone();
|
||||
for e in &exports {
|
||||
let ExportEntry::Indirect { export_name, request, span, .. } = e else { continue };
|
||||
if self.target(m, *request).is_none() {
|
||||
continue;
|
||||
}
|
||||
match self.resolve_export(m, export_name, &mut ResolveSeen::default())? {
|
||||
Ok(Some(_)) => {}
|
||||
Ok(None) => {
|
||||
let message = format!("the module '{}' has no export to give as '{export_name}'", self.specifier(m, *request));
|
||||
return Err(self.fail_at(m, span.start, ErrorType::Syntax, &message));
|
||||
}
|
||||
Err(Ambiguous) => {
|
||||
let message = format!("the export '{export_name}' is ambiguous");
|
||||
return Err(self.fail_at(m, span.start, ErrorType::Syntax, &message));
|
||||
}
|
||||
}
|
||||
}
|
||||
let imports = self.records[m].info.imports.clone();
|
||||
let Some((_, env)) = self.records[m].envs else { return Err(LinkFail::Run(Abrupt::Internal("module not instantiated".into()))) };
|
||||
for imp in imports {
|
||||
let Some(t) = self.target(m, imp.request) else { continue };
|
||||
let local = key(&imp.local.name);
|
||||
let binding = match &imp.import {
|
||||
ImportName::Namespace => self.namespace_binding(t)?,
|
||||
ImportName::Name(n) => match self.resolve_export(t, n, &mut ResolveSeen::default())? {
|
||||
Ok(Some(Resolution::Binding { module, name })) => match self.binding_of(module, &name) {
|
||||
Some((target_env, target_name)) => Binding::import(target_env, target_name),
|
||||
None => return Err(LinkFail::Run(Abrupt::Internal(format!("module binding '{name}' not found")))),
|
||||
},
|
||||
Ok(Some(Resolution::Namespace(module))) => self.namespace_binding(module)?,
|
||||
Ok(None) => {
|
||||
let message = format!("the module '{}' has no export named '{n}'", self.specifier(m, imp.request));
|
||||
return Err(self.fail_at(m, imp.local.span.start, ErrorType::Syntax, &message));
|
||||
}
|
||||
Err(Ambiguous) => {
|
||||
let message = format!("the export '{n}' of the module '{}' is ambiguous", self.specifier(m, imp.request));
|
||||
return Err(self.fail_at(m, imp.local.span.start, ErrorType::Syntax, &message));
|
||||
}
|
||||
},
|
||||
};
|
||||
if matches!(&imp.import, ImportName::Namespace) {
|
||||
self.interp.use_fuel().map_err(LinkFail::Run)?;
|
||||
let Some(Env::Decl { bindings, .. }) = self.interp.heap.env_mut(env) else {
|
||||
return Err(LinkFail::Run(Abrupt::Internal("namespace import environment not found".into())));
|
||||
};
|
||||
let Some(slot) = bindings.get_mut(&local) else {
|
||||
return Err(LinkFail::Run(Abrupt::Internal("namespace import binding not found".into())));
|
||||
};
|
||||
*slot = binding;
|
||||
} else {
|
||||
self.interp.add_import(env, local, binding).map_err(LinkFail::Run)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// An immutable binding of module `m`'s namespace object.
|
||||
fn namespace_binding(&mut self, m: usize) -> Result<Binding, LinkFail> {
|
||||
let ns = self.namespace(m)?;
|
||||
Ok(Binding { constant: true, lexical: true, ..Binding::new(Value::Object(ns), false, false) })
|
||||
}
|
||||
|
||||
/// The modules in the order they run (section 15.2.1.16.5, ModuleEvaluation): each module
|
||||
/// after the modules it imports, in the order it imports them, and each once; a module an
|
||||
/// import cycle reaches again while it waits is not waited for.
|
||||
fn evaluation_order(&self) -> Vec<(Rc<Code>, EnvId, EnvId)> {
|
||||
let mut state = vec![0u8; self.records.len()];
|
||||
let mut order = Vec::new();
|
||||
let mut stack = vec![(0usize, 0usize)];
|
||||
if let Some(s) = state.first_mut() {
|
||||
*s = 1;
|
||||
}
|
||||
while let Some(top) = stack.last_mut() {
|
||||
let m = top.0;
|
||||
let requested = self.records.get(m).map_or(&[][..], |r| r.requested.as_slice());
|
||||
if let Some(&t) = requested.get(top.1) {
|
||||
top.1 += 1;
|
||||
if let Some(s @ 0) = state.get_mut(t) {
|
||||
*s = 1;
|
||||
stack.push((t, 0));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
stack.pop();
|
||||
if let Some(r) = self.records.get(m)
|
||||
&& let Some((lex, env)) = r.envs
|
||||
{
|
||||
order.push((r.code.clone(), lex, env));
|
||||
}
|
||||
}
|
||||
order
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,759 @@
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use crate::{
|
||||
JsValue, LimitKind, Limits, LoadError, LoadedModule, ModuleLimits, Options, Progress, Realm, RunError, RunErrorKind, parse, parse_module,
|
||||
};
|
||||
|
||||
fn es() -> Realm {
|
||||
let mut realm = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits::default());
|
||||
// Modules declare no globals, so they report through this array.
|
||||
assert!(realm.run("var out = [];").is_ok());
|
||||
realm
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn global_var_records_survive_deleting_only_an_inherited_property() {
|
||||
let mut realm = es();
|
||||
realm.run("Object.defineProperty(this, 'w', {value: 1, writable: true, configurable: true});").unwrap();
|
||||
assert_eq!(realm.run("var w; delete this.w; Object.prototype.w = 7; delete w;"), Ok(JsValue::Bool(true)));
|
||||
let error = realm.run("let w = 2; w;").unwrap_err();
|
||||
assert!(matches!(error.kind, RunErrorKind::Syntax | RunErrorKind::Thrown), "{error:?}");
|
||||
|
||||
let mut realm = es();
|
||||
realm.run("Object.defineProperty(this, 'w', {value: 1, writable: true, configurable: true});").unwrap();
|
||||
assert_eq!(realm.run("var w; delete w;"), Ok(JsValue::Bool(true)));
|
||||
assert_eq!(realm.run("let w = 2; w;"), Ok(JsValue::Number(2.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn namespace_allocations_charge_binding_tables_and_symbols() {
|
||||
use crate::heap::{OBJECT_BYTES, PROP_BYTES, key};
|
||||
let mut realm = es();
|
||||
let interp = realm.interp();
|
||||
let before = interp.heap.bytes;
|
||||
let exports = (0..128).map(|n| (key(&format!("v{n}")), None)).collect();
|
||||
let namespace = interp.module_namespace(exports, &[]).unwrap();
|
||||
let symbols = interp.heap.object(namespace).unwrap().syms.as_ref().map_or(0, |symbols| symbols.len());
|
||||
let required = OBJECT_BYTES + PROP_BYTES * (128 * 2 + symbols);
|
||||
assert!(interp.heap.bytes - before >= required, "namespace charged {} bytes, needs at least {required}", interp.heap.bytes - before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_resolution_membership_work_is_bounded_per_visit() {
|
||||
let mut files: Vec<(String, String)> = (0..31).map(|n| (format!("./m{n}.mjs"), format!("export * from './m{}.mjs';", n + 1))).collect();
|
||||
let source = (0..32).map(|n| format!("export var v{n} = {n};")).collect();
|
||||
files.push(("./m31.mjs".into(), source));
|
||||
let references: Vec<_> = files.iter().map(|(name, source)| (name.as_str(), source.as_str())).collect();
|
||||
let mut load = loader(&references);
|
||||
let mut realm = es();
|
||||
crate::module::RESOLVE_CALLS.with(|count| count.set(0));
|
||||
crate::module::RESOLVE_MEMBERSHIP_CHECKS.with(|count| count.set(0));
|
||||
realm
|
||||
.run_module("main.mjs", "import * as ns from './m0.mjs'; out.push(ns.v0, ns.v31);", ModuleLimits { modules: 64, depth: 64 }, &mut load)
|
||||
.unwrap();
|
||||
let visits = crate::module::RESOLVE_CALLS.with(std::cell::Cell::get);
|
||||
let checks = crate::module::RESOLVE_MEMBERSHIP_CHECKS.with(std::cell::Cell::get);
|
||||
assert!(visits > 32);
|
||||
assert!(checks <= visits * 4, "{checks} membership checks for {visits} export visits");
|
||||
assert_eq!(realm.run("out.join('|')"), Ok(JsValue::String("0|31".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn star_aliases_resolve_each_canonical_target_once_per_name() {
|
||||
let exports: String = (0..100).map(|n| format!("export var v{n} = {n};")).collect();
|
||||
let stars: String = (0..100).map(|n| format!("export * from './alias{n}.mjs';")).collect();
|
||||
let mut supplied = HashSet::new();
|
||||
let mut load = |_: &str, specifier: &str| {
|
||||
let (key, source) = if specifier == "./stars.mjs" { ("stars", &stars) } else { ("canonical", &exports) };
|
||||
Ok(LoadedModule { key: key.into(), source: supplied.insert(key).then(|| source.clone()) })
|
||||
};
|
||||
let mut realm = es();
|
||||
crate::module::RESOLVED_STAR_EDGES.with(|count| count.set(0));
|
||||
realm
|
||||
.run_module("main.mjs", "import * as ns from './stars.mjs'; out.push(ns.v99, Object.keys(ns).length);", ModuleLimits::default(), &mut load)
|
||||
.unwrap();
|
||||
let steps = crate::module::RESOLVED_STAR_EDGES.with(|count| count.get());
|
||||
assert!(steps <= 200, "{steps} star edges inspected");
|
||||
assert_eq!(realm.run("out.join('|')").unwrap(), JsValue::String("99|100".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ending_a_module_queue_restores_normal_frame_accounting() {
|
||||
let mut realm = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits { frames: 2, ..Limits::default() });
|
||||
let mut load = loader(&[("./m.mjs", "for (var i = 0; i < 1000; i++) {}")]);
|
||||
realm.start_module("main.mjs", "import './m.mjs';", ModuleLimits::default(), &mut load).unwrap();
|
||||
assert!(matches!(realm.advance(1), Ok(Progress::Paused)));
|
||||
realm.end();
|
||||
assert_eq!(realm.run("function f() { return 1; } f();"), Ok(JsValue::Number(1.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pending_module_bodies_do_not_consume_active_call_frames() {
|
||||
let mut realm = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits { frames: 2, ..Limits::default() });
|
||||
let files = [("./a.mjs", "import './b.mjs';"), ("./b.mjs", "import './c.mjs';"), ("./c.mjs", "function f() { return 1; } f();")];
|
||||
let mut load = loader(&files);
|
||||
let result = realm.run_module("main.mjs", "import './a.mjs';", ModuleLimits::default(), &mut load);
|
||||
assert_eq!(result, Ok(JsValue::Undefined));
|
||||
let mut load = loader(&[]);
|
||||
let result = realm.run_module("main.mjs", "function f() { return f(); } f();", ModuleLimits::default(), &mut load);
|
||||
assert_eq!(result.map_err(|e| e.kind), Err(RunErrorKind::Limit(LimitKind::Frames)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn module_stack_excludes_bodies_waiting_to_run() {
|
||||
let mut realm = es();
|
||||
realm.define_host_object("$", [("stack".to_string(), crate::HostItem::Script(crate::ScriptItem::Stack))].into_iter().collect()).unwrap();
|
||||
let (result, out) = run_with(
|
||||
&mut realm,
|
||||
"import './m.mjs';",
|
||||
&[("./m.mjs", "function trace() { var s = $.stack; out.push(s.split('[global]').length - 1, s.indexOf('trace:') >= 0); } trace();")],
|
||||
ModuleLimits::default(),
|
||||
);
|
||||
assert_eq!(result, Ok(JsValue::Undefined));
|
||||
assert_eq!(out, "1|true");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn module_sources_charge_utf16_units_instead_of_utf8_bytes() {
|
||||
let mut remaining = Vec::new();
|
||||
for character in ['a', 'é', '界'] {
|
||||
let source = format!("/*{}*/ export var value = 1;", character.to_string().repeat(1000));
|
||||
let mut realm = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits::default());
|
||||
let mut load = loader(&[]);
|
||||
realm.start_module("main.mjs", &source, ModuleLimits::default(), &mut load).unwrap();
|
||||
remaining.push(realm.fuel_left());
|
||||
}
|
||||
assert!(remaining.windows(2).all(|pair| pair[0] == pair[1]), "{remaining:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_exported_functions_keep_their_public_names() {
|
||||
for (source, name) in [
|
||||
("export default function () {}", "default"),
|
||||
("export default () => {};", "default"),
|
||||
("export default (function () {});", "default"),
|
||||
("export default function named() {}", "named"),
|
||||
] {
|
||||
let out = run("import value from './m.mjs'; out.push(value.name);", &[("./m.mjs", source)]);
|
||||
assert_eq!(out, name, "{source}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn symbol_writes_through_namespace_prototypes_are_refused() {
|
||||
let out = run(
|
||||
"import * as ns from './m.mjs'; var k = Symbol('new'), child = Object.create(ns); \
|
||||
try { child[k] = 1; } catch (e) { out.push(e.name); } \
|
||||
out.push(Object.getOwnPropertySymbols(child).length); \
|
||||
Object.defineProperty(child, k, {value: 3, writable: true}); child[k] = 4; out.push(child[k]);",
|
||||
&[("./m.mjs", "export var value = 1;")],
|
||||
);
|
||||
assert_eq!(out, "TypeError|0|4");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_namespace_exposes_its_own_immutable_symbol_tag() {
|
||||
let out = run(
|
||||
"import * as ns from './m.mjs'; \
|
||||
var d = Object.getOwnPropertyDescriptor(ns, Symbol.toStringTag); \
|
||||
out.push(ns[Symbol.toStringTag], Object.getOwnPropertySymbols(ns).length, \
|
||||
d && d.writable, d && d.enumerable, d && d.configurable);",
|
||||
&[("./m.mjs", "export var value = 1;")],
|
||||
);
|
||||
assert_eq!(out, "Module|1|false|false|false");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn modules_reject_await_identifiers_before_running_dependencies() {
|
||||
for source in ["export const await = 1;", "var aw\\u0061it = 1;", "await;", "function await() {}"] {
|
||||
assert!(parse_module(source, &Options::default()).is_err(), "{source}");
|
||||
}
|
||||
let mut realm = es();
|
||||
let mut load = loader(&[("./effect.mjs", "out.push('dependency');")]);
|
||||
let result = realm.run_module("main.mjs", "import './effect.mjs'; export const await = 1;", ModuleLimits::default(), &mut load);
|
||||
assert!(result.is_err());
|
||||
assert_eq!(realm.run("out.length").unwrap(), JsValue::Number(0.0));
|
||||
assert!(realm.run("var await = 1; await").is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn synchronous_and_sliced_modules_drain_promise_jobs() {
|
||||
let source = "out.push('body'); Promise.resolve().then(function () { out.push('resolved'); }); \
|
||||
Promise.reject('rejected').catch(function (e) { out.push(e); });";
|
||||
for sliced in [false, true] {
|
||||
let mut realm = es();
|
||||
let mut load = loader(&[]);
|
||||
if sliced {
|
||||
realm.start_module("main.mjs", source, ModuleLimits::default(), &mut load).unwrap();
|
||||
loop {
|
||||
match realm.advance(100).unwrap() {
|
||||
Progress::Paused => {}
|
||||
Progress::Done(value) => {
|
||||
assert_eq!(value, JsValue::Undefined);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
assert_eq!(realm.run_module("main.mjs", source, ModuleLimits::default(), &mut load).unwrap(), JsValue::Undefined);
|
||||
}
|
||||
assert_eq!(realm.run("out.join('|')").unwrap(), JsValue::String("body|resolved|rejected".into()), "sliced={sliced}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn starting_a_module_discards_a_paused_script() {
|
||||
for (sliced, invalid) in [(false, false), (true, false), (false, true), (true, true)] {
|
||||
let mut realm = es();
|
||||
realm.start("out.push('old');").unwrap();
|
||||
assert_eq!(realm.advance(1).unwrap(), Progress::Paused);
|
||||
let mut load = loader(&[]);
|
||||
let source = if invalid { "var = ;" } else { "out.push('new');" };
|
||||
if invalid {
|
||||
let result = if sliced {
|
||||
realm.start_module("main.mjs", source, ModuleLimits::default(), &mut load)
|
||||
} else {
|
||||
realm.run_module("main.mjs", source, ModuleLimits::default(), &mut load).map(drop)
|
||||
};
|
||||
assert!(result.is_err());
|
||||
assert!(!realm.is_running(), "sliced={sliced}");
|
||||
assert_eq!(realm.run("out.join('|')").unwrap(), JsValue::String(String::new()));
|
||||
continue;
|
||||
}
|
||||
if sliced {
|
||||
realm.start_module("main.mjs", source, ModuleLimits::default(), &mut load).unwrap();
|
||||
loop {
|
||||
if let Progress::Done(_) = realm.advance(100).unwrap() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
realm.run_module("main.mjs", source, ModuleLimits::default(), &mut load).unwrap();
|
||||
}
|
||||
assert_eq!(realm.run("out.join('|')").unwrap(), JsValue::String("new".into()), "sliced={sliced}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A loader over `files`: each specifier is its own key, given with its source the first time.
|
||||
fn loader(files: &[(&str, &str)]) -> impl FnMut(&str, &str) -> Result<LoadedModule, LoadError> + use<> {
|
||||
let map: HashMap<String, String> = files.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect();
|
||||
let mut given = HashSet::new();
|
||||
move |_, specifier| {
|
||||
if !specifier.starts_with('.') && specifier != "main" {
|
||||
return Err(LoadError::Syntax(format!("bare specifier: {specifier}")));
|
||||
}
|
||||
let source = map.get(specifier).ok_or_else(|| LoadError::Other(format!("module not found: {specifier}")))?;
|
||||
let first = given.insert(specifier.to_string());
|
||||
Ok(LoadedModule { key: specifier.to_string(), source: first.then(|| source.clone()) })
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `entry` with the modules `files`. → the result and `out` joined with `|`.
|
||||
fn run_with(realm: &mut Realm, entry: &str, files: &[(&str, &str)], limits: ModuleLimits) -> (Result<JsValue, RunError>, String) {
|
||||
let mut load = loader(files);
|
||||
let result = realm.run_module("main.mjs", entry, limits, &mut load);
|
||||
let out = match realm.run("out.join('|')") {
|
||||
Ok(JsValue::String(s)) => s,
|
||||
other => panic!("{other:?}"),
|
||||
};
|
||||
(result, out)
|
||||
}
|
||||
|
||||
fn run(entry: &str, files: &[(&str, &str)]) -> String {
|
||||
match run_with(&mut es(), entry, files, ModuleLimits::default()) {
|
||||
(Ok(v), out) => {
|
||||
assert_eq!(v, JsValue::Undefined);
|
||||
out
|
||||
}
|
||||
(Err(e), _) => panic!("{entry}\n{e:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The run ends with an error whose message starts with `start`, and `out` holds `ran`.
|
||||
fn fails(entry: &str, files: &[(&str, &str)], start: &str, ran: &str) -> RunError {
|
||||
match run_with(&mut es(), entry, files, ModuleLimits::default()) {
|
||||
(Err(e), out) => {
|
||||
assert!(e.message.starts_with(start), "{entry}: {e:?}");
|
||||
assert_eq!(out, ran, "{entry}");
|
||||
e
|
||||
}
|
||||
(Ok(_), out) => panic!("{entry}: completed with {out}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn syntax(src: &str) {
|
||||
assert!(parse_module(src, &Options::default()).is_err(), "{src}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_import_reads_the_exporting_binding_each_time() {
|
||||
let counter = "export let count = 0; export function inc() { count++; }";
|
||||
let out = run("import { count, inc } from './c.mjs'; out.push(count); inc(); inc(); out.push(count);", &[("./c.mjs", counter)]);
|
||||
assert_eq!(out, "0|2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn imports_can_be_renamed_and_combined() {
|
||||
let m = "export default 'd'; export var a = 1; export const b = 2;";
|
||||
let out = run("import d, { a as x, b } from './m.mjs'; out.push(d, x, b);", &[("./m.mjs", m)]);
|
||||
assert_eq!(out, "d|1|2");
|
||||
let out = run("import d, * as ns from './m.mjs'; out.push(d, ns.a, ns['default']);", &[("./m.mjs", m)]);
|
||||
assert_eq!(out, "d|1|d");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_destructuring_declaration_exports_every_name_it_binds() {
|
||||
let m = "export const { a, b: [c, ...d] } = { a: 1, b: [2, 3, 4] }; export var [e = 5] = [];";
|
||||
let out = run("import { a, c, d, e } from './m.mjs'; out.push(a, c, d.join('+'), e);", &[("./m.mjs", m)]);
|
||||
assert_eq!(out, "1|2|3+4|5");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_exports_of_expressions_and_functions() {
|
||||
let out = run("import v from './v.mjs'; out.push(v * 2);", &[("./v.mjs", "export default 20 + 1;")]);
|
||||
assert_eq!(out, "42");
|
||||
let out = run("import f from './f.mjs'; out.push(f());", &[("./f.mjs", "export default function () { return 'anon'; }")]);
|
||||
assert_eq!(out, "anon");
|
||||
// A named default function is a declaration: hoisted, and its name is bound in the module.
|
||||
let f = "out.push(typeof g); export default function g() { return 'g'; }";
|
||||
let out = run("import h from './f.mjs'; out.push(h());", &[("./f.mjs", f)]);
|
||||
assert_eq!(out, "function|g");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_namespace_object_has_the_exports_in_order_and_takes_no_writes() {
|
||||
let m = "export var zeta = 1; export let alpha = 2; export function mid() {} export default 3;";
|
||||
let out = run(
|
||||
"import * as ns from './m.mjs';
|
||||
out.push(Object.keys(ns).join(','), Object.prototype.toString.call(ns), Object.isExtensible(ns), Object.getPrototypeOf(ns) === null);
|
||||
try { ns.alpha = 5; } catch (e) { out.push(e.name); }
|
||||
try { ns.added = 5; } catch (e) { out.push(e.name); }
|
||||
try { delete ns.alpha; } catch (e) { out.push(e.name); }
|
||||
out.push(ns.alpha, Object.getOwnPropertyDescriptor(ns, 'zeta').writable);",
|
||||
&[("./m.mjs", m)],
|
||||
);
|
||||
assert_eq!(out, "alpha,default,mid,zeta|[object Module]|false|true|TypeError|TypeError|TypeError|2|true");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_write_that_reaches_a_namespace_through_a_prototype_is_refused() {
|
||||
let m = "export var alpha = 1;";
|
||||
let out = run(
|
||||
"import * as ns from './m.mjs';
|
||||
var o = Object.create(ns);
|
||||
Object.defineProperty(o, 'own', { value: 1, writable: true });
|
||||
o.own = 2;
|
||||
try { o.alpha = 5; } catch (e) { out.push(e.name); }
|
||||
try { o.fresh = 5; } catch (e) { out.push(e.name); }
|
||||
try { Object.create(o).alpha = 5; } catch (e) { out.push(e.name); }
|
||||
out.push(o.own, Object.getOwnPropertyNames(o).join(), ns.alpha, o.alpha);",
|
||||
&[("./m.mjs", m)],
|
||||
);
|
||||
assert_eq!(out, "TypeError|TypeError|TypeError|2|own|1|1");
|
||||
// A script's sloppy write is ignored.
|
||||
let mut realm = es();
|
||||
let out = run_with(&mut realm, "import * as ns from './m.mjs'; out.ns = ns;", &[("./m.mjs", m)], ModuleLimits::default());
|
||||
assert_eq!(out, (Ok(JsValue::Undefined), String::new()));
|
||||
// A namespace has no prototype, so `hasOwnProperty` is called from `Object.prototype`.
|
||||
let sloppy = "var o = Object.create(out.ns), own = Object.prototype.hasOwnProperty; o.alpha = 5; o.fresh = 5; \
|
||||
[own.call(o, 'alpha'), own.call(o, 'fresh'), o.alpha].join()";
|
||||
assert_eq!(realm.run(sloppy), Ok(JsValue::String("false,false,1".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_namespace_takes_only_definitions_that_change_nothing() {
|
||||
let m = "export var a = 1;";
|
||||
let out = run(
|
||||
"import * as ns from './m.mjs';
|
||||
out.push(Object.seal(ns) === ns, Object.isSealed(ns), Object.isFrozen(ns));
|
||||
out.push(Object.defineProperty(ns, 'a', { value: 1, writable: true, enumerable: true, configurable: false }) === ns);
|
||||
var ds = [{ value: 2 }, { writable: false }, { enumerable: false }, { configurable: true }, { get: function () {} }];
|
||||
for (var i = 0; i < ds.length; i++) {
|
||||
try { Object.defineProperty(ns, 'a', ds[i]); out.push('defined'); } catch (e) { out.push(e.name); }
|
||||
}
|
||||
try { Object.defineProperty(ns, 'b', { value: 1 }); } catch (e) { out.push(e.name); }
|
||||
try { Object.freeze(ns); } catch (e) { out.push(e.name); }
|
||||
out.push(ns.a);",
|
||||
&[("./m.mjs", m)],
|
||||
);
|
||||
assert_eq!(out, "true|true|false|true|TypeError|TypeError|TypeError|TypeError|TypeError|TypeError|TypeError|1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_namespace_reads_live_values() {
|
||||
let m = "export var n = 1; export function bump() { n = n + 1; }";
|
||||
let out = run("import * as ns from './m.mjs'; ns.bump(); out.push(ns.n);", &[("./m.mjs", m)]);
|
||||
assert_eq!(out, "2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn assigning_to_an_import_is_a_type_error() {
|
||||
let m = "export var a = 1;";
|
||||
let out = run("import { a } from './m.mjs'; try { a = 2; } catch (e) { out.push(e.name); } out.push(a);", &[("./m.mjs", m)]);
|
||||
assert_eq!(out, "TypeError|1");
|
||||
let out = run("import * as ns from './m.mjs'; try { ns = 2; } catch (e) { out.push(e.name); }", &[("./m.mjs", m)]);
|
||||
assert_eq!(out, "TypeError");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cycle_of_two_modules_runs_each_once_dependency_first() {
|
||||
// main imports b, b imports main back: b runs first and sees main's hoisted function.
|
||||
let b = "import { fa } from 'main'; out.push('b ' + fa()); export const b = 'B';";
|
||||
let mut realm = es();
|
||||
let mut load = loader(&[("./b.mjs", b), ("main", "")]);
|
||||
let mut load = |referrer: &str, specifier: &str| {
|
||||
if specifier == "main" { Ok(LoadedModule { key: "main.mjs".into(), source: None }) } else { load(referrer, specifier) }
|
||||
};
|
||||
let entry = "import { b } from './b.mjs'; export function fa() { return 'fa'; } out.push('a ' + b);";
|
||||
let r = realm.run_module("main.mjs", entry, ModuleLimits::default(), &mut load);
|
||||
assert_eq!(r, Ok(JsValue::Undefined));
|
||||
assert_eq!(realm.run("out.join('|')"), Ok(JsValue::String("b fa|a B".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reading_an_import_before_its_module_ran_is_a_reference_error() {
|
||||
let b = "import { a } from 'main'; out.push('b'); out.push(a);";
|
||||
let mut realm = es();
|
||||
let mut inner = loader(&[("./b.mjs", b)]);
|
||||
let mut load = |referrer: &str, specifier: &str| {
|
||||
if specifier == "main" { Ok(LoadedModule { key: "main.mjs".into(), source: None }) } else { inner(referrer, specifier) }
|
||||
};
|
||||
let r = realm.run_module("main.mjs", "import './b.mjs'; export let a = 1;", ModuleLimits::default(), &mut load);
|
||||
match r {
|
||||
Err(e) => assert!(e.message.starts_with("ReferenceError"), "{e:?}"),
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
assert_eq!(realm.run("out.join('|')"), Ok(JsValue::String("b".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_namespace_export_its_module_has_not_initialized_is_a_reference_error() {
|
||||
let b = "import * as ns from 'main';
|
||||
var tries = [() => ns.a, () => Object.keys(ns), () => Object.prototype.hasOwnProperty.call(ns, 'a'), () => Object.prototype.propertyIsEnumerable.call(ns, 'a'),
|
||||
() => Object.getOwnPropertyDescriptor(ns, 'a'), () => Object.isSealed(ns), () => Object.isFrozen(ns),
|
||||
() => Object.seal(ns), () => Object.freeze(ns), () => Object.defineProperties({}, ns), () => JSON.stringify(ns),
|
||||
() => Object.create(ns).a, () => Object.create(Object.create(ns)).a];
|
||||
tries.forEach(function (f) { try { f(); out.push('no error'); } catch (e) { out.push(e.name); } });
|
||||
// Listing the export names reads none of them.
|
||||
var names = [];
|
||||
for (var k in ns) names.push(k);
|
||||
out.push(names.join(), 'a' in ns, 'a' in Object.create(ns), Object.getOwnPropertyNames(ns).join());";
|
||||
let mut realm = es();
|
||||
let mut inner = loader(&[("./b.mjs", b)]);
|
||||
let mut load = |referrer: &str, specifier: &str| {
|
||||
if specifier == "main" { Ok(LoadedModule { key: "main.mjs".into(), source: None }) } else { inner(referrer, specifier) }
|
||||
};
|
||||
let r = realm.run_module("main.mjs", "import './b.mjs'; export let a = 1;", ModuleLimits::default(), &mut load);
|
||||
assert_eq!(r, Ok(JsValue::Undefined));
|
||||
let errors = "ReferenceError|".repeat(13);
|
||||
assert_eq!(realm.run("out.join('|')"), Ok(JsValue::String(format!("{errors}a|true|true|a"))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_module_two_modules_import_runs_once() {
|
||||
let shared = "out.push('shared'); export var s = 1;";
|
||||
let a = "import { s } from './shared.mjs'; out.push('a' + s);";
|
||||
let b = "import { s } from './shared.mjs'; out.push('b' + s);";
|
||||
let out = run("import './a.mjs'; import './b.mjs'; out.push('main');", &[("./shared.mjs", shared), ("./a.mjs", a), ("./b.mjs", b)]);
|
||||
assert_eq!(out, "shared|a1|b1|main");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn re_exports_pass_names_on() {
|
||||
let base = "export var x = 1, y = 2; export default 'base';";
|
||||
let mid = "export { x as renamed } from './base.mjs'; export * from './base.mjs'; export * as all from './base.mjs';";
|
||||
let out = run(
|
||||
"import { renamed, x, y, all } from './mid.mjs'; import * as m from './mid.mjs'; out.push(renamed, x, y, all['default'], Object.keys(m).join(','));",
|
||||
&[("./base.mjs", base), ("./mid.mjs", mid)],
|
||||
);
|
||||
// `export *` does not pass `default` on.
|
||||
assert_eq!(out, "1|1|2|base|all,renamed,x,y");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_exported_import_is_a_re_export() {
|
||||
let base = "export var v = 'v';";
|
||||
let mid = "import { v } from './base.mjs'; import * as ns from './base.mjs'; export { v as w, ns };";
|
||||
let out = run("import { w, ns } from './mid.mjs'; out.push(w, ns.v);", &[("./base.mjs", base), ("./mid.mjs", mid)]);
|
||||
assert_eq!(out, "v|v");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_two_stars_give_is_ambiguous() {
|
||||
let files =
|
||||
[("./a.mjs", "export var n = 1;"), ("./b.mjs", "export var n = 2;"), ("./both.mjs", "export * from './a.mjs'; export * from './b.mjs';")];
|
||||
fails("import { n } from './both.mjs'; out.push('ran');", &files, "SyntaxError: the export 'n'", "");
|
||||
// The namespace leaves the name out.
|
||||
let out = run("import * as ns from './both.mjs'; out.push(Object.keys(ns).length);", &files);
|
||||
assert_eq!(out, "0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_export_ends_the_run_before_any_module_runs() {
|
||||
let files = [("./m.mjs", "out.push('m'); export var a = 1;")];
|
||||
let e = fails("import { nope } from './m.mjs';\nout.push('main');", &files, "SyntaxError: the module './m.mjs' has no export named 'nope'", "");
|
||||
assert_eq!((e.line, e.column), (1, 10));
|
||||
let files = [("./m.mjs", "export { nothing as gone } from './n.mjs';"), ("./n.mjs", "")];
|
||||
fails("import './m.mjs';", &files, "SyntaxError: the module './n.mjs' has no export to give as 'gone'", "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_module_the_loader_cannot_give_is_named_in_the_error() {
|
||||
let e = fails("out.push(1);\nimport { a } from './missing.mjs';", &[], "Error: module not found: ./missing.mjs", "");
|
||||
assert_eq!(e.line, 2);
|
||||
fails("import x from 'lib';", &[], "SyntaxError: bare specifier: lib", "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_syntax_error_in_an_imported_module_names_its_source() {
|
||||
let mut realm = es();
|
||||
let mut load = loader(&[("./a.mjs", "out.push('a');"), ("./bad.mjs", "\nvar = ;")]);
|
||||
let r = realm.run_module("main.mjs", "import './a.mjs'; import './bad.mjs';", ModuleLimits::default(), &mut load);
|
||||
let e = r.err().unwrap_or_else(|| panic!("ran"));
|
||||
assert_eq!((e.kind, e.line), (RunErrorKind::Syntax, 2));
|
||||
// The entry is source 0, then each module in the order it was loaded.
|
||||
assert_eq!(realm.error_source(), 2);
|
||||
assert_eq!(realm.run("out.length"), Ok(JsValue::Number(0.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn module_code_is_strict_and_its_this_is_undefined() {
|
||||
let out = run("out.push(this === undefined, (() => this)() === undefined); try { undeclared = 1; } catch (e) { out.push(e.name); }", &[]);
|
||||
assert_eq!(out, "true|true|ReferenceError");
|
||||
// Its declarations stay in the module.
|
||||
let mut realm = es();
|
||||
let (r, _) = run_with(&mut realm, "var hidden = 1; function also() {}", &[], ModuleLimits::default());
|
||||
assert_eq!(r, Ok(JsValue::Undefined));
|
||||
assert_eq!(realm.run("typeof hidden + typeof also"), Ok(JsValue::String("undefinedundefined".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_exception_in_a_module_ends_the_run_and_the_modules_after_it_do_not_run() {
|
||||
let files = [("./a.mjs", "out.push('a'); throw new TypeError('stop');"), ("./b.mjs", "try { out.push('b'); } catch (e) { out.push('caught'); }")];
|
||||
fails("import './a.mjs'; import './b.mjs'; try { out.push('main'); } catch (e) {}", &files, "TypeError: stop", "a");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_module_count_and_import_depth_are_limited() {
|
||||
let files = [("./a.mjs", "import './b.mjs';"), ("./b.mjs", "import './c.mjs';"), ("./c.mjs", "out.push('c');")];
|
||||
let mut realm = es();
|
||||
let (r, out) = run_with(&mut realm, "import './a.mjs';", &files, ModuleLimits { modules: 3, depth: 16 });
|
||||
assert!(r.as_ref().is_err_and(|e| e.message.starts_with("RangeError: module limit (3) reached at './c.mjs'")), "{r:?}");
|
||||
assert_eq!(out, "");
|
||||
let (r, _) = run_with(&mut es(), "import './a.mjs';", &files, ModuleLimits { modules: 64, depth: 2 });
|
||||
assert!(r.as_ref().is_err_and(|e| e.message.starts_with("RangeError: import depth limit (2) reached at './c.mjs'")), "{r:?}");
|
||||
let (r, out) = run_with(&mut es(), "import './a.mjs';", &files, ModuleLimits { modules: 4, depth: 3 });
|
||||
assert_eq!((r, out.as_str()), (Ok(JsValue::Undefined), "c"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_module_at_the_depth_limit_may_import_a_module_already_loaded() {
|
||||
let files = [("./a.mjs", "import './b.mjs'; out.push('a');"), ("./b.mjs", "import './a.mjs'; out.push('b');")];
|
||||
let (r, out) = run_with(&mut es(), "import './a.mjs';", &files, ModuleLimits { modules: 64, depth: 2 });
|
||||
assert_eq!((r, out.as_str()), (Ok(JsValue::Undefined), "b|a"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_module_limit_of_zero_runs_no_module() {
|
||||
let (r, out) = run_with(&mut es(), "out.push('main');", &[], ModuleLimits { modules: 0, depth: 16 });
|
||||
assert!(r.as_ref().is_err_and(|e| e.message.starts_with("RangeError: module limit (0) reached")), "{r:?}");
|
||||
assert_eq!(out, "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_module_run_is_held_to_the_fuel_limit() {
|
||||
let mut realm = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits { fuel: 50, ..Limits::default() });
|
||||
let mut load = loader(&[("./m.mjs", &"var a = 1;\n".repeat(20))]);
|
||||
let r = realm.run_module("main.mjs", "import './m.mjs';", ModuleLimits::default(), &mut load);
|
||||
assert_eq!(r.map_err(|e| e.kind), Err(RunErrorKind::Limit(LimitKind::Fuel)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_module_run_advances_in_slices_and_runs_each_module_in_turn() {
|
||||
let mut realm = es();
|
||||
let mut load = loader(&[("./a.mjs", "for (var i = 0; i < 200; i++) {} out.push('a');")]);
|
||||
let entry = "import './a.mjs'; for (var j = 0; j < 200; j++) {} out.push('main');";
|
||||
assert_eq!(realm.start_module("main.mjs", entry, ModuleLimits::default(), &mut load), Ok(()));
|
||||
let mut slices = 0;
|
||||
loop {
|
||||
match realm.advance(10) {
|
||||
Ok(Progress::Paused) => slices += 1,
|
||||
Ok(Progress::Done(v)) => {
|
||||
assert_eq!(v, JsValue::Undefined);
|
||||
break;
|
||||
}
|
||||
Err(e) => panic!("{e:?}"),
|
||||
}
|
||||
}
|
||||
assert!(slices > 20, "{slices}");
|
||||
assert_eq!(realm.run("out.join('|')"), Ok(JsValue::String("a|main".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_es5_realm_runs_no_module() {
|
||||
let mut realm = Realm::new();
|
||||
let mut load = loader(&[]);
|
||||
let r = realm.run_module("main.mjs", "export var a = 1;", ModuleLimits::default(), &mut load);
|
||||
assert_eq!(r.map_err(|e| e.kind), Err(RunErrorKind::Syntax));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_script_does_not_read_import_or_export() {
|
||||
for src in ["import a from './a.mjs';", "export var a = 1;", "import './a.mjs';"] {
|
||||
assert!(parse(src, &Options { es2015: true, ..Options::default() }).is_err(), "{src}");
|
||||
assert!(es().run(src).is_err_and(|e| e.kind == RunErrorKind::Syntax), "{src}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn module_early_errors() {
|
||||
for src in [
|
||||
"export var a; export { a };",
|
||||
"export { undeclared };",
|
||||
"export default 1; export default 2;",
|
||||
"import { a } from './x.mjs'; var a;",
|
||||
"var a; import a from './x.mjs';",
|
||||
"import { a, a } from './x.mjs';",
|
||||
"function f() { import a from './x.mjs'; }",
|
||||
"{ export var a; }",
|
||||
"import { default } from './x.mjs';",
|
||||
"export { default };",
|
||||
"import a from x;",
|
||||
"import * from './x.mjs';",
|
||||
"with (a) {}",
|
||||
"export default class {}",
|
||||
"import('./x.mjs');",
|
||||
"#include 'x.js'\n",
|
||||
// Top-level functions are lexical declarations in a module.
|
||||
"function f() {} function f() {}",
|
||||
"var f; function f() {}",
|
||||
"function f() {} var f;",
|
||||
"let f; function f() {}",
|
||||
] {
|
||||
syntax(src);
|
||||
}
|
||||
for src in [
|
||||
"import { default as d, if as i } from './x.mjs'; export { d as default, i as if };",
|
||||
"import {} from './x.mjs'; export {};",
|
||||
"export function f() {} export { f as g };",
|
||||
"var as = 1, from = 2; export { as, from };",
|
||||
"export * as default from './x.mjs';",
|
||||
"function f() {} { function f() {} } function g() { var g; function h() {} var h; }",
|
||||
] {
|
||||
assert!(parse_module(src, &Options::default()).is_ok(), "{src}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_module_lists_what_it_imports_and_exports() {
|
||||
let (_, info) =
|
||||
match parse_module("import a, { b as c } from './x.mjs'; export { c as d }; export * from './y.mjs'; import './x.mjs';", &Options::default())
|
||||
{
|
||||
Ok(p) => p,
|
||||
Err(e) => panic!("{e:?}"),
|
||||
};
|
||||
let specifiers: Vec<&str> = info.requests.iter().map(|r| r.specifier.as_str()).collect();
|
||||
assert_eq!(specifiers, ["./x.mjs", "./y.mjs"]);
|
||||
assert_eq!(info.imports.len(), 2);
|
||||
assert!(
|
||||
matches!(&info.exports[..], [crate::ExportEntry::Star { request: 1, .. }, crate::ExportEntry::Indirect { export_name, request: 0, .. }] if export_name == "d")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_specifier_with_an_unpaired_surrogate_parses_and_no_module_has_it() {
|
||||
let src = "import './\\uD800.mjs'; import './\\uFFFD.mjs'; import './\\uDC00.mjs'; import './\\uD800.mjs';";
|
||||
let (_, info) = match parse_module(src, &Options::default()) {
|
||||
Ok(p) => p,
|
||||
Err(e) => panic!("{e:?}"),
|
||||
};
|
||||
let units: Vec<&[u16]> = info.requests.iter().map(|r| r.units.as_slice()).collect();
|
||||
let dot = [u16::from(b'.'), u16::from(b'/')];
|
||||
let ext: Vec<u16> = ".mjs".encode_utf16().collect();
|
||||
let with = |u: u16| [&dot[..], &[u], &ext[..]].concat();
|
||||
assert_eq!(units, [with(0xD800).as_slice(), with(0xFFFD).as_slice(), with(0xDC00).as_slice()]);
|
||||
assert_eq!(info.requests[0].specifier, "./\u{FFFD}.mjs");
|
||||
// The run stops when the module is to be loaded, before any module runs, and the loader is
|
||||
// not asked for it.
|
||||
let e = fails("out.push('ran'); import './\\uD800.mjs';", &[], "SyntaxError: module specifier './\u{FFFD}.mjs' is not valid text", "");
|
||||
assert_eq!(e.line, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_namespace_of_many_exports_lists_each_once_in_order() {
|
||||
let names: Vec<String> = (0..3000).rev().map(|i| format!("e{i}")).collect();
|
||||
let m: String = names.iter().map(|n| format!("export var {n} = '{n}';")).collect();
|
||||
let star = "export * from './m.mjs'; export var e5 = 'own';";
|
||||
let out = run(
|
||||
"import * as ns from './star.mjs'; var k = Object.keys(ns); out.push(k.length, k[0], k[k.length - 1], ns.e5, ns.e2999);",
|
||||
&[("./m.mjs", m.as_str()), ("./star.mjs", star)],
|
||||
);
|
||||
assert_eq!(out, "3000|e0|e999|own|e2999");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn modules_survive_a_collection_while_they_link() {
|
||||
let mut realm = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits { heap_bytes: 64 << 20, ..Limits::default() });
|
||||
assert!(realm.run("var out = []; var junk = []; for (var i = 0; i < 2000; i++) junk.push({ i: i }); junk = null;").is_ok());
|
||||
let m = "export var v = 'kept'; export function f() { return v; }";
|
||||
let mut load = loader(&[("./m.mjs", m)]);
|
||||
// A collection runs at every heap reservation while the modules load and link, before any
|
||||
// of their code runs.
|
||||
let before = realm.interp().heap.collections;
|
||||
crate::interp::COLLECT_ON_RESERVE.with(|c| c.set(true));
|
||||
let started = realm.start_module(
|
||||
"main.mjs",
|
||||
"import * as ns from './m.mjs'; import { f } from './m.mjs'; out.push(ns.f(), f());",
|
||||
ModuleLimits::default(),
|
||||
&mut load,
|
||||
);
|
||||
crate::interp::COLLECT_ON_RESERVE.with(|c| c.set(false));
|
||||
assert_eq!(started, Ok(()));
|
||||
assert!(realm.interp().heap.collections > before);
|
||||
assert!(matches!(realm.advance(1_000_000), Ok(Progress::Done(JsValue::Undefined))));
|
||||
realm.collect_garbage();
|
||||
assert_eq!(realm.run("out.join('|')"), Ok(JsValue::String("kept|kept".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_heap_counts_each_module_from_when_it_loads() {
|
||||
// Each module holds about 4 MB of code (its text and its string). The heap holds one of them,
|
||||
// and not two, so the run stops while the second loads and never asks for the third.
|
||||
let body = format!("export var v = '{}';", "x".repeat(1_000_000));
|
||||
let limits = || Limits { heap_bytes: 7 << 20, ..Limits::default() };
|
||||
let mut realm = Realm::with_options(Options { es2015: true, ..Options::default() }, limits());
|
||||
assert!(realm.run("var out = [];").is_ok());
|
||||
let one = run_with(&mut realm, "import { v } from './a.mjs'; out.push(v.length);", &[("./a.mjs", body.as_str())], ModuleLimits::default());
|
||||
assert_eq!(one, (Ok(JsValue::Undefined), "1000000".to_string()));
|
||||
let mut realm = Realm::with_options(Options { es2015: true, ..Options::default() }, limits());
|
||||
let asked = std::cell::RefCell::new(Vec::new());
|
||||
let mut inner = loader(&[("./a.mjs", body.as_str()), ("./b.mjs", body.as_str()), ("./c.mjs", "")]);
|
||||
let mut load = |referrer: &str, specifier: &str| {
|
||||
asked.borrow_mut().push(specifier.to_string());
|
||||
inner(referrer, specifier)
|
||||
};
|
||||
let r = realm.run_module("main.mjs", "import './a.mjs'; import './b.mjs'; import './c.mjs';", ModuleLimits::default(), &mut load);
|
||||
assert!(matches!(r, Err(RunError { kind: RunErrorKind::Limit(LimitKind::Heap), .. })), "{r:?}");
|
||||
assert_eq!(*asked.borrow(), ["./a.mjs", "./b.mjs"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_module_keeps_no_expression_value_alive_after_its_statement() {
|
||||
// The heap holds one of these arrays and not two, so each must be collectable once the
|
||||
// expression statement that made it ends.
|
||||
let big = "function big() { var a = []; for (var i = 0; i < 50000; i++) a[i] = { i: i }; return a; }";
|
||||
let mut realm = es();
|
||||
assert!(realm.run(&format!("{big} var held = big();")).is_ok());
|
||||
let with_one = realm.collect_garbage();
|
||||
assert!(realm.run("held = null;").is_ok());
|
||||
let without = realm.collect_garbage();
|
||||
let one = with_one - without;
|
||||
realm.set_limits(Limits { heap_bytes: without + one * 3 / 2, ..Limits::default() });
|
||||
let entry = format!("{big} big(); big(); try {{ big(); }} finally {{ big(); }} out.push('done');");
|
||||
let (r, out) = run_with(&mut realm, &entry, &[], ModuleLimits::default());
|
||||
assert_eq!((r, out.as_str()), (Ok(JsValue::Undefined), "done"));
|
||||
// Script and eval code still complete with the value of their last expression statement.
|
||||
assert_eq!(realm.run("1; 2;"), Ok(JsValue::Number(2.0)));
|
||||
assert_eq!(realm.run("eval('3; 4;')"), Ok(JsValue::Number(4.0)));
|
||||
assert_eq!(realm.run("try { 5; } finally { 6; }"), Ok(JsValue::Number(5.0)));
|
||||
}
|
||||
@@ -7,6 +7,7 @@
|
||||
//! stack, and prefix operators, assignment chains, `else if` chains and labels with loops, so long
|
||||
//! runs of them do not nest at all.
|
||||
|
||||
mod module;
|
||||
mod pattern;
|
||||
mod xml;
|
||||
|
||||
@@ -134,6 +135,9 @@ pub(crate) struct Parser<'s> {
|
||||
scopes: Vec<Scope>,
|
||||
/// What `super` and `new.target` may do in the function being read.
|
||||
supers: SuperRules,
|
||||
/// Read a module ([`Parser::parse_module`]): its top-level function declarations are lexical
|
||||
/// declarations (ECMA-262 2015 section 15.2.1.11).
|
||||
module: bool,
|
||||
/// Where each shorthand property with an initializer (`{a = 1}`) not yet read as part of a
|
||||
/// destructuring pattern starts; one left when its expression ends is a `SyntaxError`.
|
||||
cover_inits: Vec<u32>,
|
||||
@@ -175,6 +179,7 @@ impl<'s> Parser<'s> {
|
||||
es2015: options.es2015,
|
||||
scopes: if options.es2015 { vec![Scope { function: true, ..Scope::default() }] } else { Vec::new() },
|
||||
supers: SuperRules::default(),
|
||||
module: false,
|
||||
cover_inits: Vec::new(),
|
||||
cover_ok: false,
|
||||
rest_commas: HashSet::new(),
|
||||
@@ -332,6 +337,9 @@ impl<'s> Parser<'s> {
|
||||
/// Checks a name used as an identifier: not a reserved word written with escapes, and not a
|
||||
/// strict-mode reserved word in strict code.
|
||||
fn check_identifier(&self, token: &Token, name: &str) -> Result<()> {
|
||||
if self.module && name == "await" {
|
||||
return Err(self.error_at_token(token, "'await' is a reserved word in modules"));
|
||||
}
|
||||
if token.escaped && Keyword::from_word(name).is_some() {
|
||||
return Err(self.error_at_token(token, format!("keyword '{name}' must not contain escaped characters")));
|
||||
}
|
||||
@@ -431,6 +439,9 @@ impl<'s> Parser<'s> {
|
||||
/// body or the script, lexical in a block.
|
||||
fn declare_function(&mut self, id: crate::ast::FunctionId) -> Result<()> {
|
||||
let Some((name, generator)) = self.ast.function(id).and_then(|f| Some((f.name.clone()?, f.generator))) else { return Ok(()) };
|
||||
if self.module && self.scopes.len() == 1 {
|
||||
return self.declare_lexical(&name, true);
|
||||
}
|
||||
match self.scopes.last_mut() {
|
||||
Some(scope) if scope.function => {
|
||||
if scope.lexical.contains_key(&name.name) {
|
||||
|
||||
@@ -0,0 +1,481 @@
|
||||
//! Module code (ECMA-262 2015 section 15.2): the import and export declarations at the top of a
|
||||
//! module, read into a [`ModuleInfo`], and their early errors (section 15.2.1.1).
|
||||
//!
|
||||
//! A module is strict mode code throughout. An import binds its names as lexical declarations at
|
||||
//! the top of the module, so a `var`, `let`, `const`, function or another import of the same name
|
||||
//! is a redeclaration. An exported declaration is kept as the declaration; `export default` of an
|
||||
//! expression or an anonymous function binds [`DEFAULT_BINDING`]. Each exported name may be
|
||||
//! exported once, and a name an `export { … }` list exports from the module itself must be one it
|
||||
//! declares or imports.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use super::{Parser, Result, describe};
|
||||
use crate::ast::{
|
||||
Binding, DEFAULT_BINDING, ExportEntry, FunctionKind, ImportEntry, ImportName, LexKind, ModuleInfo, ModuleRequest, Name, Program, Stmt, StmtId,
|
||||
VarDecl,
|
||||
};
|
||||
use crate::token::{Keyword, Punct, Span, Token, TokenKind};
|
||||
|
||||
/// A name an `export { … }` list without `from` exports: the module's own binding (or import)
|
||||
/// `local`, exported as `export_name`.
|
||||
struct ClauseExport {
|
||||
export_name: String,
|
||||
local: String,
|
||||
span: Span,
|
||||
}
|
||||
|
||||
#[derive(Eq)]
|
||||
struct RequestUnits(Vec<u16>);
|
||||
|
||||
impl std::hash::Hash for RequestUnits {
|
||||
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
|
||||
std::hash::Hash::hash(&self.0, state);
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for RequestUnits {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
#[cfg(test)]
|
||||
REQUEST_SEARCH_STEPS.with(|steps| steps.set(steps.get() + 1));
|
||||
self.0 == other.0
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Eq)]
|
||||
struct ImportLocal<'a>(&'a str);
|
||||
|
||||
impl std::hash::Hash for ImportLocal<'_> {
|
||||
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
|
||||
std::hash::Hash::hash(self.0, state);
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for ImportLocal<'_> {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
#[cfg(test)]
|
||||
EXPORT_SEARCH_STEPS.with(|steps| steps.set(steps.get() + 1));
|
||||
self.0 == other.0
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
static REQUEST_SEARCH_STEPS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
static EXPORT_SEARCH_STEPS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
impl Parser<'_> {
|
||||
/// Reads the source as a module: its statements, without its import and export declarations
|
||||
/// but with the declarations they export, and what it imports and exports.
|
||||
pub(crate) fn parse_module(mut self) -> Result<(Program, ModuleInfo, Vec<Token>)> {
|
||||
self.module = true;
|
||||
#[cfg(test)]
|
||||
REQUEST_SEARCH_STEPS.with(|steps| steps.set(0));
|
||||
let mut info = ModuleInfo::default();
|
||||
let mut requests = HashMap::new();
|
||||
let mut clause = Vec::new();
|
||||
let mut body = Vec::new();
|
||||
while self.tok.kind != TokenKind::Eof {
|
||||
if self.at_keyword(Keyword::Import) {
|
||||
self.import_declaration(&mut info, &mut requests)?;
|
||||
} else if self.at_keyword(Keyword::Export) {
|
||||
if let Some(stmt) = self.export_declaration(&mut info, &mut clause, &mut requests)? {
|
||||
body.push(stmt);
|
||||
}
|
||||
} else {
|
||||
body.push(self.parse_statement_item()?);
|
||||
}
|
||||
}
|
||||
self.finish_exports(&mut info, clause)?;
|
||||
if let Some(tokens) = &mut self.tokens {
|
||||
tokens.push(self.tok.clone());
|
||||
}
|
||||
let program =
|
||||
Program { ast: self.ast, body, strict: true, directives: self.directives, lines: self.lines, es2015: self.es2015, supers: self.supers };
|
||||
Ok((program, info, self.tokens.unwrap_or_default()))
|
||||
}
|
||||
|
||||
/// The current token is the contextual keyword `word` (`as` or `from`), written without escapes.
|
||||
fn at_contextual(&self, word: &str) -> bool {
|
||||
self.tok.ident() == Some(word) && !self.tok.escaped
|
||||
}
|
||||
|
||||
fn expect_contextual(&mut self, word: &str) -> Result<()> {
|
||||
if self.at_contextual(word) {
|
||||
self.bump()?;
|
||||
return Ok(());
|
||||
}
|
||||
Err(self.error_at_token(&self.tok, format!("expected '{word}' but found {}", describe(&self.tok))))
|
||||
}
|
||||
|
||||
/// A module specifier: a string literal, added to the module's requests once. → its index.
|
||||
/// Any string value is a specifier here; the host decides which it can load.
|
||||
fn module_specifier(&mut self, info: &mut ModuleInfo, requests: &mut HashMap<RequestUnits, usize>) -> Result<usize> {
|
||||
let TokenKind::String(units) = &self.tok.kind else {
|
||||
return Err(self.error_at_token(&self.tok, format!("expected a module specifier string but found {}", describe(&self.tok))));
|
||||
};
|
||||
if self.tok.legacy_octal {
|
||||
return Err(self.error_at_token(&self.tok, "octal escape sequences are not allowed in strict mode"));
|
||||
}
|
||||
let units = RequestUnits(units.to_vec());
|
||||
let span = self.bump()?.span;
|
||||
if let Some(index) = requests.get(&units) {
|
||||
return Ok(*index);
|
||||
}
|
||||
let specifier = String::from_utf16_lossy(&units.0);
|
||||
let index = info.requests.len();
|
||||
info.requests.push(ModuleRequest { specifier, units: units.0.clone(), span });
|
||||
requests.insert(units, index);
|
||||
Ok(info.requests.len() - 1)
|
||||
}
|
||||
|
||||
/// A name as an import or export list gives it: any identifier name, keywords included. → the
|
||||
/// name and whether it was an identifier (not a keyword).
|
||||
fn list_name(&mut self) -> Result<(Name, bool)> {
|
||||
let Some(name) = self.tok.identifier_name().map(str::to_string) else {
|
||||
return Err(self.error_at_token(&self.tok, format!("expected a name but found {}", describe(&self.tok))));
|
||||
};
|
||||
let ident = matches!(self.tok.kind, TokenKind::Ident(_));
|
||||
let token = self.bump()?;
|
||||
Ok((Name { name, span: token.span }, ident))
|
||||
}
|
||||
|
||||
/// `import …;` (section 15.2.2). Each name it binds is declared in the module's scope.
|
||||
fn import_declaration(&mut self, info: &mut ModuleInfo, requests: &mut HashMap<RequestUnits, usize>) -> Result<()> {
|
||||
let import = self.bump()?;
|
||||
if self.at(Punct::LParen) {
|
||||
return Err(self.error_at_token(&import, "import() is not supported"));
|
||||
}
|
||||
if matches!(self.tok.kind, TokenKind::String(_)) {
|
||||
self.module_specifier(info, requests)?;
|
||||
return self.semicolon();
|
||||
}
|
||||
let mut bound: Vec<(ImportName, Name)> = Vec::new();
|
||||
let mut list = true;
|
||||
if matches!(self.tok.kind, TokenKind::Ident(_)) {
|
||||
let local = self.binding_identifier()?;
|
||||
bound.push((ImportName::Name("default".into()), local));
|
||||
list = self.eat(Punct::Comma)?;
|
||||
}
|
||||
if list {
|
||||
if self.eat(Punct::Star)? {
|
||||
self.expect_contextual("as")?;
|
||||
let local = self.binding_identifier()?;
|
||||
bound.push((ImportName::Namespace, local));
|
||||
} else {
|
||||
self.expect(Punct::LBrace)?;
|
||||
while !self.at(Punct::RBrace) {
|
||||
if matches!(self.tok.kind, TokenKind::Ident(_)) && !self.next_is_as() {
|
||||
// A name without `as` binds itself, so it must be one a declaration may bind.
|
||||
let local = self.binding_identifier()?;
|
||||
bound.push((ImportName::Name(local.name.clone()), local));
|
||||
} else {
|
||||
let (imported, _) = self.list_name()?;
|
||||
self.expect_contextual("as")?;
|
||||
let local = self.binding_identifier()?;
|
||||
bound.push((ImportName::Name(imported.name), local));
|
||||
}
|
||||
if !self.eat(Punct::Comma)? {
|
||||
break;
|
||||
}
|
||||
}
|
||||
self.expect(Punct::RBrace)?;
|
||||
}
|
||||
}
|
||||
self.expect_contextual("from")?;
|
||||
let request = self.module_specifier(info, requests)?;
|
||||
self.semicolon()?;
|
||||
for (import, local) in bound {
|
||||
self.declare_lexical(&local, false)?;
|
||||
info.imports.push(ImportEntry { request, import, local });
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The token after the current one is the contextual keyword `as`.
|
||||
fn next_is_as(&self) -> bool {
|
||||
self.peek().is_some_and(|t| !t.escaped && t.ident() == Some("as"))
|
||||
}
|
||||
|
||||
/// `export …` (section 15.2.3). → the declaration it exports, which runs in place.
|
||||
fn export_declaration(
|
||||
&mut self,
|
||||
info: &mut ModuleInfo,
|
||||
clause: &mut Vec<ClauseExport>,
|
||||
requests: &mut HashMap<RequestUnits, usize>,
|
||||
) -> Result<Option<StmtId>> {
|
||||
let export = self.bump()?;
|
||||
let span = export.span;
|
||||
if self.eat(Punct::Star)? {
|
||||
if self.at_contextual("as") {
|
||||
self.bump()?;
|
||||
let (name, _) = self.list_name()?;
|
||||
self.expect_contextual("from")?;
|
||||
let request = self.module_specifier(info, requests)?;
|
||||
self.semicolon()?;
|
||||
info.exports.push(ExportEntry::Indirect { export_name: name.name, request, import: ImportName::Namespace, span: name.span });
|
||||
return Ok(None);
|
||||
}
|
||||
self.expect_contextual("from")?;
|
||||
let request = self.module_specifier(info, requests)?;
|
||||
self.semicolon()?;
|
||||
info.exports.push(ExportEntry::Star { request, span });
|
||||
return Ok(None);
|
||||
}
|
||||
if self.at(Punct::LBrace) {
|
||||
self.bump()?;
|
||||
// Each name: the name it refers to (and whether that was an identifier) and the name it
|
||||
// is exported as.
|
||||
let mut names: Vec<(Name, bool, Name)> = Vec::new();
|
||||
while !self.at(Punct::RBrace) {
|
||||
let (local, ident) = self.list_name()?;
|
||||
let exported = if self.at_contextual("as") {
|
||||
self.bump()?;
|
||||
self.list_name()?.0
|
||||
} else {
|
||||
local.clone()
|
||||
};
|
||||
names.push((local, ident, exported));
|
||||
if !self.eat(Punct::Comma)? {
|
||||
break;
|
||||
}
|
||||
}
|
||||
self.expect(Punct::RBrace)?;
|
||||
if self.at_contextual("from") {
|
||||
self.bump()?;
|
||||
let request = self.module_specifier(info, requests)?;
|
||||
self.semicolon()?;
|
||||
for (local, _, exported) in names {
|
||||
let import = ImportName::Name(local.name);
|
||||
info.exports.push(ExportEntry::Indirect { export_name: exported.name, request, import, span: exported.span });
|
||||
}
|
||||
return Ok(None);
|
||||
}
|
||||
self.semicolon()?;
|
||||
for (local, ident, exported) in names {
|
||||
// Without `from`, each name refers to a binding of the module (section 15.2.3.1).
|
||||
if !ident || crate::token::strict_reserved(&local.name) {
|
||||
return Err(self.error_at_offset(local.span.start, format!("'{}' cannot be exported as a binding", local.name)));
|
||||
}
|
||||
clause.push(ClauseExport { export_name: exported.name, local: local.name, span: local.span });
|
||||
}
|
||||
return Ok(None);
|
||||
}
|
||||
if self.at_keyword(Keyword::Default) {
|
||||
self.bump()?;
|
||||
return self.export_default(info, span).map(Some);
|
||||
}
|
||||
let exportable = self.at_keyword(Keyword::Var) || self.at_keyword(Keyword::Function) || self.at_lexical_declaration().is_some();
|
||||
if !exportable {
|
||||
return Err(self.error_at_token(&self.tok, format!("expected a declaration after 'export' but found {}", describe(&self.tok))));
|
||||
}
|
||||
let stmt = self.parse_statement_item()?;
|
||||
let names: Vec<Name> = match self.ast.stmt(stmt) {
|
||||
Some(Stmt::Var(decls) | Stmt::Lexical(_, decls)) => decls.iter().flat_map(|d| self.ast.bound_names(&d.target)).collect(),
|
||||
Some(Stmt::FunctionDecl(fid)) => self.ast.function(*fid).and_then(|f| f.name.clone()).into_iter().collect(),
|
||||
_ => return Err(self.error_at_offset(span.start, "expected a declaration after 'export'")),
|
||||
};
|
||||
for name in names {
|
||||
info.exports.push(ExportEntry::Local { export_name: name.name.clone(), local: name.name, span: name.span });
|
||||
}
|
||||
Ok(Some(stmt))
|
||||
}
|
||||
|
||||
/// `export default …` after `default`: a function declaration (named or not) or an expression.
|
||||
fn export_default(&mut self, info: &mut ModuleInfo, span: Span) -> Result<StmtId> {
|
||||
if self.at_keyword(Keyword::Class) {
|
||||
return Err(self.error_at_token(&self.tok, "classes are not supported"));
|
||||
}
|
||||
if self.at_keyword(Keyword::Function) {
|
||||
self.enter()?;
|
||||
let result = self.default_function();
|
||||
self.leave();
|
||||
let (stmt, fid, local) = result?;
|
||||
self.declare_function(fid)?;
|
||||
info.exports.push(ExportEntry::Local { export_name: "default".into(), local, span });
|
||||
return Ok(stmt);
|
||||
}
|
||||
let start = self.tok.span;
|
||||
let value = self.parse_assignment(false)?;
|
||||
self.semicolon()?;
|
||||
let target = Binding::Name(Name { name: DEFAULT_BINDING.into(), span: start });
|
||||
let stmt = self.ast.push_stmt(Stmt::Lexical(LexKind::Const, vec![VarDecl { target, init: Some(value) }]), self.span_from(start));
|
||||
info.exports.push(ExportEntry::Local { export_name: "default".into(), local: DEFAULT_BINDING.into(), span });
|
||||
Ok(stmt)
|
||||
}
|
||||
|
||||
/// `function name(…) {…}` or `function (…) {…}` after `export default`: a declaration of
|
||||
/// `name`, or of [`DEFAULT_BINDING`] for a function without one.
|
||||
fn default_function(&mut self) -> Result<(StmtId, crate::ast::FunctionId, String)> {
|
||||
let keyword = self.expect_keyword(Keyword::Function)?;
|
||||
let start = keyword.span;
|
||||
let generator = self.es2015 && self.eat(Punct::Star)?;
|
||||
let name = if matches!(self.tok.kind, TokenKind::Ident(_)) {
|
||||
self.function_name()?
|
||||
} else {
|
||||
(Name { name: DEFAULT_BINDING.into(), span: start }, keyword)
|
||||
};
|
||||
let local = name.0.name.clone();
|
||||
let fid = self.parse_function_rest(FunctionKind::Declaration, Some(name), start, generator)?;
|
||||
let stmt = self.ast.push_stmt(Stmt::FunctionDecl(fid), self.span_from(start));
|
||||
Ok((stmt, fid, local))
|
||||
}
|
||||
|
||||
/// The early errors of the exports as a whole (section 15.2.1.1): no name exported twice, and
|
||||
/// each name an `export { … }` list takes from the module itself declared or imported there. An
|
||||
/// exported named import becomes a re-export of its imported binding (section 15.2.1.16.1).
|
||||
/// A namespace import keeps its local binding.
|
||||
fn finish_exports(&self, info: &mut ModuleInfo, clause: Vec<ClauseExport>) -> Result<()> {
|
||||
#[cfg(test)]
|
||||
EXPORT_SEARCH_STEPS.with(|steps| steps.set(0));
|
||||
let mut imports = HashMap::with_capacity(info.imports.len());
|
||||
for import in &info.imports {
|
||||
imports.entry(ImportLocal(&import.local.name)).or_insert(import);
|
||||
}
|
||||
let top = self.scopes.first();
|
||||
for c in clause {
|
||||
let declared = top.is_some_and(|s| s.lexical.contains_key(&c.local) || s.vars.contains(&c.local));
|
||||
if !declared {
|
||||
return Err(self.error_at_offset(c.span.start, format!("'{}' is exported but not declared in the module", c.local)));
|
||||
}
|
||||
let imported = imports.get(&ImportLocal(&c.local));
|
||||
let entry = match imported {
|
||||
Some(i) if matches!(&i.import, ImportName::Name(_)) => {
|
||||
ExportEntry::Indirect { export_name: c.export_name, request: i.request, import: i.import.clone(), span: c.span }
|
||||
}
|
||||
_ => ExportEntry::Local { export_name: c.export_name, local: c.local, span: c.span },
|
||||
};
|
||||
info.exports.push(entry);
|
||||
}
|
||||
let mut seen = HashSet::new();
|
||||
for e in &info.exports {
|
||||
let (name, span) = match e {
|
||||
ExportEntry::Local { export_name, span, .. } | ExportEntry::Indirect { export_name, span, .. } => (export_name, span),
|
||||
ExportEntry::Star { .. } => continue,
|
||||
};
|
||||
if !seen.insert(name.as_str()) {
|
||||
return Err(self.error_at_offset(span.start, format!("'{name}' is exported more than once")));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{EXPORT_SEARCH_STEPS, REQUEST_SEARCH_STEPS};
|
||||
use crate::{Options, parse_module};
|
||||
|
||||
fn run_namespace_modules(main: &str, files: &[(&str, &str)]) -> (Result<crate::JsValue, crate::RunError>, crate::Realm) {
|
||||
let mut realm = crate::Realm::with_options(Options { es2015: true, ..Options::default() }, crate::Limits::default());
|
||||
realm.run("var out = [];").unwrap();
|
||||
let mut load = |_: &str, specifier: &str| {
|
||||
files.iter().find(|(name, _)| *name == specifier).map_or_else(
|
||||
|| Err(crate::LoadError::Other(format!("missing module {specifier}"))),
|
||||
|(_, source)| Ok(crate::LoadedModule { key: specifier.into(), source: Some((*source).into()) }),
|
||||
)
|
||||
};
|
||||
let result = realm.run_module("main.mjs", main, crate::ModuleLimits::default(), &mut load);
|
||||
(result, realm)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn namespace_reexport_bindings_keep_their_origin() {
|
||||
let files = [
|
||||
("./a.mjs", "import * as ns from './shared.mjs'; export {ns};"),
|
||||
("./b.mjs", "import * as ns from './shared.mjs'; export {ns};"),
|
||||
("./barrel.mjs", "export * from './a.mjs'; export * from './b.mjs';"),
|
||||
("./shared.mjs", "export var value = 7;"),
|
||||
];
|
||||
let (result, _) = run_namespace_modules("import {ns} from './barrel.mjs'; out.push(ns.value);", &files);
|
||||
assert!(result.as_ref().is_err_and(|error| error.message.contains("ambiguous")), "{result:?}");
|
||||
let files = [
|
||||
("./a.mjs", "import {value} from './shared.mjs'; export {value};"),
|
||||
("./b.mjs", "import {value} from './shared.mjs'; export {value};"),
|
||||
("./barrel.mjs", "export * from './a.mjs'; export * from './b.mjs';"),
|
||||
("./shared.mjs", "export var value = 7; export function change() { value = 9; }"),
|
||||
];
|
||||
let (result, mut realm) =
|
||||
run_namespace_modules("import {value} from './barrel.mjs'; import {change} from './shared.mjs'; change(); out.push(value);", &files);
|
||||
assert!(result.is_ok(), "{result:?}");
|
||||
assert_eq!(realm.run("out.join('|')"), Ok(crate::JsValue::String("9".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn namespace_reexports_link_through_cycles() {
|
||||
let files = [("./a.mjs", "import * as ns from './b.mjs'; export {ns};"), ("./b.mjs", "import * as ns from './a.mjs'; export {ns};")];
|
||||
let (result, mut realm) = run_namespace_modules("import * as a from './a.mjs'; out.push(a.ns.ns === a);", &files);
|
||||
assert!(result.is_ok(), "{result:?}");
|
||||
assert_eq!(realm.run("out.join('|')"), Ok(crate::JsValue::String("true".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn module_specifiers_reject_legacy_octal_escapes() {
|
||||
for source in
|
||||
[r"import './\141.mjs';", r"import value from './\141.mjs';", r"export * from './\141.mjs';", r"export { value } from './\141.mjs';"]
|
||||
{
|
||||
assert!(parse_module(source, &Options::default()).is_err(), "{source}");
|
||||
}
|
||||
for source in [r"import './\u0061.mjs';", r"export * from './\x61.mjs';", r"import './\uD800.mjs';"] {
|
||||
assert!(parse_module(source, &Options::default()).is_ok(), "{source}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn module_request_search_work_is_bounded_by_request_count() {
|
||||
let count = 1_000;
|
||||
let mut source = String::new();
|
||||
for index in 0..count {
|
||||
source.push_str(&format!("import './{index}.mjs';"));
|
||||
}
|
||||
source.push_str(r"import './\u0030.mjs'; import './\uD800.mjs'; import './\uFFFD.mjs'; import './\uDC00.mjs'; import './\uD800.mjs';");
|
||||
let (_, info) = match parse_module(&source, &Options::default()) {
|
||||
Ok(parsed) => parsed,
|
||||
Err(error) => panic!("{error:?}"),
|
||||
};
|
||||
assert_eq!(info.requests.len(), count + 3);
|
||||
for (index, request) in info.requests.iter().take(count).enumerate() {
|
||||
assert_eq!(request.specifier, format!("./{index}.mjs"));
|
||||
}
|
||||
assert_eq!(info.requests[count].units[2], 0xD800);
|
||||
assert_eq!(info.requests[count + 1].units[2], 0xFFFD);
|
||||
assert_eq!(info.requests[count + 2].units[2], 0xDC00);
|
||||
let steps = REQUEST_SEARCH_STEPS.with(std::cell::Cell::get);
|
||||
assert!(steps > 0, "the repeated requests compare their exact UTF-16 keys");
|
||||
assert!(steps <= 2 * (count + 5), "{steps} request-search steps for {} requests", count + 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn imported_export_resolution_work_is_bounded_by_binding_count() {
|
||||
let count = 1_000;
|
||||
let bindings = (0..count).map(|index| format!("value as local{index}")).collect::<Vec<_>>().join(",");
|
||||
let exports = (0..count).map(|index| format!("local{index} as exported{index}")).collect::<Vec<_>>().join(",");
|
||||
let source = format!(
|
||||
"import {{{bindings}}} from './values.mjs'; import * as ns from './namespace.mjs'; export {{{exports},ns as namespace,local0 as again}};"
|
||||
);
|
||||
let (_, info) = match parse_module(&source, &Options::default()) {
|
||||
Ok(parsed) => parsed,
|
||||
Err(error) => panic!("{error:?}"),
|
||||
};
|
||||
assert_eq!(info.imports.len(), count + 1);
|
||||
assert_eq!(info.exports.len(), count + 2);
|
||||
for (index, export) in info.exports.iter().take(count).enumerate() {
|
||||
assert!(matches!(export, crate::ExportEntry::Indirect { export_name, request: 0, import: crate::ast::ImportName::Name(name), .. }
|
||||
if export_name == &format!("exported{index}") && name == "value"));
|
||||
}
|
||||
assert!(matches!(&info.exports[count], crate::ExportEntry::Local { export_name, local, .. } if export_name == "namespace" && local == "ns"));
|
||||
assert!(
|
||||
matches!(&info.exports[count + 1], crate::ExportEntry::Indirect { request: 0, import: crate::ast::ImportName::Name(name), .. } if name == "value")
|
||||
);
|
||||
let steps = EXPORT_SEARCH_STEPS.with(std::cell::Cell::get);
|
||||
assert!(steps > 0);
|
||||
assert!(steps <= 3 * (count + 2), "{steps} import-local comparisons for {} exports", count + 2);
|
||||
for source in [
|
||||
"import {value as x} from './values.mjs'; export {x,x};",
|
||||
"import {value as x} from './values.mjs'; import * as x from './namespace.mjs';",
|
||||
] {
|
||||
assert!(parse_module(source, &Options::default()).is_err(), "{source}");
|
||||
}
|
||||
}
|
||||
}
|
||||
+89
-24
@@ -7,9 +7,14 @@ use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use crate::bytecode::CodeKind;
|
||||
use crate::heap::{Func, HIDDEN, Object, Prop, key};
|
||||
use crate::interp::{Abrupt, CompileError, Interp};
|
||||
use crate::module::{LinkFail, ModuleLimits, ModuleLoader};
|
||||
use crate::value::Value;
|
||||
use crate::{Options, SyntaxError};
|
||||
|
||||
fn internal_error(message: &str) -> RunError {
|
||||
RunError { kind: RunErrorKind::Internal, message: message.to_string(), line: 0, column: 0, authored: false }
|
||||
}
|
||||
|
||||
/// The limits a run is held to. Reaching one ends the run with [`RunErrorKind::Limit`]; scripts
|
||||
/// cannot catch it, and their `finally` blocks do not run.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
@@ -287,6 +292,78 @@ impl Realm {
|
||||
/// Compiles `source` and readies the realm for a run.
|
||||
fn compile(&mut self, source: &str) -> Result<std::rc::Rc<crate::bytecode::Code>, RunError> {
|
||||
self.end();
|
||||
self.reset_run()?;
|
||||
let interp = &mut self.interp;
|
||||
let strict = interp.options.strict;
|
||||
interp.evaluated = next_tag(interp.evaluated);
|
||||
self.script_tag = interp.evaluated;
|
||||
interp.source_tag = self.script_tag;
|
||||
let code = interp.encode_source(source).and_then(|units| interp.compile_source(&units, strict, CodeKind::Global));
|
||||
interp.source_tag = UNKNOWN_SOURCE;
|
||||
match code {
|
||||
Ok(code) => Ok(code),
|
||||
Err(CompileError::Syntax(e)) => {
|
||||
interp.error_tag = self.script_tag;
|
||||
Err(e.into())
|
||||
}
|
||||
Err(CompileError::Internal(m)) => Err(RunError { kind: RunErrorKind::Internal, message: m, line: 0, column: 0, authored: false }),
|
||||
}
|
||||
}
|
||||
|
||||
/// Begins a run of the module `key` with `source` (ECMA-262 2015 section 15.2), which
|
||||
/// [`Realm::advance`] carries on as it does a script [`Realm::start`] began. `load` gives each
|
||||
/// module a module imports ([`ModuleLoader`]). Every module is loaded, parsed and linked before
|
||||
/// any runs, so a syntax error, an import of a missing or ambiguous export, a module `load`
|
||||
/// cannot give or a module past `limits` ends the run here, with no code run. The first module
|
||||
/// has [`Realm::script_tag`] as its source's tag, and each module loaded after it the next tag,
|
||||
/// in the order `load` first gave their sources, as the sources an evaluator gives during a run
|
||||
/// take theirs. A realm without [`Options::es2015`] runs no module: that is a syntax error.
|
||||
/// A paused or waiting run ends before loading; its globals remain available.
|
||||
pub fn start_module(&mut self, key: &str, source: &str, limits: ModuleLimits, load: &mut ModuleLoader<'_>) -> Result<(), RunError> {
|
||||
self.end();
|
||||
self.reset_run()?;
|
||||
if !self.interp.options.es2015 {
|
||||
let message = "modules need ECMAScript 2015; this script runs ECMAScript 5".to_string();
|
||||
return Err(RunError { kind: RunErrorKind::Syntax, message, line: 0, column: 0, authored: false });
|
||||
}
|
||||
let interp = &mut self.interp;
|
||||
interp.evaluated = next_tag(interp.evaluated);
|
||||
self.script_tag = interp.evaluated;
|
||||
let marks = (interp.temp_envs_mark(), interp.temp_roots_mark(), interp.temp_codes_mark());
|
||||
let linked = crate::module::link(interp, key, source, self.script_tag, limits, load);
|
||||
let pushed = match linked {
|
||||
Ok(modules) => interp.push_module_frames(&modules).map_err(LinkFail::Run),
|
||||
Err(fail) => Err(fail),
|
||||
};
|
||||
let interp = &mut self.interp;
|
||||
interp.drop_temp_envs(marks.0);
|
||||
interp.drop_temp_roots(marks.1);
|
||||
interp.drop_temp_codes(marks.2);
|
||||
match pushed {
|
||||
Ok(()) => Ok(()),
|
||||
Err(LinkFail::Syntax { tag, error }) => {
|
||||
self.interp.error_tag = tag;
|
||||
Err(error.into())
|
||||
}
|
||||
Err(LinkFail::At { tag, line, column, abrupt }) => {
|
||||
let e = self.outcome(Err(abrupt)).err();
|
||||
self.interp.error_tag = tag;
|
||||
Err(e.map_or_else(|| internal_error("a module failed without an error"), |e| RunError { line, column, ..e }))
|
||||
}
|
||||
Err(LinkFail::Run(abrupt)) => self.outcome(Err(abrupt)).map(drop),
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs the module `key` with `source` to its end ([`Realm::start_module`]), drains its queued
|
||||
/// Promise jobs, and returns `undefined`.
|
||||
pub fn run_module(&mut self, key: &str, source: &str, limits: ModuleLimits, load: &mut ModuleLoader<'_>) -> Result<JsValue, RunError> {
|
||||
self.start_module(key, source, limits, load)?;
|
||||
let result = self.interp.execute().and_then(|value| self.interp.drain_jobs(value));
|
||||
self.outcome(result)
|
||||
}
|
||||
|
||||
/// Readies the realm for a run: its state from the last run cleared and its fuel filled.
|
||||
fn reset_run(&mut self) -> Result<(), RunError> {
|
||||
self.script_tag = UNKNOWN_SOURCE;
|
||||
self.rejections = (Vec::new(), 0);
|
||||
let interp = &mut self.interp;
|
||||
@@ -328,21 +405,7 @@ impl Realm {
|
||||
}),
|
||||
};
|
||||
}
|
||||
let interp = &mut self.interp;
|
||||
let strict = interp.options.strict;
|
||||
interp.evaluated = next_tag(interp.evaluated);
|
||||
self.script_tag = interp.evaluated;
|
||||
interp.source_tag = self.script_tag;
|
||||
let code = interp.encode_source(source).and_then(|units| interp.compile_source(&units, strict, CodeKind::Global));
|
||||
interp.source_tag = UNKNOWN_SOURCE;
|
||||
match code {
|
||||
Ok(code) => Ok(code),
|
||||
Err(CompileError::Syntax(e)) => {
|
||||
interp.error_tag = self.script_tag;
|
||||
Err(e.into())
|
||||
}
|
||||
Err(CompileError::Internal(m)) => Err(RunError { kind: RunErrorKind::Internal, message: m, line: 0, column: 0, authored: false }),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The end of a run: its completion value or error, with the interpreter's stacks emptied.
|
||||
@@ -358,7 +421,7 @@ impl Realm {
|
||||
// A generator whose body was running when the run ended cannot go on.
|
||||
let running: Vec<_> = interp.frames.iter().filter_map(|f| f.generator).collect();
|
||||
running.into_iter().for_each(|g| interp.end_generator(Some(g)));
|
||||
interp.frames.clear();
|
||||
interp.clear_frames();
|
||||
interp.temp_roots.clear();
|
||||
interp.join_stack.clear();
|
||||
interp.waiting = false;
|
||||
@@ -549,16 +612,17 @@ impl Realm {
|
||||
self.interp.script_name = name;
|
||||
}
|
||||
|
||||
/// Which source the last error's `line` and `column` are in: 0 for the script last given to
|
||||
/// [`Realm::run`] or [`Realm::start`], `n` for the `n`th source a
|
||||
/// [`crate::HostItem::Evaluator`] gave since then, and [`UNKNOWN_SOURCE`] otherwise, which
|
||||
/// includes code from an earlier script and from the sources given during its run.
|
||||
/// Which source the last error's `line` and `column` are in: 0 for the most recent script or
|
||||
/// module entry source. Later sources are numbered from 1 as tags are assigned: modules in
|
||||
/// load order, then sources a [`crate::HostItem::Evaluator`] gives. Module execution order
|
||||
/// can differ from load order. A script run without modules numbers only evaluator sources.
|
||||
/// [`UNKNOWN_SOURCE`] includes code from earlier runs and their module or evaluator sources.
|
||||
pub fn error_source(&self) -> u32 {
|
||||
self.source_of(self.interp.error_tag)
|
||||
}
|
||||
|
||||
/// The source tag of the code the last error's `line` and `column` are in, which stays the same
|
||||
/// from run to run: each script given to [`Realm::run`] or [`Realm::start`] and each source a
|
||||
/// from run to run: each script or module entry, each dependency loaded, and each source a
|
||||
/// [`crate::HostItem::Evaluator`] gives gets the next tag, so a function an earlier script
|
||||
/// defined has its script's tag. [`UNKNOWN_SOURCE`] for code that `eval` or `Function`
|
||||
/// compiled, an error with no place, and sources given once the tags are used up.
|
||||
@@ -566,9 +630,10 @@ impl Realm {
|
||||
self.interp.error_tag
|
||||
}
|
||||
|
||||
/// The source tag ([`Realm::error_tag`]) of the script the last [`Realm::run`] or
|
||||
/// [`Realm::start`] compiled; the `n`th source an evaluator gave during that run has this tag
|
||||
/// plus `n`. [`UNKNOWN_SOURCE`] when that call compiled nothing.
|
||||
/// The source tag ([`Realm::error_tag`]) of the most recent script or module entry source.
|
||||
/// Dependency modules receive subsequent tags in load order, followed by evaluator sources
|
||||
/// as they are given. A script run without modules assigns subsequent tags only to evaluator
|
||||
/// sources. [`UNKNOWN_SOURCE`] when no entry tag has been assigned or the tags are used up.
|
||||
pub fn script_tag(&self) -> u32 {
|
||||
self.script_tag
|
||||
}
|
||||
|
||||
+21
-2
@@ -408,8 +408,27 @@ impl Interp {
|
||||
Some(Prop::Accessor { set: None, .. }) => return self.reject_sym(throw, &k, "it has only a getter"),
|
||||
None => {}
|
||||
}
|
||||
let proto = self.object(id)?.proto;
|
||||
match proto.map(|p| self.find_sym(p, &k)).transpose()?.flatten() {
|
||||
let mut cur = self.object(id)?.proto;
|
||||
let mut inherited = None;
|
||||
let mut steps = 0usize;
|
||||
while let Some(object) = cur {
|
||||
if matches!(self.object(object)?.class, crate::heap::Class::ModuleNamespace(_)) {
|
||||
return self.reject_sym(throw, &k, "a module namespace object is read-only");
|
||||
}
|
||||
if let Some(property) = self.get_own_sym(object, &k)? {
|
||||
inherited = Some(property);
|
||||
break;
|
||||
}
|
||||
cur = self.object(object)?.proto;
|
||||
if cur.is_some() {
|
||||
self.use_fuel()?;
|
||||
}
|
||||
steps += 1;
|
||||
if steps > 1_000_000 {
|
||||
return Err(crate::interp::Abrupt::Internal("prototype chain too long".into()));
|
||||
}
|
||||
}
|
||||
match inherited {
|
||||
Some(Prop::Accessor { set: Some(s), .. }) => return self.call(&Value::Object(s), &Value::Object(id), &[v]).map(drop),
|
||||
Some(Prop::Accessor { set: None, .. }) => return self.reject_sym(throw, &k, "it has only a getter"),
|
||||
Some(Prop::Data { flags, .. }) if flags & WRITABLE == 0 => return self.reject_sym(throw, &k, "it is read-only"),
|
||||
|
||||
+199
-2
@@ -31,7 +31,10 @@
|
||||
//! A fifth test reads the ECMAScript 2015 subset that `Options::es2015` covers (`let`, `const`,
|
||||
//! arrow functions, templates, default and rest parameters, classes, `super` and `new.target`,
|
||||
//! and from ECMAScript 2020 optional chains and `??`) without and with that option, and
|
||||
//! prints both counts; its failures with the option go to `es2015-failures.txt`.
|
||||
//! prints both counts; its failures with the option go to `es2015-failures.txt`. A sixth test runs
|
||||
//! the module tests under `test/language/module-code`, `import` and `export` as modules, reading
|
||||
//! the fixture files they import from the suite, and as scripts for comparison; its failures as
|
||||
//! modules go to `module-failures.txt`.
|
||||
//!
|
||||
//! A sixth test runs the tests under the folders [`ES2015_COLLECTION_BUILT_INS`] names (`Map`, `Set`,
|
||||
//! `WeakMap`, `WeakSet`, `ArrayBuffer`, `DataView`, `TypedArray` and `TypedArrayConstructors`) in
|
||||
@@ -73,7 +76,11 @@
|
||||
use std::collections::HashSet;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vectorcraft_js::{JsValue, Limits, Options, Punct, Realm, RunErrorKind, Token, TokenKind, parse, tokenize};
|
||||
use vectorcraft_js::{
|
||||
JsValue, Limits, LoadError, LoadedModule, ModuleLimits, Options, Progress, Punct, Realm, RunErrorKind, Token, TokenKind, parse, tokenize,
|
||||
tokenize_module,
|
||||
};
|
||||
|
||||
/// A test file's metadata, from its `/*--- … ---*/` block.
|
||||
#[derive(Default)]
|
||||
struct Meta {
|
||||
@@ -453,6 +460,12 @@ fn needs_missing_builtin_in(sources: &[&str], missing: &HashSet<&str>, options:
|
||||
Err(_) => return true,
|
||||
}
|
||||
}
|
||||
uses_missing_builtin(&lists, missing)
|
||||
}
|
||||
|
||||
/// The tokens `lists` (of a test and the harness files it includes) use a missing built-in, as
|
||||
/// [`needs_missing_builtin`] counts them.
|
||||
fn uses_missing_builtin(lists: &[Vec<Token>], missing: &HashSet<&str>) -> bool {
|
||||
let strings_are_code = lists.iter().any(|tokens| runs_strings_as_code(tokens));
|
||||
lists.iter().flatten().any(|t| match &t.kind {
|
||||
TokenKind::Ident(name) => missing.contains(name.as_str()),
|
||||
@@ -967,6 +980,190 @@ fn run_es2015(dir: &Path) {
|
||||
assert_eq!(before.panicked + after.panicked, 0, "the interpreter panicked; see {}", report.display());
|
||||
}
|
||||
|
||||
/// The folders under `test/language/` whose module tests [`modules_run`] reads.
|
||||
const MODULE_FOLDERS: &[&str] = &["module-code", "import", "export"];
|
||||
|
||||
/// The feature tags a module test may carry: those of [`ES2015_FEATURES`] and `export * as ns from`.
|
||||
const MODULE_FEATURES: &[&str] =
|
||||
&["let", "const", "arrow-function", "template", "default-parameters", "rest-parameters", "export-star-as-namespace-from-module"];
|
||||
|
||||
#[test]
|
||||
fn modules_run() {
|
||||
let Some(dir) = suite_dir() else {
|
||||
println!("test262 modules: SKIPPED (no suite; run cargo xtask test262)");
|
||||
return;
|
||||
};
|
||||
let handle = std::thread::Builder::new().stack_size(64 << 20).spawn(move || run_modules(&dir)).unwrap();
|
||||
handle.join().unwrap();
|
||||
}
|
||||
|
||||
/// The `/`-separated path, from the suite's folder, of the module `specifier` names for the module
|
||||
/// at `referrer` (a path from the suite's folder too): only a `./` or `../` path that stays inside
|
||||
/// `test/`.
|
||||
fn module_path(referrer: &str, specifier: &str) -> Result<String, LoadError> {
|
||||
if !(specifier.starts_with("./") || specifier.starts_with("../")) {
|
||||
return Err(LoadError::Syntax(format!("the runner reads only relative specifiers: '{specifier}'")));
|
||||
}
|
||||
let mut names: Vec<&str> = referrer.split('/').collect();
|
||||
names.pop();
|
||||
for name in specifier.split('/') {
|
||||
match name {
|
||||
"" | "." => {}
|
||||
".." if names.len() > 1 => {
|
||||
names.pop();
|
||||
}
|
||||
".." => return Err(LoadError::Other(format!("'{specifier}' leads out of the suite's tests"))),
|
||||
name => names.push(name),
|
||||
}
|
||||
}
|
||||
Ok(names.join("/"))
|
||||
}
|
||||
|
||||
/// Runs a module test's `source` (at `rel`, a path from the suite's folder) in a new realm with
|
||||
/// `options`, after `prelude` (the harness) as a script; the modules it imports are read from the
|
||||
/// suite. `Err` describes a failure. `negative` is the phase (`resolution` or `runtime`) and the
|
||||
/// error the test expects. A `resolution` test's module must parse, and the run must end with the
|
||||
/// error while the modules load and link, before any runs; an imported module that does not parse
|
||||
/// counts for a `SyntaxError`. A `runtime` test's modules must load and link, and the error must be thrown
|
||||
/// while they run.
|
||||
fn run_module_one(dir: &Path, prelude: &str, rel: &str, source: &str, negative: Option<(&str, &str)>, options: &Options) -> Result<(), String> {
|
||||
let mut realm = Realm::with_options(options.clone(), Limits { fuel: 20_000_000, heap_bytes: 256 << 20, ..Limits::default() });
|
||||
realm.run(prelude).map_err(|e| format!("the harness failed: {}", e.message))?;
|
||||
let mut given = HashSet::new();
|
||||
let mut load = |referrer: &str, specifier: &str| {
|
||||
let key = module_path(referrer, specifier)?;
|
||||
let path = inside(dir, &key).map_err(LoadError::Other)?;
|
||||
let source = if given.insert(key.clone()) { Some(read_source(&path).map_err(LoadError::Other)?) } else { None };
|
||||
Ok(LoadedModule { key, source })
|
||||
};
|
||||
let resolution = negative.is_some_and(|(phase, _)| phase == "resolution");
|
||||
if resolution && let Err(e) = vectorcraft_js::parse_module(source, options) {
|
||||
return Err(format!("did not parse; a resolution error was expected: {} (line {})", e.message, e.line));
|
||||
}
|
||||
let started = realm.start_module(rel, source, ModuleLimits::default(), &mut load);
|
||||
let result = match started {
|
||||
Ok(()) if resolution => return Err("linked; an error while linking was expected".to_string()),
|
||||
Err(e) if !resolution && negative.is_some() => {
|
||||
return Err(format!("did not start; an error while running was expected: {:?}: {} (line {})", e.kind, e.message, e.line));
|
||||
}
|
||||
Err(e) => Err(e),
|
||||
Ok(()) => loop {
|
||||
match realm.advance(u64::MAX) {
|
||||
Ok(Progress::Paused) => {}
|
||||
Ok(Progress::Done(v)) => break Ok(v),
|
||||
Err(e) => break Err(e),
|
||||
}
|
||||
},
|
||||
};
|
||||
match (result, negative.map(|(_, t)| t)) {
|
||||
(Ok(_), None) => Ok(()),
|
||||
(Ok(_), Some(t)) => Err(format!("completed; a {t} was expected")),
|
||||
(Err(e), Some("SyntaxError")) if resolution && e.kind == RunErrorKind::Syntax => Ok(()),
|
||||
(Err(e), Some(t)) if e.kind == RunErrorKind::Thrown => {
|
||||
realm.bind_last_thrown("__thrown");
|
||||
match realm.run(&format!("typeof __thrown === 'object' && __thrown !== null && __thrown.constructor === {t}")) {
|
||||
Ok(JsValue::Bool(true)) => Ok(()),
|
||||
_ => Err(format!("threw {} (line {}); a {t} was expected", e.message, e.line)),
|
||||
}
|
||||
}
|
||||
(Err(e), _) => Err(format!("{:?}: {} (line {}, column {})", e.kind, e.message, e.line, e.column)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs the module tests (`flags: [module]`) under [`MODULE_FOLDERS`] whose feature tags are all in
|
||||
/// [`MODULE_FEATURES`], leaving out asynchronous tests and those that use a missing built-in: each
|
||||
/// once as a strict script with [`Options::es2015`], as they could run before modules, and once as
|
||||
/// a module, and prints both counts. A `negative: phase: parse` test must not parse as a module,
|
||||
/// and a `phase: resolution` one must end before it runs with the error its `type:` names.
|
||||
/// Failures as a module go to `module-failures.txt`.
|
||||
fn run_modules(dir: &Path) {
|
||||
let harness = |name: &str| or_fail(inside(dir, &format!("harness/{name}")).and_then(|p| read_source(&p)));
|
||||
let prelude = format!("{}\n{}\n", harness("assert.js"), harness("sta.js"));
|
||||
let missing = missing_builtins(&[TEXT_BUILTINS]);
|
||||
let options = Options { es2015: true, ..Options::default() };
|
||||
let (mut selected, mut skipped) = (0usize, 0usize);
|
||||
let (mut before, mut after) = ((0usize, 0usize), (0usize, 0usize));
|
||||
let mut failures = String::new();
|
||||
let mut panics = 0usize;
|
||||
for folder in MODULE_FOLDERS {
|
||||
let root = or_fail(inside(dir, &format!("test/language/{folder}")));
|
||||
assert!(root.is_dir(), "{} is not a test262 checkout", dir.display());
|
||||
for path in or_fail(test_files(&root)) {
|
||||
let rel = path.strip_prefix(dir).unwrap_or(&path).display().to_string().replace('\\', "/");
|
||||
let source = or_fail(read_source(&path));
|
||||
let meta = meta(&source);
|
||||
let has = |flag: &str| meta.flags.iter().any(|f| f == flag);
|
||||
if !has("module") || !meta.features.iter().all(|f| MODULE_FEATURES.contains(&f.as_str())) {
|
||||
continue;
|
||||
}
|
||||
let includes: String = meta.includes.iter().map(|i| harness(i) + "\n").collect();
|
||||
let phase = meta.negative_phase.as_deref();
|
||||
// A module that must not parse has no tokens to look at, and one that does not parse
|
||||
// runs, to fail.
|
||||
let missing_builtin = phase != Some("parse")
|
||||
&& match (tokenize_module(&source, &options), tokenize(&includes, &options)) {
|
||||
(Ok(test), Ok(harness)) => uses_missing_builtin(&[test, harness], &missing),
|
||||
(Err(_), Ok(_)) => false,
|
||||
(_, Err(_)) => true,
|
||||
};
|
||||
if has("async") || missing_builtin {
|
||||
skipped += 1;
|
||||
continue;
|
||||
}
|
||||
selected += 1;
|
||||
let negative_type = meta.negative_type.clone().filter(|_| matches!(phase, Some("runtime" | "resolution")));
|
||||
let negative = phase.zip(negative_type.as_deref());
|
||||
let as_script = if matches!(phase, Some("parse" | "resolution")) {
|
||||
parse(&source, &Options { strict: true, ..options.clone() }).is_err()
|
||||
} else {
|
||||
run_one(&format!("\"use strict\";\n{prelude}{includes}{source}"), negative_type.as_deref(), &options).is_ok()
|
||||
};
|
||||
if as_script {
|
||||
before.0 += 1;
|
||||
} else {
|
||||
before.1 += 1;
|
||||
}
|
||||
let outcome = if phase == Some("parse") {
|
||||
match vectorcraft_js::parse_module(&source, &options) {
|
||||
Err(_) => Ok(()),
|
||||
Ok(_) => Err("parsed; a SyntaxError was expected".to_string()),
|
||||
}
|
||||
} else {
|
||||
let prelude = format!("{prelude}{includes}");
|
||||
match std::panic::catch_unwind(|| run_module_one(dir, &prelude, &rel, &source, negative, &options)) {
|
||||
Ok(r) => r,
|
||||
Err(_) => {
|
||||
panics += 1;
|
||||
Err("PANIC".to_string())
|
||||
}
|
||||
}
|
||||
};
|
||||
match outcome {
|
||||
Ok(()) => after.0 += 1,
|
||||
Err(why) => {
|
||||
after.1 += 1;
|
||||
failures.push_str(&format!("{rel}: {why}\n"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(selected > 0, "no module tests under {}", dir.display());
|
||||
let report = dir.join("module-failures.txt");
|
||||
if let Err(e) = std::fs::write(&report, &failures) {
|
||||
println!("could not write {}: {e}", report.display());
|
||||
}
|
||||
println!(
|
||||
"test262 modules: {selected} tests. As scripts: {} passed, {} failed. As modules: {} passed, {} failed. Skipped {skipped} \
|
||||
asynchronous or missing-built-in tests. Failures: {}",
|
||||
before.0,
|
||||
before.1,
|
||||
after.0,
|
||||
after.1,
|
||||
report.display()
|
||||
);
|
||||
assert_eq!(panics, 0, "the interpreter panicked; see {}", report.display());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn annex_b_runs() {
|
||||
let Some(dir) = suite_dir() else {
|
||||
|
||||
@@ -2028,7 +2028,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.installPlugin",
|
||||
"Install Plug-in…",
|
||||
"",
|
||||
"{path?: a .wasm file | dataBase64?: the module, name?: the file name shown as its source (with dataBase64), replace?: bool (true: the user agreed it takes the place of the plug-in with its id, as plugin.install), hash?: the module's SHA-256 (as plugin.install)} install a WebAssembly plug-in (plugin.install); without a path pick one (the web opens the browser's file picker; File › Open of a .wasm installs it too). A plug-in that lists permissions the user hasn't granted it asks the user first, showing its name, id, version, file SHA-256 and what each permission lets it do, so does a filter that asks for a heavy budget, and so does one without replace that would take the place of another module with its id and get its settings and cache (needsReplace in plugin.inspect), showing its id and file SHA-256: OK installs it if the file still has the SHA-256 shown, Cancel installs nothing. Only a person can press OK: ui.dialog.confirm, answer_dialog and synthetic input are refused. When automation asked (a control or MCP request, synthetic input, or a file dialog one of them opened, even when the person picked the file), replace: true doesn't skip the question about replacing, and nothing in the dialog installs it, the person's OK included: the person chooses Object › Plug-ins › Install Plug-in… to install it → plugin.install's result | {pending: \"pluginInstall\"} while it asks | {pending: \"pluginInstall\", approval: \"personMustStartInstall\"} while it asks what automation asked | null on the web without path or dataBase64, once the browser's file picker opens (the picked file is handled as above) | {pending: true} on the web while a Web Worker checks module bytes no worker has checked yet, after which the install goes on as above in the app",
|
||||
"{path?: a .wasm file | dataBase64?: the module, name?: the file name shown as its source (with dataBase64), replace?: bool (true: the user agreed it takes the place of the plug-in with its id, as plugin.install), hash?: the module's SHA-256 (as plugin.install)} install a WebAssembly plug-in (plugin.install); without a path pick one (the web opens the browser's file picker; File › Open of a .wasm installs it too). A plug-in that lists permissions the user hasn't granted it asks the user first, showing its name, id, version, file SHA-256 and what each permission lets it do, so does a filter that asks for a heavy budget, showing its id and file SHA-256, and so does one without replace that would take the place of another module with its id and get its settings and cache (needsReplace in plugin.inspect), showing its id and file SHA-256: OK installs it if the file still has the SHA-256 shown, Cancel installs nothing. Only a person can press OK: ui.dialog.confirm, answer_dialog and synthetic input are refused. When automation asked (a control or MCP request, synthetic input, or a file dialog one of them opened, even when the person picked the file), replace: true doesn't skip the question about replacing, and nothing in the dialog installs it, the person's OK included: the person chooses Object › Plug-ins › Install Plug-in… to install it → plugin.install's result | {pending: \"pluginInstall\"} while it asks | {pending: \"pluginInstall\", approval: \"personMustStartInstall\"} while it asks what automation asked | null on the web without path or dataBase64, once the browser's file picker opens (the picked file is handled as above) | {pending: true} on the web while a Web Worker checks module bytes no worker has checked yet, after which the install goes on as above in the app",
|
||||
),
|
||||
(
|
||||
"ui.failedPlugins",
|
||||
@@ -2070,13 +2070,13 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.runScript",
|
||||
"Other Script…",
|
||||
"Cmd+F12",
|
||||
"{path? | source?, name?} run a .js or .jsx file (script.run), after the warning unless Preferences › General › Show External Script Warning is off (dialog `scriptRun`: `choice`, `skip`, and `reaches`, which ui.dialog.set cannot set: the `kind`, `needs`, `outside`, `includes` and `truncated` of script.check's report on the script, which the warning lists, or null when the check failed); without a file pick one (the web opens the browser's file picker); with Preferences › General › Run Startup Scripts on, the startup scripts run first (script.startup.run) and script.run's reply also holds `startup`, script.startup.run's reply; while a startup script runs before it the reply is {running: true, queued: true}, and a later failure to start shows in the status bar",
|
||||
"{path? | source?, name?} run a .js, .mjs or .jsx file (script.run), after the warning unless Preferences › General › Show External Script Warning is off (dialog `scriptRun`: `choice`, `skip`, and `reaches`, which ui.dialog.set cannot set: the `kind`, `needs`, `outside`, `includes` and `truncated` of script.check's report on the script, which the warning lists, or null when the check failed); without a file pick one (the web opens the browser's file picker); with Preferences › General › Run Startup Scripts on, the startup scripts run first (script.startup.run) and script.run's reply also holds `startup`, script.startup.run's reply; while a startup script runs before it the reply is {running: true, queued: true}, and a later failure to start shows in the status bar",
|
||||
),
|
||||
(
|
||||
"ui.runInstalledScript",
|
||||
"Run Script",
|
||||
"",
|
||||
"{path: a script's path as script.listInstalled gives it} run a script of the Scripts folder, as its File › Scripts item does (script.run with installed reads the file once, checks it again and runs that text, so its #include lines and $.evalFile read in the folder that read found), without the warning Other Script… shows; a file that is no longer a .js or .jsx file in the folder or a subfolder at most 4 levels below it, or that is or lies behind a link or is hidden, is not run, and the menu's listing is read again; with Preferences › General › Run Startup Scripts on, the startup scripts run first (script.startup.run) and script.run's reply also holds `startup`, script.startup.run's reply; while a startup script runs before it the reply is {running: true, queued: true}, and a later failure to start shows in the status bar",
|
||||
"{path: a script's path as script.listInstalled gives it} run a script of the Scripts folder, as its File › Scripts item does (script.run with installed reads the file once, checks it again and runs that text, so its #include lines and $.evalFile read in the folder that read found), without the warning Other Script… shows; a file that is no longer a .js, .mjs or .jsx file in the folder or a subfolder at most 4 levels below it, or that is or lies behind a link or is hidden, is not run, and the menu's listing is read again; with Preferences › General › Run Startup Scripts on, the startup scripts run first (script.startup.run) and script.run's reply also holds `startup`, script.startup.run's reply; while a startup script runs before it the reply is {running: true, queued: true}, and a later failure to start shows in the status bar",
|
||||
),
|
||||
(
|
||||
"ui.checkScript",
|
||||
|
||||
@@ -33,7 +33,8 @@
|
||||
//! them well: labels, units, groups, help and conditions ([`dialog`]). What a plug-in may do is
|
||||
//! the set of [`permissions`] its manifest lists, which the user approves when it is installed. A
|
||||
//! filter or a live effect may also add menu commands of its own ([`Command`]), which the host
|
||||
//! runs through `vc_run` with the command's id in `_context`. The web build checks modules and
|
||||
//! runs through `vc_run` with the command's id in `_context`. Its name, command labels and
|
||||
//! parameter text may come in other languages too ([`translations`]). The web build checks modules and
|
||||
//! runs filters in a worker of its own ([`worker`]).
|
||||
//!
|
||||
//! An object filter may also be written in JavaScript ([`js`]): its manifest gives
|
||||
@@ -60,6 +61,7 @@ pub mod safe_mode;
|
||||
#[cfg(any(test, feature = "test-steady"))]
|
||||
pub mod steady;
|
||||
pub mod storage;
|
||||
pub mod translations;
|
||||
pub mod wat;
|
||||
pub mod worker;
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ use serde_json::{Map, Value, json};
|
||||
|
||||
use crate::dialog::ParamUi;
|
||||
use crate::permissions::{self, API_LEVEL, APPEARANCE_API, CONTEXT_API, INPUTS_API, OUTPUT_KINDS_API, PROGRESS_API, Permission, WRITES_API};
|
||||
use crate::translations::Translations;
|
||||
use crate::{Error, Result};
|
||||
|
||||
/// Longest manifest the host reads.
|
||||
@@ -725,6 +726,10 @@ pub struct Manifest {
|
||||
/// What runs its code: WebAssembly when left out, or `"js"` for a JavaScript filter.
|
||||
#[serde(default, skip_serializing_if = "Runtime::is_wasm")]
|
||||
pub runtime: Runtime,
|
||||
/// Its name, command labels and parameter text in other languages, shown in place of the
|
||||
/// manifest's own when the UI is in one of them ([`crate::translations`]).
|
||||
#[serde(default, skip_serializing_if = "Translations::is_empty")]
|
||||
pub translations: Translations,
|
||||
}
|
||||
|
||||
impl Manifest {
|
||||
@@ -779,13 +784,15 @@ impl Manifest {
|
||||
commands: Vec::new(),
|
||||
command_allowlist: Vec::new(),
|
||||
runtime: Runtime::Wasm,
|
||||
translations: Translations::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The manifest command `c` runs with: this one with `c`'s label as its name and `c`'s
|
||||
/// parameters as its own, so dialogs show them and [`Manifest::resolve_params`] checks them.
|
||||
/// parameters as its own, so dialogs show them and [`Manifest::resolve_params`] checks them,
|
||||
/// and with `c`'s text in each language as its translations.
|
||||
pub fn for_command(&self, c: &Command) -> Manifest {
|
||||
Manifest { name: c.label.clone(), params: c.params.clone(), commands: Vec::new(), ..self.clone() }
|
||||
Manifest { name: c.label.clone(), params: c.params.clone(), commands: Vec::new(), translations: self.command_translations(c), ..self.clone() }
|
||||
}
|
||||
|
||||
/// The command with id `id`.
|
||||
@@ -890,6 +897,7 @@ impl Manifest {
|
||||
self.validate_params()?;
|
||||
self.validate_commands()?;
|
||||
self.validate_allowlist()?;
|
||||
self.validate_translations()?;
|
||||
self.validate_runtime()
|
||||
}
|
||||
|
||||
|
||||
@@ -235,7 +235,7 @@ pub fn names(permissions: &[Permission]) -> Vec<&'static str> {
|
||||
|
||||
/// Is `c` a character that changes the direction text is laid out in, or a line or paragraph
|
||||
/// separator, which a prompt must not let a manifest string use to disguise itself?
|
||||
fn is_bidi_or_separator(c: char) -> bool {
|
||||
pub(crate) fn is_bidi_or_separator(c: char) -> bool {
|
||||
matches!(c, '\u{061C}' | '\u{200E}' | '\u{200F}' | '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}' | '\u{2028}' | '\u{2029}')
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,589 @@
|
||||
//! Text a plug-in gives in other languages: its manifest's `translations` (docs/plugins.md ›
|
||||
//! Translations).
|
||||
//!
|
||||
//! `translations` maps language codes (`de`, `pt-br`, `zh-hant`, compared without regard to case)
|
||||
//! to the text shown in that language: the plug-in's `name`, its commands' labels, its parameters'
|
||||
//! labels, help and choice labels, and its group headings. Every entry is optional; text a language
|
||||
//! leaves out comes from the language without its last part (`pt-br`, then `pt`) and then from the
|
||||
//! manifest's own text. The text is shown only: command ids, parameter names, the values a choice
|
||||
//! passes, `plugin.list` and the install approval keep the manifest's own text.
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::dialog::{MAX_HELP, MAX_LABEL};
|
||||
use crate::manifest::{Command, Manifest, ParamSpec};
|
||||
use crate::permissions::{self, MAX_SHOWN_FIELD, MAX_SHOWN_NAME};
|
||||
use crate::{Error, Result};
|
||||
|
||||
/// Most languages a manifest's `translations` gives text in.
|
||||
pub const MAX_LANGUAGES: usize = 16;
|
||||
/// Longest language code, in bytes.
|
||||
pub const MAX_LANGUAGE_CODE: usize = 35;
|
||||
/// Longest translated plug-in name, command label or choice label, in characters.
|
||||
pub const MAX_NAME: usize = 64;
|
||||
|
||||
/// Named entries in the order the manifest gives them; each name at most once.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Entries<T>(pub Vec<(String, T)>);
|
||||
|
||||
impl<T> Default for Entries<T> {
|
||||
fn default() -> Self {
|
||||
Entries(Vec::new())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Entries<T> {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.0.is_empty()
|
||||
}
|
||||
|
||||
/// The entry named `name`.
|
||||
pub fn get(&self, name: &str) -> Option<&T> {
|
||||
self.0.iter().find(|(k, _)| k == name).map(|(_, v)| v)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Serialize> Serialize for Entries<T> {
|
||||
fn serialize<S: serde::Serializer>(&self, s: S) -> std::result::Result<S::Ok, S::Error> {
|
||||
use serde::ser::SerializeMap;
|
||||
let mut m = s.serialize_map(Some(self.0.len()))?;
|
||||
for (k, v) in &self.0 {
|
||||
m.serialize_entry(k, v)?;
|
||||
}
|
||||
m.end()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de, T: Deserialize<'de>> Deserialize<'de> for Entries<T> {
|
||||
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Self, D::Error> {
|
||||
struct V<T>(std::marker::PhantomData<T>);
|
||||
impl<'de, T: Deserialize<'de>> serde::de::Visitor<'de> for V<T> {
|
||||
type Value = Entries<T>;
|
||||
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||
f.write_str("an object")
|
||||
}
|
||||
fn visit_map<A: serde::de::MapAccess<'de>>(self, mut map: A) -> std::result::Result<Self::Value, A::Error> {
|
||||
let mut seen = HashSet::new();
|
||||
let mut out = Vec::new();
|
||||
while let Some(k) = map.next_key::<String>()? {
|
||||
if !seen.insert(k.clone()) {
|
||||
let shown = permissions::display_text(&k, MAX_SHOWN_FIELD);
|
||||
return Err(serde::de::Error::custom(format!("`{shown}` is given twice")));
|
||||
}
|
||||
out.push((k, map.next_value()?));
|
||||
}
|
||||
Ok(Entries(out))
|
||||
}
|
||||
}
|
||||
d.deserialize_any(V(std::marker::PhantomData))
|
||||
}
|
||||
}
|
||||
|
||||
/// A parameter's text in one language.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ParamText {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub label: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub help: Option<String>,
|
||||
/// A choice's labels, by the value each option passes.
|
||||
#[serde(default, skip_serializing_if = "Entries::is_empty")]
|
||||
pub options: Entries<String>,
|
||||
}
|
||||
|
||||
/// A command's text in one language.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct CommandText {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub label: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Entries::is_empty")]
|
||||
pub params: Entries<ParamText>,
|
||||
}
|
||||
|
||||
/// A plug-in's text in one language.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Catalog {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub name: Option<String>,
|
||||
/// By parameter name.
|
||||
#[serde(default, skip_serializing_if = "Entries::is_empty")]
|
||||
pub params: Entries<ParamText>,
|
||||
/// Group headings, by the `group` the parameters give.
|
||||
#[serde(default, skip_serializing_if = "Entries::is_empty")]
|
||||
pub groups: Entries<String>,
|
||||
/// By command id.
|
||||
#[serde(default, skip_serializing_if = "Entries::is_empty")]
|
||||
pub commands: Entries<CommandText>,
|
||||
}
|
||||
|
||||
/// A manifest's `translations`, by language code.
|
||||
pub type Translations = Entries<Catalog>;
|
||||
|
||||
/// Is `tag` a language code: a language of 2 or 3 letters, then parts of 2 to 8 letters and
|
||||
/// digits, each after a `-`, at most [`MAX_LANGUAGE_CODE`] bytes in all (`de`, `pt-BR`,
|
||||
/// `zh-Hant-TW`)?
|
||||
pub fn valid_language_code(tag: &str) -> bool {
|
||||
let mut parts = tag.split('-');
|
||||
tag.len() <= MAX_LANGUAGE_CODE
|
||||
&& parts.next().is_some_and(|l| (2..=3).contains(&l.len()) && l.bytes().all(|b| b.is_ascii_alphabetic()))
|
||||
&& parts.all(|p| (2..=8).contains(&p.len()) && p.bytes().all(|b| b.is_ascii_alphanumeric()))
|
||||
}
|
||||
|
||||
/// The codes text for language `lang` is looked up under, most specific first: `lang`, then
|
||||
/// `lang` without its last part, down to the language alone (`zh-hant-tw`, `zh-hant`, `zh`).
|
||||
fn lookup_codes(lang: &str) -> impl Iterator<Item = &str> {
|
||||
std::iter::successors(Some(lang), |l| l.rfind('-').map(|i| &l[..i]))
|
||||
}
|
||||
|
||||
impl Translations {
|
||||
/// The first text `f` finds for language `lang` ([`lookup_codes`]).
|
||||
fn find<'a, T>(&'a self, lang: &str, f: impl Fn(&'a Catalog) -> Option<T>) -> Option<T> {
|
||||
lookup_codes(lang).find_map(|code| self.0.iter().filter(|(k, _)| k.eq_ignore_ascii_case(code)).find_map(|(_, c)| f(c)))
|
||||
}
|
||||
|
||||
/// The plug-in's name these translations give for language `lang` (`None`: they give none).
|
||||
pub fn name_in(&self, lang: &str) -> Option<&str> {
|
||||
self.find(lang, |c| c.name.as_deref())
|
||||
}
|
||||
}
|
||||
|
||||
/// Is `s` text a translation may give: 1 to `max` characters, not all spaces, without control
|
||||
/// characters (`\n` too, unless `lines`) or characters that change the direction text is laid out
|
||||
/// in or separate lines?
|
||||
fn fits(s: &str, max: usize, lines: bool) -> bool {
|
||||
!s.trim().is_empty()
|
||||
&& s.chars().count() <= max
|
||||
&& s.chars().all(|c| (!c.is_control() || (lines && c == '\n')) && !permissions::is_bidi_or_separator(c))
|
||||
}
|
||||
|
||||
/// `translations.<path>` as an error names it, each part escaped as prompts show text.
|
||||
fn key(path: &[&str]) -> String {
|
||||
let parts: Vec<String> = path.iter().map(|p| permissions::display_text(p, MAX_SHOWN_FIELD)).collect();
|
||||
format!("`translations.{}`", parts.join("."))
|
||||
}
|
||||
|
||||
/// Text `s` as a dialog shows it: each line with its control and bidirectional characters escaped
|
||||
/// and cut at [`MAX_HELP`] characters.
|
||||
fn shown_text(s: &str) -> String {
|
||||
let lines: Vec<String> = s.split('\n').map(|l| permissions::display_text(l, MAX_HELP)).collect();
|
||||
lines.join("\n")
|
||||
}
|
||||
|
||||
/// Checks text `s` at `path` against `max` characters (`lines`: `\n` allowed).
|
||||
fn check_text(s: &str, max: usize, lines: bool, path: &[&str]) -> Result<()> {
|
||||
if fits(s, max, lines) {
|
||||
return Ok(());
|
||||
}
|
||||
let at = key(path);
|
||||
Err(Error::Manifest(format!("{at} must be 1-{max} printable characters, without direction or line-separator characters")))
|
||||
}
|
||||
|
||||
/// The error for the key at `path`, which names a parameter, choice value, group or command the
|
||||
/// manifest doesn't declare, or translates a field the manifest doesn't give (`options` of a
|
||||
/// parameter that isn't a choice, `help` of a parameter without one).
|
||||
fn undeclared(path: &[&str]) -> Error {
|
||||
let at = key(path);
|
||||
Error::Manifest(format!("{at} names or translates something the manifest doesn't declare"))
|
||||
}
|
||||
|
||||
/// Checks the text of parameters `texts` against the parameters `params` they name, at `path`.
|
||||
fn check_params(texts: &Entries<ParamText>, params: &[(String, crate::Param)], path: &[&str]) -> Result<()> {
|
||||
for (k, t) in &texts.0 {
|
||||
let here = [path, &[k.as_str()]].concat();
|
||||
let Some((_, p)) = params.iter().find(|(name, _)| name == k) else {
|
||||
return Err(undeclared(&here));
|
||||
};
|
||||
if let Some(label) = &t.label {
|
||||
check_text(label, MAX_LABEL, false, &[here.as_slice(), &["label"]].concat())?;
|
||||
}
|
||||
if let Some(help) = &t.help {
|
||||
let at = [here.as_slice(), &["help"]].concat();
|
||||
if p.ui.help.is_none() {
|
||||
return Err(undeclared(&at));
|
||||
}
|
||||
check_text(help, MAX_HELP, true, &at)?;
|
||||
}
|
||||
if t.options.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let ParamSpec::Choice { options, .. } = &p.spec else {
|
||||
return Err(undeclared(&[here.as_slice(), &["options"]].concat()));
|
||||
};
|
||||
for (value, label) in &t.options.0 {
|
||||
let at = [here.as_slice(), &["options", value.as_str()]].concat();
|
||||
if !options.contains(value) {
|
||||
return Err(undeclared(&at));
|
||||
}
|
||||
check_text(label, MAX_NAME, false, &at)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
impl Manifest {
|
||||
/// `translations` gives at most [`MAX_LANGUAGES`] languages, each by a distinct language code
|
||||
/// ([`valid_language_code`]; case doesn't tell codes apart), and names only what the manifest
|
||||
/// declares: its parameters, their choices' values, its groups and its commands. Each text
|
||||
/// follows the rules of the text it translates, without direction or line-separator
|
||||
/// characters, and `help` translates a `help` the parameter gives. The error names the key.
|
||||
pub(crate) fn validate_translations(&self) -> Result<()> {
|
||||
let langs = &self.translations.0;
|
||||
if langs.len() > MAX_LANGUAGES {
|
||||
return Err(Error::Manifest(format!("`translations` gives at most {MAX_LANGUAGES} languages")));
|
||||
}
|
||||
let groups: HashSet<&str> =
|
||||
self.params.iter().chain(self.commands.iter().flat_map(|c| c.params.iter())).filter_map(|(_, p)| p.ui.group.as_deref()).collect();
|
||||
for (i, (lang, c)) in langs.iter().enumerate() {
|
||||
let lang = lang.as_str();
|
||||
if !valid_language_code(lang) || langs.get(..i).is_some_and(|before| before.iter().any(|(b, _)| b.eq_ignore_ascii_case(lang))) {
|
||||
let at = key(&[lang]);
|
||||
return Err(Error::Manifest(format!("{at} is not a language code such as `de` or `pt-BR`, or repeats one given before it")));
|
||||
}
|
||||
if let Some(name) = &c.name {
|
||||
check_text(name, MAX_NAME, false, &[lang, "name"])?;
|
||||
}
|
||||
check_params(&c.params, &self.params, &[lang, "params"])?;
|
||||
for (g, heading) in &c.groups.0 {
|
||||
let g = g.as_str();
|
||||
if !groups.contains(g) {
|
||||
return Err(undeclared(&[lang, "groups", g]));
|
||||
}
|
||||
check_text(heading, MAX_LABEL, false, &[lang, "groups", g])?;
|
||||
}
|
||||
for (id, t) in &c.commands.0 {
|
||||
let id = id.as_str();
|
||||
let Some(command) = self.command(id) else {
|
||||
return Err(undeclared(&[lang, "commands", id]));
|
||||
};
|
||||
if let Some(label) = &t.label {
|
||||
check_text(label, MAX_NAME, false, &[lang, "commands", id, "label"])?;
|
||||
}
|
||||
check_params(&t.params, &command.params, &[lang, "commands", id, "params"])?;
|
||||
}
|
||||
}
|
||||
// A dropdown tells its options apart by their labels: in each language, with the labels a
|
||||
// language leaves out taken from the language without its region, no two may be the same.
|
||||
for (lang, _) in langs {
|
||||
self.check_option_labels(lang, &[lang, "params"])?;
|
||||
}
|
||||
for c in self.commands.iter().filter(|c| c.params.iter().any(|(_, p)| matches!(p.spec, ParamSpec::Choice { .. }))) {
|
||||
let own = self.for_command(c);
|
||||
for (lang, _) in langs {
|
||||
own.check_option_labels(lang, &[lang, "commands", c.id.as_str(), "params"])?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Checks that no two options of a choice show the same label in language `lang`, naming the
|
||||
/// choice's `options` under `path`. Labels are compared as dialogs show them, with control and
|
||||
/// bidirectional characters escaped, so an option value holding U+202E and a translation
|
||||
/// giving the text `\u{202E}` count as the same label.
|
||||
fn check_option_labels(&self, lang: &str, path: &[&str]) -> Result<()> {
|
||||
for (k, p) in &self.params {
|
||||
let ParamSpec::Choice { options, .. } = &p.spec else { continue };
|
||||
let shown: Vec<String> = options.iter().map(|o| shown_text(self.option_label_in(k, o, lang))).collect();
|
||||
if shown.iter().enumerate().any(|(i, s)| shown.get(..i).is_some_and(|before| before.contains(s))) {
|
||||
let at = key(&[path, &[k.as_str(), "options"]].concat());
|
||||
return Err(Error::Manifest(format!("{at} gives two options the same label")));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The translations command `c`'s manifest ([`Manifest::for_command`]) shows: in each language,
|
||||
/// `c`'s label as its name, `c`'s parameters' text and the group headings.
|
||||
pub(crate) fn command_translations(&self, c: &Command) -> Translations {
|
||||
let langs = self.translations.0.iter().map(|(lang, cat)| {
|
||||
let own = cat.commands.get(&c.id);
|
||||
let catalog = Catalog {
|
||||
name: own.and_then(|t| t.label.clone()),
|
||||
params: own.map(|t| t.params.clone()).unwrap_or_default(),
|
||||
groups: cat.groups.clone(),
|
||||
commands: Entries::default(),
|
||||
};
|
||||
(lang.clone(), catalog)
|
||||
});
|
||||
Entries(langs.collect())
|
||||
}
|
||||
|
||||
/// The plug-in's name in language `lang` (an app language code such as `de` or `pt-br`): its
|
||||
/// translation, else the manifest's `name`.
|
||||
pub fn name_in(&self, lang: &str) -> &str {
|
||||
self.translations.name_in(lang).unwrap_or(&self.name)
|
||||
}
|
||||
|
||||
/// [`Manifest::name_in`] as menus show it: trimmed, control and bidirectional characters
|
||||
/// escaped, at most [`MAX_SHOWN_NAME`] characters.
|
||||
pub fn shown_name(&self, lang: &str) -> String {
|
||||
permissions::display_text(self.name_in(lang).trim(), MAX_SHOWN_NAME)
|
||||
}
|
||||
|
||||
/// Command `c`'s label in language `lang`, as menus show it ([`Command::shown_label`]).
|
||||
pub fn shown_command_label(&self, c: &Command, lang: &str) -> String {
|
||||
let label = self.translations.find(lang, |t| t.commands.get(&c.id).and_then(|t| t.label.as_deref())).unwrap_or(&c.label);
|
||||
permissions::display_text(label.trim(), MAX_SHOWN_NAME)
|
||||
}
|
||||
|
||||
/// The label command `c`'s menu item shows in language `lang` ([`Command::menu_label`]):
|
||||
/// [`Manifest::shown_command_label`], and for a command placed in another menu, followed by
|
||||
/// [`Manifest::shown_name`] in parentheses.
|
||||
pub fn shown_command_menu_label(&self, c: &Command, lang: &str) -> String {
|
||||
let label = self.shown_command_label(c, lang);
|
||||
match c.place {
|
||||
None => label,
|
||||
Some(_) => format!("{label} ({})", self.shown_name(lang)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Parameter `k`'s label in language `lang`: its translation, else its `label` (`None`: it
|
||||
/// has neither).
|
||||
pub fn param_label_in(&self, k: &str, lang: &str) -> Option<&str> {
|
||||
let own = self.param(k).and_then(|p| p.ui.label.as_deref());
|
||||
self.translations.find(lang, |c| c.params.get(k).and_then(|t| t.label.as_deref())).or(own)
|
||||
}
|
||||
|
||||
/// Parameter `k`'s help in language `lang`: its translation, else its `help`.
|
||||
pub fn param_help_in(&self, k: &str, lang: &str) -> Option<&str> {
|
||||
let own = self.param(k).and_then(|p| p.ui.help.as_deref());
|
||||
self.translations.find(lang, |c| c.params.get(k).and_then(|t| t.help.as_deref())).or(own)
|
||||
}
|
||||
|
||||
/// The label of value `option` of choice `k` in language `lang`: its translation, else the
|
||||
/// value itself.
|
||||
pub fn option_label_in<'a>(&'a self, k: &str, option: &'a str, lang: &str) -> &'a str {
|
||||
self.translations.find(lang, |c| c.params.get(k).and_then(|t| t.options.get(option)).map(String::as_str)).unwrap_or(option)
|
||||
}
|
||||
|
||||
/// The heading of group `group` in language `lang`: its translation, else `group`.
|
||||
pub fn group_in<'a>(&'a self, group: &'a str, lang: &str) -> &'a str {
|
||||
self.translations.find(lang, |c| c.groups.get(group).map(String::as_str)).unwrap_or(group)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::*;
|
||||
|
||||
const TRANSLATED: &str = r#"{"id":"org.example.tidy","name":"Tidy","kind":"filter",
|
||||
"params":{"mode":{"type":"choice","options":["soft","hard"],"label":"Mode","group":"Shape","help":"How hard."},
|
||||
"steps":{"type":"int","min":1,"max":9,"group":"Shape"}},
|
||||
"commands":[{"id":"grow","label":"Grow","params":{"by":{"type":"number","min":0,"max":10,"default":2,"label":"By","group":"Shape"}}},
|
||||
{"id":"shrink","label":"Shrink"}],
|
||||
"translations":{
|
||||
"de":{"name":"Aufräumen","params":{"mode":{"label":"Modus","help":"Wie stark.","options":{"soft":"Weich"}},"steps":{"label":"Schritte"}},
|
||||
"groups":{"Shape":"Form"},
|
||||
"commands":{"grow":{"label":"Wachsen","params":{"by":{"label":"Um"}}}}},
|
||||
"pt":{"name":"Arrumar","commands":{"shrink":{"label":"Encolher"}}},
|
||||
"pt-BR":{"name":"Organizar"}}}"#;
|
||||
|
||||
fn translated() -> Manifest {
|
||||
Manifest::parse(TRANSLATED.as_bytes()).unwrap()
|
||||
}
|
||||
|
||||
/// A German UI shows the German text; any language without a catalog shows the manifest's own.
|
||||
#[test]
|
||||
fn a_language_shows_its_text_and_others_the_manifests_own() {
|
||||
let m = translated();
|
||||
assert_eq!(m.name_in("de"), "Aufräumen");
|
||||
assert_eq!(m.shown_name("de"), "Aufräumen");
|
||||
assert_eq!(m.name_in("de-at"), "Aufräumen", "a region falls back to its language");
|
||||
for other in ["en", "fr", "ja", "zh-hant"] {
|
||||
assert_eq!(m.name_in(other), "Tidy", "{other}");
|
||||
assert_eq!(m.param_label_in("mode", other), Some("Mode"), "{other}");
|
||||
assert_eq!(m.param_label_in("steps", other), None, "{other}");
|
||||
assert_eq!(m.option_label_in("mode", "soft", other), "soft", "{other}");
|
||||
assert_eq!(m.group_in("Shape", other), "Shape", "{other}");
|
||||
}
|
||||
assert_eq!(m.param_label_in("mode", "de"), Some("Modus"));
|
||||
assert_eq!(m.param_label_in("steps", "de"), Some("Schritte"), "a label for a parameter that gives none");
|
||||
assert_eq!(m.param_help_in("mode", "de"), Some("Wie stark."));
|
||||
assert_eq!((m.option_label_in("mode", "soft", "de"), m.option_label_in("mode", "hard", "de")), ("Weich", "hard"));
|
||||
assert_eq!(m.group_in("Shape", "de"), "Form");
|
||||
let grow = m.command("grow").unwrap();
|
||||
assert_eq!((m.shown_command_label(grow, "de"), m.shown_command_label(grow, "en")), ("Wachsen".into(), "Grow".into()));
|
||||
// A command's dialog shows its own text in that language.
|
||||
let run = m.for_command(grow);
|
||||
assert_eq!((run.name_in("de"), run.param_label_in("by", "de"), run.group_in("Shape", "de")), ("Wachsen", Some("Um"), "Form"));
|
||||
assert_eq!((run.name_in("en"), run.param_label_in("by", "en")), ("Grow", Some("By")));
|
||||
// The text is shown only: what runs and what plugin.list reads keep the manifest's own.
|
||||
assert_eq!((m.name.as_str(), grow.label.as_str(), grow.id.as_str()), ("Tidy", "Grow", "grow"));
|
||||
assert_eq!(Value::Object(m.resolve_params(&json!({"mode": "soft"})).unwrap())["mode"], json!("soft"));
|
||||
}
|
||||
|
||||
/// `pt-br` text comes from `pt-br`, then `pt`, then the manifest, each piece on its own.
|
||||
#[test]
|
||||
fn a_region_falls_back_to_its_language_and_then_the_manifest() {
|
||||
let m = translated();
|
||||
assert_eq!(m.name_in("pt-br"), "Organizar", "codes match without regard to case");
|
||||
assert_eq!(m.name_in("pt"), "Arrumar");
|
||||
assert_eq!(m.name_in("pt-pt"), "Arrumar");
|
||||
let shrink = m.command("shrink").unwrap();
|
||||
assert_eq!(m.shown_command_label(shrink, "pt-br"), "Encolher", "from pt");
|
||||
let grow = m.command("grow").unwrap();
|
||||
assert_eq!(m.shown_command_label(grow, "pt-br"), "Grow", "from the manifest");
|
||||
}
|
||||
|
||||
/// A command placed in another menu names its plug-in after its label, both in the language
|
||||
/// shown; one in its plug-in's submenu shows its label alone.
|
||||
#[test]
|
||||
fn a_placed_command_names_its_plugin_in_the_language_shown() {
|
||||
let m = Manifest::parse(
|
||||
r#"{"id":"org.example.ridge","name":"Ridge","api":2,"kind":"filter",
|
||||
"commands":[{"id":"low","label":"Low Area","menu":{"path":["Select"]}},{"id":"stay","label":"Stay"}],
|
||||
"translations":{"de":{"name":"Grat","commands":{"low":{"label":"Tiefe Fläche"},"stay":{"label":"Bleiben"}}}}}"#
|
||||
.as_bytes(),
|
||||
)
|
||||
.unwrap();
|
||||
let (low, stay) = (m.command("low").unwrap(), m.command("stay").unwrap());
|
||||
assert_eq!(m.shown_command_menu_label(low, "de"), "Tiefe Fläche (Grat)");
|
||||
assert_eq!(m.shown_command_menu_label(low, "fr"), "Low Area (Ridge)");
|
||||
assert_eq!(m.shown_command_menu_label(low, "en"), low.menu_label(&m.name), "the manifest's own text as before");
|
||||
assert_eq!((m.shown_command_menu_label(stay, "de"), m.shown_command_menu_label(stay, "en")), ("Bleiben".into(), "Stay".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn translations_round_trip_and_are_left_out_when_absent() {
|
||||
let m = translated();
|
||||
let written = serde_json::to_value(&m).unwrap();
|
||||
assert_eq!(written["translations"]["pt-BR"], json!({"name": "Organizar"}));
|
||||
assert_eq!(Manifest::parse(&serde_json::to_vec(&m).unwrap()).unwrap(), m);
|
||||
let plain = Manifest::parse(br#"{"id":"a","name":"x","kind":"filter"}"#).unwrap();
|
||||
assert!(serde_json::to_value(&plain).unwrap().get("translations").is_none());
|
||||
assert_eq!(plain.name_in("de"), "x");
|
||||
}
|
||||
|
||||
/// A bad code, text a source field couldn't hold, text that changes direction, and a key the
|
||||
/// manifest doesn't declare are refused with an error naming the key.
|
||||
#[test]
|
||||
fn bad_translations_are_refused_naming_the_key() {
|
||||
let with = |translations: &str| {
|
||||
format!(
|
||||
r#"{{"id":"a","name":"x","kind":"filter","params":{{"mode":{{"type":"choice","options":["a","b"],"group":"G"}},
|
||||
"n":{{"type":"number","min":0,"max":1,"default":0}}}},"commands":[{{"id":"c","label":"C"}}],"translations":{translations}}}"#
|
||||
)
|
||||
};
|
||||
let long = "x".repeat(MAX_NAME + 1);
|
||||
let long_label = format!(r#"{{"de":{{"params":{{"n":{{"label":"{}"}}}}}}}}"#, "x".repeat(MAX_LABEL + 1));
|
||||
let long_name = format!(r#"{{"de":{{"name":"{long}"}}}}"#);
|
||||
for (translations, says) in [
|
||||
(r#"{"german":{"name":"X"}}"#, "`translations.german` is not a language code"),
|
||||
(r#"{"d":{"name":"X"}}"#, "`translations.d` is not a language code"),
|
||||
(r#"{"de-":{"name":"X"}}"#, "`translations.de-` is not a language code"),
|
||||
(r#"{"de_DE":{"name":"X"}}"#, "`translations.de_DE` is not a language code"),
|
||||
(r#"{"x-klingon":{"name":"X"}}"#, "`translations.x-klingon` is not a language code"),
|
||||
(r#"{"":{"name":"X"}}"#, "`translations.` is not a language code"),
|
||||
(r#"{"de":{"name":"X"},"DE":{"name":"Y"}}"#, "`translations.DE` is not a language code such as `de` or `pt-BR`, or repeats one"),
|
||||
(r#"{"de":{"name":""}}"#, "`translations.de.name` must be 1-64"),
|
||||
(r#"{"de":{"name":" "}}"#, "`translations.de.name` must be 1-64"),
|
||||
(long_name.as_str(), "`translations.de.name` must be 1-64"),
|
||||
(r#"{"de":{"name":"a\u0007b"}}"#, "`translations.de.name`"),
|
||||
(r#"{"de":{"commands":{"c":{"label":"a\nb"}}}}"#, "`translations.de.commands.c.label` must be"),
|
||||
(
|
||||
r#"{"de":{"commands":{"nope":{"label":"N"}}}}"#,
|
||||
"`translations.de.commands.nope` names or translates something the manifest doesn't declare",
|
||||
),
|
||||
(r#"{"de":{"params":{"nope":{"label":"N"}}}}"#, "`translations.de.params.nope` names or translates"),
|
||||
(long_label.as_str(), "`translations.de.params.n.label` must be 1-64"),
|
||||
(r#"{"de":{"params":{"n":{"help":"H"}}}}"#, "`translations.de.params.n.help` names or translates"),
|
||||
(r#"{"de":{"params":{"n":{"options":{"a":"A"}}}}}"#, "`translations.de.params.n.options` names or translates"),
|
||||
(r#"{"de":{"params":{"mode":{"options":{"c":"C"}}}}}"#, "`translations.de.params.mode.options.c` names or translates"),
|
||||
(r#"{"de":{"params":{"mode":{"options":{"a":""}}}}}"#, "`translations.de.params.mode.options.a` must be"),
|
||||
(r#"{"de":{"params":{"mode":{"options":{"a":"b"}}}}}"#, "`translations.de.params.mode.options` gives two options the same label"),
|
||||
(r#"{"de":{"params":{"mode":{"options":{"a":"X","b":"X"}}}}}"#, "gives two options the same label"),
|
||||
(
|
||||
r#"{"pt":{"params":{"mode":{"options":{"a":"Leve"}}}},"pt-BR":{"params":{"mode":{"options":{"b":"Leve"}}}}}"#,
|
||||
"`translations.pt-BR.params.mode.options` gives two options the same label",
|
||||
),
|
||||
(r#"{"de":{"groups":{"H":"Ha"}}}"#, "`translations.de.groups.H` names or translates"),
|
||||
] {
|
||||
let e = Manifest::parse(with(translations).as_bytes()).unwrap_err().to_string();
|
||||
assert!(e.contains(says), "{translations}: {e}");
|
||||
}
|
||||
// Characters that change the direction of the text or separate lines, written as JSON
|
||||
// escapes: right-to-left and left-to-right overrides, isolates, and a line separator.
|
||||
let esc = |c: u32| format!("\\u{c:04X}");
|
||||
for (translations, says) in [
|
||||
(format!(r#"{{"de":{{"name":"Flip{}txt"}}}}"#, esc(0x202E)), "`translations.de.name` must be"),
|
||||
(format!(r#"{{"de":{{"name":"Flip{}txt"}}}}"#, esc(0x2067)), "`translations.de.name` must be"),
|
||||
(format!(r#"{{"de":{{"name":"a{}b"}}}}"#, esc(0x2028)), "`translations.de.name` must be"),
|
||||
(format!(r#"{{"de":{{"commands":{{"c":{{"label":"{}C"}}}}}}}}"#, esc(0x202E)), "`translations.de.commands.c.label` must be"),
|
||||
(format!(r#"{{"de":{{"params":{{"n":{{"label":"{}N"}}}}}}}}"#, esc(0x202D)), "`translations.de.params.n.label` must be"),
|
||||
(format!(r#"{{"de":{{"params":{{"mode":{{"options":{{"a":"{}A"}}}}}}}}}}"#, esc(0x202B)), "`translations.de.params.mode.options.a`"),
|
||||
(format!(r#"{{"de":{{"groups":{{"G":"{}Ge"}}}}}}"#, esc(0x2066)), "`translations.de.groups.G` must be"),
|
||||
(format!(r#"{{"de{}":{{"name":"X"}}}}"#, esc(0x202E)), "`translations.de\\u{202E}` is not a language code"),
|
||||
] {
|
||||
let e = Manifest::parse(with(&translations).as_bytes()).unwrap_err().to_string();
|
||||
assert!(e.contains(says), "{translations}: {e}");
|
||||
}
|
||||
// An option value holding U+202E shows as the text `\u{202E}`, so a translation giving
|
||||
// that text for another option shows the same label.
|
||||
let escaped = format!(
|
||||
r#"{{"id":"a","name":"x","kind":"filter","params":{{"mode":{{"type":"choice","options":["soft","{}"]}}}},
|
||||
"translations":{{"de":{{"params":{{"mode":{{"options":{{"soft":"\\u{{202E}}"}}}}}}}}}}}}"#,
|
||||
esc(0x202E)
|
||||
);
|
||||
let e = Manifest::parse(escaped.as_bytes()).unwrap_err().to_string();
|
||||
assert!(e.contains("`translations.de.params.mode.options` gives two options the same label"), "{e}");
|
||||
// Keys and types serde reads: an unknown key, a repeated one, and a value of the wrong type.
|
||||
for (translations, says) in [
|
||||
(r#"{"de":{"title":"X"}}"#, "unknown field `title`"),
|
||||
(r#"{"de":{"params":{"n":{"unit":"mm"}}}}"#, "unknown field `unit`"),
|
||||
(r#"{"de":{"name":"X","name":"Y"}}"#, "duplicate field `name`"),
|
||||
(r#"{"de":{"params":{"n":{"label":"A"},"n":{"label":"B"}}}}"#, "`n` is given twice"),
|
||||
(r#"{"de":{"name":"X"},"de":{"name":"Y"}}"#, "`de` is given twice"),
|
||||
(r#"{"de":{"name":7}}"#, "manifest"),
|
||||
(r#"["de"]"#, "manifest"),
|
||||
(r#""de""#, "manifest"),
|
||||
("null", "expected an object"),
|
||||
(r#"{"de":null}"#, "manifest"),
|
||||
(r#"{"de":{"params":null}}"#, "expected an object"),
|
||||
(r#"{"de":{"groups":null}}"#, "expected an object"),
|
||||
(r#"{"de":{"commands":null}}"#, "expected an object"),
|
||||
(r#"{"de":{"params":{"mode":{"options":null}}}}"#, "expected an object"),
|
||||
] {
|
||||
let e = Manifest::parse(with(translations).as_bytes()).unwrap_err().to_string();
|
||||
assert!(e.contains(says), "{translations}: {e}");
|
||||
}
|
||||
// Right-to-left text without direction characters is text like any other.
|
||||
let arabic = Manifest::parse(with(r#"{"ar":{"name":"ترتيب","commands":{"c":{"label":"تكبير"}}}}"#).as_bytes()).unwrap();
|
||||
assert_eq!(arabic.name_in("ar"), "ترتيب");
|
||||
}
|
||||
|
||||
/// At most 16 languages, and the whole manifest, translations included, stays within the
|
||||
/// manifest's byte limit.
|
||||
#[test]
|
||||
fn languages_and_manifest_size_are_capped() {
|
||||
const CODES: [&str; 17] = ["de", "fr", "es", "it", "pt", "nl", "sv", "da", "fi", "pl", "cs", "hu", "ro", "tr", "ru", "uk", "ja"];
|
||||
let manifest = |n: usize| {
|
||||
let langs: Vec<String> = CODES.iter().take(n).map(|c| format!(r#""{c}":{{"name":"X"}}"#)).collect();
|
||||
format!(r#"{{"id":"a","name":"x","kind":"filter","translations":{{{}}}}}"#, langs.join(","))
|
||||
};
|
||||
assert_eq!(Manifest::parse(manifest(MAX_LANGUAGES).as_bytes()).unwrap().translations.0.len(), MAX_LANGUAGES);
|
||||
let e = Manifest::parse(manifest(MAX_LANGUAGES + 1).as_bytes()).unwrap_err().to_string();
|
||||
assert!(e.contains("`translations` gives at most 16 languages"), "{e}");
|
||||
let help = "h".repeat(crate::manifest::MAX_MANIFEST_BYTES);
|
||||
let big = format!(
|
||||
r#"{{"id":"a","name":"x","kind":"filter","params":{{"n":{{"type":"bool","help":"H"}}}},"translations":{{"de":{{"params":{{"n":{{"help":"{help}"}}}}}}}}}}"#
|
||||
);
|
||||
assert!(Manifest::parse(big.as_bytes()).unwrap_err().to_string().contains("limit"), "the manifest's byte limit applies");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn language_codes() {
|
||||
for good in ["de", "DE", "pt-br", "pt-BR", "zh-Hant", "zh-Hant-TW", "es-419", "fil", "sr-Latn-RS"] {
|
||||
assert!(valid_language_code(good), "{good}");
|
||||
}
|
||||
let long = format!("de-{}", ["abcdefgh"; 4].join("-"));
|
||||
for bad in ["", "d", "deutsch", "de-", "-de", "de--at", "de_AT", "de-a", "x-test", "i-klingon", "de-abcdefghi", "1d", long.as_str()] {
|
||||
assert!(!valid_language_code(bad), "{bad}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -185,11 +185,12 @@ pub(crate) fn heading(cx: &EffectCx) -> String {
|
||||
}
|
||||
|
||||
/// The effect's name in the UI language as the Effect menu shows it ([`crate::i18n::effect_name`]).
|
||||
/// A plug-in effect's name is shown as it is.
|
||||
/// A plug-in effect's name is the plug-in's in the UI language
|
||||
/// ([`super::plugin::effect_name`]).
|
||||
pub(crate) fn label(id: &str) -> String {
|
||||
let name = vectorcraft_effects::effect_info(id).map(|i| i.label.trim_end_matches('…').to_string()).unwrap_or_else(|| id.to_string());
|
||||
if vectorcraft_plugins::effect::plugin_id(id).is_some() {
|
||||
return name;
|
||||
return super::plugin::effect_name(id).unwrap_or(name);
|
||||
}
|
||||
crate::i18n::effect_name(crate::i18n::current(), id).unwrap_or(name)
|
||||
}
|
||||
|
||||
@@ -14,6 +14,8 @@ use craft::ui::value_drag::SliderScale;
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_plugins::{Manifest, Param as PluginParam, ParamSpec};
|
||||
|
||||
use crate::i18n::LangExt as _;
|
||||
|
||||
/// The fields of the form dialogs ([`grid_params`]) that are distances, by dialog kind.
|
||||
fn lengths(kind: &str) -> &'static [&'static str] {
|
||||
match kind {
|
||||
@@ -290,11 +292,42 @@ fn text_row(
|
||||
.opens_with(start)
|
||||
}
|
||||
|
||||
/// The row of the plug-in parameter `key`, without its visibility.
|
||||
fn plugin_row(key: &str, p: &PluginParam) -> Param {
|
||||
/// The UI language's code, which a plug-in's translations are looked up under.
|
||||
fn plugin_lang() -> &'static str {
|
||||
crate::i18n::current().code()
|
||||
}
|
||||
|
||||
/// Plug-in text `s` as a dialog shows it: each line with its control and bidirectional characters
|
||||
/// escaped ([`vectorcraft_plugins::permissions::display_text`]), so a label or help can't reorder
|
||||
/// the text around it.
|
||||
fn plugin_text(s: &str) -> String {
|
||||
let lines: Vec<String> =
|
||||
s.split('\n').map(|l| vectorcraft_plugins::permissions::display_text(l, vectorcraft_plugins::dialog::MAX_HELP)).collect();
|
||||
lines.join("\n")
|
||||
}
|
||||
|
||||
/// Parameter `k`'s `label` in manifest `m`, in the UI language as dialogs show it ([`plugin_text`]);
|
||||
/// `None` when it gives none.
|
||||
pub(crate) fn plugin_param_label(m: &Manifest, k: &str) -> Option<String> {
|
||||
m.param_label_in(k, plugin_lang()).map(plugin_text)
|
||||
}
|
||||
|
||||
/// Parameter `k`'s `help` in manifest `m`, in the UI language as dialogs show it.
|
||||
pub(crate) fn plugin_param_help(m: &Manifest, k: &str) -> Option<String> {
|
||||
m.param_help_in(k, plugin_lang()).map(plugin_text)
|
||||
}
|
||||
|
||||
/// The label of value `option` of choice `k` in manifest `m`, in the UI language as dialogs show it.
|
||||
pub(crate) fn plugin_option_label(m: &Manifest, k: &str, option: &str) -> String {
|
||||
plugin_text(m.option_label_in(k, option, plugin_lang()))
|
||||
}
|
||||
|
||||
/// The row of the plug-in parameter `key` of manifest `m`, without its visibility. Its label, help and choices are
|
||||
/// the plug-in's text in the UI language ([`vectorcraft_plugins::translations`]), escaped as [`plugin_text`] shows it.
|
||||
fn plugin_row(m: &Manifest, key: &str, p: &PluginParam) -> Param {
|
||||
let unit_text = p.ui.unit.as_deref().unwrap_or_default();
|
||||
let unit = unit_kind(unit_text);
|
||||
let base = p.ui.label.clone().unwrap_or_else(|| humanize(key));
|
||||
let base = plugin_param_label(m, key).unwrap_or_else(|| humanize(key));
|
||||
let base = base.trim_end_matches(':');
|
||||
// A unit the framework has no kind for stays in the label, so the plug-in's own unit is still shown.
|
||||
let name = Label::from(if unit.is_none() && !unit_text.is_empty() { format!("{base} ({unit_text})") } else { base.to_owned() });
|
||||
@@ -328,7 +361,7 @@ fn plugin_row(key: &str, p: &PluginParam) -> Param {
|
||||
}
|
||||
ParamSpec::Bool { default } => Param::new(key, name, ParamKind::bool(*default)),
|
||||
ParamSpec::Choice { options, default } => {
|
||||
let entries = options.iter().map(|o| (o.clone(), Label::from(o.clone()))).collect();
|
||||
let entries = options.iter().map(|o| (o.clone(), Label::from(plugin_option_label(m, key, o)))).collect();
|
||||
Param::new(key, name, ParamKind::choice(entries, default.clone()))
|
||||
}
|
||||
ParamSpec::Text { default, max_length } => text_row(
|
||||
@@ -355,8 +388,8 @@ fn plugin_row(key: &str, p: &PluginParam) -> Param {
|
||||
if let Some(unit) = unit {
|
||||
row = row.unit(unit);
|
||||
}
|
||||
if let Some(help) = &p.ui.help {
|
||||
row = row.tooltip(help.clone());
|
||||
if let Some(help) = plugin_param_help(m, key) {
|
||||
row = row.tooltip(help);
|
||||
}
|
||||
if let Some(url) = &p.ui.help_url {
|
||||
row = row.help_link(url.clone());
|
||||
@@ -365,9 +398,9 @@ fn plugin_row(key: &str, p: &PluginParam) -> Param {
|
||||
}
|
||||
|
||||
/// A plug-in's parameter rows from its manifest (the filter, live effect and exporter dialogs): a row each, labelled
|
||||
/// as the manifest says (else from the parameter's name), with its help on the label and on a help button that opens
|
||||
/// its page ([`open_help`]). Parameters outside any group come first, then each group as a section that folds
|
||||
/// ([`Manifest::sections`]).
|
||||
/// as the manifest says in the UI language (else from the parameter's name), with its help on the label and on a help
|
||||
/// button that opens its page ([`open_help`]). Parameters outside any group come first, then each group as a section
|
||||
/// that folds ([`Manifest::sections`]), headed by the group's text in the UI language.
|
||||
///
|
||||
/// A parameter whose `visibleWhen` the values don't meet is hidden by its row, as [`Manifest::visible`] decides it:
|
||||
/// shown only when every parameter it names is itself shown, so a row carries its own conditions and those of the
|
||||
@@ -391,11 +424,11 @@ pub(crate) fn plugin_params(manifest: &Manifest, _fields: &Map<String, Value>) -
|
||||
let mut rows = Vec::new();
|
||||
for (group, members) in manifest.sections() {
|
||||
if let Some(group) = group {
|
||||
rows.push(Param::group(Label::from(group.to_owned())));
|
||||
rows.push(Param::group(Label::from(plugin_text(manifest.group_in(group, plugin_lang())))));
|
||||
}
|
||||
for (key, p) in members {
|
||||
let when = conditions.remove(key.as_str()).unwrap_or_default();
|
||||
rows.push(when.into_iter().fold(plugin_row(key, p), |row, (other, allowed)| row.visible_when_in(other, allowed)));
|
||||
rows.push(when.into_iter().fold(plugin_row(manifest, key, p), |row, (other, allowed)| row.visible_when_in(other, allowed)));
|
||||
}
|
||||
}
|
||||
rows
|
||||
@@ -501,7 +534,6 @@ pub(super) fn humanized(k: &str) -> String {
|
||||
#[cfg(test)]
|
||||
mod plugin_field_tests {
|
||||
use super::*;
|
||||
use crate::i18n::LangExt as _;
|
||||
|
||||
/// [`json_of`] reads back what [`fields_of`] took in: numbers as the command reads them, a flag pair as a bool,
|
||||
/// unknown keys through, UI-only keys dropped.
|
||||
|
||||
@@ -56,6 +56,7 @@ use vectorcraft_plugins::{Budget, ContextMenu, ContextWhen, Kind, Manifest, Plug
|
||||
use super::form;
|
||||
use super::preview::LivePreview;
|
||||
use crate::VectorcraftApp;
|
||||
use crate::i18n::LangExt as _;
|
||||
use crate::menus::{Sep, c, cp, placeholder, sub};
|
||||
|
||||
/// The key of the hosted dialog of plug-in filters.
|
||||
@@ -66,6 +67,75 @@ const CMD: &str = "plugin.run";
|
||||
/// Object › Plug-ins' disabled row while no filter plug-in is installed.
|
||||
pub const NO_FILTERS: &str = "No filter plug-ins installed";
|
||||
|
||||
/// The UI language's code, which a plug-in's translations are looked up under
|
||||
/// ([`vectorcraft_plugins::translations`]): plug-in text comes from the plug-in, never from the
|
||||
/// app's catalogs.
|
||||
fn lang() -> &'static str {
|
||||
crate::i18n::current().code()
|
||||
}
|
||||
|
||||
/// Menu path `path` (English, `›`-separated) with each segment put through `tr`, except the
|
||||
/// segments after Object › Plug-ins or Effect › Plug-ins: those are a plug-in's name and its items,
|
||||
/// already in the UI language from the plug-in's translations.
|
||||
pub(crate) fn translate_path<'a>(path: &'a str, tr: impl Fn(&'a str) -> &'a str) -> String {
|
||||
let parts: Vec<&str> = path.split(" › ").collect();
|
||||
let plugin = matches!(parts.as_slice(), ["Object" | "Effect", "Plug-ins", _, ..]);
|
||||
parts.iter().enumerate().map(|(i, s)| if plugin && i >= 2 { s } else { tr(s) }).collect::<Vec<_>>().join(" › ")
|
||||
}
|
||||
|
||||
/// Plug-in `id`'s name in the UI language as menus show it, without a trailing ellipsis (`None`
|
||||
/// while no such plug-in is installed).
|
||||
pub(crate) fn shown_name(id: &str) -> Option<String> {
|
||||
registry::get(id).map(|p| p.manifest().shown_name(lang()).trim_end_matches('…').to_string())
|
||||
}
|
||||
|
||||
/// The name of live effect `effect` (an effect id) in the UI language when a plug-in gives it
|
||||
/// ([`shown_name`]); `None` for a built-in effect.
|
||||
pub(crate) fn effect_name(effect: &str) -> Option<String> {
|
||||
vectorcraft_plugins::effect::plugin_id(effect).and_then(shown_name)
|
||||
}
|
||||
|
||||
/// Effect › Plug-ins' label for live effect `e`: its plug-in's name in the UI language, with an
|
||||
/// ellipsis when it opens a dialog ([`label`]); the catalog's label once the plug-in is gone.
|
||||
pub(crate) fn effect_item_label(e: &vectorcraft_effects::EffectInfo) -> &'static str {
|
||||
match vectorcraft_plugins::effect::plugin_id(e.id).and_then(registry::get) {
|
||||
Some(p) => label(&p.manifest().shown_name(lang()), !p.manifest().params.is_empty()),
|
||||
None => e.label,
|
||||
}
|
||||
}
|
||||
|
||||
/// The menu label of plug-in item `key` (`plugin:<filter id>` or `effect:<effect id>`) in language
|
||||
/// `code`, as [`object_menu`] and [`effect_menu`] show it in that language; `None` for any other key
|
||||
/// or a plug-in that is not installed.
|
||||
pub(crate) fn item_label_in(key: &str, code: &str) -> Option<&'static str> {
|
||||
let m = item_plugin(key)?;
|
||||
let m = m.manifest();
|
||||
Some(label(&m.shown_name(code), !m.params.is_empty()))
|
||||
}
|
||||
|
||||
/// Menu path `group` of plug-in item `key` ([`item_label_in`]) with its plug-in's submenu, the
|
||||
/// segment after Object › Plug-ins or Effect › Plug-ins, named in language `code`; `group` as it
|
||||
/// is for an item without a submenu.
|
||||
pub(crate) fn item_group_in(key: &str, group: &str, code: &str) -> String {
|
||||
let mut parts: Vec<String> = group.split(" › ").map(str::to_string).collect();
|
||||
if parts.get(1).is_some_and(|p| p == "Plug-ins")
|
||||
&& let (Some(plugin), Some(submenu)) = (item_plugin(key), parts.get_mut(2))
|
||||
{
|
||||
*submenu = plugin.manifest().shown_name(code);
|
||||
}
|
||||
parts.join(" › ")
|
||||
}
|
||||
|
||||
/// The plug-in of item `key` (`plugin:<filter id>` or `effect:<effect id>`), if it is installed.
|
||||
fn item_plugin(key: &str) -> Option<Arc<Plugin>> {
|
||||
let id = match (key.strip_prefix("plugin:"), key.strip_prefix("effect:")) {
|
||||
(Some(id), _) => id,
|
||||
(_, Some(effect)) => vectorcraft_plugins::effect::plugin_id(effect)?,
|
||||
_ => return None,
|
||||
};
|
||||
registry::get(id)
|
||||
}
|
||||
|
||||
/// A menu label for plug-in `name`: with an ellipsis when it opens a dialog.
|
||||
fn label(name: &str, has_params: bool) -> &'static str {
|
||||
let dots = if has_params && !name.ends_with('…') { "…" } else { "" };
|
||||
@@ -75,7 +145,7 @@ fn label(name: &str, has_params: bool) -> &'static str {
|
||||
/// A filter or live effect `plugin`'s item `own`, as the menu lists it: alone, or for a plug-in
|
||||
/// with commands of its own, a submenu named after it holding `own` and then its commands. Each
|
||||
/// command runs its command id (`plugin.<id>.<command>`), with an ellipsis when it has parameters,
|
||||
/// whose dialog [`open_command`] opens.
|
||||
/// whose dialog [`open_command`] opens. Names and labels are in the UI language.
|
||||
fn with_commands(plugin: &Plugin, own: Node) -> Node {
|
||||
let m = plugin.manifest();
|
||||
if m.commands.is_empty() {
|
||||
@@ -84,9 +154,9 @@ fn with_commands(plugin: &Plugin, own: Node) -> Node {
|
||||
let mut items = vec![own, Sep];
|
||||
items.extend(m.commands.iter().map(|command| {
|
||||
let id = registry::intern(&vectorcraft_engine::cmd::plugin::command_id(&m.id, &command.id));
|
||||
c(label(&command.shown_label(), !command.params.is_empty()), id)
|
||||
c(label(&m.shown_command_label(command, lang()), !command.params.is_empty()), id)
|
||||
}));
|
||||
sub(registry::intern(&permissions::display_text(m.name.trim(), permissions::MAX_SHOWN_NAME)), items)
|
||||
sub(registry::intern(&m.shown_name(lang())), items)
|
||||
}
|
||||
|
||||
/// Moves each plug-in command whose manifest's `menu` names another menu
|
||||
@@ -116,7 +186,7 @@ pub fn place_commands(tree: &mut [(&'static str, Vec<Node>)]) {
|
||||
menu.iter().find(|it| is_anchor(it, anchor_key(a))).and_then(own_key).map(str::to_string)
|
||||
});
|
||||
let id = registry::intern(&vectorcraft_engine::cmd::plugin::command_id(&m.id, &command.id));
|
||||
let item = c(label(&command.menu_label(&m.name), !command.params.is_empty()), id);
|
||||
let item = c(label(&m.shown_command_menu_label(command, lang()), !command.params.is_empty()), id);
|
||||
match spots.iter_mut().find(|s| s.0 == place.path && s.1 == after) {
|
||||
Some(s) => s.2.push(item),
|
||||
None => spots.push((place.path, after, vec![item])),
|
||||
@@ -274,13 +344,16 @@ pub fn canvas_item_enabled(app: &VectorcraftApp, id: &str, p: &Value) -> bool {
|
||||
}
|
||||
|
||||
/// Object › Plug-ins: the installed object filters (each with its commands, if it has any) and
|
||||
/// generators, then Edit Generated Art…, Install Plug-in…, Reload Plug-ins and Plug-ins That Didn't
|
||||
/// Load… ([`super::failed_plugins`]).
|
||||
/// generators by their names in the UI language, then Edit Generated Art…, Install Plug-in…, Reload
|
||||
/// Plug-ins and Plug-ins That Didn't Load… ([`super::failed_plugins`]).
|
||||
pub fn object_menu() -> Vec<Node> {
|
||||
let mut items: Vec<Node> = registry::list()
|
||||
.iter()
|
||||
.filter(|p| matches!(p.manifest().kind, Kind::Filter | Kind::Generator))
|
||||
.map(|p| with_commands(p, cp(label(&p.manifest().name, !p.manifest().params.is_empty()), "plugin.dialog", json!({ "id": p.id() }))))
|
||||
.map(|p| {
|
||||
let m = p.manifest();
|
||||
with_commands(p, cp(label(&m.shown_name(lang()), !m.params.is_empty()), "plugin.dialog", json!({ "id": p.id() })))
|
||||
})
|
||||
.collect();
|
||||
if items.is_empty() {
|
||||
items.push(placeholder(NO_FILTERS));
|
||||
@@ -298,11 +371,15 @@ pub fn object_menu() -> Vec<Node> {
|
||||
/// File › Open With's disabled row while no importer plug-in is installed.
|
||||
pub const NO_IMPORTERS: &str = "No importer plug-ins installed";
|
||||
|
||||
/// File › Open With: the installed importers (`file.openWith {importer}`), each by its name.
|
||||
/// File › Open With: the installed importers (`file.openWith {importer}`), each by its name in the
|
||||
/// UI language.
|
||||
pub fn open_with_menu() -> Vec<Node> {
|
||||
let items: Vec<Node> = vectorcraft_plugins::import::installed()
|
||||
.iter()
|
||||
.map(|p| cp(label(&p.manifest().name, true), "file.openWith", json!({ "importer": vectorcraft_plugins::export::format_id(p.id()) })))
|
||||
.map(|p| {
|
||||
let importer = vectorcraft_plugins::export::format_id(p.id());
|
||||
cp(label(&p.manifest().shown_name(lang()), true), "file.openWith", json!({ "importer": importer }))
|
||||
})
|
||||
.collect();
|
||||
if items.is_empty() { vec![placeholder(NO_IMPORTERS)] } else { items }
|
||||
}
|
||||
@@ -313,9 +390,10 @@ pub fn effect_menu() -> Option<Node> {
|
||||
let items: Vec<Node> = vectorcraft_effects::plugin_effects()
|
||||
.into_iter()
|
||||
.map(|e| {
|
||||
let label = effect_item_label(&e);
|
||||
let own = match e.defaults.as_object().is_some_and(|o| o.is_empty()) {
|
||||
true => cp(e.label, "effect.apply", json!({ "effect": e.id })),
|
||||
false => cp(e.label, "effect.dialog", json!({ "effect": e.id })),
|
||||
true => cp(label, "effect.apply", json!({ "effect": e.id })),
|
||||
false => cp(label, "effect.dialog", json!({ "effect": e.id })),
|
||||
};
|
||||
match vectorcraft_plugins::effect::plugin_id(e.id).and_then(registry::get) {
|
||||
Some(plugin) => with_commands(&plugin, own),
|
||||
@@ -432,7 +510,12 @@ impl Opened {
|
||||
|
||||
/// How a hosted plug-in dialog looks.
|
||||
struct Look {
|
||||
/// The heading: the plug-in's or command's label, as it is (plug-in text is never translated).
|
||||
/// The plug-in the dialog is for.
|
||||
plugin: String,
|
||||
/// The plug-in command the dialog is for (`plugin.<plug-in id>.<command id>`); `None` for the
|
||||
/// plug-in's own dialog.
|
||||
command: Option<String>,
|
||||
/// The heading once the plug-in or command is gone: its manifest's own text ([`Look::heading`]).
|
||||
title: String,
|
||||
/// The plug-in's description, drawn above the rows.
|
||||
description: String,
|
||||
@@ -444,17 +527,44 @@ struct Look {
|
||||
ok: Option<&'static str>,
|
||||
}
|
||||
|
||||
impl Look {
|
||||
/// The heading ([`heading`]), read each time the dialog is built so a change of language shows at once.
|
||||
fn heading(&self) -> String {
|
||||
heading(&self.plugin, self.command.as_deref(), &self.title)
|
||||
}
|
||||
}
|
||||
|
||||
/// The heading of the dialog of plug-in `plugin`, or of its command `command`
|
||||
/// (`plugin.<plug-in id>.<command id>`): the command's label, else the plug-in's name, in the UI language as menus
|
||||
/// show it; `gone` once the plug-in or command is no longer installed.
|
||||
pub(super) fn heading(plugin: &str, command: Option<&str>, gone: &str) -> String {
|
||||
let shown = match command {
|
||||
None => shown_name(plugin),
|
||||
Some(c) => vectorcraft_engine::cmd::plugin::command_of(c).map(|(p, c)| p.manifest().shown_command_label(&c, lang())),
|
||||
};
|
||||
shown.unwrap_or_else(|| gone.to_string())
|
||||
}
|
||||
|
||||
/// The builder of a hosted plug-in dialog over its values: the rows of `all` whose parameter is
|
||||
/// shown for the values (`m.visible`), after the description.
|
||||
/// shown for the values (`m.visible`), after the description. The rows are made again in the UI
|
||||
/// language when it changes while the dialog is open; the field values stay as they are.
|
||||
fn build(key: &'static str, m: Manifest, all: Arc<[Param]>, look: Look) -> impl for<'b> Fn(&'b mut DialogFields) -> ParamDialog<'b> + Send + 'static {
|
||||
let rows_in = std::sync::Mutex::new((lang(), all));
|
||||
move |fields| {
|
||||
let all = {
|
||||
let mut made = rows_in.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if made.0 != lang() {
|
||||
*made = (lang(), form::plugin_params(&m, &m.defaults()).into());
|
||||
}
|
||||
Arc::clone(&made.1)
|
||||
};
|
||||
let shown = m.visible(&form::json_of(&all, fields));
|
||||
let mut rows = Vec::with_capacity(all.len() + 1);
|
||||
if !look.description.is_empty() {
|
||||
rows.push(Param::read_only_text("description", "", look.description.clone()).full_width());
|
||||
}
|
||||
rows.extend(all.iter().filter(|p| shown.contains(p.key.as_str())).cloned());
|
||||
let mut dialog = ParamDialog::new(key, look.title.clone(), Cow::Owned(rows)).previews(look.previews);
|
||||
let mut dialog = ParamDialog::new(key, look.heading(), Cow::Owned(rows)).previews(look.previews);
|
||||
if let Some(ok) = look.ok {
|
||||
dialog = dialog.ok_label(ok.into());
|
||||
}
|
||||
@@ -731,7 +841,15 @@ fn open_filter(
|
||||
let own = plugin.manifest();
|
||||
let heavy = own.budget == Budget::Heavy;
|
||||
let light = !heavy && !crate::plugin_runs::in_workers(app);
|
||||
let look = Look { title: heading.clone(), description: own.description.clone(), previews: light, note: heavy, ok: None };
|
||||
let look = Look {
|
||||
plugin: plugin.id().to_string(),
|
||||
command: command.clone(),
|
||||
title: heading.clone(),
|
||||
description: own.description.clone(),
|
||||
previews: light,
|
||||
note: heavy,
|
||||
ok: None,
|
||||
};
|
||||
let instance = command.as_deref().unwrap_or(plugin.id()).to_string();
|
||||
let (id, params) = open_hosted(app, KIND, &instance, m, values, look)?;
|
||||
let kind = Opened::Filter {
|
||||
@@ -830,7 +948,15 @@ const EDIT_DOC_GONE: &str = "the document it was prepared for is no longer activ
|
||||
/// defaults, for new generated art, or for drawing the object of `edit` again.
|
||||
fn open_generate(app: &mut VectorcraftApp, plugin: &Plugin, edit: Option<EditTarget>, values: &Map<String, Value>) -> Result<(), String> {
|
||||
let m = plugin.manifest();
|
||||
let look = Look { title: m.name.trim_end_matches('…').to_string(), description: m.description.clone(), previews: false, note: false, ok: None };
|
||||
let look = Look {
|
||||
plugin: plugin.id().to_string(),
|
||||
command: None,
|
||||
title: m.name.trim_end_matches('…').to_string(),
|
||||
description: m.description.clone(),
|
||||
previews: false,
|
||||
note: false,
|
||||
ok: None,
|
||||
};
|
||||
let rows = vectorcraft_plugins::generate::resolve_over(plugin, values, &Value::Null).map_err(|error| error.to_string())?;
|
||||
let (id, params) = open_hosted(app, GENERATE_KIND, plugin.id(), m.clone(), rows, look)?;
|
||||
app.plugin_dialog = Some(PluginDialog { id, kind: Opened::Generate { plugin: plugin.id().to_string(), edit, params } });
|
||||
@@ -889,6 +1015,8 @@ pub const IMPORT_KIND: &str = "pluginImport";
|
||||
pub fn open_export(app: &mut VectorcraftApp, plugin: &Plugin, export: Value) {
|
||||
let m = plugin.manifest();
|
||||
let look = Look {
|
||||
plugin: plugin.id().to_string(),
|
||||
command: None,
|
||||
title: m.name.trim_end_matches('…').to_string(),
|
||||
description: m.description.clone(),
|
||||
previews: false,
|
||||
@@ -910,6 +1038,8 @@ pub fn open_export(app: &mut VectorcraftApp, plugin: &Plugin, export: Value) {
|
||||
pub fn open_import(app: &mut VectorcraftApp, plugin: &Plugin, open: Value) {
|
||||
let m = plugin.manifest();
|
||||
let look = Look {
|
||||
plugin: plugin.id().to_string(),
|
||||
command: None,
|
||||
title: m.name.trim_end_matches('…').to_string(),
|
||||
description: m.description.clone(),
|
||||
previews: false,
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
//! A script's ScriptUI dialog is in [`script_window`]; these questions and dialogs open over it.
|
||||
//!
|
||||
//! `ui.runScript {path? | source?, name?}` shows the warning for that script; without either it
|
||||
//! asks for a `.js` or `.jsx` file through the app's file asks. With Preferences › General › Show
|
||||
//! asks for a `.js`, `.mjs` or `.jsx` file through the app's file asks. With Preferences › General › Show
|
||||
//! External Script Warning off, the chosen script runs at once. With General › Run Startup Scripts
|
||||
//! on, the startup scripts run first (`script.startup.run`). The warning (kind `scriptRun`) is a
|
||||
//! prompt: its `choice` field (`proceed` runs, `cancel` does not), `skip` (true: turn the warning
|
||||
@@ -551,7 +551,8 @@ pub(crate) fn picked_script(app: &mut VectorcraftApp, picked: Picked) -> Result<
|
||||
return Err(TOO_LARGE.to_string());
|
||||
}
|
||||
let source = String::from_utf8(bytes).map_err(|_| "the script is not UTF-8 text".to_string())?;
|
||||
return chosen(app, json!({"source": source, "name": name}));
|
||||
let module = Path::new(&name).extension().is_some_and(|e| e.eq_ignore_ascii_case("mjs"));
|
||||
return chosen(app, json!({"source": source, "name": name, "module": module}));
|
||||
}
|
||||
match picked.paths().into_iter().next() {
|
||||
Some(path) => chosen(app, json!({ "path": path.to_string_lossy() })),
|
||||
@@ -563,7 +564,7 @@ pub(crate) fn picked_script(app: &mut VectorcraftApp, picked: Picked) -> Result<
|
||||
pub(crate) fn chosen(app: &mut VectorcraftApp, params: Value) -> Result<Value, String> {
|
||||
let path = params.get("path").and_then(Value::as_str);
|
||||
if path.is_some_and(|path| !runs(path)) {
|
||||
return Err("Choose a .js or .jsx script".into());
|
||||
return Err("Choose a .js, .mjs or .jsx script".into());
|
||||
}
|
||||
if !app.session.prefs.show_external_script_warning {
|
||||
return crate::script_runs::run_chosen(app, params);
|
||||
|
||||
@@ -11,6 +11,7 @@ use vectorcraft_plugins::wat as tpl;
|
||||
use super::tests_export::fields;
|
||||
use super::tests_plugin_export::top;
|
||||
use crate::VectorcraftApp;
|
||||
use crate::i18n::LangExt as _;
|
||||
|
||||
/// A filter whose parameters use every presentation key.
|
||||
fn manifest(id: &str) -> String {
|
||||
@@ -33,9 +34,14 @@ type Harness = egui_kittest::Harness<'static, VectorcraftApp>;
|
||||
|
||||
/// The dialog of plug-in `id` in a window running whole app frames.
|
||||
fn harness(id: &str) -> Harness {
|
||||
harness_of(id, &manifest(id))
|
||||
}
|
||||
|
||||
/// The dialog of plug-in `id`, installed from `manifest`, in a window running whole app frames.
|
||||
fn harness_of(id: &str, manifest: &str) -> Harness {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
|
||||
let wasm = wat::parse_str(tpl::module(&manifest(id), tpl::ECHO, "", 1)).unwrap();
|
||||
let wasm = wat::parse_str(tpl::module(manifest, tpl::ECHO, "", 1)).unwrap();
|
||||
app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wasm)})).unwrap();
|
||||
let mut fonts = false;
|
||||
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 800.0)).build_ui_state(
|
||||
@@ -155,3 +161,99 @@ fn the_help_button_opens_the_parameter_s_page() {
|
||||
assert!(opened(&h).is_empty(), "nothing opened for automation");
|
||||
remove(&mut h, id);
|
||||
}
|
||||
|
||||
/// A row of a plug-in's dialog as shown: its key, its label and its choices' (value, label) pairs.
|
||||
type ShownRow = (String, String, Vec<(String, String)>);
|
||||
|
||||
/// A plug-in's dialog shows the text its manifest's `translations` give in the UI language (the
|
||||
/// heading, a label, a group heading and a choice's label) and its own text in any other language;
|
||||
/// the choice still passes its value. Plug-in text with a right-to-left override is shown escaped.
|
||||
#[test]
|
||||
fn plugin_dialogs_show_the_plugins_text_in_the_ui_language() {
|
||||
let id = "test.dialogs.translated";
|
||||
// The override as a JSON escape in the manifest.
|
||||
let rlo = format!("\\u{:04X}", 0x202E);
|
||||
let manifest = format!(
|
||||
r#"{{"id":"{id}","name":"Tidy","kind":"filter","params":{{
|
||||
"mode":{{"type":"choice","options":["soft","hard"],"label":"Mode","group":"Shape","help":"How hard."}},
|
||||
"flip":{{"type":"bool","label":"Flip{rlo}txt"}}}},
|
||||
"commands":[{{"id":"grow","label":"Grow","params":{{"by":{{"type":"number","min":0,"max":10,"default":2,"label":"By"}}}}}}],
|
||||
"translations":{{"de":{{"name":"Aufräumen","params":{{"mode":{{"label":"Modus","options":{{"soft":"Weich"}}}}}},
|
||||
"groups":{{"Shape":"Form"}},"commands":{{"grow":{{"label":"Wachsen","params":{{"by":{{"label":"Um"}}}}}}}}}}}}}}"#
|
||||
);
|
||||
let module = wat::parse_str(tpl::returning(&manifest, r#"{"objects":[]}"#)).unwrap();
|
||||
let installed = vectorcraft_plugins::registry::install_bytes(&module).unwrap();
|
||||
// The rows' labels, section headings and choice labels in `lang`, as (key, label, choices).
|
||||
let shown = |lang: &str, m: &vectorcraft_plugins::Manifest| {
|
||||
crate::i18n::set_current(crate::i18n::Lang::from_code(lang).expect("language registered"));
|
||||
let rows = super::form::plugin_params(m, &Map::new());
|
||||
crate::i18n::set_current(crate::i18n::Lang::EN);
|
||||
rows.iter()
|
||||
.map(|p| {
|
||||
let choices: Vec<(String, String)> = match &p.kind {
|
||||
craft::ui::patterns::form_dialogs::ParamKind::Choice { options, .. } => {
|
||||
options.iter().map(|(v, l)| (v.clone(), l.as_str().to_string())).collect()
|
||||
}
|
||||
_ => Vec::new(),
|
||||
};
|
||||
(p.key.clone(), p.label.as_str().to_string(), choices)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
let label = |rows: &[ShownRow], key: &str| rows.iter().find(|r| r.0 == key).map(|r| r.1.clone()).unwrap_or_else(|| panic!("no row for {key}"));
|
||||
let sections = |rows: &[ShownRow]| rows.iter().filter(|r| r.0.starts_with("section:")).map(|r| r.1.clone()).collect::<Vec<_>>();
|
||||
let choices = |rows: &[ShownRow]| rows.iter().find(|r| r.0 == "mode").map(|r| r.2.clone()).unwrap_or_default();
|
||||
let m = installed.manifest();
|
||||
let (de, en) = (shown("de", m), shown("en", m));
|
||||
assert_eq!((label(&de, "mode"), sections(&de)), ("Modus".to_string(), vec!["Form".to_string()]));
|
||||
assert_eq!(choices(&de), [("soft".to_string(), "Weich".to_string()), ("hard".to_string(), "hard".to_string())], "values stay");
|
||||
assert_eq!((label(&en, "mode"), sections(&en)), ("Mode".to_string(), vec!["Shape".to_string()]));
|
||||
assert_eq!(choices(&en), [("soft".to_string(), "soft".to_string()), ("hard".to_string(), "hard".to_string())]);
|
||||
assert_eq!(label(&de, "flip"), "Flip\\u{202E}txt");
|
||||
assert!(!de.iter().chain(&en).any(|r| r.1.contains('\u{202E}')), "the override is never shown as one");
|
||||
// The heading follows the language it is drawn in, for the filter and for its command.
|
||||
let command = format!("plugin.{id}.grow");
|
||||
let heading = |lang: &str, command: Option<&str>, gone: &str| {
|
||||
crate::i18n::set_current(crate::i18n::Lang::from_code(lang).unwrap());
|
||||
let shown = super::plugin::heading(id, command, gone);
|
||||
crate::i18n::set_current(crate::i18n::Lang::EN);
|
||||
shown
|
||||
};
|
||||
assert_eq!((heading("de", None, "Tidy"), heading("en", None, "Tidy")), ("Aufräumen".to_string(), "Tidy".to_string()));
|
||||
assert_eq!((heading("de", Some(&command), "Grow"), heading("fr", Some(&command), "Grow")), ("Wachsen".to_string(), "Grow".to_string()));
|
||||
let grow = m.for_command(m.command("grow").unwrap());
|
||||
assert_eq!(label(&shown("de", &grow), "by"), "Um");
|
||||
vectorcraft_plugins::registry::remove(id);
|
||||
assert_eq!(heading("de", None, "Tidy"), "Tidy", "the manifest's own name once the plug-in is gone");
|
||||
}
|
||||
|
||||
/// A change of the UI language while a plug-in's dialog is open shows its rows in the new
|
||||
/// language, and the values set before stay.
|
||||
#[test]
|
||||
fn an_open_plugin_dialog_follows_a_change_of_language() {
|
||||
use craft::ui::patterns::form_dialogs::HostedParamDialog;
|
||||
let id = "test.ui.fields.relabel";
|
||||
let manifest = format!(
|
||||
r#"{{"id":"{id}","name":"Relabel","version":"1","kind":"filter","params":{{
|
||||
"size":{{"type":"number","min":1,"max":9,"default":3,"label":"Size"}}}},
|
||||
"translations":{{"de":{{"params":{{"size":{{"label":"Größe"}}}}}}}}}}"#
|
||||
);
|
||||
let mut h = harness_of(id, &manifest);
|
||||
let labels = |h: &Harness| {
|
||||
let dialog = h.get_by_role(egui::accesskit::Role::Dialog);
|
||||
(dialog.query_all_by_label_contains("Size").count() > 0, dialog.query_all_by_label_contains("Größe").count() > 0)
|
||||
};
|
||||
assert_eq!(labels(&h), (true, false));
|
||||
set(&mut h, "size", json!(7)).unwrap();
|
||||
h.state_mut().session.prefs.interface_language = "de".into();
|
||||
h.run_steps(2);
|
||||
let shown = labels(&h);
|
||||
let rows = super::form::plugin_params(vectorcraft_plugins::registry::get(id).unwrap().manifest(), &Map::new());
|
||||
let dialogs = h.state().dialogs().unwrap();
|
||||
let values = dialogs.with(|host| host.get::<HostedParamDialog>().map(|d| super::form::json_of(&rows, d.fields())));
|
||||
h.state_mut().session.prefs.interface_language = "en".into();
|
||||
h.run_steps(2);
|
||||
remove(&mut h, id);
|
||||
assert_eq!(shown, (false, true), "the label in German");
|
||||
assert_eq!(values.unwrap()["size"].as_f64(), Some(7.0), "the value set before");
|
||||
}
|
||||
@@ -7390,6 +7390,7 @@ axis Y Axis Y ос
|
||||
# Plug-in permissions (Install Plug-in…, plugin.install grant)
|
||||
Install “{name}”, which asks for these permissions? Да се инсталира ли „{name}“, който иска тези права?
|
||||
ID: {id} ID: {id}
|
||||
Manifest name: {name} Име в манифеста: {name}
|
||||
Version: {version} Версия: {version}
|
||||
Install “{name}” in place of the plug-in with the same ID? Да се инсталира ли „{name}“ на мястото на приставката със същия ID?
|
||||
This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Този файл не е приставката, инсталирана преди с този ID. Той получава настройките и кеша, пазени за този ID.
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -6745,6 +6745,7 @@ axis Y Axis Y osa
|
||||
# Plug-in permissions (Install Plug-in…, plugin.install grant)
|
||||
Install “{name}”, which asks for these permissions? Instalirati „{name}”, koji traži ove dozvole?
|
||||
ID: {id} ID: {id}
|
||||
Manifest name: {name} Naziv u manifestu: {name}
|
||||
Version: {version} Verzija: {version}
|
||||
Install “{name}” in place of the plug-in with the same ID? Instalirati „{name}” umjesto dodatka s istim ID-om?
|
||||
This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Ova datoteka nije dodatak ranije instaliran s ovim ID-om. Dobija postavke i predmemoriju sačuvane za taj ID.
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -6466,7 +6466,7 @@ digits Malayalam Malaiàlam
|
||||
Do not show this warning again No tornis a mostrar aquest avís
|
||||
Stop the script and undo what it did? Then quit again. Voleu aturar l'script i desfer el que ha fet? Després, torneu a sortir.
|
||||
This script has added a great many objects. Continue, or stop it and undo what it did? Aquest script ha afegit moltíssims objectes. Voleu continuar, o aturar-lo i desfer el que ha fet?
|
||||
@msg Choose a .js or .jsx script Trieu un script .js o .jsx
|
||||
@msg Choose a .js, .mjs or .jsx script Trieu un script .js, .mjs o .jsx
|
||||
@msg Ran {name} S'ha executat {name}
|
||||
@msg The script was stopped and its changes were undone L'script s'ha aturat i s'han desfet els seus canvis
|
||||
@msg a script is running: stop it or wait for it to finish s'està executant un script: atureu-lo o espereu que acabi
|
||||
@@ -6638,7 +6638,7 @@ liquify-list-end {0}, {1} {0} i {1}
|
||||
@msg `args` is larger than 1 MiB `args` ocupa més d'1 MiB
|
||||
@msg `path` is empty `path` és buit
|
||||
@msg `installed` takes a `path`, not a `source` `installed` admet un `path`, no un `source`
|
||||
@msg `path` must name a .js or .jsx file `path` ha d’indicar un fitxer .js o .jsx
|
||||
@msg `path` must name a .js, .mjs or .jsx file `path` ha d’indicar un fitxer .js, .mjs o .jsx
|
||||
@msg give exactly one of `path` and `source` indiqueu exactament un de `path` i `source`
|
||||
@msg Running a script S'està executant un script
|
||||
@msg Copied the script report S’ha copiat l’informe de l’script
|
||||
@@ -7906,6 +7906,7 @@ variable-list-end {0}, {1} {0} i {1}
|
||||
# Plug-in permissions (Install Plug-in…, plugin.install grant)
|
||||
Install “{name}”, which asks for these permissions? Instal·la «{name}», que demana aquests permisos?
|
||||
ID: {id} ID: {id}
|
||||
Manifest name: {name} Nom al manifest: {name}
|
||||
Version: {version} Versió: {version}
|
||||
Install “{name}” in place of the plug-in with the same ID? Instal·la «{name}» en lloc del complement amb el mateix ID?
|
||||
This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Aquest fitxer no és el complement instal·lat abans amb aquest ID. Rep la configuració i la memòria cau desades per a aquest ID.
|
||||
@@ -8019,6 +8020,11 @@ variable-list-end {0}, {1} {0} i {1}
|
||||
@msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed a «{name}» no se li ha concedit `{p}`, que la seva sortida necessita: no s’ha canviat res
|
||||
@msg a heavy filter runs in the background, so it can't declare `commands` un filtre pesat s’executa en segon pla, de manera que no pot declarar `commands`
|
||||
@msg at most {MAX_COMMANDS} `commands` com a màxim {MAX_COMMANDS} `commands`
|
||||
@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` dona com a màxim {MAX_LANGUAGES} idiomes
|
||||
@msg {at} gives two options the same label {at} dona la mateixa etiqueta a dues opcions
|
||||
@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} no és un codi d’idioma com `de` o `pt-BR`, o en repeteix un de donat abans
|
||||
@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} ha de tenir 1-{max} caràcters imprimibles, sense caràcters de direcció ni separadors de línia
|
||||
@msg {at} names or translates something the manifest doesn't declare {at} anomena o tradueix alguna cosa que el manifest no declara
|
||||
@msg command {name} is declared twice l’ordre {name} està declarada dues vegades
|
||||
@msg command {name}: `label` must be 1-64 printable characters ordre {name}: `label` ha de tenir 1-64 caràcters imprimibles
|
||||
@msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter ordre {name}: fes servir un id d’1-{MAX_COMMAND_ID} caràcters d’a-z 0-9 _ que comenci per una lletra
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -5273,7 +5273,7 @@ imageTrace Outline Obrys
|
||||
Do not show this warning again Toto upozornění již nezobrazovat
|
||||
Stop the script and undo what it did? Then quit again. Zastavit skript a vrátit jeho změny? Potom aplikaci ukončete znovu.
|
||||
This script has added a great many objects. Continue, or stop it and undo what it did? Tento skript přidal velmi mnoho objektů. Pokračovat, nebo jej zastavit a vrátit jeho změny?
|
||||
@msg Choose a .js or .jsx script Vyberte skript .js nebo .jsx
|
||||
@msg Choose a .js, .mjs or .jsx script Vyberte skript .js, .mjs nebo .jsx
|
||||
@msg Ran {name} Spuštěno: {name}
|
||||
@msg The script was stopped and its changes were undone Skript byl zastaven a jeho změny byly vráceny
|
||||
@msg a script is running: stop it or wait for it to finish běží skript: zastavte jej nebo počkejte na jeho dokončení
|
||||
@@ -5420,7 +5420,7 @@ liquify-list-end {0}, {1} {0} a {1}
|
||||
@msg `args` is larger than 1 MiB `args` je větší než 1 MiB
|
||||
@msg `path` is empty `path` je prázdný
|
||||
@msg `installed` takes a `path`, not a `source` `installed` přijímá `path`, ne `source`
|
||||
@msg `path` must name a .js or .jsx file `path` musí označovat soubor .js nebo .jsx
|
||||
@msg `path` must name a .js, .mjs or .jsx file `path` musí označovat soubor .js, .mjs nebo .jsx
|
||||
@msg give exactly one of `path` and `source` zadejte právě jedno z `path` a `source`
|
||||
@msg Running a script Běží skript
|
||||
@msg Copied the script report Zpráva o skriptu zkopírována
|
||||
@@ -7517,6 +7517,7 @@ axis Y Axis osa Y
|
||||
# Plug-in permissions (Install Plug-in…, plugin.install grant)
|
||||
Install “{name}”, which asks for these permissions? Nainstalovat „{name}“, který žádá o tato oprávnění?
|
||||
ID: {id} ID: {id}
|
||||
Manifest name: {name} Název v manifestu: {name}
|
||||
Version: {version} Verze: {version}
|
||||
Install “{name}” in place of the plug-in with the same ID? Nainstalovat „{name}“ místo zásuvného modulu se stejným ID?
|
||||
This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Tento soubor není zásuvný modul dříve nainstalovaný s tímto ID. Získá nastavení a mezipaměť uchovávané pro toto ID.
|
||||
@@ -7630,6 +7631,11 @@ axis Y Axis osa Y
|
||||
@msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed „{name}“ nedostal `{p}`, které jeho výstup potřebuje: nic se nezměnilo
|
||||
@msg a heavy filter runs in the background, so it can't declare `commands` těžký filtr běží na pozadí, takže nemůže deklarovat `commands`
|
||||
@msg at most {MAX_COMMANDS} `commands` nejvýše {MAX_COMMANDS} `commands`
|
||||
@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` uvádí nejvýše {MAX_LANGUAGES} jazyků
|
||||
@msg {at} gives two options the same label {at} dává dvěma možnostem stejný popisek
|
||||
@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} není kód jazyka jako `de` nebo `pt-BR`, nebo opakuje kód uvedený dříve
|
||||
@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} musí mít 1-{max} tisknutelných znaků, bez znaků směru textu a oddělovačů řádků
|
||||
@msg {at} names or translates something the manifest doesn't declare {at} pojmenovává nebo překládá něco, co manifest nedeklaruje
|
||||
@msg command {name} is declared twice příkaz {name} je deklarován dvakrát
|
||||
@msg command {name}: `label` must be 1-64 printable characters příkaz {name}: `label` musí mít 1-64 tisknutelných znaků
|
||||
@msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter příkaz {name}: použijte id o 1-{MAX_COMMAND_ID} znacích z a-z 0-9 _, které začíná písmenem
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -54,7 +54,7 @@
|
||||
@msg it decompresses to more than {_1} MB den udpakkes til mere end {_1} MB
|
||||
@msg its editing data is for a different page dens redigeringsdata er til en anden side
|
||||
@msg `fontHeightReference` must be "emBox", "capHeight", "xHeight" or "icfBox" `fontHeightReference` skal være "emBox", "capHeight", "xHeight" eller "icfBox"
|
||||
@msg Choose a .js or .jsx script Vælg et .js- eller .jsx-script
|
||||
@msg Choose a .js, .mjs or .jsx script Vælg et .js-, .mjs- eller .jsx-script
|
||||
@msg Ran {name} Kørte {name}
|
||||
@msg The script was stopped and its changes were undone Scriptet blev stoppet, og dets ændringer blev fortrudt
|
||||
@msg a script is running: stop it or wait for it to finish et script kører: stop det, eller vent, til det er færdigt
|
||||
@@ -245,7 +245,7 @@ liquify-list-end {0}, {1} {0} og {1}
|
||||
@msg `args` is larger than 1 MiB `args` er større end 1 MiB
|
||||
@msg `path` is empty `path` er tom
|
||||
@msg `installed` takes a `path`, not a `source` `installed` tager en `path`, ikke en `source`
|
||||
@msg `path` must name a .js or .jsx file `path` skal angive en .js- eller .jsx-fil
|
||||
@msg `path` must name a .js, .mjs or .jsx file `path` skal angive en .js-, .mjs- eller .jsx-fil
|
||||
@msg give exactly one of `path` and `source` angiv præcis én af `path` og `source`
|
||||
@msg Running a script Kører et script
|
||||
@msg Data Recovery can't keep copies in {path}: {e} Datagendannelse kan ikke opbevare kopier i {path}: {e}
|
||||
@@ -797,6 +797,11 @@ liquify-list-end {0}, {1} {0} og {1}
|
||||
@msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed »{name}« fik ikke tildelt `{p}`, som dets output kræver: intet blev ændret
|
||||
@msg a heavy filter runs in the background, so it can't declare `commands` et tungt filter kører i baggrunden, så det kan ikke angive `commands`
|
||||
@msg at most {MAX_COMMANDS} `commands` højst {MAX_COMMANDS} `commands`
|
||||
@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` angiver højst {MAX_LANGUAGES} sprog
|
||||
@msg {at} gives two options the same label {at} giver to valgmuligheder samme etiket
|
||||
@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} er ikke en sprogkode som `de` eller `pt-BR`, eller gentager en, der er angivet før
|
||||
@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} skal være 1-{max} tegn, der kan udskrives, uden retnings- eller linjeskilletegn
|
||||
@msg {at} names or translates something the manifest doesn't declare {at} navngiver eller oversætter noget, som manifestet ikke erklærer
|
||||
@msg command {name} is declared twice kommandoen {name} er erklæret to gange
|
||||
@msg command {name}: `label` must be 1-64 printable characters kommandoen {name}: `label` skal være 1-64 tegn, der kan udskrives
|
||||
@msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter kommandoen {name}: brug et id på 1-{MAX_COMMAND_ID} tegn fra a-z 0-9 _, der starter med et bogstav
|
||||
@@ -9745,6 +9750,7 @@ axis Y Axis Y-akse
|
||||
# Plug-in permissions (Install Plug-in…, plugin.install grant)
|
||||
Install “{name}”, which asks for these permissions? Installér »{name}«, som beder om disse rettigheder?
|
||||
ID: {id} ID: {id}
|
||||
Manifest name: {name} Navn i manifestet: {name}
|
||||
Version: {version} Version: {version}
|
||||
Install “{name}” in place of the plug-in with the same ID? Installér »{name}« i stedet for det plug-in, der har samme id?
|
||||
This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Denne fil er ikke det plug-in, der før var installeret med dette id. Den får de indstillinger og den cache, der er gemt for dette id.
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -4859,7 +4859,7 @@ theme Appearance Erscheinungsbild
|
||||
Do not show this warning again Diese Warnung nicht mehr anzeigen
|
||||
Stop the script and undo what it did? Then quit again. Skript stoppen und seine Änderungen rückgängig machen? Beenden Sie danach erneut.
|
||||
This script has added a great many objects. Continue, or stop it and undo what it did? Dieses Skript hat sehr viele Objekte hinzugefügt. Fortfahren oder das Skript stoppen und seine Änderungen rückgängig machen?
|
||||
@msg Choose a .js or .jsx script Wählen Sie ein .js- oder .jsx-Skript
|
||||
@msg Choose a .js, .mjs or .jsx script Wählen Sie ein .js-, .mjs- oder .jsx-Skript
|
||||
@msg Ran {name} {name} ausgeführt
|
||||
@msg The script was stopped and its changes were undone Das Skript wurde gestoppt und seine Änderungen wurden rückgängig gemacht
|
||||
@msg a script is running: stop it or wait for it to finish ein Skript wird ausgeführt: stoppen Sie es oder warten Sie, bis es fertig ist
|
||||
@@ -7098,6 +7098,7 @@ axis Y Axis Y-Achse
|
||||
# Plug-in permissions (Install Plug-in…, plugin.install grant)
|
||||
Install “{name}”, which asks for these permissions? „{name}“ installieren, das diese Berechtigungen verlangt?
|
||||
ID: {id} ID: {id}
|
||||
Manifest name: {name} Name im Manifest: {name}
|
||||
Version: {version} Version: {version}
|
||||
Install “{name}” in place of the plug-in with the same ID? „{name}“ anstelle des Plug-ins mit derselben ID installieren?
|
||||
This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Diese Datei ist nicht das Plug-in, das vorher mit dieser ID installiert war. Sie erhält die Einstellungen und den Cache, die für diese ID gespeichert sind.
|
||||
@@ -7211,6 +7212,11 @@ axis Y Axis Y-Achse
|
||||
@msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed „{name}“ wurde `{p}` nicht gewährt, das seine Ausgabe braucht: Es wurde nichts geändert
|
||||
@msg a heavy filter runs in the background, so it can't declare `commands` ein schwerer Filter läuft im Hintergrund und kann daher keine `commands` deklarieren
|
||||
@msg at most {MAX_COMMANDS} `commands` höchstens {MAX_COMMANDS} `commands`
|
||||
@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` gibt höchstens {MAX_LANGUAGES} Sprachen an
|
||||
@msg {at} gives two options the same label {at} gibt zwei Optionen dieselbe Beschriftung
|
||||
@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} ist kein Sprachcode wie `de` oder `pt-BR` oder wiederholt einen zuvor angegebenen
|
||||
@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} muss 1-{max} druckbare Zeichen lang sein, ohne Schreibrichtungs- oder Zeilentrennzeichen
|
||||
@msg {at} names or translates something the manifest doesn't declare {at} benennt oder übersetzt etwas, das das Manifest nicht deklariert
|
||||
@msg command {name} is declared twice der Befehl {name} ist doppelt deklariert
|
||||
@msg command {name}: `label` must be 1-64 printable characters Befehl {name}: `label` muss 1-64 druckbare Zeichen haben
|
||||
@msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter Befehl {name}: Verwenden Sie eine ID aus 1-{MAX_COMMAND_ID} Zeichen aus a-z 0-9 _, die mit einem Buchstaben beginnt
|
||||
@@ -8586,7 +8592,7 @@ breakText Glyphs Glyphen
|
||||
@msg `args` is larger than 1 MiB `args` ist größer als 1 MiB
|
||||
@msg `path` is empty `path` ist leer
|
||||
@msg `installed` takes a `path`, not a `source` `installed` nimmt einen `path`, keine `source`
|
||||
@msg `path` must name a .js or .jsx file `path` muss eine .js- oder .jsx-Datei angeben
|
||||
@msg `path` must name a .js, .mjs or .jsx file `path` muss eine .js-, .mjs- oder .jsx-Datei angeben
|
||||
@msg give exactly one of `path` and `source` geben Sie genau eines von `path` und `source` an
|
||||
@msg `answers` must be a list of answers `answers` muss eine Liste von Antworten sein
|
||||
@msg `artboard` must be the index of an artboard of the document `artboard` muss der Index einer Zeichenfläche des Dokuments sein
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -2656,7 +2656,7 @@ axis Both Και τα δύο
|
||||
Do not show this warning again Να μην εμφανιστεί ξανά αυτή η προειδοποίηση
|
||||
Stop the script and undo what it did? Then quit again. Διακοπή του σεναρίου και αναίρεση όσων έκανε; Έπειτα κάντε ξανά έξοδο.
|
||||
This script has added a great many objects. Continue, or stop it and undo what it did? Αυτό το σενάριο πρόσθεσε πάρα πολλά αντικείμενα. Συνέχεια, ή διακοπή και αναίρεση όσων έκανε;
|
||||
@msg Choose a .js or .jsx script Επιλέξτε ένα σενάριο .js ή .jsx
|
||||
@msg Choose a .js, .mjs or .jsx script Επιλέξτε ένα σενάριο .js, .mjs ή .jsx
|
||||
@msg Ran {name} Εκτελέστηκε: {name}
|
||||
@msg The script was stopped and its changes were undone Το σενάριο διακόπηκε και οι αλλαγές του αναιρέθηκαν
|
||||
@msg a script is running: stop it or wait for it to finish εκτελείται ένα σενάριο: διακόψτε το ή περιμένετε να τελειώσει
|
||||
@@ -2829,7 +2829,7 @@ liquify-list-end {0}, {1} {0} και {1}
|
||||
@msg `args` is larger than 1 MiB το `args` είναι μεγαλύτερο από 1 MiB
|
||||
@msg `path` is empty το `path` είναι κενό
|
||||
@msg `installed` takes a `path`, not a `source` το `installed` δέχεται `path`, όχι `source`
|
||||
@msg `path` must name a .js or .jsx file το `path` πρέπει να ορίζει αρχείο .js ή .jsx
|
||||
@msg `path` must name a .js, .mjs or .jsx file το `path` πρέπει να ορίζει αρχείο .js, .mjs ή .jsx
|
||||
@msg give exactly one of `path` and `source` δώστε ακριβώς ένα από τα `path` και `source`
|
||||
@msg Running a script Εκτελείται σενάριο
|
||||
@msg Copied the script report Η αναφορά του σεναρίου αντιγράφηκε
|
||||
@@ -7509,6 +7509,7 @@ axis Y Axis Άξονας Y
|
||||
# Plug-in permissions (Install Plug-in…, plugin.install grant)
|
||||
Install “{name}”, which asks for these permissions? Να εγκατασταθεί το «{name}», που ζητά αυτά τα δικαιώματα;
|
||||
ID: {id} Αναγνωριστικό: {id}
|
||||
Manifest name: {name} Όνομα στο manifest: {name}
|
||||
Version: {version} Έκδοση: {version}
|
||||
Install “{name}” in place of the plug-in with the same ID? Να εγκατασταθεί το «{name}» στη θέση του πρόσθετου με το ίδιο αναγνωριστικό;
|
||||
This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Αυτό το αρχείο δεν είναι το πρόσθετο που ήταν εγκατεστημένο πριν με αυτό το αναγνωριστικό. Παίρνει τις ρυθμίσεις και την κρυφή μνήμη που διατηρούνται για αυτό το αναγνωριστικό.
|
||||
@@ -7622,6 +7623,11 @@ axis Y Axis Άξονας Y
|
||||
@msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed στο «{name}» δεν παραχωρήθηκε το `{p}`, που χρειάζεται η έξοδός του: δεν άλλαξε τίποτα
|
||||
@msg a heavy filter runs in the background, so it can't declare `commands` ένα βαρύ φίλτρο εκτελείται στο παρασκήνιο, οπότε δεν μπορεί να δηλώνει `commands`
|
||||
@msg at most {MAX_COMMANDS} `commands` το πολύ {MAX_COMMANDS} `commands`
|
||||
@msg `translations` gives at most {MAX_LANGUAGES} languages το `translations` δίνει το πολύ {MAX_LANGUAGES} γλώσσες
|
||||
@msg {at} gives two options the same label το {at} δίνει την ίδια ετικέτα σε δύο επιλογές
|
||||
@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it το {at} δεν είναι κωδικός γλώσσας όπως `de` ή `pt-BR`, ή επαναλαμβάνει έναν που δόθηκε πριν
|
||||
@msg {at} must be 1-{max} printable characters, without direction or line-separator characters το {at} πρέπει να έχει 1-{max} εκτυπώσιμους χαρακτήρες, χωρίς χαρακτήρες κατεύθυνσης ή διαχωρισμού γραμμών
|
||||
@msg {at} names or translates something the manifest doesn't declare το {at} ονομάζει ή μεταφράζει κάτι που το manifest δεν δηλώνει
|
||||
@msg command {name} is declared twice η εντολή {name} δηλώνεται δύο φορές
|
||||
@msg command {name}: `label` must be 1-64 printable characters εντολή {name}: το `label` πρέπει να έχει 1-64 εκτυπώσιμους χαρακτήρες
|
||||
@msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter εντολή {name}: χρησιμοποιήστε αναγνωριστικό 1-{MAX_COMMAND_ID} χαρακτήρων από a-z 0-9 _ που αρχίζει με γράμμα
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -4935,7 +4935,7 @@ axis Both Ambos
|
||||
Do not show this warning again No volver a mostrar esta advertencia
|
||||
Stop the script and undo what it did? Then quit again. ¿Detener el script y deshacer lo que hizo? Después, vuelva a salir.
|
||||
This script has added a great many objects. Continue, or stop it and undo what it did? Este script ha añadido muchísimos objetos. ¿Continuar, o detenerlo y deshacer lo que hizo?
|
||||
@msg Choose a .js or .jsx script Elija un script .js o .jsx
|
||||
@msg Choose a .js, .mjs or .jsx script Elija un script .js, .mjs o .jsx
|
||||
@msg Ran {name} Se ejecutó {name}
|
||||
@msg The script was stopped and its changes were undone El script se detuvo y sus cambios se deshicieron
|
||||
@msg a script is running: stop it or wait for it to finish se está ejecutando un script: deténgalo o espere a que termine
|
||||
@@ -5107,7 +5107,7 @@ liquify-list-end {0}, {1} {0}, {1}
|
||||
@msg `args` is larger than 1 MiB `args` ocupa más de 1 MiB
|
||||
@msg `path` is empty `path` está vacío
|
||||
@msg `installed` takes a `path`, not a `source` `installed` admite un `path`, no un `source`
|
||||
@msg `path` must name a .js or .jsx file `path` debe indicar un archivo .js o .jsx
|
||||
@msg `path` must name a .js, .mjs or .jsx file `path` debe indicar un archivo .js, .mjs o .jsx
|
||||
@msg give exactly one of `path` and `source` indique exactamente uno de `path` y `source`
|
||||
@msg Running a script Ejecutando un script
|
||||
@msg Copied the script report Se copió el informe del script
|
||||
@@ -7495,6 +7495,7 @@ axis Y Axis Eje Y
|
||||
# Plug-in permissions (Install Plug-in…, plugin.install grant)
|
||||
Install “{name}”, which asks for these permissions? ¿Instalar “{name}”, que pide estos permisos?
|
||||
ID: {id} ID: {id}
|
||||
Manifest name: {name} Nombre en el manifiesto: {name}
|
||||
Version: {version} Versión: {version}
|
||||
Install “{name}” in place of the plug-in with the same ID? ¿Instalar “{name}” en lugar del plugin con el mismo ID?
|
||||
This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Este archivo no es el plugin instalado antes con este ID. Recibe la configuración y la caché guardadas para ese ID.
|
||||
@@ -7608,6 +7609,11 @@ axis Y Axis Eje Y
|
||||
@msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed a “{name}” no se le concedió `{p}`, que su resultado necesita: no se cambió nada
|
||||
@msg a heavy filter runs in the background, so it can't declare `commands` un filtro pesado se ejecuta en segundo plano, así que no puede declarar `commands`
|
||||
@msg at most {MAX_COMMANDS} `commands` como máximo {MAX_COMMANDS} `commands`
|
||||
@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` da como máximo {MAX_LANGUAGES} idiomas
|
||||
@msg {at} gives two options the same label {at} da la misma etiqueta a dos opciones
|
||||
@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} no es un código de idioma como `de` o `pt-BR`, o repite uno dado antes
|
||||
@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} debe tener 1-{max} caracteres imprimibles, sin caracteres de dirección ni separadores de línea
|
||||
@msg {at} names or translates something the manifest doesn't declare {at} nombra o traduce algo que el manifiesto no declara
|
||||
@msg command {name} is declared twice el comando {name} está declarado dos veces
|
||||
@msg command {name}: `label` must be 1-64 printable characters comando {name}: `label` debe tener 1-64 caracteres imprimibles
|
||||
@msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter comando {name}: usa un id de 1-{MAX_COMMAND_ID} caracteres de a-z 0-9 _ que empiece por una letra
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -5178,7 +5178,7 @@ imageTrace Outline Ääriviiva
|
||||
Do not show this warning again Älä näytä tätä varoitusta uudelleen
|
||||
Stop the script and undo what it did? Then quit again. Pysäytetäänkö komentosarja ja kumotaan sen muutokset? Lopeta sitten uudelleen.
|
||||
This script has added a great many objects. Continue, or stop it and undo what it did? Tämä komentosarja on lisännyt hyvin paljon objekteja. Jatketaanko, vai pysäytetäänkö se ja kumotaan sen muutokset?
|
||||
@msg Choose a .js or .jsx script Valitse .js- tai .jsx-komentosarja
|
||||
@msg Choose a .js, .mjs or .jsx script Valitse .js-, .mjs- tai .jsx-komentosarja
|
||||
@msg Ran {name} Suoritettu: {name}
|
||||
@msg The script was stopped and its changes were undone Komentosarja pysäytettiin ja sen muutokset kumottiin
|
||||
@msg a script is running: stop it or wait for it to finish komentosarja on käynnissä: pysäytä se tai odota sen valmistumista
|
||||
@@ -5350,7 +5350,7 @@ liquify-list-end {0}, {1} {0} ja {1}
|
||||
@msg `args` is larger than 1 MiB `args` on suurempi kuin 1 MiB
|
||||
@msg `path` is empty `path` on tyhjä
|
||||
@msg `installed` takes a `path`, not a `source` `installed` ottaa `path`-arvon, ei `source`-arvoa
|
||||
@msg `path` must name a .js or .jsx file `path` on oltava .js- tai .jsx-tiedosto
|
||||
@msg `path` must name a .js, .mjs or .jsx file `path` on oltava .js-, .mjs- tai .jsx-tiedosto
|
||||
@msg give exactly one of `path` and `source` anna tasan yksi arvoista `path` ja `source`
|
||||
@msg Running a script Suoritetaan komentosarjaa
|
||||
@msg Copied the script report Komentosarjan raportti kopioitiin
|
||||
@@ -7586,6 +7586,7 @@ axis Y Axis Y-akseli
|
||||
# Plug-in permissions (Install Plug-in…, plugin.install grant)
|
||||
Install “{name}”, which asks for these permissions? Asennetaanko ”{name}”, joka pyytää näitä käyttöoikeuksia?
|
||||
ID: {id} Tunnus: {id}
|
||||
Manifest name: {name} Nimi manifestissa: {name}
|
||||
Version: {version} Versio: {version}
|
||||
Install “{name}” in place of the plug-in with the same ID? Asennetaanko ”{name}” samaa tunnusta käyttävän laajennuksen tilalle?
|
||||
This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Tämä tiedosto ei ole laajennus, joka oli aiemmin asennettu tällä tunnuksella. Se saa tälle tunnukselle säilytetyt asetukset ja välimuistin.
|
||||
@@ -7699,6 +7700,11 @@ axis Y Axis Y-akseli
|
||||
@msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed ”{name}” ei saanut käyttöoikeutta `{p}`, jota sen tulos tarvitsee: mitään ei muutettu
|
||||
@msg a heavy filter runs in the background, so it can't declare `commands` raskas suodin suoritetaan taustalla, joten se ei voi määritellä `commands`-kohtaa
|
||||
@msg at most {MAX_COMMANDS} `commands` enintään {MAX_COMMANDS} `commands`
|
||||
@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` antaa enintään {MAX_LANGUAGES} kieltä
|
||||
@msg {at} gives two options the same label {at} antaa kahdelle vaihtoehdolle saman nimen
|
||||
@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} ei ole kielikoodi kuten `de` tai `pt-BR`, tai toistaa aiemmin annetun koodin
|
||||
@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} saa olla 1-{max} tulostettavaa merkkiä ilman suunta- tai rivinerotinmerkkejä
|
||||
@msg {at} names or translates something the manifest doesn't declare {at} nimeää tai kääntää jotain, mitä manifesti ei määrittele
|
||||
@msg command {name} is declared twice komento {name} on määritelty kahdesti
|
||||
@msg command {name}: `label` must be 1-64 printable characters komento {name}: `label`-kentässä on oltava 1-64 tulostettavaa merkkiä
|
||||
@msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter komento {name}: käytä 1-{MAX_COMMAND_ID} merkin tunnusta merkeistä a-z 0-9 _, joka alkaa kirjaimella
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -4917,7 +4917,7 @@ axis Both Les deux
|
||||
Do not show this warning again Ne plus afficher cet avertissement
|
||||
Stop the script and undo what it did? Then quit again. Arrêter le script et annuler ce qu’il a fait ? Quittez ensuite à nouveau.
|
||||
This script has added a great many objects. Continue, or stop it and undo what it did? Ce script a ajouté un très grand nombre d’objets. Continuer, ou l’arrêter et annuler ce qu’il a fait ?
|
||||
@msg Choose a .js or .jsx script Choisissez un script .js ou .jsx
|
||||
@msg Choose a .js, .mjs or .jsx script Choisissez un script .js, .mjs ou .jsx
|
||||
@msg Ran {name} {name} exécuté
|
||||
@msg The script was stopped and its changes were undone Le script a été arrêté et ses modifications ont été annulées
|
||||
@msg a script is running: stop it or wait for it to finish un script est en cours d’exécution : arrêtez-le ou attendez qu’il se termine
|
||||
@@ -5063,7 +5063,7 @@ liquify-list-end {0}, {1} {0} et {1}
|
||||
@msg `args` is larger than 1 MiB `args` dépasse 1 Mio
|
||||
@msg `path` is empty `path` est vide
|
||||
@msg `installed` takes a `path`, not a `source` `installed` prend un `path`, pas un `source`
|
||||
@msg `path` must name a .js or .jsx file `path` doit désigner un fichier .js ou .jsx
|
||||
@msg `path` must name a .js, .mjs or .jsx file `path` doit désigner un fichier .js, .mjs ou .jsx
|
||||
@msg give exactly one of `path` and `source` indiquez exactement un paramètre parmi `path` et `source`
|
||||
@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` est réservé à une exécution sans personne à qui demander : dans l’application, la personne répond à chaque boîte de dialogue
|
||||
@msg Running a script Exécution d’un script
|
||||
@@ -7513,6 +7513,7 @@ axis Y Axis Axe Y
|
||||
# Plug-in permissions (Install Plug-in…, plugin.install grant)
|
||||
Install “{name}”, which asks for these permissions? Installer « {name} », qui demande ces autorisations ?
|
||||
ID: {id} ID : {id}
|
||||
Manifest name: {name} Le manifeste le nomme {name}
|
||||
Version: {version} Version : {version}
|
||||
Install “{name}” in place of the plug-in with the same ID? Installer « {name} » à la place du module externe qui a le même ID ?
|
||||
This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Ce fichier n’est pas le module externe installé auparavant avec cet ID. Il reçoit les réglages et le cache conservés pour cet ID.
|
||||
@@ -7626,6 +7627,11 @@ axis Y Axis Axe Y
|
||||
@msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed « {name} » n’a pas reçu `{p}`, dont sa sortie a besoin : rien n’a été modifié
|
||||
@msg a heavy filter runs in the background, so it can't declare `commands` un filtre lourd s’exécute en arrière-plan, il ne peut donc pas déclarer `commands`
|
||||
@msg at most {MAX_COMMANDS} `commands` au plus {MAX_COMMANDS} `commands`
|
||||
@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` donne au plus {MAX_LANGUAGES} langues
|
||||
@msg {at} gives two options the same label {at} donne le même libellé à deux options
|
||||
@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} n’est pas un code de langue comme `de` ou `pt-BR`, ou répète un code donné avant
|
||||
@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} doit compter 1-{max} caractères imprimables, sans caractères de direction ni séparateurs de ligne
|
||||
@msg {at} names or translates something the manifest doesn't declare {at} nomme ou traduit quelque chose que le manifeste ne déclare pas
|
||||
@msg command {name} is declared twice la commande {name} est déclarée deux fois
|
||||
@msg command {name}: `label` must be 1-64 printable characters commande {name} : `label` doit compter 1-64 caractères imprimables
|
||||
@msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter commande {name} : utilisez un id de 1-{MAX_COMMAND_ID} caractères parmi a-z 0-9 _ commençant par une lettre
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -1891,6 +1891,7 @@
|
||||
Max Ascender મહત્તમ એસેન્ડર
|
||||
ICF Top/Right ICF ઉપર/જમણે
|
||||
ID: {id} ID: {id}
|
||||
Manifest name: {name} મેનિફેસ્ટમાં નામ: {name}
|
||||
Identify Objects By ઑબ્જેક્ટ્સ આ રીતે ઓળખો
|
||||
If a drawing tablet's pen doesn't draw, choose an X11 (XWayland) option. જો ડ્રોઇંગ ટેબ્લેટની પેન દોરતી ન હોય, તો X11 (XWayland) વિકલ્પ પસંદ કરો.
|
||||
Ignore અવગણો
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 72 and column 5.
|
@@ -6670,6 +6670,7 @@ arrowhead Feather पंख
|
||||
# Plug-in permissions (Install Plug-in…, plugin.install grant)
|
||||
Install “{name}”, which asks for these permissions? "{name}" स्थापित करें, जो ये अनुमतियां मांगता है?
|
||||
ID: {id} ID: {id}
|
||||
Manifest name: {name} मैनिफ़ेस्ट में नाम: {name}
|
||||
Version: {version} संस्करण: {version}
|
||||
Install “{name}” in place of the plug-in with the same ID? समान ID वाले प्लग-इन की जगह “{name}” इंस्टॉल करें?
|
||||
This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. यह फ़ाइल इस ID के साथ पहले इंस्टॉल किया गया प्लग-इन नहीं है। इसे उस ID के लिए रखी गई सेटिंग्स और कैश मिलते हैं।
|
||||
@@ -6764,6 +6765,11 @@ arrowhead Feather पंख
|
||||
@msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed “{name}” को `{p}` नहीं दी गई, जो उसके आउटपुट को चाहिए: कुछ नहीं बदला
|
||||
@msg a heavy filter runs in the background, so it can't declare `commands` भारी फ़िल्टर पृष्ठभूमि में चलता है, इसलिए वह `commands` घोषित नहीं कर सकता
|
||||
@msg at most {MAX_COMMANDS} `commands` अधिकतम {MAX_COMMANDS} `commands`
|
||||
@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` अधिकतम {MAX_LANGUAGES} भाषाएँ देता है
|
||||
@msg {at} gives two options the same label {at} दो विकल्पों को एक ही लेबल देता है
|
||||
@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} `de` या `pt-BR` जैसा भाषा कोड नहीं है, या पहले दिए गए कोड को दोहराता है
|
||||
@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} में 1-{max} मुद्रण योग्य वर्ण होने चाहिए, दिशा या पंक्ति-विभाजक वर्णों के बिना
|
||||
@msg {at} names or translates something the manifest doesn't declare {at} ऐसी चीज़ का नाम लेता है या अनुवाद करता है जिसे मैनिफ़ेस्ट घोषित नहीं करता
|
||||
@msg command {name} is declared twice कमांड {name} दो बार घोषित है
|
||||
@msg command {name}: `label` must be 1-64 printable characters कमांड {name}: `label` में 1-64 प्रिंट करने योग्य वर्ण होने चाहिए
|
||||
@msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter कमांड {name}: a-z 0-9 _ के 1-{MAX_COMMAND_ID} वर्णों वाली ऐसी id इस्तेमाल करें जो अक्षर से शुरू हो
|
||||
@@ -7668,7 +7674,7 @@ arrowhead Feather पंख
|
||||
Do not show this warning again यह चेतावनी फिर न दिखाएँ
|
||||
Stop the script and undo what it did? Then quit again. स्क्रिप्ट रोककर उसके बदलाव पूर्ववत करें? फिर दोबारा बाहर निकलें।
|
||||
This script has added a great many objects. Continue, or stop it and undo what it did? इस स्क्रिप्ट ने बहुत सारे ऑब्जेक्ट जोड़े हैं। जारी रखें, या इसे रोककर इसके बदलाव पूर्ववत करें?
|
||||
@msg Choose a .js or .jsx script .js या .jsx स्क्रिप्ट चुनें
|
||||
@msg Choose a .js, .mjs or .jsx script .js, .mjs या .jsx स्क्रिप्ट चुनें
|
||||
@msg Ran {name} {name} चलाई गई
|
||||
@msg The script was stopped and its changes were undone स्क्रिप्ट रोकी गई और उसके बदलाव पूर्ववत किए गए
|
||||
@msg a script is running: stop it or wait for it to finish एक स्क्रिप्ट चल रही है: उसे रोकें या पूरा होने की प्रतीक्षा करें
|
||||
@@ -7841,7 +7847,7 @@ liquify-list-end {0}, {1} {0} और {1}
|
||||
@msg `args` is larger than 1 MiB `args` 1 MiB से बड़ा है
|
||||
@msg `path` is empty `path` खाली है
|
||||
@msg `installed` takes a `path`, not a `source` `installed` एक `path` लेता है, `source` नहीं
|
||||
@msg `path` must name a .js or .jsx file `path` में किसी .js या .jsx फ़ाइल का नाम होना चाहिए
|
||||
@msg `path` must name a .js, .mjs or .jsx file `path` में किसी .js, .mjs या .jsx फ़ाइल का नाम होना चाहिए
|
||||
@msg give exactly one of `path` and `source` `path` और `source` में से ठीक एक दें
|
||||
@msg Running a script स्क्रिप्ट चल रही है
|
||||
@msg Copied the script report Copied स्क्रिप्ट रिपोर्ट
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -5794,7 +5794,7 @@ imageTrace Outline Körvonal
|
||||
Do not show this warning again Ne jelenjen meg többé ez a figyelmeztetés
|
||||
Stop the script and undo what it did? Then quit again. Leállítja a parancsfájlt, és visszavonja a módosításait? Ezután lépjen ki újra.
|
||||
This script has added a great many objects. Continue, or stop it and undo what it did? Ez a parancsfájl nagyon sok objektumot adott hozzá. Folytatja, vagy leállítja és visszavonja a módosításait?
|
||||
@msg Choose a .js or .jsx script Válasszon .js vagy .jsx parancsfájlt
|
||||
@msg Choose a .js, .mjs or .jsx script Válasszon .js, .mjs vagy .jsx parancsfájlt
|
||||
@msg Ran {name} Lefutott: {name}
|
||||
@msg The script was stopped and its changes were undone A parancsfájl leállt, a módosításai visszavonva
|
||||
@msg a script is running: stop it or wait for it to finish egy parancsfájl fut: állítsa le, vagy várja meg, hogy befejeződjön
|
||||
@@ -5942,7 +5942,7 @@ liquify-list-end {0}, {1} {0} és {1}
|
||||
@msg `args` is larger than 1 MiB `args`: nagyobb 1 MiB-nál
|
||||
@msg `path` is empty a `path` üres
|
||||
@msg `installed` takes a `path`, not a `source` az `installed` `path` értéket vár, nem `source` értéket
|
||||
@msg `path` must name a .js or .jsx file a `path` értékének .js vagy .jsx fájlt kell megadnia
|
||||
@msg `path` must name a .js, .mjs or .jsx file a `path` értékének .js, .mjs vagy .jsx fájlt kell megadnia
|
||||
@msg give exactly one of `path` and `source` pontosan egyet adj meg ezek közül: `path`, `source`
|
||||
@msg Running a script Parancsfájl futtatása
|
||||
@msg Copied the script report Szkriptjelentés másolva
|
||||
@@ -7502,6 +7502,7 @@ axis Y Axis Y tengely
|
||||
# Plug-in permissions (Install Plug-in…, plugin.install grant)
|
||||
Install “{name}”, which asks for these permissions? Telepíted a(z) „{name}” bővítményt, amely ezeket az engedélyeket kéri?
|
||||
ID: {id} Azonosító: {id}
|
||||
Manifest name: {name} Név a manifestben: {name}
|
||||
Version: {version} Verzió: {version}
|
||||
Install “{name}” in place of the plug-in with the same ID? Telepíted a(z) „{name}” bővítményt az azonos azonosítójú bővítmény helyére?
|
||||
This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Ez a fájl nem az a bővítmény, amely korábban ezzel az azonosítóval volt telepítve. Megkapja az ehhez az azonosítóhoz tárolt beállításokat és gyorsítótárat.
|
||||
@@ -7615,6 +7616,11 @@ axis Y Axis Y tengely
|
||||
@msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed a(z) „{name}” nem kapta meg a(z) `{p}` engedélyt, amelyre a kimenetének szüksége van: semmi sem változott
|
||||
@msg a heavy filter runs in the background, so it can't declare `commands` a nehéz szűrő a háttérben fut, ezért nem deklarálhat `commands` értéket
|
||||
@msg at most {MAX_COMMANDS} `commands` legfeljebb {MAX_COMMANDS} `commands`
|
||||
@msg `translations` gives at most {MAX_LANGUAGES} languages a `translations` legfeljebb {MAX_LANGUAGES} nyelvet adhat meg
|
||||
@msg {at} gives two options the same label {at} két lehetőségnek ugyanazt a címkét adja
|
||||
@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} nem olyan nyelvkód, mint a `de` vagy a `pt-BR`, vagy egy korábban megadottat ismétel
|
||||
@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} 1-{max} nyomtatható karakter lehet, irány- és sorelválasztó karakterek nélkül
|
||||
@msg {at} names or translates something the manifest doesn't declare {at} olyasmit nevez meg vagy fordít, amit a manifest nem deklarál
|
||||
@msg command {name} is declared twice a(z) {name} parancs kétszer van deklarálva
|
||||
@msg command {name}: `label` must be 1-64 printable characters {name} parancs: a `label` 1-64 nyomtatható karakter legyen
|
||||
@msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter {name} parancs: használj 1-{MAX_COMMAND_ID} karakteres, a-z 0-9 _ karakterekből álló, betűvel kezdődő azonosítót
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -54,7 +54,7 @@
|
||||
@msg it decompresses to more than {_1} MB hasil dekompresinya lebih dari {_1} MB
|
||||
@msg its editing data is for a different page data penyuntingannya untuk halaman lain
|
||||
@msg `fontHeightReference` must be "emBox", "capHeight", "xHeight" or "icfBox" `fontHeightReference` harus "emBox", "capHeight", "xHeight" atau "icfBox"
|
||||
@msg Choose a .js or .jsx script Pilih skrip .js atau .jsx
|
||||
@msg Choose a .js, .mjs or .jsx script Pilih skrip .js, .mjs, atau .jsx
|
||||
@msg Ran {name} {name} dijalankan
|
||||
@msg The script was stopped and its changes were undone Skrip dihentikan dan perubahannya dibatalkan
|
||||
@msg a script is running: stop it or wait for it to finish skrip sedang berjalan: hentikan atau tunggu hingga selesai
|
||||
@@ -151,7 +151,7 @@
|
||||
@msg `args` is larger than 1 MiB `args` lebih besar dari 1 MiB
|
||||
@msg `path` is empty `path` kosong
|
||||
@msg `installed` takes a `path`, not a `source` `installed` menerima `path`, bukan `source`
|
||||
@msg `path` must name a .js or .jsx file `path` harus menyebut file .js atau .jsx
|
||||
@msg `path` must name a .js, .mjs or .jsx file `path` harus menyebut file .js, .mjs, atau .jsx
|
||||
@msg give exactly one of `path` and `source` berikan tepat satu dari `path` dan `source`
|
||||
@msg [{j}] `{_1}`: {why} [{j}] `{_1}`: {why}
|
||||
@msg `answers[{i}]` {e} `answers[{i}]` {e}
|
||||
@@ -678,6 +678,11 @@
|
||||
@msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed “{name}” tidak diberi `{p}`, yang diperlukan keluarannya: tidak ada yang diubah
|
||||
@msg a heavy filter runs in the background, so it can't declare `commands` filter berat berjalan di latar belakang, sehingga tidak dapat mendeklarasikan `commands`
|
||||
@msg at most {MAX_COMMANDS} `commands` paling banyak {MAX_COMMANDS} `commands`
|
||||
@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` memberikan paling banyak {MAX_LANGUAGES} bahasa
|
||||
@msg {at} gives two options the same label {at} memberikan label yang sama untuk dua opsi
|
||||
@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} bukan kode bahasa seperti `de` atau `pt-BR`, atau mengulang kode yang diberikan sebelumnya
|
||||
@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} harus berisi 1-{max} karakter yang dapat dicetak, tanpa karakter arah atau pemisah baris
|
||||
@msg {at} names or translates something the manifest doesn't declare {at} menamai atau menerjemahkan sesuatu yang tidak dideklarasikan manifes
|
||||
@msg command {name} is declared twice perintah {name} dideklarasikan dua kali
|
||||
@msg command {name}: `label` must be 1-64 printable characters perintah {name}: `label` harus berupa 1-64 karakter yang dapat dicetak
|
||||
@msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter perintah {name}: gunakan id sepanjang 1-{MAX_COMMAND_ID} karakter dari a-z 0-9 _ yang diawali huruf
|
||||
@@ -7527,6 +7532,7 @@ axis Y Axis Sumbu Y
|
||||
# Plug-in permissions (Install Plug-in…, plugin.install grant)
|
||||
Install “{name}”, which asks for these permissions? Instal “{name}”, yang meminta izin berikut?
|
||||
ID: {id} ID: {id}
|
||||
Manifest name: {name} Nama di manifes: {name}
|
||||
Version: {version} Versi: {version}
|
||||
Install “{name}” in place of the plug-in with the same ID? Instal “{name}” sebagai pengganti plug-in dengan ID yang sama?
|
||||
This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. File ini bukan plug-in yang sebelumnya diinstal dengan ID ini. File ini mendapatkan pengaturan dan cache yang disimpan untuk ID tersebut.
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -4997,7 +4997,7 @@ axis Both Entrambi
|
||||
Do not show this warning again Non mostrare più questo avviso
|
||||
Stop the script and undo what it did? Then quit again. Interrompere lo script e annullare ciò che ha fatto? Poi esci di nuovo.
|
||||
This script has added a great many objects. Continue, or stop it and undo what it did? Questo script ha aggiunto moltissimi oggetti. Continuare, oppure interromperlo e annullare ciò che ha fatto?
|
||||
@msg Choose a .js or .jsx script Scegli uno script .js o .jsx
|
||||
@msg Choose a .js, .mjs or .jsx script Scegli uno script .js, .mjs o .jsx
|
||||
@msg Ran {name} {name} eseguito
|
||||
@msg The script was stopped and its changes were undone Lo script è stato interrotto e le sue modifiche sono state annullate
|
||||
@msg a script is running: stop it or wait for it to finish è in esecuzione uno script: interrompilo o attendi che finisca
|
||||
@@ -7137,6 +7137,7 @@ axis Y Axis Asse Y
|
||||
# Plug-in permissions (Install Plug-in…, plugin.install grant)
|
||||
Install “{name}”, which asks for these permissions? Installare “{name}”, che chiede queste autorizzazioni?
|
||||
ID: {id} ID: {id}
|
||||
Manifest name: {name} Nome nel manifest: {name}
|
||||
Version: {version} Versione: {version}
|
||||
Install “{name}” in place of the plug-in with the same ID? Installare “{name}” al posto del plug-in con lo stesso ID?
|
||||
This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Questo file non è il plug-in installato prima con questo ID. Riceve le impostazioni e la cache conservate per quell’ID.
|
||||
@@ -7250,6 +7251,11 @@ axis Y Axis Asse Y
|
||||
@msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed a “{name}” non è stata concessa `{p}`, che serve al suo risultato: non è stato modificato nulla
|
||||
@msg a heavy filter runs in the background, so it can't declare `commands` un filtro pesante viene eseguito in background, quindi non può dichiarare `commands`
|
||||
@msg at most {MAX_COMMANDS} `commands` al massimo {MAX_COMMANDS} `commands`
|
||||
@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` indica al massimo {MAX_LANGUAGES} lingue
|
||||
@msg {at} gives two options the same label {at} dà la stessa etichetta a due opzioni
|
||||
@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} non è un codice di lingua come `de` o `pt-BR`, o ripete uno indicato prima
|
||||
@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} deve avere 1-{max} caratteri stampabili, senza caratteri di direzione o separatori di riga
|
||||
@msg {at} names or translates something the manifest doesn't declare {at} nomina o traduce qualcosa che il manifest non dichiara
|
||||
@msg command {name} is declared twice il comando {name} è dichiarato due volte
|
||||
@msg command {name}: `label` must be 1-64 printable characters comando {name}: `label` deve avere 1-64 caratteri stampabili
|
||||
@msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter comando {name}: usa un id di 1-{MAX_COMMAND_ID} caratteri tra a-z 0-9 _ che inizi con una lettera
|
||||
@@ -8627,7 +8633,7 @@ breakText Glyphs Glifi
|
||||
@msg `args` is larger than 1 MiB `args` supera 1 MiB
|
||||
@msg `path` is empty `path` è vuoto
|
||||
@msg `installed` takes a `path`, not a `source` `installed` accetta un `path`, non un `source`
|
||||
@msg `path` must name a .js or .jsx file `path` deve indicare un file .js o .jsx
|
||||
@msg `path` must name a .js, .mjs or .jsx file `path` deve indicare un file .js, .mjs o .jsx
|
||||
@msg give exactly one of `path` and `source` indica esattamente uno tra `path` e `source`
|
||||
@msg `answers` must be a list of answers `answers` deve essere un elenco di risposte
|
||||
@msg `artboard` must be the index of an artboard of the document `artboard` deve essere l'indice di una tavola da disegno del documento
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -5824,7 +5824,7 @@ variable-list-end {0}, {1} {0}、{1}
|
||||
Do not show this warning again 今後この警告を表示しない
|
||||
Stop the script and undo what it did? Then quit again. スクリプトを停止して変更を取り消しますか?その後、もう一度終了してください。
|
||||
This script has added a great many objects. Continue, or stop it and undo what it did? このスクリプトは非常に多くのオブジェクトを追加しました。続行しますか、それとも停止して変更を取り消しますか?
|
||||
@msg Choose a .js or .jsx script .js または .jsx スクリプトを選択してください
|
||||
@msg Choose a .js, .mjs or .jsx script .js、.mjs または .jsx スクリプトを選択してください
|
||||
@msg Ran {name} {name} を実行しました
|
||||
@msg The script was stopped and its changes were undone スクリプトを停止し、変更を取り消しました
|
||||
@msg a script is running: stop it or wait for it to finish スクリプトの実行中です: 停止するか、終了するまでお待ちください
|
||||
@@ -5971,7 +5971,7 @@ liquify-list-end {0}, {1} {0}、{1}
|
||||
@msg `args` is larger than 1 MiB `args` が 1 MiB を超えています
|
||||
@msg `path` is empty `path` が空です
|
||||
@msg `installed` takes a `path`, not a `source` `installed` には `source` ではなく `path` を指定してください
|
||||
@msg `path` must name a .js or .jsx file `path` には .js または .jsx ファイルを指定してください
|
||||
@msg `path` must name a .js, .mjs or .jsx file `path` には .js、.mjs または .jsx ファイルを指定してください
|
||||
@msg give exactly one of `path` and `source` `path` と `source` のうち 1 つだけを指定してください
|
||||
@msg Running a script スクリプトを実行中
|
||||
@msg Copied the script report スクリプトのレポートをコピーしました
|
||||
@@ -7212,6 +7212,7 @@ axis Y Axis Y 軸
|
||||
# Plug-in permissions (Install Plug-in…, plugin.install grant)
|
||||
Install “{name}”, which asks for these permissions? これらの権限を求める「{name}」をインストールしますか?
|
||||
ID: {id} ID: {id}
|
||||
Manifest name: {name} マニフェストの名前: {name}
|
||||
Version: {version} バージョン: {version}
|
||||
Install “{name}” in place of the plug-in with the same ID? 同じ ID のプラグインの代わりに「{name}」をインストールしますか?
|
||||
This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. このファイルは、以前にこの ID でインストールされていたプラグインではありません。この ID 用に保持されている設定とキャッシュを引き継ぎます。
|
||||
@@ -7325,6 +7326,11 @@ axis Y Axis Y 軸
|
||||
@msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed 「{name}」には出力に必要な `{p}` が付与されていません。何も変更されませんでした
|
||||
@msg a heavy filter runs in the background, so it can't declare `commands` 重いフィルターはバックグラウンドで実行されるため、`commands` を宣言できません
|
||||
@msg at most {MAX_COMMANDS} `commands` `commands` は最大 {MAX_COMMANDS} 個です
|
||||
@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` に指定できる言語は最大 {MAX_LANGUAGES} 個です
|
||||
@msg {at} gives two options the same label {at} で 2 つの選択肢に同じラベルが付いています
|
||||
@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} は `de` や `pt-BR` のような言語コードではないか、前に指定したコードの繰り返しです
|
||||
@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} は方向制御文字や行区切り文字を含まない 1-{max} 文字の印字可能な文字にしてください
|
||||
@msg {at} names or translates something the manifest doesn't declare {at} はマニフェストで宣言されていないものを指定または翻訳しています
|
||||
@msg command {name} is declared twice コマンド {name} が 2 回宣言されています
|
||||
@msg command {name}: `label` must be 1-64 printable characters コマンド {name}: `label` は印刷可能な 1-64 文字にしてください
|
||||
@msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter コマンド {name}: a-z 0-9 _ からなり英字で始まる 1-{MAX_COMMAND_ID} 文字の ID を使用してください
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -2140,7 +2140,7 @@
|
||||
@msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` უნდა იყოს მთელი რიცხვი 1-დან {_1}-მდე
|
||||
@msg `max` must be 1 to {MAX_WORDS} `max` უნდა იყოს 1-დან {MAX_WORDS}-მდე
|
||||
@msg `path` is empty `path` ცარიელია
|
||||
@msg `path` must name a .js or .jsx file `path` უნდა მიუთითებდეს .js ან .jsx ფაილს
|
||||
@msg `path` must name a .js, .mjs or .jsx file `path` უნდა მიუთითებდეს .js, .mjs ან .jsx ფაილს
|
||||
@msg `reference` must be a whole number from 0 to 8 `reference` უნდა იყოს მთელი რიცხვი 0-დან 8-მდე
|
||||
@msg `ringSeed` must be below 2^53, not {r} `ringSeed` უნდა იყოს 2^53-ზე ნაკლები და არა {r}
|
||||
@msg `source` is the only path, line or label that graph group `target` stands for `source` ერთადერთი ტრაექტორია, ხაზი ან წარწერაა, რომელსაც დიაგრამის ჯგუფი `target` წარმოადგენს
|
||||
@@ -8505,7 +8505,7 @@ imageTrace Outline კონტური
|
||||
Do not show this warning again აღარ აჩვენო ეს გაფრთხილება
|
||||
Stop the script and undo what it did? Then quit again. შეჩერდეს სკრიპტი და გაუქმდეს მისი ცვლილებები? შემდეგ ხელახლა გამოდით.
|
||||
This script has added a great many objects. Continue, or stop it and undo what it did? ამ სკრიპტმა ძალიან ბევრი ობიექტი დაამატა. გაგრძელდეს, თუ შეჩერდეს და გაუქმდეს მისი ცვლილებები?
|
||||
@msg Choose a .js or .jsx script აირჩიეთ .js ან .jsx სკრიპტი
|
||||
@msg Choose a .js, .mjs or .jsx script აირჩიეთ .js, .mjs ან .jsx სკრიპტი
|
||||
@msg Ran {name} გაშვებულია: {name}
|
||||
@msg The script was stopped and its changes were undone სკრიპტი შეჩერდა და მისი ცვლილებები გაუქმდა
|
||||
@msg a script is running: stop it or wait for it to finish სკრიპტი მუშაობს: შეაჩერეთ ან დაელოდეთ დასრულებას
|
||||
@@ -9624,6 +9624,7 @@ axis Y Axis Y ღერძი
|
||||
# Plug-in permissions (Install Plug-in…, plugin.install grant)
|
||||
Install “{name}”, which asks for these permissions? დავაყენოთ „{name}“, რომელიც ამ ნებართვებს ითხოვს?
|
||||
ID: {id} ID: {id}
|
||||
Manifest name: {name} სახელი მანიფესტში: {name}
|
||||
Version: {version} ვერსია: {version}
|
||||
Install “{name}” in place of the plug-in with the same ID? დავაყენოთ „{name}“ იმავე ID-ის მქონე პლაგინის ნაცვლად?
|
||||
This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. ეს ფაილი არ არის ამ ID-ით ადრე დაყენებული პლაგინი. ის მიიღებს ამ ID-სთვის შენახულ პარამეტრებს და ქეშს.
|
||||
@@ -9737,6 +9738,11 @@ axis Y Axis Y ღერძი
|
||||
@msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed „{name}“-ს არ მიეცა `{p}`, რომელიც მის შედეგს სჭირდება: არაფერი შეცვლილა
|
||||
@msg a heavy filter runs in the background, so it can't declare `commands` მძიმე ფილტრი ფონურ რეჟიმში მუშაობს, ამიტომ მას არ შეუძლია `commands`-ის გამოცხადება
|
||||
@msg at most {MAX_COMMANDS} `commands` მაქსიმუმ {MAX_COMMANDS} `commands`
|
||||
@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` იძლევა მაქსიმუმ {MAX_LANGUAGES} ენას
|
||||
@msg {at} gives two options the same label {at} ორ ვარიანტს ერთსა და იმავე წარწერას აძლევს
|
||||
@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} არ არის ენის კოდი, როგორიცაა `de` ან `pt-BR`, ან იმეორებს ადრე მოცემულ კოდს
|
||||
@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} უნდა იყოს 1-{max} დასაბეჭდი სიმბოლო, მიმართულების და ხაზის გამყოფი სიმბოლოების გარეშე
|
||||
@msg {at} names or translates something the manifest doesn't declare {at} ასახელებს ან თარგმნის რაღაცას, რასაც მანიფესტი არ აცხადებს
|
||||
@msg command {name} is declared twice ბრძანება {name} ორჯერაა გამოცხადებული
|
||||
@msg command {name}: `label` must be 1-64 printable characters ბრძანება {name}: `label` უნდა შედგებოდეს 1-64 დასაბეჭდი სიმბოლოსგან
|
||||
@msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter ბრძანება {name}: გამოიყენეთ 1-{MAX_COMMAND_ID} სიმბოლოიანი id a-z 0-9 _ სიმბოლოებიდან, რომელიც ასოთი იწყება
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -5753,7 +5753,7 @@ variable-list-end {0}, {1} {0} 및 {1}
|
||||
Do not show this warning again 이 경고를 다시 표시하지 않음
|
||||
Stop the script and undo what it did? Then quit again. 스크립트를 중지하고 변경 내용을 취소할까요? 그런 다음 다시 종료하세요.
|
||||
This script has added a great many objects. Continue, or stop it and undo what it did? 이 스크립트가 매우 많은 개체를 추가했습니다. 계속할까요, 아니면 중지하고 변경 내용을 취소할까요?
|
||||
@msg Choose a .js or .jsx script .js 또는 .jsx 스크립트를 선택하세요
|
||||
@msg Choose a .js, .mjs or .jsx script .js, .mjs 또는 .jsx 스크립트를 선택하세요
|
||||
@msg Ran {name} {name} 실행됨
|
||||
@msg The script was stopped and its changes were undone 스크립트를 중지하고 변경 내용을 취소했습니다
|
||||
@msg a script is running: stop it or wait for it to finish 스크립트 실행 중: 중지하거나 끝날 때까지 기다리세요
|
||||
@@ -5900,7 +5900,7 @@ liquify-list-end {0}, {1} {0} 및 {1}
|
||||
@msg `args` is larger than 1 MiB `args`이(가) 1 MiB보다 큽니다
|
||||
@msg `path` is empty `path`이(가) 비어 있습니다
|
||||
@msg `installed` takes a `path`, not a `source` `installed`에는 `source`가 아니라 `path`를 지정하세요
|
||||
@msg `path` must name a .js or .jsx file `path`은(는) .js 또는 .jsx 파일을 가리켜야 합니다
|
||||
@msg `path` must name a .js, .mjs or .jsx file `path`은(는) .js, .mjs 또는 .jsx 파일을 가리켜야 합니다
|
||||
@msg give exactly one of `path` and `source` `path`, `source` 중 정확히 하나를 지정하세요
|
||||
@msg Running a script 스크립트 실행 중
|
||||
@msg Copied the script report 스크립트 보고서를 복사했습니다
|
||||
@@ -7109,6 +7109,7 @@ axis Y Axis Y축
|
||||
# Plug-in permissions (Install Plug-in…, plugin.install grant)
|
||||
Install “{name}”, which asks for these permissions? 이 권한을 요청하는 “{name}”을(를) 설치하시겠습니까?
|
||||
ID: {id} ID: {id}
|
||||
Manifest name: {name} 매니페스트의 이름: {name}
|
||||
Version: {version} 버전: {version}
|
||||
Install “{name}” in place of the plug-in with the same ID? 같은 ID의 플러그인 대신 “{name}”을(를) 설치하시겠습니까?
|
||||
This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. 이 파일은 이전에 이 ID로 설치된 플러그인이 아닙니다. 이 ID에 보관된 설정과 캐시를 받습니다.
|
||||
@@ -7222,6 +7223,11 @@ axis Y Axis Y축
|
||||
@msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed “{name}”에 출력에 필요한 `{p}` 권한이 부여되지 않았습니다. 아무것도 변경되지 않았습니다
|
||||
@msg a heavy filter runs in the background, so it can't declare `commands` 무거운 필터는 백그라운드에서 실행되므로 `commands`를 선언할 수 없습니다
|
||||
@msg at most {MAX_COMMANDS} `commands` `commands`는 최대 {MAX_COMMANDS}개입니다
|
||||
@msg `translations` gives at most {MAX_LANGUAGES} languages `translations`에는 언어를 최대 {MAX_LANGUAGES}개까지 지정할 수 있습니다
|
||||
@msg {at} gives two options the same label {at}에서 두 옵션에 같은 레이블을 지정했습니다
|
||||
@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at}은(는) `de`나 `pt-BR` 같은 언어 코드가 아니거나 앞에서 지정한 코드를 반복합니다
|
||||
@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at}은(는) 방향 문자나 줄 구분 문자 없이 인쇄 가능한 문자 1-{max}자여야 합니다
|
||||
@msg {at} names or translates something the manifest doesn't declare {at}은(는) 매니페스트가 선언하지 않은 항목을 지정하거나 번역합니다
|
||||
@msg command {name} is declared twice 명령 {name}이(가) 두 번 선언되었습니다
|
||||
@msg command {name}: `label` must be 1-64 printable characters 명령 {name}: `label`은 인쇄 가능한 문자 1-64자여야 합니다
|
||||
@msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter 명령 {name}: a-z 0-9 _로 이루어지고 문자로 시작하는 1-{MAX_COMMAND_ID}자 ID를 사용하세요
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -54,7 +54,7 @@
|
||||
@msg it decompresses to more than {_1} MB gedecomprimeerd is het groter dan {_1} MB
|
||||
@msg its editing data is for a different page zijn bewerkingsgegevens horen bij een andere pagina
|
||||
@msg `fontHeightReference` must be "emBox", "capHeight", "xHeight" or "icfBox" `fontHeightReference` moet "emBox", "capHeight", "xHeight" of "icfBox" zijn
|
||||
@msg Choose a .js or .jsx script Kies een .js- of .jsx-script
|
||||
@msg Choose a .js, .mjs or .jsx script Kies een .js-, .mjs- of .jsx-script
|
||||
@msg Ran {name} {name} uitgevoerd
|
||||
@msg The script was stopped and its changes were undone Het script is gestopt en de wijzigingen ervan zijn ongedaan gemaakt
|
||||
@msg a script is running: stop it or wait for it to finish er wordt een script uitgevoerd: stop het of wacht tot het klaar is
|
||||
@@ -221,7 +221,7 @@ liquify-list-end {0}, {1} {0} en {1}
|
||||
@msg `args` is larger than 1 MiB `args` is groter dan 1 MiB
|
||||
@msg `path` is empty `path` is leeg
|
||||
@msg `installed` takes a `path`, not a `source` `installed` neemt een `path`, geen `source`
|
||||
@msg `path` must name a .js or .jsx file `path` moet een .js- of .jsx-bestand aanwijzen
|
||||
@msg `path` must name a .js, .mjs or .jsx file `path` moet een .js-, .mjs- of .jsx-bestand aanwijzen
|
||||
@msg give exactly one of `path` and `source` geef precies een van `path` en `source`
|
||||
@msg Running a script Er wordt een script uitgevoerd
|
||||
@msg Data Recovery can't keep copies in {path}: {e} Gegevensherstel kan geen kopieën bewaren in {path}: {e}
|
||||
@@ -640,6 +640,11 @@ liquify-list-end {0}, {1} {0} en {1}
|
||||
@msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed „{name}” heeft `{p}` niet gekregen, wat de uitvoer ervan nodig heeft: er is niets gewijzigd
|
||||
@msg a heavy filter runs in the background, so it can't declare `commands` een zwaar filter wordt op de achtergrond uitgevoerd, dus kan het geen `commands` declareren
|
||||
@msg at most {MAX_COMMANDS} `commands` maximaal {MAX_COMMANDS} `commands`
|
||||
@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` geeft maximaal {MAX_LANGUAGES} talen
|
||||
@msg {at} gives two options the same label {at} geeft twee opties hetzelfde label
|
||||
@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} is geen taalcode zoals `de` of `pt-BR`, of herhaalt een eerder gegeven code
|
||||
@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} moet 1-{max} afdrukbare tekens zijn, zonder richtings- of regelscheidingstekens
|
||||
@msg {at} names or translates something the manifest doesn't declare {at} noemt of vertaalt iets wat het manifest niet declareert
|
||||
@msg command {name} is declared twice opdracht {name} is twee keer gedeclareerd
|
||||
@msg command {name}: `label` must be 1-64 printable characters opdracht {name}: `label` moet uit 1-64 afdrukbare tekens bestaan
|
||||
@msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter opdracht {name}: gebruik een id van 1-{MAX_COMMAND_ID} tekens uit a-z 0-9 _ die met een letter begint
|
||||
@@ -9589,6 +9594,7 @@ axis Y Axis Y-as
|
||||
# Plug-in permissions (Install Plug-in…, plugin.install grant)
|
||||
Install “{name}”, which asks for these permissions? „{name}” installeren, dat om deze machtigingen vraagt?
|
||||
ID: {id} ID: {id}
|
||||
Manifest name: {name} Naam in het manifest: {name}
|
||||
Version: {version} Versie: {version}
|
||||
Install “{name}” in place of the plug-in with the same ID? „{name}” installeren in plaats van de plug-in met dezelfde ID?
|
||||
This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Dit bestand is niet de plug-in die eerder met deze ID was geïnstalleerd. Het krijgt de instellingen en cache die voor die ID bewaard zijn.
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -5099,7 +5099,7 @@ imageTrace Outline Kontur
|
||||
Do not show this warning again Nie pokazuj więcej tego ostrzeżenia
|
||||
Stop the script and undo what it did? Then quit again. Zatrzymać skrypt i cofnąć jego zmiany? Następnie zakończ program ponownie.
|
||||
This script has added a great many objects. Continue, or stop it and undo what it did? Ten skrypt dodał bardzo wiele obiektów. Kontynuować, czy zatrzymać go i cofnąć jego zmiany?
|
||||
@msg Choose a .js or .jsx script Wybierz skrypt .js lub .jsx
|
||||
@msg Choose a .js, .mjs or .jsx script Wybierz skrypt .js, .mjs lub .jsx
|
||||
@msg Ran {name} Wykonano: {name}
|
||||
@msg The script was stopped and its changes were undone Skrypt został zatrzymany, a jego zmiany cofnięte
|
||||
@msg a script is running: stop it or wait for it to finish skrypt jest uruchomiony: zatrzymaj go lub poczekaj na jego zakończenie
|
||||
@@ -7370,6 +7370,7 @@ axis Y Axis Oś Y
|
||||
# Plug-in permissions (Install Plug-in…, plugin.install grant)
|
||||
Install “{name}”, which asks for these permissions? Zainstalować „{name}”, wtyczkę, która prosi o te uprawnienia?
|
||||
ID: {id} ID: {id}
|
||||
Manifest name: {name} Nazwa w manifeście: {name}
|
||||
Version: {version} Wersja: {version}
|
||||
Install “{name}” in place of the plug-in with the same ID? Zainstalować „{name}” zamiast wtyczki o tym samym ID?
|
||||
This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Ten plik nie jest wtyczką zainstalowaną wcześniej z tym ID. Otrzyma ustawienia i pamięć podręczną przechowywane dla tego ID.
|
||||
@@ -7483,6 +7484,11 @@ axis Y Axis Oś Y
|
||||
@msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed „{name}” nie otrzymała `{p}`, którego potrzebuje jej wynik: nic nie zmieniono
|
||||
@msg a heavy filter runs in the background, so it can't declare `commands` ciężki filtr działa w tle, więc nie może deklarować `commands`
|
||||
@msg at most {MAX_COMMANDS} `commands` najwyżej {MAX_COMMANDS} `commands`
|
||||
@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` podaje najwyżej {MAX_LANGUAGES} języków
|
||||
@msg {at} gives two options the same label {at} nadaje dwóm opcjom tę samą etykietę
|
||||
@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} nie jest kodem języka takim jak `de` czy `pt-BR` albo powtarza kod podany wcześniej
|
||||
@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} musi mieć 1-{max} drukowalnych znaków, bez znaków kierunku tekstu i separatorów wierszy
|
||||
@msg {at} names or translates something the manifest doesn't declare {at} nazywa lub tłumaczy coś, czego manifest nie deklaruje
|
||||
@msg command {name} is declared twice polecenie {name} jest zadeklarowane dwa razy
|
||||
@msg command {name}: `label` must be 1-64 printable characters polecenie {name}: `label` musi mieć 1-64 drukowalnych znaków
|
||||
@msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter polecenie {name}: użyj id z 1-{MAX_COMMAND_ID} znaków spośród a-z 0-9 _, zaczynającego się od litery
|
||||
@@ -8830,7 +8836,7 @@ breakText Glyphs Glify
|
||||
@msg `args` is larger than 1 MiB `args` ma rozmiar większy niż 1 MiB
|
||||
@msg `path` is empty `path` jest puste
|
||||
@msg `installed` takes a `path`, not a `source` `installed` przyjmuje `path`, a nie `source`
|
||||
@msg `path` must name a .js or .jsx file `path` musi wskazywać plik .js lub .jsx
|
||||
@msg `path` must name a .js, .mjs or .jsx file `path` musi wskazywać plik .js, .mjs lub .jsx
|
||||
@msg give exactly one of `path` and `source` podaj dokładnie jedno z: `path` i `source`
|
||||
@msg `answers` must be a list of answers `answers` musi być listą odpowiedzi
|
||||
@msg `artboard` must be the index of an artboard of the document `artboard` musi być indeksem obszaru kompozycji dokumentu
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -6144,7 +6144,7 @@ variable-list-end {0}, {1} {0} e {1}
|
||||
Do not show this warning again Não mostrar este aviso novamente
|
||||
Stop the script and undo what it did? Then quit again. Parar o script e desfazer o que ele fez? Depois, saia novamente.
|
||||
This script has added a great many objects. Continue, or stop it and undo what it did? Este script adicionou muitíssimos objetos. Continuar, ou pará-lo e desfazer o que ele fez?
|
||||
@msg Choose a .js or .jsx script Escolha um script .js ou .jsx
|
||||
@msg Choose a .js, .mjs or .jsx script Escolha um script .js, .mjs ou .jsx
|
||||
@msg Ran {name} {name} executado
|
||||
@msg The script was stopped and its changes were undone O script foi parado e suas alterações foram desfeitas
|
||||
@msg a script is running: stop it or wait for it to finish um script está em execução: pare-o ou aguarde até que termine
|
||||
@@ -7416,6 +7416,7 @@ axis Y Axis Eixo Y
|
||||
# Plug-in permissions (Install Plug-in…, plugin.install grant)
|
||||
Install “{name}”, which asks for these permissions? Instalar “{name}”, que pede estas permissões?
|
||||
ID: {id} ID: {id}
|
||||
Manifest name: {name} Nome no manifesto: {name}
|
||||
Version: {version} Versão: {version}
|
||||
Install “{name}” in place of the plug-in with the same ID? Instalar “{name}” no lugar do plug-in com o mesmo ID?
|
||||
This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Este arquivo não é o plug-in instalado antes com este ID. Ele recebe as configurações e o cache guardados para esse ID.
|
||||
@@ -7529,6 +7530,11 @@ axis Y Axis Eixo Y
|
||||
@msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed “{name}” não recebeu `{p}`, de que sua saída precisa: nada foi alterado
|
||||
@msg a heavy filter runs in the background, so it can't declare `commands` um filtro pesado é executado em segundo plano, então não pode declarar `commands`
|
||||
@msg at most {MAX_COMMANDS} `commands` no máximo {MAX_COMMANDS} `commands`
|
||||
@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` dá no máximo {MAX_LANGUAGES} idiomas
|
||||
@msg {at} gives two options the same label {at} dá o mesmo rótulo a duas opções
|
||||
@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} não é um código de idioma como `de` ou `pt-BR`, ou repete um dado antes
|
||||
@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} deve ter 1-{max} caracteres imprimíveis, sem caracteres de direção ou separadores de linha
|
||||
@msg {at} names or translates something the manifest doesn't declare {at} nomeia ou traduz algo que o manifesto não declara
|
||||
@msg command {name} is declared twice o comando {name} está declarado duas vezes
|
||||
@msg command {name}: `label` must be 1-64 printable characters comando {name}: `label` deve ter 1-64 caracteres imprimíveis
|
||||
@msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter comando {name}: use um id de 1-{MAX_COMMAND_ID} caracteres de a-z 0-9 _ que comece com uma letra
|
||||
@@ -9201,7 +9207,7 @@ swatch Yellow Green Verde-amarelado
|
||||
@msg `args` is larger than 1 MiB `args` tem mais de 1 MiB
|
||||
@msg `path` is empty `path` está vazio
|
||||
@msg `installed` takes a `path`, not a `source` `installed` aceita um `path`, não um `source`
|
||||
@msg `path` must name a .js or .jsx file `path` deve indicar um arquivo .js ou .jsx
|
||||
@msg `path` must name a .js, .mjs or .jsx file `path` deve indicar um arquivo .js, .mjs ou .jsx
|
||||
@msg give exactly one of `path` and `source` informe exatamente um de `path` e `source`
|
||||
@msg `answers` must be a list of answers `answers` deve ser uma lista de respostas
|
||||
@msg `artboard` must be the index of an artboard of the document `artboard` deve ser o índice de uma prancheta do documento
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -4973,7 +4973,7 @@ axis Both Оба
|
||||
Do not show this warning again Больше не показывать это предупреждение
|
||||
Stop the script and undo what it did? Then quit again. Остановить скрипт и отменить его изменения? Затем выйдите ещё раз.
|
||||
This script has added a great many objects. Continue, or stop it and undo what it did? Этот скрипт добавил очень много объектов. Продолжить или остановить его и отменить его изменения?
|
||||
@msg Choose a .js or .jsx script Выберите скрипт .js или .jsx
|
||||
@msg Choose a .js, .mjs or .jsx script Выберите скрипт .js, .mjs или .jsx
|
||||
@msg Ran {name} Выполнено: {name}
|
||||
@msg The script was stopped and its changes were undone Скрипт остановлен, его изменения отменены
|
||||
@msg a script is running: stop it or wait for it to finish выполняется скрипт: остановите его или дождитесь завершения
|
||||
@@ -5132,7 +5132,7 @@ liquify-list-end {0}, {1} {0} и {1}
|
||||
@msg `args` is larger than 1 MiB `args` больше 1 МиБ
|
||||
@msg `path` is empty параметр `path` пуст
|
||||
@msg `installed` takes a `path`, not a `source` `installed` принимает `path`, а не `source`
|
||||
@msg `path` must name a .js or .jsx file `path` должен указывать на файл .js или .jsx
|
||||
@msg `path` must name a .js, .mjs or .jsx file `path` должен указывать на файл .js, .mjs или .jsx
|
||||
@msg give exactly one of `path` and `source` укажите ровно одно из: `path` и `source`
|
||||
@msg Running a script Выполняется скрипт
|
||||
@msg Copied the script report Отчёт о сценарии скопирован
|
||||
@@ -7139,6 +7139,7 @@ axis Y Axis Ось Y
|
||||
# Plug-in permissions (Install Plug-in…, plugin.install grant)
|
||||
Install “{name}”, which asks for these permissions? Установить «{name}», которому нужны эти разрешения?
|
||||
ID: {id} ID: {id}
|
||||
Manifest name: {name} Имя в манифесте: {name}
|
||||
Version: {version} Версия: {version}
|
||||
Install “{name}” in place of the plug-in with the same ID? Установить «{name}» вместо модуля с тем же ID?
|
||||
This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Этот файл не является модулем, установленным ранее с этим ID. Он получит настройки и кэш, сохранённые для этого ID.
|
||||
@@ -7252,6 +7253,11 @@ axis Y Axis Ось Y
|
||||
@msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed «{name}» не получил разрешение `{p}`, нужное для его результата: ничего не изменено
|
||||
@msg a heavy filter runs in the background, so it can't declare `commands` тяжёлый фильтр выполняется в фоне, поэтому не может объявлять `commands`
|
||||
@msg at most {MAX_COMMANDS} `commands` не более {MAX_COMMANDS} `commands`
|
||||
@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` задаёт не более {MAX_LANGUAGES} языков
|
||||
@msg {at} gives two options the same label {at} даёт двум вариантам одинаковую подпись
|
||||
@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} не является кодом языка вроде `de` или `pt-BR` или повторяет код, заданный ранее
|
||||
@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} должен содержать 1-{max} печатных символов без символов направления текста и разделителей строк
|
||||
@msg {at} names or translates something the manifest doesn't declare {at} называет или переводит то, что манифест не объявляет
|
||||
@msg command {name} is declared twice команда {name} объявлена дважды
|
||||
@msg command {name}: `label` must be 1-64 printable characters команда {name}: `label` должен содержать 1-64 печатаемых символа
|
||||
@msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter команда {name}: используйте id из 1-{MAX_COMMAND_ID} символов a-z 0-9 _, начинающийся с буквы
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -4832,7 +4832,7 @@ axis Both Båda
|
||||
Do not show this warning again Visa inte den här varningen igen
|
||||
Stop the script and undo what it did? Then quit again. Stoppa skriptet och ångra det det gjort? Avsluta sedan igen.
|
||||
This script has added a great many objects. Continue, or stop it and undo what it did? Det här skriptet har lagt till väldigt många objekt. Fortsätta, eller stoppa det och ångra det det gjort?
|
||||
@msg Choose a .js or .jsx script Välj ett .js- eller .jsx-skript
|
||||
@msg Choose a .js, .mjs or .jsx script Välj ett .js-, .mjs- eller .jsx-skript
|
||||
@msg Ran {name} Körde {name}
|
||||
@msg The script was stopped and its changes were undone Skriptet stoppades och dess ändringar ångrades
|
||||
@msg a script is running: stop it or wait for it to finish ett skript körs: stoppa det eller vänta tills det är klart
|
||||
@@ -5005,7 +5005,7 @@ liquify-list-end {0}, {1} {0} och {1}
|
||||
@msg `args` is larger than 1 MiB `args` är större än 1 MiB
|
||||
@msg `path` is empty `path` är tomt
|
||||
@msg `installed` takes a `path`, not a `source` `installed` tar en `path`, inte en `source`
|
||||
@msg `path` must name a .js or .jsx file `path` måste ange en .js- eller .jsx-fil
|
||||
@msg `path` must name a .js, .mjs or .jsx file `path` måste ange en .js-, .mjs- eller .jsx-fil
|
||||
@msg give exactly one of `path` and `source` ange exakt en av `path` och `source`
|
||||
@msg Running a script Kör ett skript
|
||||
@msg Copied the script report Kopierade skriptrapporten
|
||||
@@ -7519,6 +7519,7 @@ axis Y Axis Y-axel
|
||||
# Plug-in permissions (Install Plug-in…, plugin.install grant)
|
||||
Install “{name}”, which asks for these permissions? Installera ”{name}”, som begär dessa behörigheter?
|
||||
ID: {id} ID: {id}
|
||||
Manifest name: {name} Namn i manifestet: {name}
|
||||
Version: {version} Version: {version}
|
||||
Install “{name}” in place of the plug-in with the same ID? Installera ”{name}” i stället för det plugin som har samma id?
|
||||
This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Den här filen är inte det plugin som tidigare installerades med detta id. Den får de inställningar och den cache som sparats för detta id.
|
||||
@@ -7613,6 +7614,11 @@ axis Y Axis Y-axel
|
||||
@msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed ”{name}” beviljades inte `{p}`, som dess utdata behöver: ingenting ändrades
|
||||
@msg a heavy filter runs in the background, so it can't declare `commands` ett tungt filter körs i bakgrunden, så det kan inte deklarera `commands`
|
||||
@msg at most {MAX_COMMANDS} `commands` högst {MAX_COMMANDS} `commands`
|
||||
@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` anger högst {MAX_LANGUAGES} språk
|
||||
@msg {at} gives two options the same label {at} ger två alternativ samma etikett
|
||||
@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} är inte en språkkod som `de` eller `pt-BR`, eller upprepar en som angetts tidigare
|
||||
@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} måste vara 1-{max} utskrivbara tecken, utan riktnings- eller radavgränsartecken
|
||||
@msg {at} names or translates something the manifest doesn't declare {at} namnger eller översätter något som manifestet inte deklarerar
|
||||
@msg command {name} is declared twice kommandot {name} deklareras två gånger
|
||||
@msg command {name}: `label` must be 1-64 printable characters kommando {name}: `label` måste ha 1-64 utskrivbara tecken
|
||||
@msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter kommando {name}: använd ett id med 1-{MAX_COMMAND_ID} tecken av a-z 0-9 _ som börjar med en bokstav
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -4678,7 +4678,7 @@ axis Both Her İkisi
|
||||
Do not show this warning again Bu uyarıyı bir daha gösterme
|
||||
Stop the script and undo what it did? Then quit again. Betik durdurulsun ve yaptıkları geri alınsın mı? Ardından yeniden çıkın.
|
||||
This script has added a great many objects. Continue, or stop it and undo what it did? Bu betik çok sayıda nesne ekledi. Devam edilsin mi, yoksa durdurulup yaptıkları geri mi alınsın?
|
||||
@msg Choose a .js or .jsx script Bir .js veya .jsx betiği seçin
|
||||
@msg Choose a .js, .mjs or .jsx script Bir .js, .mjs veya .jsx betiği seçin
|
||||
@msg Ran {name} {name} çalıştırıldı
|
||||
@msg The script was stopped and its changes were undone Betik durduruldu ve değişiklikleri geri alındı
|
||||
@msg a script is running: stop it or wait for it to finish bir betik çalışıyor: durdurun veya bitmesini bekleyin
|
||||
@@ -4833,7 +4833,7 @@ liquify-list-end {0}, {1} {0} ve {1}
|
||||
@msg `args` is larger than 1 MiB `args` 1 MiB'tan büyük
|
||||
@msg `path` is empty `path` boş
|
||||
@msg `installed` takes a `path`, not a `source` `installed` bir `path` alır, `source` almaz
|
||||
@msg `path` must name a .js or .jsx file `path` bir .js veya .jsx dosyasını adlandırmalıdır
|
||||
@msg `path` must name a .js, .mjs or .jsx file `path` bir .js, .mjs veya .jsx dosyasını adlandırmalıdır
|
||||
@msg give exactly one of `path` and `source` `path` ve `source` değerlerinden tam olarak birini verin
|
||||
@msg Running a script Betik çalıştırılıyor
|
||||
@msg Copied the script report Komut dosyası raporu kopyalandı
|
||||
@@ -7589,6 +7589,7 @@ axis Y Axis Y ekseni
|
||||
# Plug-in permissions (Install Plug-in…, plugin.install grant)
|
||||
Install “{name}”, which asks for these permissions? Bu izinleri isteyen “{name}” yüklensin mi?
|
||||
ID: {id} Kimlik: {id}
|
||||
Manifest name: {name} Manifestteki ad: {name}
|
||||
Version: {version} Sürüm: {version}
|
||||
Install “{name}” in place of the plug-in with the same ID? Aynı kimliğe sahip eklentinin yerine “{name}” yüklensin mi?
|
||||
This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Bu dosya, daha önce bu kimlikle yüklenen eklenti değil. O kimlik için saklanan ayarları ve önbelleği alır.
|
||||
@@ -7702,6 +7703,11 @@ axis Y Axis Y ekseni
|
||||
@msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed “{name}” öğesine çıktısının ihtiyaç duyduğu `{p}` izni verilmedi: hiçbir şey değiştirilmedi
|
||||
@msg a heavy filter runs in the background, so it can't declare `commands` ağır bir filtre arka planda çalışır, bu yüzden `commands` bildiremez
|
||||
@msg at most {MAX_COMMANDS} `commands` en fazla {MAX_COMMANDS} `commands`
|
||||
@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` en fazla {MAX_LANGUAGES} dil verir
|
||||
@msg {at} gives two options the same label {at} iki seçeneğe aynı etiketi veriyor
|
||||
@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at}, `de` veya `pt-BR` gibi bir dil kodu değil ya da daha önce verilmiş bir kodu yineliyor
|
||||
@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at}, yön veya satır ayırıcı karakterleri olmadan 1-{max} yazdırılabilir karakter olmalıdır
|
||||
@msg {at} names or translates something the manifest doesn't declare {at}, manifestin bildirmediği bir şeyi adlandırıyor veya çeviriyor
|
||||
@msg command {name} is declared twice {name} komutu iki kez bildirilmiş
|
||||
@msg command {name}: `label` must be 1-64 printable characters {name} komutu: `label` 1-64 yazdırılabilir karakter olmalıdır
|
||||
@msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter {name} komutu: a-z 0-9 _ karakterlerinden oluşan ve harfle başlayan 1-{MAX_COMMAND_ID} karakterlik bir kimlik kullanın
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -4981,7 +4981,7 @@ axis Both Обидві
|
||||
Do not show this warning again Більше не показувати це попередження
|
||||
Stop the script and undo what it did? Then quit again. Зупинити скрипт і скасувати його зміни? Потім вийдіть ще раз.
|
||||
This script has added a great many objects. Continue, or stop it and undo what it did? Цей скрипт додав дуже багато об’єктів. Продовжити чи зупинити його та скасувати його зміни?
|
||||
@msg Choose a .js or .jsx script Виберіть скрипт .js або .jsx
|
||||
@msg Choose a .js, .mjs or .jsx script Виберіть скрипт .js, .mjs або .jsx
|
||||
@msg Ran {name} Виконано: {name}
|
||||
@msg The script was stopped and its changes were undone Скрипт зупинено, його зміни скасовано
|
||||
@msg a script is running: stop it or wait for it to finish виконується скрипт: зупиніть його або дочекайтеся завершення
|
||||
@@ -7119,6 +7119,7 @@ axis Y Axis Вісь Y
|
||||
# Plug-in permissions (Install Plug-in…, plugin.install grant)
|
||||
Install “{name}”, which asks for these permissions? Встановити «{name}», якому потрібні ці дозволи?
|
||||
ID: {id} ID: {id}
|
||||
Manifest name: {name} Назва в маніфесті: {name}
|
||||
Version: {version} Версія: {version}
|
||||
Install “{name}” in place of the plug-in with the same ID? Встановити «{name}» замість модуля з тим самим ID?
|
||||
This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Цей файл не є модулем, установленим раніше з цим ID. Він отримає налаштування й кеш, збережені для цього ID.
|
||||
@@ -7232,6 +7233,11 @@ axis Y Axis Вісь Y
|
||||
@msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed «{name}» не отримав дозволу `{p}`, потрібного для його результату: нічого не змінено
|
||||
@msg a heavy filter runs in the background, so it can't declare `commands` важкий фільтр виконується у фоні, тому не може оголошувати `commands`
|
||||
@msg at most {MAX_COMMANDS} `commands` щонайбільше {MAX_COMMANDS} `commands`
|
||||
@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` задає щонайбільше {MAX_LANGUAGES} мов
|
||||
@msg {at} gives two options the same label {at} дає двом варіантам однаковий підпис
|
||||
@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} не є кодом мови на кшталт `de` чи `pt-BR` або повторює код, заданий раніше
|
||||
@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} має містити 1-{max} друкованих символів без символів напрямку тексту й розділювачів рядків
|
||||
@msg {at} names or translates something the manifest doesn't declare {at} називає або перекладає те, чого маніфест не оголошує
|
||||
@msg command {name} is declared twice команду {name} оголошено двічі
|
||||
@msg command {name}: `label` must be 1-64 printable characters команда {name}: `label` має містити 1-64 друковані символи
|
||||
@msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter команда {name}: використайте id з 1-{MAX_COMMAND_ID} символів a-z 0-9 _, що починається з літери
|
||||
@@ -8786,7 +8792,7 @@ breakText Glyphs Гліфи
|
||||
@msg `args` is larger than 1 MiB `args` більший за 1 МіБ
|
||||
@msg `path` is empty параметр `path` порожній
|
||||
@msg `installed` takes a `path`, not a `source` `installed` приймає `path`, а не `source`
|
||||
@msg `path` must name a .js or .jsx file `path` має вказувати на файл .js або .jsx
|
||||
@msg `path` must name a .js, .mjs or .jsx file `path` має вказувати на файл .js, .mjs або .jsx
|
||||
@msg give exactly one of `path` and `source` укажіть рівно одне з: `path`, `source`
|
||||
@msg `answers` must be a list of answers `answers` має бути списком відповідей
|
||||
@msg `artboard` must be the index of an artboard of the document `artboard` має бути індексом монтажної області документа
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -5460,7 +5460,7 @@ theme Appearance Giao diện
|
||||
Do not show this warning again Không hiện lại cảnh báo này
|
||||
Stop the script and undo what it did? Then quit again. Dừng tập lệnh và hoàn tác những gì nó đã làm? Sau đó hãy thoát lại.
|
||||
This script has added a great many objects. Continue, or stop it and undo what it did? Tập lệnh này đã thêm rất nhiều đối tượng. Tiếp tục, hay dừng lại và hoàn tác những gì nó đã làm?
|
||||
@msg Choose a .js or .jsx script Chọn một tập lệnh .js hoặc .jsx
|
||||
@msg Choose a .js, .mjs or .jsx script Chọn một tập lệnh .js, .mjs hoặc .jsx
|
||||
@msg Ran {name} Đã chạy {name}
|
||||
@msg The script was stopped and its changes were undone Tập lệnh đã dừng và các thay đổi của nó đã được hoàn tác
|
||||
@msg a script is running: stop it or wait for it to finish một tập lệnh đang chạy: hãy dừng nó hoặc chờ nó kết thúc
|
||||
@@ -5632,7 +5632,7 @@ liquify-list-end {0}, {1} {0} và {1}
|
||||
@msg `args` is larger than 1 MiB `args` lớn hơn 1 MiB
|
||||
@msg `path` is empty `path` trống
|
||||
@msg `installed` takes a `path`, not a `source` `installed` nhận `path`, không nhận `source`
|
||||
@msg `path` must name a .js or .jsx file `path` phải chỉ đến tệp .js hoặc .jsx
|
||||
@msg `path` must name a .js, .mjs or .jsx file `path` phải chỉ đến tệp .js, .mjs hoặc .jsx
|
||||
@msg give exactly one of `path` and `source` hãy cung cấp đúng một trong `path` và `source`
|
||||
@msg Running a script Đang chạy tập lệnh
|
||||
@msg Copied the script report Đã sao chép báo cáo script
|
||||
@@ -7168,6 +7168,7 @@ axis Y Axis Trục Y
|
||||
# Plug-in permissions (Install Plug-in…, plugin.install grant)
|
||||
Install “{name}”, which asks for these permissions? Cài đặt “{name}”, plug-in yêu cầu các quyền này?
|
||||
ID: {id} ID: {id}
|
||||
Manifest name: {name} Tên trong manifest: {name}
|
||||
Version: {version} Phiên bản: {version}
|
||||
Install “{name}” in place of the plug-in with the same ID? Cài đặt “{name}” thay cho plug-in có cùng ID?
|
||||
This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Tệp này không phải là plug-in đã cài đặt trước đây với ID này. Tệp sẽ nhận cài đặt và bộ nhớ đệm được lưu cho ID đó.
|
||||
@@ -7281,6 +7282,11 @@ axis Y Axis Trục Y
|
||||
@msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed “{name}” chưa được cấp `{p}`, quyền mà đầu ra của nó cần: không có gì thay đổi
|
||||
@msg a heavy filter runs in the background, so it can't declare `commands` bộ lọc nặng chạy ở chế độ nền nên không thể khai báo `commands`
|
||||
@msg at most {MAX_COMMANDS} `commands` tối đa {MAX_COMMANDS} `commands`
|
||||
@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` chỉ định tối đa {MAX_LANGUAGES} ngôn ngữ
|
||||
@msg {at} gives two options the same label {at} đặt cùng một nhãn cho hai tùy chọn
|
||||
@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} không phải mã ngôn ngữ như `de` hoặc `pt-BR`, hoặc lặp lại mã đã cho trước đó
|
||||
@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} phải có 1-{max} ký tự in được, không có ký tự định hướng hoặc ký tự phân cách dòng
|
||||
@msg {at} names or translates something the manifest doesn't declare {at} đặt tên hoặc dịch một thứ mà manifest không khai báo
|
||||
@msg command {name} is declared twice lệnh {name} được khai báo hai lần
|
||||
@msg command {name}: `label` must be 1-64 printable characters lệnh {name}: `label` phải có 1-64 ký tự in được
|
||||
@msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter lệnh {name}: hãy dùng id gồm 1-{MAX_COMMAND_ID} ký tự từ a-z 0-9 _ và bắt đầu bằng một chữ cái
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -5489,7 +5489,7 @@ imageTrace Outline 轮廓
|
||||
Do not show this warning again 不再显示此警告
|
||||
Stop the script and undo what it did? Then quit again. 要停止脚本并撤销其更改吗?然后请再次退出。
|
||||
This script has added a great many objects. Continue, or stop it and undo what it did? 此脚本已添加大量对象。要继续,还是停止并撤销其更改?
|
||||
@msg Choose a .js or .jsx script 请选择 .js 或 .jsx 脚本
|
||||
@msg Choose a .js, .mjs or .jsx script 请选择 .js、.mjs 或 .jsx 脚本
|
||||
@msg Ran {name} 已运行 {name}
|
||||
@msg The script was stopped and its changes were undone 脚本已停止,其更改已撤销
|
||||
@msg a script is running: stop it or wait for it to finish 脚本正在运行:请停止它或等待其完成
|
||||
@@ -7349,6 +7349,7 @@ axis Y Axis Y 轴
|
||||
# Plug-in permissions (Install Plug-in…, plugin.install grant)
|
||||
Install “{name}”, which asks for these permissions? 要安装需要这些权限的“{name}”吗?
|
||||
ID: {id} ID:{id}
|
||||
Manifest name: {name} 清单中的名称:{name}
|
||||
Version: {version} 版本:{version}
|
||||
Install “{name}” in place of the plug-in with the same ID? 要安装“{name}”来替换具有相同 ID 的插件吗?
|
||||
This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. 此文件不是之前以此 ID 安装的插件。它将获得为该 ID 保存的设置和缓存。
|
||||
@@ -7462,6 +7463,11 @@ axis Y Axis Y 轴
|
||||
@msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed “{name}”未获授予其输出所需的 `{p}`:未作任何更改
|
||||
@msg a heavy filter runs in the background, so it can't declare `commands` 重型滤镜在后台运行,因此不能声明 `commands`
|
||||
@msg at most {MAX_COMMANDS} `commands` 最多 {MAX_COMMANDS} 个 `commands`
|
||||
@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` 最多给出 {MAX_LANGUAGES} 种语言
|
||||
@msg {at} gives two options the same label {at} 为两个选项给出了相同的标签
|
||||
@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} 不是 `de` 或 `pt-BR` 这样的语言代码,或重复了前面给出的代码
|
||||
@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} 必须为 1-{max} 个可打印字符,且不含方向字符或行分隔符
|
||||
@msg {at} names or translates something the manifest doesn't declare {at} 指定或翻译了清单未声明的内容
|
||||
@msg command {name} is declared twice 命令 {name} 声明了两次
|
||||
@msg command {name}: `label` must be 1-64 printable characters 命令 {name}:`label` 必须是 1-64 个可打印字符
|
||||
@msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter 命令 {name}:请使用由 a-z 0-9 _ 组成、以字母开头的 1-{MAX_COMMAND_ID} 个字符的 ID
|
||||
@@ -8838,7 +8844,7 @@ breakText Glyphs 字形
|
||||
@msg `args` is larger than 1 MiB `args` 大于 1 MiB
|
||||
@msg `path` is empty `path` 为空
|
||||
@msg `installed` takes a `path`, not a `source` `installed` 需要 `path`,而不是 `source`
|
||||
@msg `path` must name a .js or .jsx file `path` 必须指向 .js 或 .jsx 文件
|
||||
@msg `path` must name a .js, .mjs or .jsx file `path` 必须指向 .js、.mjs 或 .jsx 文件
|
||||
@msg give exactly one of `path` and `source` `path` 和 `source` 中必须且只能给出一个
|
||||
@msg `answers` must be a list of answers `answers` 必须是回答的列表
|
||||
@msg `artboard` must be the index of an artboard of the document `artboard` 必须是文档中某个画板的索引
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -2821,7 +2821,7 @@ file-filter Templates 範本
|
||||
Do not show this warning again 不再顯示此警告
|
||||
Stop the script and undo what it did? Then quit again. 要停止指令碼並還原其變更嗎?然後請再次結束。
|
||||
This script has added a great many objects. Continue, or stop it and undo what it did? 此指令碼已新增大量物件。要繼續,還是停止並還原其變更?
|
||||
@msg Choose a .js or .jsx script 請選擇 .js 或 .jsx 指令碼
|
||||
@msg Choose a .js, .mjs or .jsx script 請選擇 .js、.mjs 或 .jsx 指令碼
|
||||
@msg Ran {name} 已執行 {name}
|
||||
@msg The script was stopped and its changes were undone 指令碼已停止,其變更已還原
|
||||
@msg a script is running: stop it or wait for it to finish 指令碼正在執行:請停止它或等待其完成
|
||||
@@ -2968,7 +2968,7 @@ liquify-list-end {0}, {1} {0}和{1}
|
||||
@msg `args` is larger than 1 MiB `args` 大於 1 MiB
|
||||
@msg `path` is empty `path` 為空
|
||||
@msg `installed` takes a `path`, not a `source` `installed` 需要 `path`,而不是 `source`
|
||||
@msg `path` must name a .js or .jsx file `path` 必須指向 .js 或 .jsx 檔案
|
||||
@msg `path` must name a .js, .mjs or .jsx file `path` 必須指向 .js、.mjs 或 .jsx 檔案
|
||||
@msg give exactly one of `path` and `source` `path` 和 `source` 請只提供其中一個
|
||||
@msg Running a script 正在執行指令碼
|
||||
@msg Copied the script report 已複製指令碼報告
|
||||
@@ -7168,6 +7168,7 @@ axis Y Axis Y 軸
|
||||
# Plug-in permissions (Install Plug-in…, plugin.install grant)
|
||||
Install “{name}”, which asks for these permissions? 要安裝需要這些權限的「{name}」嗎?
|
||||
ID: {id} ID:{id}
|
||||
Manifest name: {name} 資訊清單中的名稱:{name}
|
||||
Version: {version} 版本:{version}
|
||||
Install “{name}” in place of the plug-in with the same ID? 要安裝「{name}」來取代具有相同 ID 的增效模組嗎?
|
||||
This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. 此檔案不是先前以此 ID 安裝的增效模組。它會取得為該 ID 保存的設定和快取。
|
||||
@@ -7281,6 +7282,11 @@ axis Y Axis Y 軸
|
||||
@msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed 「{name}」未獲授予其輸出所需的 `{p}`:未做任何變更
|
||||
@msg a heavy filter runs in the background, so it can't declare `commands` 重型濾鏡在背景執行,因此不能宣告 `commands`
|
||||
@msg at most {MAX_COMMANDS} `commands` 最多 {MAX_COMMANDS} 個 `commands`
|
||||
@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` 最多提供 {MAX_LANGUAGES} 種語言
|
||||
@msg {at} gives two options the same label {at} 為兩個選項提供了相同的標籤
|
||||
@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} 不是 `de` 或 `pt-BR` 這類語言代碼,或重複了前面提供的代碼
|
||||
@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} 必須為 1-{max} 個可列印字元,且不含方向字元或行分隔字元
|
||||
@msg {at} names or translates something the manifest doesn't declare {at} 指定或翻譯了資訊清單未宣告的內容
|
||||
@msg command {name} is declared twice 指令 {name} 宣告了兩次
|
||||
@msg command {name}: `label` must be 1-64 printable characters 指令 {name}:`label` 必須是 1-64 個可列印字元
|
||||
@msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter 指令 {name}:請使用由 a-z 0-9 _ 組成、以字母開頭的 1-{MAX_COMMAND_ID} 個字元的 ID
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -9,6 +9,7 @@ use craft::platform::open::same_file;
|
||||
use super::save::{notes_of, show_with_notes, suggested};
|
||||
use super::{Value, VectorcraftApp, dialogs, fileio, json};
|
||||
use crate::file_asks::{self, Owner};
|
||||
use crate::i18n::LangExt as _;
|
||||
|
||||
/// Template extensions New from Template's open dialog lists first.
|
||||
const TEMPLATE_EXTS: &[&str] = &["vctemplate", "ait", "vectorcraft", "drawcraft"];
|
||||
@@ -294,10 +295,11 @@ fn permission_words(name: &str, commands: &[String], context: bool) -> String {
|
||||
/// Installs the plug-in module that `module` names (`plugin.install`'s `path`, or `dataBase64`
|
||||
/// with `name`) → `plugin.install`'s result. A plug-in that lists permissions no person has granted
|
||||
/// it yet asks first, showing its name, id, version, file hash and what each permission lets it
|
||||
/// do, so does a filter that asks for a heavy budget, and so does a module that would take the
|
||||
/// place of another one with its id and get its settings and cache (`replace`); OK installs it if
|
||||
/// the module still has the hash the prompt showed, Cancel installs nothing → `{pending}` while it
|
||||
/// asks. The `grant` and `allowHeavy` of a request are ignored: only the dialog's OK approves.
|
||||
/// do, so does a filter that asks for a heavy budget, showing its id and file hash, and so does a
|
||||
/// module that would take the place of another one with its id and get its settings and cache
|
||||
/// (`replace`). When the name shown is a translation, the id lines also give the manifest's own
|
||||
/// name. OK installs it if the module still has the hash the prompt showed, Cancel installs
|
||||
/// nothing → `{pending}` while it asks. The `grant` and `allowHeavy` of a request are ignored: only the dialog's OK approves.
|
||||
/// Every question opens the approval dialog ([`dialogs::plugin::ask_install`]). When automation
|
||||
/// asked ([`VectorcraftApp::automation_asked`]), the question has no OK that installs, its
|
||||
/// `replace: true` doesn't skip asking about replacing, and the answer while it asks adds
|
||||
@@ -336,12 +338,25 @@ pub(crate) fn install_module_as(app: &mut VectorcraftApp, module: Value, automat
|
||||
install["hash"] = info["hash"].clone();
|
||||
}
|
||||
let shown = |k: &str, max: usize| permissions::display_text(info[k].as_str().unwrap_or_default(), max);
|
||||
let name = shown("name", permissions::MAX_SHOWN_NAME);
|
||||
let identity = [
|
||||
crate::i18n::fmt(tl!("ID: {id}"), &[("id", &shown("id", permissions::MAX_SHOWN_FIELD))]),
|
||||
crate::i18n::fmt(tl!("File SHA-256: {hash}"), &[("hash", &shown("hash", 64))]),
|
||||
]
|
||||
.join("\n");
|
||||
// The question names the plug-in in the UI language when its manifest translates the name, and
|
||||
// then also gives the manifest's own name; both are fixed while the question is asked.
|
||||
let own_name = shown("name", permissions::MAX_SHOWN_NAME);
|
||||
let translations: vectorcraft_plugins::translations::Translations = serde_json::from_value(info["translations"].clone()).unwrap_or_default();
|
||||
let name = translations
|
||||
.name_in(crate::i18n::current().code())
|
||||
.map(|n| permissions::display_text(n.trim(), permissions::MAX_SHOWN_NAME))
|
||||
.unwrap_or_else(|| own_name.clone());
|
||||
let id_lines = |id_line: String| {
|
||||
let mut lines = vec![id_line];
|
||||
if name != own_name {
|
||||
lines.push(crate::i18n::fmt(tl!("Manifest name: {name}"), &[("name", &own_name)]));
|
||||
}
|
||||
lines
|
||||
};
|
||||
let id_line = crate::i18n::fmt(tl!("ID: {id}"), &[("id", &shown("id", permissions::MAX_SHOWN_FIELD))]);
|
||||
let mut identity = id_lines(id_line.clone());
|
||||
identity.push(crate::i18n::fmt(tl!("File SHA-256: {hash}"), &[("hash", &shown("hash", 64))]));
|
||||
let identity = identity.join("\n");
|
||||
let takes_place = tl!("This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID.");
|
||||
if asks_replace {
|
||||
install["replace"] = json!(true);
|
||||
@@ -351,7 +366,7 @@ pub(crate) fn install_module_as(app: &mut VectorcraftApp, module: Value, automat
|
||||
let asked = info["permissions"].as_array().cloned().unwrap_or_default();
|
||||
let mut paragraphs = vec![];
|
||||
if needs_grant {
|
||||
let mut lines = vec![crate::i18n::fmt(tl!("ID: {id}"), &[("id", &shown("id", permissions::MAX_SHOWN_FIELD))])];
|
||||
let mut lines = id_lines(id_line);
|
||||
let version = shown("version", permissions::MAX_SHOWN_FIELD);
|
||||
if !version.is_empty() {
|
||||
lines.push(crate::i18n::fmt(tl!("Version: {version}"), &[("version", &version)]));
|
||||
@@ -368,6 +383,10 @@ pub(crate) fn install_module_as(app: &mut VectorcraftApp, module: Value, automat
|
||||
install["grant"] = Value::Array(asked.clone());
|
||||
}
|
||||
if heavy {
|
||||
// A heavy filter that asks nothing else shows its id and file hash first.
|
||||
if !needs_grant && !asks_replace {
|
||||
paragraphs.push(identity.clone());
|
||||
}
|
||||
let (minutes, times) = vectorcraft_plugins::heavy_terms();
|
||||
paragraphs.push(crate::i18n::fmt(
|
||||
tl!(
|
||||
|
||||
@@ -93,11 +93,17 @@ fn slot_label(app: &VectorcraftApp, id: &str) -> Option<String> {
|
||||
Some(text)
|
||||
}
|
||||
|
||||
/// The name Last Effect gives effect `e`: its Effect menu label, a plug-in's name in the UI language
|
||||
/// as Effect › Plug-ins shows it ([`crate::dialogs::plugin::effect_item_label`]).
|
||||
fn last_effect_name(e: &str) -> &str {
|
||||
vectorcraft_effects::effect_info(e).map(|i| crate::dialogs::plugin::effect_item_label(&i)).unwrap_or(e)
|
||||
}
|
||||
|
||||
/// The labels that follow the last effect, the envelope being edited, the history and the perspective grid.
|
||||
fn command_label(app: &VectorcraftApp, id: &str, label: &str) -> Option<String> {
|
||||
let text: String = match id {
|
||||
"effect.last" => match &app.last_effect {
|
||||
Some((e, _)) => format!("Last Effect: {}", vectorcraft_effects::effect_info(e).map(|i| i.label).unwrap_or(e.as_str())),
|
||||
Some((e, _)) => format!("Last Effect: {}", last_effect_name(e)),
|
||||
None => label.into(),
|
||||
},
|
||||
// Repeat Pathfinder is named after the Shape Mode or Pathfinder operation that ran last.
|
||||
@@ -169,7 +175,8 @@ pub(crate) fn shows_a_name(id: &str, label: &str) -> bool {
|
||||
)
|
||||
|| vectorcraft_engine::cmd::plugin::is_command_id(id)
|
||||
|| (id == "window.workspace" && !crate::workspaces::builtins().iter().any(|w| w.name.eq_ignore_ascii_case(label.trim())))
|
||||
|| (matches!(id, "effect.apply" | "effect.dialog") && vectorcraft_effects::plugin_effects().iter().any(|e| e.label == label))
|
||||
|| (matches!(id, "effect.apply" | "effect.dialog")
|
||||
&& vectorcraft_effects::plugin_effects().iter().any(|e| e.label == label || crate::dialogs::plugin::effect_item_label(e) == label))
|
||||
}
|
||||
|
||||
/// Does the menu item `id` with `params` list an installed plug-in (an Object › Plug-ins filter, an
|
||||
@@ -207,7 +214,12 @@ pub fn display_label(app: &VectorcraftApp, id: &str, label: &str) -> String {
|
||||
"window.toolbarAdvanced" => crate::i18n::tr(lang, label).to_string(),
|
||||
"effect.last" => match &app.last_effect {
|
||||
Some((e, _)) => {
|
||||
let name = crate::i18n::effect_menu_label(lang, e).unwrap_or_else(|| e.clone());
|
||||
// A plug-in's name is already in the UI language from its translations.
|
||||
let name = if vectorcraft_plugins::effect::plugin_id(e).is_some() {
|
||||
last_effect_name(e).to_string()
|
||||
} else {
|
||||
crate::i18n::effect_menu_label(lang, e).unwrap_or_else(|| e.clone())
|
||||
};
|
||||
fmt(tl!("Last Effect: {name}"), &[("name", &name)])
|
||||
}
|
||||
None => crate::i18n::tr_id(lang, id, label).to_string(),
|
||||
|
||||
@@ -2029,7 +2029,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.installPlugin",
|
||||
"Install Plug-in…",
|
||||
"",
|
||||
"{path?: a .wasm file | dataBase64?: the module, name?: the file name shown as its source (with dataBase64), replace?: bool (true: the user agreed it takes the place of the plug-in with its id, as plugin.install), hash?: the module's SHA-256 (as plugin.install)} install a WebAssembly plug-in (plugin.install); without a path pick one (the web opens the browser's file picker; File › Open of a .wasm installs it too). A plug-in that lists permissions the user hasn't granted it asks the user first, showing its name, id, version, file SHA-256 and what each permission lets it do, so does a filter that asks for a heavy budget, and so does one without replace that would take the place of another module with its id and get its settings and cache (needsReplace in plugin.inspect), showing its id and file SHA-256: OK installs it if the file still has the SHA-256 shown, Cancel installs nothing. Only a person can press OK: ui.dialog.confirm, answer_dialog and synthetic input are refused. When automation asked (a control or MCP request, synthetic input, or a file dialog one of them opened, even when the person picked the file), replace: true doesn't skip the question about replacing, and nothing in the dialog installs it, the person's OK included: the person chooses Object › Plug-ins › Install Plug-in… to install it → plugin.install's result | {pending: \"pluginInstall\"} while it asks | {pending: \"pluginInstall\", approval: \"personMustStartInstall\"} while it asks what automation asked | null on the web without path or dataBase64, once the browser's file picker opens (the picked file is handled as above) | {pending: true} on the web while a Web Worker checks module bytes no worker has checked yet, after which the install goes on as above in the app",
|
||||
"{path?: a .wasm file | dataBase64?: the module, name?: the file name shown as its source (with dataBase64), replace?: bool (true: the user agreed it takes the place of the plug-in with its id, as plugin.install), hash?: the module's SHA-256 (as plugin.install)} install a WebAssembly plug-in (plugin.install); without a path pick one (the web opens the browser's file picker; File › Open of a .wasm installs it too). A plug-in that lists permissions the user hasn't granted it asks the user first, showing its name, id, version, file SHA-256 and what each permission lets it do, so does a filter that asks for a heavy budget, showing its id and file SHA-256, and so does one without replace that would take the place of another module with its id and get its settings and cache (needsReplace in plugin.inspect), showing its id and file SHA-256: OK installs it if the file still has the SHA-256 shown, Cancel installs nothing. Only a person can press OK: ui.dialog.confirm, answer_dialog and synthetic input are refused. When automation asked (a control or MCP request, synthetic input, or a file dialog one of them opened, even when the person picked the file), replace: true doesn't skip the question about replacing, and nothing in the dialog installs it, the person's OK included: the person chooses Object › Plug-ins › Install Plug-in… to install it → plugin.install's result | {pending: \"pluginInstall\"} while it asks | {pending: \"pluginInstall\", approval: \"personMustStartInstall\"} while it asks what automation asked | null on the web without path or dataBase64, once the browser's file picker opens (the picked file is handled as above) | {pending: true} on the web while a Web Worker checks module bytes no worker has checked yet, after which the install goes on as above in the app",
|
||||
),
|
||||
(
|
||||
"ui.failedPlugins",
|
||||
@@ -2071,13 +2071,13 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.runScript",
|
||||
"Other Script…",
|
||||
"Cmd+F12",
|
||||
"{path? | source?, name?} run a .js or .jsx file (script.run), after the warning unless Preferences › General › Show External Script Warning is off (dialog `scriptRun`: `choice`, `skip`, and `reaches`, which ui.dialog.set cannot set: the `kind`, `needs`, `outside`, `includes` and `truncated` of script.check's report on the script, which the warning lists, or null when the check failed); without a file pick one (the web opens the browser's file picker); with Preferences › General › Run Startup Scripts on, the startup scripts run first (script.startup.run) and script.run's reply also holds `startup`, script.startup.run's reply; while a startup script runs before it the reply is {running: true, queued: true}, and a later failure to start shows in the status bar",
|
||||
"{path? | source?, name?} run a .js, .mjs or .jsx file (script.run), after the warning unless Preferences › General › Show External Script Warning is off (dialog `scriptRun`: `choice`, `skip`, and `reaches`, which ui.dialog.set cannot set: the `kind`, `needs`, `outside`, `includes` and `truncated` of script.check's report on the script, which the warning lists, or null when the check failed); without a file pick one (the web opens the browser's file picker); with Preferences › General › Run Startup Scripts on, the startup scripts run first (script.startup.run) and script.run's reply also holds `startup`, script.startup.run's reply; while a startup script runs before it the reply is {running: true, queued: true}, and a later failure to start shows in the status bar",
|
||||
),
|
||||
(
|
||||
crate::scripts_menu::COMMAND,
|
||||
"Run Script",
|
||||
"",
|
||||
"{path: a script's path as script.listInstalled gives it} run a script of the Scripts folder, as its File › Scripts item does (script.run with installed reads the file once, checks it again and runs that text, so its #include lines and $.evalFile read in the folder that read found), without the warning Other Script… shows; a file that is no longer a .js or .jsx file in the folder or a subfolder at most 4 levels below it, or that is or lies behind a link or is hidden, is not run, and the menu's listing is read again; with Preferences › General › Run Startup Scripts on, the startup scripts run first (script.startup.run) and script.run's reply also holds `startup`, script.startup.run's reply; while a startup script runs before it the reply is {running: true, queued: true}, and a later failure to start shows in the status bar",
|
||||
"{path: a script's path as script.listInstalled gives it} run a script of the Scripts folder, as its File › Scripts item does (script.run with installed reads the file once, checks it again and runs that text, so its #include lines and $.evalFile read in the folder that read found), without the warning Other Script… shows; a file that is no longer a .js, .mjs or .jsx file in the folder or a subfolder at most 4 levels below it, or that is or lies behind a link or is hidden, is not run, and the menu's listing is read again; with Preferences › General › Run Startup Scripts on, the startup scripts run first (script.startup.run) and script.run's reply also holds `startup`, script.startup.run's reply; while a startup script runs before it the reply is {running: true, queued: true}, and a later failure to start shows in the status bar",
|
||||
),
|
||||
(
|
||||
"ui.checkScript",
|
||||
|
||||
+189
-21
@@ -13,7 +13,7 @@ use craft::ui::patterns::panels::{CommandPalette, PanelWords};
|
||||
use craft::ui::primitives::IconSpec;
|
||||
use craft::ui::runtime::env::Env;
|
||||
|
||||
use crate::i18n::Lang;
|
||||
use crate::i18n::{Lang, LangExt as _};
|
||||
use crate::{VectorcraftApp, menus};
|
||||
|
||||
/// Engine commands the palette leaves out, each with the UI command of the same name that runs it
|
||||
@@ -102,6 +102,13 @@ struct Draft {
|
||||
label: String,
|
||||
/// Does the label translate? An installed filter plug-in's name does not.
|
||||
translates: bool,
|
||||
/// Is this a plug-in command, whose label and plug-in name come from the plug-in's own
|
||||
/// translations?
|
||||
plugin_command: bool,
|
||||
/// For a filter or live-effect plug-in item whose path and label give the plug-in's name in the
|
||||
/// UI language from its translations: the path and label with the manifest's own text, which a
|
||||
/// query also matches ([`Draft::plain`]).
|
||||
own: Option<(String, String)>,
|
||||
id: String,
|
||||
/// Has [`distinct_names`] given the result its [`context`]?
|
||||
in_context: bool,
|
||||
@@ -111,21 +118,74 @@ struct Draft {
|
||||
|
||||
impl Draft {
|
||||
fn new(path: &str, label: &str, id: String) -> Draft {
|
||||
Draft { path: path.to_string(), label: label.to_string(), translates: true, id, in_context: false, keyed: false }
|
||||
Draft {
|
||||
path: path.to_string(),
|
||||
label: label.to_string(),
|
||||
translates: true,
|
||||
plugin_command: false,
|
||||
own: None,
|
||||
id,
|
||||
in_context: false,
|
||||
keyed: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The name in `lang`: the path's segments and the label translate on their own, and the id
|
||||
/// follows in parentheses when the result shows it.
|
||||
fn name(&self, lang: crate::i18n::Lang) -> String {
|
||||
// A built-in effect's label translates by its effect id first, as the Effect menu's does.
|
||||
// A plug-in command shows its label and its plug-in's name as its menu item does.
|
||||
if self.plugin_command
|
||||
&& let Some((plugin, command)) = vectorcraft_engine::cmd::plugin::command_of(&self.id)
|
||||
{
|
||||
let m = plugin.manifest();
|
||||
// A command placed in another menu keeps that menu's path, and its label names the plug-in.
|
||||
let placed = vectorcraft_engine::cmd::plugin::placed_menu(&plugin, &command).is_some();
|
||||
let path = if self.in_context || placed {
|
||||
shown_label(lang, &self.path)
|
||||
} else {
|
||||
let top = self.path.rsplit_once(" › ").map_or("", |(top, _)| top);
|
||||
format!("{} › {}", shown_label(lang, top), m.shown_name(lang.code()))
|
||||
};
|
||||
let label = if placed { m.shown_command_menu_label(&command, lang.code()) } else { m.shown_command_label(&command, lang.code()) };
|
||||
let name = format!("{path} › {label}");
|
||||
return if self.keyed { format!("{name} ({})", self.id) } else { name };
|
||||
}
|
||||
// A built-in effect's label translates by its effect id first, as the Effect menu's does. A
|
||||
// filter or live-effect plug-in's name and submenu are the ones its translations give in `lang`.
|
||||
let label = match self.id.strip_prefix("effect:") {
|
||||
_ if !self.translates => self.label.as_str(),
|
||||
_ if !self.translates => crate::dialogs::plugin::item_label_in(&self.id, lang.code()).unwrap_or(self.label.as_str()),
|
||||
Some(effect) => crate::i18n::tr_id(lang, effect, &self.label),
|
||||
None => crate::i18n::tr(lang, &self.label),
|
||||
};
|
||||
let name = if self.path.is_empty() { label.to_string() } else { format!("{} › {label}", shown_label(lang, &self.path)) };
|
||||
let path = match self.translates {
|
||||
true => std::borrow::Cow::Borrowed(self.path.as_str()),
|
||||
false => std::borrow::Cow::Owned(crate::dialogs::plugin::item_group_in(&self.id, &self.path, lang.code())),
|
||||
};
|
||||
let name = if path.is_empty() { label.to_string() } else { format!("{} › {label}", shown_label(lang, &path)) };
|
||||
if self.keyed { format!("{name} ({})", self.id) } else { name }
|
||||
}
|
||||
|
||||
/// The English name a query matches: a plug-in item that shows a translated name by the
|
||||
/// manifest's own text ([`Draft::own`]), a plug-in command by its plug-in's own name and its own
|
||||
/// label, and any other result by its name in English.
|
||||
fn plain(&self) -> String {
|
||||
if self.plugin_command
|
||||
&& let Some((plugin, command)) = vectorcraft_engine::cmd::plugin::command_of(&self.id)
|
||||
{
|
||||
use vectorcraft_plugins::permissions;
|
||||
if vectorcraft_engine::cmd::plugin::placed_menu(&plugin, &command).is_some() {
|
||||
return format!("{} › {}", self.path, command.menu_label(&plugin.manifest().name));
|
||||
}
|
||||
let own = permissions::display_text(plugin.manifest().name.trim(), permissions::MAX_SHOWN_NAME);
|
||||
let top = self.path.rsplit_once(" › ").map_or("", |(top, _)| top);
|
||||
return format!("{top} › {own} › {}", command.shown_label());
|
||||
}
|
||||
match &self.own {
|
||||
Some((path, label)) if path.is_empty() => label.clone(),
|
||||
Some((path, label)) => format!("{path} › {label}"),
|
||||
None => self.name(crate::i18n::Lang::EN),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The engine commands the palette lists. Aliases kept for older scripts run a command that is listed already, a wrapped
|
||||
@@ -147,9 +207,12 @@ pub(crate) fn listed_engine_commands() -> impl Iterator<Item = &'static vectorcr
|
||||
/// plug-in command, UI command, tool, panel and Effect menu item.
|
||||
fn drafts() -> Vec<Draft> {
|
||||
let mut out = vec![];
|
||||
for c in listed_engine_commands().chain(vectorcraft_engine::cmd::plugin::command_specs()) {
|
||||
for c in listed_engine_commands() {
|
||||
out.push(Draft::new(&c.menu.join(" › "), c.label, c.id.to_string()));
|
||||
}
|
||||
for c in vectorcraft_engine::cmd::plugin::command_specs() {
|
||||
out.push(Draft { plugin_command: true, ..Draft::new(&c.menu.join(" › "), c.label, c.id.to_string()) });
|
||||
}
|
||||
// `plugin.dialog` runs nothing without an id: [`named_drafts`] lists each filter instead. A
|
||||
// script of the Scripts folder runs from File › Scripts, by its path. The palette's own toggle
|
||||
// is no result ([`PALETTE_TOGGLE`]). A UI command that wraps an engine command, or has an
|
||||
@@ -171,9 +234,12 @@ fn drafts() -> Vec<Draft> {
|
||||
}
|
||||
// An Effect menu item runs what its item runs; a live-effect plug-in's name does not translate.
|
||||
for e in crate::shortcut_editor::effect_items().iter() {
|
||||
let plugin = vectorcraft_plugins::effect::plugin_id(&e.effect).is_some();
|
||||
let id = format!("effect:{}", e.effect);
|
||||
out.push(Draft {
|
||||
translates: vectorcraft_plugins::effect::plugin_id(&e.effect).is_none(),
|
||||
..Draft::new(&e.group, &e.label, format!("effect:{}", e.effect))
|
||||
translates: !plugin,
|
||||
own: if plugin { crate::shortcut_editor::own_plugin_text_of(&id) } else { None },
|
||||
..Draft::new(&e.group, &e.label, id)
|
||||
});
|
||||
}
|
||||
out
|
||||
@@ -257,9 +323,10 @@ fn distinct_names(drafts: &mut [Draft], langs: &[crate::i18n::Lang]) {
|
||||
}
|
||||
|
||||
/// A palette label in `lang`: each `›`-separated menu segment and the command label translate on
|
||||
/// their own.
|
||||
/// their own, except a plug-in's name and items after Object › Plug-ins or Effect › Plug-ins
|
||||
/// ([`crate::dialogs::plugin::translate_path`]).
|
||||
fn shown_label(lang: crate::i18n::Lang, label: &str) -> String {
|
||||
label.split(" › ").map(|s| crate::i18n::tr(lang, s)).collect::<Vec<_>>().join(" › ")
|
||||
crate::dialogs::plugin::translate_path(label, |s| crate::i18n::tr(lang, s))
|
||||
}
|
||||
|
||||
/// The label of the item of the menu bar that runs result `id`, English `menu_item`, in `lang`,
|
||||
@@ -289,11 +356,10 @@ fn item_label(lang: crate::i18n::Lang, id: &str, menu_item: &str) -> String {
|
||||
/// translated ([`distinct_names`]).
|
||||
fn named_drafts(lang: Lang) -> Vec<Draft> {
|
||||
let mut drafts = drafts();
|
||||
drafts.extend(
|
||||
crate::shortcut_editor::filter_items()
|
||||
.iter()
|
||||
.map(|f| Draft { translates: false, ..Draft::new(&f.group, &f.label, format!("plugin:{}", f.id)) }),
|
||||
);
|
||||
drafts.extend(crate::shortcut_editor::filter_items().iter().map(|f| {
|
||||
let id = format!("plugin:{}", f.id);
|
||||
Draft { translates: false, own: crate::shortcut_editor::own_plugin_text_of(&id), ..Draft::new(&f.group, &f.label, id) }
|
||||
}));
|
||||
distinct_names(&mut drafts, &[Lang::EN, lang]);
|
||||
drafts
|
||||
}
|
||||
@@ -527,7 +593,11 @@ fn entries(app: &VectorcraftApp, lang: Lang) -> Vec<HelpEntry> {
|
||||
.map(|(d, params)| {
|
||||
let home = homes.get(&d.id);
|
||||
let shown = d.name(lang);
|
||||
let path = shown_label(lang, &d.path);
|
||||
// A plug-in command's path names its plug-in as the menu does ([`Draft::name`]).
|
||||
let path = match shown.rsplit_once(" › ") {
|
||||
Some((path, _)) if d.plugin_command && !d.in_context => path.to_string(),
|
||||
_ => shown_label(lang, &d.path),
|
||||
};
|
||||
// A row with a home shows its label without the menu path in front of it. A path that
|
||||
// makes the name distinct ([`distinct_names`]) stays, unless the row's home shows that
|
||||
// same path or it is the Tools in front of a tool's name, which the tool's toolbar shows.
|
||||
@@ -539,15 +609,21 @@ fn entries(app: &VectorcraftApp, lang: Lang) -> Vec<HelpEntry> {
|
||||
};
|
||||
let segments: Vec<String> = if d.path.is_empty() { Vec::new() } else { path.split(" › ").map(str::to_string).collect() };
|
||||
let wrapped = WRAPPED.iter().find(|(_, ui)| *ui == d.id).map(|(engine, _)| (*engine).to_string());
|
||||
// A plug-in item is also found by its manifest's own text ([`Draft::plain`]).
|
||||
let (english, plain) = (d.name(Lang::EN), d.plain());
|
||||
let entry = HelpEntry::new(crate::keymap::command_of(&d.id), label)
|
||||
.with_english(d.name(Lang::EN))
|
||||
.with_english(plain.clone())
|
||||
.with_path(segments)
|
||||
.with_home(home_text(app, d, home))
|
||||
.with_icon(IconSpec::svg(IconId::new(kind_of(&d.id).0)))
|
||||
.with_ids(std::iter::once(d.id.clone()).chain(wrapped))
|
||||
.with_tie_order(tie_order(&d.id, home.is_some()));
|
||||
let description = description(params);
|
||||
if description.is_empty() { entry } else { entry.with_words(description) }
|
||||
// The name in English matches too where the manifest's own text differs from it.
|
||||
let mut words = description(params);
|
||||
if english != plain {
|
||||
words = if words.is_empty() { english } else { format!("{words}\n{english}") };
|
||||
}
|
||||
if words.is_empty() { entry } else { entry.with_words(words) }
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -905,8 +981,6 @@ mod tests {
|
||||
use vectorcraft_engine::Session;
|
||||
use vectorcraft_testkit::fixtures::Fixture;
|
||||
|
||||
use crate::i18n::LangExt as _;
|
||||
|
||||
/// An app over `session` in a window of its own with its menu model built, in English.
|
||||
fn app_on(session: Session) -> VectorcraftApp {
|
||||
crate::i18n::set_current(Lang::EN);
|
||||
@@ -1951,6 +2025,100 @@ mod tests {
|
||||
vectorcraft_plugins::registry::remove(two);
|
||||
}
|
||||
|
||||
/// A plug-in command's result shows its label and its plug-in's name in the language the
|
||||
/// plug-in translates them into, and the manifest's own text in a language it doesn't.
|
||||
#[test]
|
||||
fn a_plugin_command_result_shows_the_plugins_translation() {
|
||||
use vectorcraft_plugins::wat as tpl;
|
||||
let _names = crate::tests::SHARED_PLUGIN_NAMES.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let id = "test.UI.palette_translated";
|
||||
let manifest = format!(
|
||||
r#"{{"id":"{id}","name":"Groom","version":"1","kind":"filter","commands":[{{"id":"grow","label":"Expand Rim"}}],
|
||||
"translations":{{"de":{{"name":"Pflegen","commands":{{"grow":{{"label":"Erweitern"}}}}}}}}}}"#
|
||||
);
|
||||
vectorcraft_plugins::registry::install_bytes(&wat::parse_str(tpl::returning(&manifest, r#"{"objects":[]}"#)).unwrap()).unwrap();
|
||||
let key = format!("plugin.{id}.grow");
|
||||
let shown = |code: &str| {
|
||||
let lang = Lang::from_code(code).unwrap();
|
||||
(name_of(&names(lang), &key), crate::i18n::tr(lang, "Object"), crate::i18n::tr(lang, "Plug-ins"))
|
||||
};
|
||||
let (de, fr) = (shown("de"), shown("fr"));
|
||||
vectorcraft_plugins::registry::remove(id);
|
||||
assert_eq!(de.0, format!("{} › {} › Pflegen › Erweitern", de.1, de.2));
|
||||
assert_eq!(fr.0, format!("{} › {} › Groom › Expand Rim", fr.1, fr.2));
|
||||
}
|
||||
|
||||
/// A plug-in command whose plug-in translates its name and label into English shows the
|
||||
/// translation, and a search for the manifest's own text still finds it.
|
||||
#[test]
|
||||
fn a_plugin_command_with_english_translations_is_found_by_its_own_text() {
|
||||
use vectorcraft_plugins::wat as tpl;
|
||||
let _names = crate::tests::SHARED_PLUGIN_NAMES.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let id = "test.UI.palette_english_command";
|
||||
let manifest = format!(
|
||||
r#"{{"id":"{id}","name":"Trim Pack","version":"1","kind":"filter","commands":[{{"id":"shave","label":"Shave Ends"}}],
|
||||
"translations":{{"en":{{"name":"Trimmer","commands":{{"shave":{{"label":"Cut Tips"}}}}}}}}}}"#
|
||||
);
|
||||
vectorcraft_plugins::registry::install_bytes(&wat::parse_str(tpl::returning(&manifest, r#"{"objects":[]}"#)).unwrap()).unwrap();
|
||||
let key = format!("plugin.{id}.shave");
|
||||
crate::i18n::set_current(Lang::EN);
|
||||
let app = app_on(Session::new());
|
||||
let found = entries(&app, Lang::EN).iter().find(|e| id_of(e) == key).map(|e| (e.label().as_str().to_string(), haystack(e)));
|
||||
vectorcraft_plugins::registry::remove(id);
|
||||
let (shown, haystack) = found.expect("the command is a result");
|
||||
assert!(shown.ends_with("Cut Tips"), "{shown}");
|
||||
assert!(haystack.contains("trimmer"), "{haystack}");
|
||||
assert!(haystack.contains("trim pack › shave ends"), "{haystack}");
|
||||
}
|
||||
|
||||
/// A filter whose name the UI language translates shows the translation, English included, and
|
||||
/// a search for the manifest's own name still finds it; in German, so does a search for its
|
||||
/// English translation.
|
||||
#[test]
|
||||
fn a_translated_filter_is_found_by_its_manifest_name() {
|
||||
use vectorcraft_plugins::wat as tpl;
|
||||
let _names = crate::tests::SHARED_PLUGIN_NAMES.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let id = "test.UI.palette_translated_filter";
|
||||
let manifest = format!(
|
||||
r#"{{"id":"{id}","name":"Polish Edges","version":"1","kind":"filter","translations":{{"de":{{"name":"Kanten polieren"}},"en":{{"name":"Smooth Edges"}}}}}}"#
|
||||
);
|
||||
vectorcraft_plugins::registry::install_bytes(&wat::parse_str(tpl::returning(&manifest, r#"{"objects":[]}"#)).unwrap()).unwrap();
|
||||
let app = app_on(Session::new());
|
||||
let key = format!("plugin:{id}");
|
||||
let found = |lang: Lang| {
|
||||
crate::i18n::set_current(lang);
|
||||
let found = entries(&app, lang).iter().find(|e| id_of(e) == key).map(|e| (e.label().as_str().to_string(), haystack(e)));
|
||||
let by_english = ranked(&built_for(&app), "smooth edges").contains(&key);
|
||||
crate::i18n::set_current(Lang::EN);
|
||||
(found, by_english)
|
||||
};
|
||||
let (de, en) = (found(Lang::from_code("de").unwrap()), found(Lang::EN));
|
||||
vectorcraft_plugins::registry::remove(id);
|
||||
for ((found, by_english), name) in [(de, "Kanten polieren"), (en, "Smooth Edges")] {
|
||||
let (shown, haystack) = found.expect("the filter is a result");
|
||||
assert!(shown.ends_with(name), "{shown}");
|
||||
assert!(haystack.contains("polish edges"), "{haystack}");
|
||||
assert!(by_english, "a search for the English translation finds {name}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A plug-in's name in the path of its own item, in the submenu a plug-in with commands gets,
|
||||
/// stays as the plug-in gives it where it matches text the app translates ("Open" in German).
|
||||
#[test]
|
||||
fn a_plugin_submenu_name_is_not_translated_by_the_app() {
|
||||
use vectorcraft_plugins::wat as tpl;
|
||||
let _names = crate::tests::SHARED_PLUGIN_NAMES.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let id = "test.UI.palette_submenu_name";
|
||||
let manifest = format!(r#"{{"id":"{id}","name":"Open","version":"1","kind":"filter","commands":[{{"id":"go","label":"Go"}}]}}"#);
|
||||
vectorcraft_plugins::registry::install_bytes(&wat::parse_str(tpl::returning(&manifest, r#"{"objects":[]}"#)).unwrap()).unwrap();
|
||||
let de = Lang::from_code("de").unwrap();
|
||||
let shown = names(de).into_iter().find(|(i, _)| *i == format!("plugin:{id}")).map(|(_, n)| n);
|
||||
vectorcraft_plugins::registry::remove(id);
|
||||
assert_ne!(crate::i18n::tr(de, "Open"), "Open", "German translates the app's Open");
|
||||
let path = format!("{} › {}", crate::i18n::tr(de, "Object"), crate::i18n::tr(de, "Plug-ins"));
|
||||
assert_eq!(shown, Some(format!("{path} › Open › Open")));
|
||||
}
|
||||
|
||||
/// The home English result `id` shows with the app's current layout.
|
||||
fn home_of(app: &VectorcraftApp, id: &str) -> String {
|
||||
crate::i18n::set_current(Lang::EN);
|
||||
|
||||
@@ -359,11 +359,12 @@ fn built_in_effect(id: &str) -> bool {
|
||||
}
|
||||
|
||||
/// [`effect_label`] as shown: a built-in effect's name in the UI language as the Effect menu
|
||||
/// shows it ([`crate::i18n::effect_name`]), a plug-in's as it is.
|
||||
/// shows it ([`crate::i18n::effect_name`]), a plug-in's by the name the plug-in
|
||||
/// gives in the UI language ([`crate::dialogs::plugin::effect_name`]).
|
||||
pub(crate) fn shown_effect_label(id: &str) -> String {
|
||||
match built_in_effect(id).then(|| crate::i18n::effect_name(crate::i18n::current(), id)).flatten() {
|
||||
Some(name) => name,
|
||||
None => effect_label(id),
|
||||
None => crate::dialogs::plugin::effect_name(id).unwrap_or_else(|| effect_label(id)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1006,7 +1007,9 @@ fn effect_editor<'r>(app: &VectorcraftApp, pass: &'r RefCell<Pass>, item: Option
|
||||
if rows.is_empty() { stored_params(&effect, &values) } else { rows }
|
||||
};
|
||||
let fields = fields_of(¶ms, &values);
|
||||
let (name, id) = (effect_label(&e.id), e.id.clone());
|
||||
// A plug-in effect's editor is named as its row is, by the plug-in's name in the UI language.
|
||||
let name = crate::dialogs::plugin::effect_name(&e.id).unwrap_or_else(|| effect_label(&e.id));
|
||||
let id = e.id.clone();
|
||||
move |ui| {
|
||||
if free_distort {
|
||||
// The button keeps its own name: the label says what it edits.
|
||||
@@ -1835,8 +1838,11 @@ fn effects_move(
|
||||
/// their Effect-menu submenu; a pick opens the effect dialog.
|
||||
pub(crate) fn fx_menu(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
let mut groups: Vec<(String, Vec<(String, String)>)> = vec![];
|
||||
let plugins: Vec<_> = vectorcraft_effects::plugin_effects().into_iter().map(catalog_entry).collect();
|
||||
// Built-in effects named as the Effect menu names them; a plug-in's by the name it gives.
|
||||
let plugins: Vec<_> = vectorcraft_effects::plugin_effects()
|
||||
.into_iter()
|
||||
.map(|e| (e.id.to_string(), crate::dialogs::plugin::effect_item_label(&e).trim_end_matches('…').to_string(), catalog_entry(e).2))
|
||||
.collect();
|
||||
// Built-in effects named as the Effect menu names them; a plug-in's by the name it gives in it.
|
||||
let lang = crate::i18n::current();
|
||||
let built_in = catalog().iter().map(|(id, label, menu)| (id, crate::i18n::effect_name(lang, id).unwrap_or_else(|| label.clone()), menu));
|
||||
for (id, label, menu) in built_in.chain(plugins.iter().map(|(id, label, menu)| (id, label.clone(), menu))) {
|
||||
|
||||
@@ -215,6 +215,34 @@ fn a_plug_in_effect_s_editor_follows_its_manifest() {
|
||||
panel.app().run("plugin.remove", json!({"id": "test.ui.inlinekeys"})).unwrap();
|
||||
}
|
||||
|
||||
/// A plug-in effect's editor is named by the plug-in's name in the UI language, as its row is.
|
||||
#[test]
|
||||
fn a_plug_in_effect_s_editor_is_named_in_the_ui_language() {
|
||||
use vectorcraft_plugins::wat as tpl;
|
||||
let id = "test.ui.inlinename";
|
||||
let manifest = format!(
|
||||
r#"{{"id":"{id}","name":"Hatch","version":"1","kind":"effect","params":{{"width":{{"type":"number","min":0,"max":10,"default":1,"label":"Width"}}}},
|
||||
"translations":{{"de":{{"name":"Schraffur"}}}}}}"#
|
||||
);
|
||||
let src = tpl::module(&manifest, tpl::ECHO, "", 1);
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wat::parse_str(src).unwrap())})).unwrap();
|
||||
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
|
||||
app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap();
|
||||
app.run("effect.apply", json!({"effect": format!("plugin.{id}")})).unwrap();
|
||||
app.ui.appearance_panel.open.insert(RowKey::Effect(0));
|
||||
let mut panel = Panel::new(app, show);
|
||||
let group = craft::ui::contract::Role::GROUP;
|
||||
let en = panel.shows_role("Hatch", group);
|
||||
crate::i18n::set_current(crate::i18n::Lang::from_code("de").unwrap());
|
||||
panel.frame();
|
||||
let de = (panel.shows_role("Schraffur", group), panel.shows_role("Hatch", group));
|
||||
crate::i18n::set_current(crate::i18n::Lang::EN);
|
||||
panel.app().run("plugin.remove", json!({"id": id})).unwrap();
|
||||
assert!(en, "the editor in English");
|
||||
assert_eq!(de, (true, false), "the editor in German");
|
||||
}
|
||||
|
||||
/// Glass with a loaded texture lists Loaded Texture in its Texture menu, as its dialog does.
|
||||
#[test]
|
||||
fn the_effect_editor_lists_a_loaded_glass_texture() {
|
||||
|
||||
@@ -18,6 +18,7 @@ use craft::ui::runtime::commands;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::file_asks::{self, Owner};
|
||||
use crate::i18n::LangExt as _;
|
||||
use crate::keymap::{command_of, entry_key, stored, stored_key};
|
||||
use crate::menus::Node;
|
||||
use crate::shortcut_sheet::PageSize;
|
||||
@@ -110,6 +111,10 @@ pub struct Entry {
|
||||
/// Keyboard Shortcuts adds the key to the entry's name: another entry has the same group and
|
||||
/// label ([`distinct_names`]).
|
||||
pub shows_key: bool,
|
||||
/// For a plug-in item whose `group` and `label` name the plug-in and its command in the UI
|
||||
/// language from the plug-in's translations: the group and label with the manifest's own text,
|
||||
/// which status and error messages use ([`english_name`]). `None` for every other entry.
|
||||
pub english: Option<(String, String)>,
|
||||
}
|
||||
|
||||
/// The editor's entries, the Effect menu's effect items and Object › Plug-ins' filter items while
|
||||
@@ -117,15 +122,20 @@ pub struct Entry {
|
||||
pub(crate) struct Snapshot {
|
||||
/// The plug-in revision read before the menus were walked.
|
||||
pub revision: u64,
|
||||
/// The UI language the menus were walked in, which names plug-in items in a plug-in's own
|
||||
/// translations.
|
||||
pub lang: &'static str,
|
||||
pub effects: Arc<[EffectItem]>,
|
||||
pub filters: Arc<[FilterItem]>,
|
||||
pub entries: Arc<[Entry]>,
|
||||
}
|
||||
|
||||
/// The entries for the plug-ins installed now: rebuilt when a plug-in is installed or removed, so
|
||||
/// a live-effect or filter plug-in installed later has its row, and one removed has none.
|
||||
/// a live-effect or filter plug-in installed later has its row, and one removed has none, and when
|
||||
/// the UI language changes, so plug-in items show the plug-in's text in it.
|
||||
pub(crate) fn snapshot() -> Arc<Snapshot> {
|
||||
static LAST: Mutex<Option<Arc<Snapshot>>> = Mutex::new(None);
|
||||
let lang = crate::i18n::current().code();
|
||||
let mut revision = menus::plugin_revision();
|
||||
let last = LAST.lock().unwrap_or_else(|e| e.into_inner()).clone();
|
||||
// A test's walk hook runs even when a snapshot of this revision is already stored.
|
||||
@@ -138,13 +148,13 @@ pub(crate) fn snapshot() -> Arc<Snapshot> {
|
||||
};
|
||||
#[cfg(not(test))]
|
||||
let hooked = false;
|
||||
if let Some(s) = last.filter(|s| s.revision == revision && !hooked) {
|
||||
if let Some(s) = last.filter(|s| s.revision == revision && s.lang == lang && !hooked) {
|
||||
return s;
|
||||
}
|
||||
// When a plug-in is installed or removed during the walk, the entries may not match
|
||||
// `revision`, and the keymap cached for it would lack rows or hold extra ones. The menus are
|
||||
// walked again at the new revision, and a snapshot that still doesn't match is not cached.
|
||||
let mut s = build_snapshot(revision);
|
||||
let mut s = build_snapshot(revision, lang);
|
||||
for _ in 0..8 {
|
||||
let now = menus::plugin_revision();
|
||||
if now == revision {
|
||||
@@ -156,13 +166,14 @@ pub(crate) fn snapshot() -> Arc<Snapshot> {
|
||||
return s;
|
||||
}
|
||||
revision = now;
|
||||
s = build_snapshot(revision);
|
||||
s = build_snapshot(revision, lang);
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// The snapshot of the menus as they are now, under plug-in revision `revision`.
|
||||
fn build_snapshot(revision: u64) -> Arc<Snapshot> {
|
||||
/// The snapshot of the menus as they are now, under plug-in revision `revision`, walked in UI
|
||||
/// language `lang`.
|
||||
fn build_snapshot(revision: u64, lang: &'static str) -> Arc<Snapshot> {
|
||||
// Built without the lock held: the Effect menu is walked anew.
|
||||
#[cfg(test)]
|
||||
if let Some(f) = tests::WHILE_WALKING.take() {
|
||||
@@ -180,6 +191,7 @@ fn build_snapshot(revision: u64) -> Arc<Snapshot> {
|
||||
group: e.group.clone(),
|
||||
is_tool: false,
|
||||
shows_key: false,
|
||||
english: vectorcraft_plugins::effect::plugin_id(&e.effect).and_then(|id| own_plugin_text(id, lang, &e.group, &e.label)),
|
||||
}))
|
||||
.chain(filters.iter().map(|f| Entry {
|
||||
key: format!("plugin:{}", f.id),
|
||||
@@ -187,18 +199,53 @@ fn build_snapshot(revision: u64) -> Arc<Snapshot> {
|
||||
group: f.group.clone(),
|
||||
is_tool: false,
|
||||
shows_key: false,
|
||||
english: own_plugin_text(&f.id, lang, &f.group, &f.label),
|
||||
}))
|
||||
.chain(vectorcraft_engine::cmd::plugin::command_specs().into_iter().map(|c| Entry {
|
||||
key: c.id.into(),
|
||||
label: c.label.into(),
|
||||
group: c.menu.join(" › "),
|
||||
is_tool: false,
|
||||
shows_key: false,
|
||||
.chain(vectorcraft_engine::cmd::plugin::command_specs().into_iter().map(|c| {
|
||||
// A plug-in command's label and its plug-in's name in `lang`, as its menu shows them. A
|
||||
// command placed in another menu keeps that menu's path.
|
||||
let own = (c.menu.join(" › "), c.label.to_string());
|
||||
let (label, group) = match vectorcraft_engine::cmd::plugin::command_of(c.id) {
|
||||
Some((plugin, command)) if vectorcraft_engine::cmd::plugin::placed_menu(&plugin, &command).is_some() => {
|
||||
(plugin.manifest().shown_command_menu_label(&command, lang), own.0.clone())
|
||||
}
|
||||
Some((plugin, command)) => {
|
||||
let m = plugin.manifest();
|
||||
let path: Vec<String> = c.menu.iter().take(2).map(|s| s.to_string()).chain([m.shown_name(lang)]).collect();
|
||||
(m.shown_command_label(&command, lang), path.join(" › "))
|
||||
}
|
||||
None => (own.1.clone(), own.0.clone()),
|
||||
};
|
||||
let english = (own != (group.clone(), label.clone())).then_some(own);
|
||||
Entry { key: c.id.into(), label, group, is_tool: false, shows_key: false, english }
|
||||
}))
|
||||
.chain(tail.iter().cloned())
|
||||
.collect();
|
||||
distinct_names(&mut entries);
|
||||
Arc::new(Snapshot { revision, effects, filters, entries: entries.into() })
|
||||
Arc::new(Snapshot { revision, lang, effects, filters, entries: entries.into() })
|
||||
}
|
||||
|
||||
/// The group and label of plug-in `id`'s menu item, shown as `group` and `label` in UI language
|
||||
/// `lang`, with the manifest's own name in place of the name its translations give there
|
||||
/// ([`Entry::english`]); `None` when no such plug-in is installed or `lang` shows its own name.
|
||||
fn own_plugin_text(id: &str, lang: &str, group: &str, label: &str) -> Option<(String, String)> {
|
||||
use vectorcraft_plugins::permissions;
|
||||
let plugin = vectorcraft_plugins::registry::get(id)?;
|
||||
let m = plugin.manifest();
|
||||
let (shown, own) = (m.shown_name(lang), permissions::display_text(m.name.trim(), permissions::MAX_SHOWN_NAME));
|
||||
if shown == own {
|
||||
return None;
|
||||
}
|
||||
// A plug-in with commands of its own has a submenu named after it.
|
||||
let parts: Vec<&str> = group.split(" › ").collect();
|
||||
let submenu = matches!(parts.as_slice(), ["Object" | "Effect", "Plug-ins", name, ..] if *name == shown);
|
||||
let group = parts.iter().enumerate().map(|(i, s)| if submenu && i == 2 { own.as_str() } else { *s }).collect::<Vec<_>>().join(" › ");
|
||||
let label = match label.strip_prefix(shown.as_str()) {
|
||||
Some(rest) if own.ends_with('…') => format!("{own}{}", rest.trim_start_matches('…')),
|
||||
Some(rest) => format!("{own}{rest}"),
|
||||
None => label.to_string(),
|
||||
};
|
||||
Some((group, label))
|
||||
}
|
||||
|
||||
/// Every tool, command and panel the editor can give a shortcut; [`listed`] says which it lists.
|
||||
@@ -212,7 +259,14 @@ fn fixed_entries() -> &'static (Vec<Entry>, Vec<Entry>) {
|
||||
static E: OnceLock<(Vec<Entry>, Vec<Entry>)> = OnceLock::new();
|
||||
E.get_or_init(|| {
|
||||
let mut v: Vec<Entry> = vectorcraft_tools::catalog::all_tools()
|
||||
.map(|t| Entry { key: format!("tool:{}", t.id), label: t.label.to_string(), group: "Tools".into(), is_tool: true, shows_key: false })
|
||||
.map(|t| Entry {
|
||||
key: format!("tool:{}", t.id),
|
||||
label: t.label.to_string(),
|
||||
group: "Tools".into(),
|
||||
is_tool: true,
|
||||
shows_key: false,
|
||||
english: None,
|
||||
})
|
||||
.collect();
|
||||
let mut seen = HashSet::new();
|
||||
// The commands listed only because an item of the menu bar runs them as a key press would
|
||||
@@ -227,7 +281,7 @@ fn fixed_entries() -> &'static (Vec<Entry>, Vec<Entry>) {
|
||||
by_the_menu_bar.insert(c.id);
|
||||
}
|
||||
let group = command_group(c.id, c.menu);
|
||||
v.push(Entry { key: c.id.into(), label: c.label.into(), group, is_tool: false, shows_key: false });
|
||||
v.push(Entry { key: c.id.into(), label: c.label.into(), group, is_tool: false, shows_key: false, english: None });
|
||||
}
|
||||
v.extend(crate::state::all_panels().map(|(id, label)| Entry {
|
||||
key: format!("panel:{id}"),
|
||||
@@ -235,6 +289,7 @@ fn fixed_entries() -> &'static (Vec<Entry>, Vec<Entry>) {
|
||||
group: "Window".into(),
|
||||
is_tool: false,
|
||||
shows_key: false,
|
||||
english: None,
|
||||
}));
|
||||
// Each effect of the Effect menu comes next, by its own key (#3296): see [`snapshot`].
|
||||
let mut tail = vec![];
|
||||
@@ -246,7 +301,14 @@ fn fixed_entries() -> &'static (Vec<Entry>, Vec<Entry>) {
|
||||
if !own {
|
||||
by_the_menu_bar.insert(id);
|
||||
}
|
||||
tail.push(Entry { key: id.to_string(), label: label.to_string(), group: command_group(id, &[]), is_tool: false, shows_key: false });
|
||||
tail.push(Entry {
|
||||
key: id.to_string(),
|
||||
label: label.to_string(),
|
||||
group: command_group(id, &[]),
|
||||
is_tool: false,
|
||||
shows_key: false,
|
||||
english: None,
|
||||
});
|
||||
}
|
||||
// A command listed only because an item of the menu bar runs it can have the group and
|
||||
// label of another entry. When that entry is an engine command that no item of the menu bar
|
||||
@@ -376,15 +438,19 @@ fn build_filter_items() -> Vec<FilterItem> {
|
||||
out
|
||||
}
|
||||
|
||||
/// Entry `e`'s label in the UI language. A plug-in's own name is not translated.
|
||||
/// Entry `e`'s label in the UI language. A plug-in's own name and its commands' labels, already in
|
||||
/// the UI language from the plug-in's translations, are not translated again.
|
||||
pub(crate) fn shown_label(e: &Entry) -> &str {
|
||||
let plugin = e.key.starts_with("plugin:") || e.key.strip_prefix("effect:").and_then(vectorcraft_plugins::effect::plugin_id).is_some();
|
||||
let plugin = e.key.starts_with("plugin:")
|
||||
|| vectorcraft_engine::cmd::plugin::is_command_id(&e.key)
|
||||
|| e.key.strip_prefix("effect:").and_then(vectorcraft_plugins::effect::plugin_id).is_some();
|
||||
if plugin { &e.label } else { tl!(&e.label) }
|
||||
}
|
||||
|
||||
/// A menu path in the UI language, one segment at a time.
|
||||
/// A menu path in the UI language, one segment at a time; a plug-in's name after Object › Plug-ins
|
||||
/// or Effect › Plug-ins stays as the plug-in gives it ([`crate::dialogs::plugin::translate_path`]).
|
||||
pub(crate) fn shown_group(group: &str) -> String {
|
||||
group.split(" › ").map(|s| tl!(s)).collect::<Vec<_>>().join(" › ")
|
||||
crate::dialogs::plugin::translate_path(group, |s| tl!(s))
|
||||
}
|
||||
|
||||
/// How Keyboard Shortcuts names entry `e`: a tool by its label, the others after their menu, and
|
||||
@@ -393,9 +459,13 @@ pub(crate) fn shown_name(e: &Entry) -> String {
|
||||
name_of(e, &shown_group(&e.group), shown_label(e))
|
||||
}
|
||||
|
||||
/// [`shown_name`] in English, for a status or error message, which is translated when shown.
|
||||
/// [`shown_name`] in English, for a status or error message, which is translated when shown; a
|
||||
/// plug-in item by its manifest's own text ([`Entry::english`]).
|
||||
fn english_name(e: &Entry) -> String {
|
||||
name_of(e, &e.group, &e.label)
|
||||
match &e.english {
|
||||
Some((group, label)) => name_of(e, group, label),
|
||||
None => name_of(e, &e.group, &e.label),
|
||||
}
|
||||
}
|
||||
|
||||
/// Entry `e`'s name with its group and label as `group` and `label`.
|
||||
@@ -534,8 +604,13 @@ fn distinct_names(entries: &mut [Entry]) {
|
||||
// The entries of each name that more than one entry has.
|
||||
fn shared(entries: &[Entry]) -> Vec<Vec<usize>> {
|
||||
let mut by_name: HashMap<String, Vec<usize>> = HashMap::new();
|
||||
// A plug-in item counts under the name it shows and under its manifest's own name.
|
||||
for (i, e) in entries.iter().enumerate() {
|
||||
by_name.entry(english_name(e)).or_default().push(i);
|
||||
let (shown, english) = (name_of(e, &e.group, &e.label), english_name(e));
|
||||
if english != shown {
|
||||
by_name.entry(english).or_default().push(i);
|
||||
}
|
||||
by_name.entry(shown).or_default().push(i);
|
||||
}
|
||||
by_name.into_values().filter(|list| list.len() > 1).collect()
|
||||
}
|
||||
@@ -934,6 +1009,16 @@ pub fn entry(key: &str) -> Option<Entry> {
|
||||
entries().iter().find(|e| e.key == key).cloned()
|
||||
}
|
||||
|
||||
/// The group and label of plug-in item `key` (`plugin:<id>` or `effect:<id>`) with the manifest's
|
||||
/// own text, when the item shows the plug-in's name in the UI language from its translations
|
||||
/// ([`Entry::english`]); `None` for every other entry.
|
||||
pub(crate) fn own_plugin_text_of(key: &str) -> Option<(String, String)> {
|
||||
if !key.starts_with("plugin:") && !key.starts_with("effect:") {
|
||||
return None;
|
||||
}
|
||||
entries().iter().find(|e| e.key == key).and_then(|e| e.english.clone())
|
||||
}
|
||||
|
||||
/// Reads a set in the `vectorcraft-shortcuts` form earlier versions wrote: its name (an earlier
|
||||
/// name maps to today's; none is [`CUSTOM`]) and its overrides, with its hold shortcuts.
|
||||
pub fn import_json(v: &Value) -> Result<(String, Overrides), String> {
|
||||
@@ -1721,7 +1806,6 @@ pub fn run_command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option<Resu
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::i18n::LangExt as _;
|
||||
use craft::keymap::Scopes;
|
||||
|
||||
/// Runs `f` again until no plug-in was installed or removed while it ran, and returns what it
|
||||
@@ -2678,6 +2762,7 @@ mod tests {
|
||||
group: group.into(),
|
||||
is_tool: false,
|
||||
shows_key: false,
|
||||
english: None,
|
||||
};
|
||||
let menu = "Object › Plug-ins";
|
||||
let mut rows = vec![
|
||||
@@ -2703,6 +2788,55 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// The entries are built again when the UI language changes, so Keyboard Shortcuts lists
|
||||
/// plug-in items in the new language.
|
||||
#[test]
|
||||
fn the_entries_are_built_again_when_the_language_changes() {
|
||||
let (en, again, de) = with_steady_plugins(|| {
|
||||
let en = snapshot();
|
||||
let again = snapshot();
|
||||
crate::i18n::set_current(crate::i18n::Lang::from_code("de").unwrap());
|
||||
let de = snapshot();
|
||||
crate::i18n::set_current(crate::i18n::Lang::EN);
|
||||
(en, again, de)
|
||||
});
|
||||
assert!(Arc::ptr_eq(&en, &again), "kept while nothing changes");
|
||||
assert_eq!((en.lang, de.lang), ("en", "de"));
|
||||
}
|
||||
|
||||
/// A shortcut conflict names a translated plug-in's filter and command by the manifest's own
|
||||
/// text, as status and error messages name every entry in English, while Keyboard Shortcuts
|
||||
/// lists them in the UI language.
|
||||
#[test]
|
||||
fn a_shortcut_conflict_names_a_translated_plugin_by_its_own_text() {
|
||||
let (mut app, ctx) = app();
|
||||
let id = "test.shortcuts.translated.conflict";
|
||||
// Names no other test's plug-in has, since tests running beside this one share the registry.
|
||||
let manifest = format!(
|
||||
r#"{{"id":"{id}","name":"Neaten","kind":"filter","commands":[{{"id":"grow","label":"Grow Rim"}}],"translations":{{"de":{{"name":"Ordnen","commands":{{"grow":{{"label":"Rand wachsen"}}}}}}}}}}"#
|
||||
);
|
||||
let module = wat::parse_str(vectorcraft_plugins::wat::returning(&manifest, r#"{"objects":[]}"#)).unwrap();
|
||||
app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&module)})).unwrap();
|
||||
// A frame gives the window's keymap the plug-in's entries.
|
||||
crate::tests::synthetic::key_frame(&mut app, &ctx, vec![]);
|
||||
let (grow, own) = (format!("plugin.{id}.grow"), format!("plugin:{id}"));
|
||||
let set = |app: &mut VectorcraftApp, id: &str, shortcut: Value| app.run("shortcuts.set", json!({"id": id, "shortcut": shortcut}));
|
||||
crate::i18n::set_current(crate::i18n::Lang::from_code("de").unwrap());
|
||||
let mut conflict = |first: &str, second: &str| {
|
||||
set(&mut app, first, json!("Cmd+Alt+Shift+F7")).unwrap();
|
||||
let err = set(&mut app, second, json!("Cmd+Alt+Shift+F7")).unwrap_err();
|
||||
set(&mut app, first, Value::Null).unwrap();
|
||||
err
|
||||
};
|
||||
let (by_command, by_filter) = (conflict(&grow, &own), conflict(&own, &grow));
|
||||
let label = entry(&grow).map(|e| e.label);
|
||||
crate::i18n::set_current(crate::i18n::Lang::EN);
|
||||
app.run("plugin.remove", json!({"id": id})).unwrap();
|
||||
assert_eq!(label.as_deref(), Some("Rand wachsen"), "the row is in German");
|
||||
assert!(by_command.ends_with("is already used by Object › Plug-ins › Neaten › Grow Rim"), "{by_command}");
|
||||
assert!(by_filter.ends_with("is already used by Object › Plug-ins › Neaten › Neaten"), "{by_filter}");
|
||||
}
|
||||
|
||||
/// A command with items in more than one menu is shown under the path of its first item with
|
||||
/// no params, or else of its first item: Recolor Artwork… under Edit › Edit Colors, not Edit ›
|
||||
/// Edit Colors › Recolor with Preset.
|
||||
|
||||
@@ -1831,6 +1831,7 @@ fn a_filter_plugin_row_translates_its_path_and_not_its_name() {
|
||||
group: "Object › Plug-ins".into(),
|
||||
is_tool: false,
|
||||
shows_key: false,
|
||||
english: None,
|
||||
};
|
||||
let path = format!("{} › {}", crate::i18n::tr(zh, "Object"), crate::i18n::tr(zh, "Plug-ins"));
|
||||
let (filter, command) = (crate::shortcut_editor::shown_name(&entry("plugin:a.b")), crate::shortcut_editor::shown_name(&entry("object.group")));
|
||||
|
||||
@@ -364,6 +364,12 @@ impl Panel {
|
||||
tree.keys().into_iter().any(|key| tree.role_of(key) == Some(Role::STATUS) && tree.name_of(key) == Some(text))
|
||||
}
|
||||
|
||||
/// Whether the latest frame shows a node of `role` named `name`, where nodes of other roles share the name.
|
||||
pub(crate) fn shows_role(&self, name: &str, role: craft::ui::contract::Role) -> bool {
|
||||
let tree = self.fixture.tree();
|
||||
self.fixture.by_role(role).into_iter().any(|t| tree.name_of(t.node) == Some(name))
|
||||
}
|
||||
|
||||
/// Whether some of the control named `name` can be seen in the latest frame: inside its arena's clip and inside the
|
||||
/// window.
|
||||
pub(crate) fn in_view(&self, name: &str) -> bool {
|
||||
|
||||
@@ -16,6 +16,7 @@ use vectorcraft_plugins::{registry, wat as tpl};
|
||||
|
||||
use super::plugins::{approve, window};
|
||||
use crate::dialogs::plugin::InstallPrompt;
|
||||
use crate::i18n::LangExt as _;
|
||||
use crate::{VectorcraftApp, dialogs, export_progress, plugin_runs};
|
||||
|
||||
/// An app with a new 200 × 200 pt document.
|
||||
@@ -135,6 +136,38 @@ fn installing_a_heavy_filter_asks_first() {
|
||||
assert!(h.state().pending_plugin_install.is_none());
|
||||
}
|
||||
|
||||
/// The heavy-budget question gives the filter's ID and file SHA-256, and also the manifest's own
|
||||
/// name when the name it asks with is a translation.
|
||||
#[test]
|
||||
fn the_heavy_budget_question_shows_the_id_hash_and_manifest_name() {
|
||||
let mut h = window(app());
|
||||
let id = "test.ui.heavy.translated";
|
||||
let manifest =
|
||||
format!(r#"{{"id":"{id}","name":"Route","version":"1","kind":"filter","budget":"heavy","translations":{{"de":{{"name":"Fräsen"}}}}}}"#);
|
||||
let bytes = wat::parse_str(tpl::spinning(&manifest, 1, r#"{"objects":[]}"#)).unwrap();
|
||||
let hash = vectorcraft_plugins::permissions::sha256_hex(&bytes);
|
||||
let data = vectorcraft_format::base64_encode(&bytes);
|
||||
let ask = |h: &mut Harness<'static, VectorcraftApp>, lang: &str| {
|
||||
crate::i18n::set_current(crate::i18n::Lang::from_code(lang).unwrap());
|
||||
let r = h.state_mut().run("ui.installPlugin", json!({ "dataBase64": data }));
|
||||
let pending = h.state().pending_plugin_install.as_ref().map(|p| (p.message.clone(), p.detail.clone()));
|
||||
crate::i18n::set_current(crate::i18n::Lang::EN);
|
||||
frame(h);
|
||||
answer(h, false);
|
||||
assert_eq!(r.unwrap()["pending"], dialogs::plugin::INSTALL_KIND);
|
||||
pending.unwrap()
|
||||
};
|
||||
let (message, detail) = ask(&mut h, "de");
|
||||
assert!(message.contains("Fräsen") && !message.contains("Route"), "{message}");
|
||||
for shown in [id, "Route", hash.as_str()] {
|
||||
assert!(detail.contains(shown), "{shown}: {detail}");
|
||||
}
|
||||
let (message, detail) = ask(&mut h, "en");
|
||||
assert_eq!(message, "Install “Route”, which asks for a heavy budget?");
|
||||
assert!(detail.starts_with(&format!("ID: {id}\nFile SHA-256: {hash}\n\n")), "no second name line: {detail}");
|
||||
assert!(registry::get(id).is_none());
|
||||
}
|
||||
|
||||
/// The dialog has no Preview; OK closes it and the filter runs in the background, the status bar
|
||||
/// saying so, and its result is one undo step named after it, selected.
|
||||
#[test]
|
||||
|
||||
@@ -6,6 +6,7 @@ use serde_json::{Value, json};
|
||||
use vectorcraft_engine::Session;
|
||||
use vectorcraft_plugins::wat as tpl;
|
||||
|
||||
use crate::i18n::LangExt as _;
|
||||
use crate::{VectorcraftApp, dialogs, io, menus};
|
||||
|
||||
const DESATURATE: &[u8] = include_bytes!("../../../plugins/tests/fixtures/desaturate.wasm");
|
||||
@@ -1025,3 +1026,222 @@ fn opening_a_javascript_manifest_by_path_does_not_read_it_first() {
|
||||
assert_eq!(vectorcraft_plugins::registry::get(id).and_then(|p| p.script().map(str::to_string)).as_deref(), Some("open.js"));
|
||||
app.run("plugin.remove", json!({"id": id})).unwrap();
|
||||
}
|
||||
|
||||
/// The approval names a plug-in whose manifest translates its name in the UI language and also
|
||||
/// gives the manifest's own name, both escaped; a language without a translation shows the
|
||||
/// manifest's name alone. What OK installs stays bound to the id and hash shown.
|
||||
#[test]
|
||||
fn the_install_approval_shows_the_translated_and_the_manifests_own_name() {
|
||||
let mut h = window(app());
|
||||
let id = "test.ui.translated_approval";
|
||||
let manifest = json!({"id": id, "name": "Tidy", "version": "1", "kind": "filter", "permissions": ["doc.read"],
|
||||
"translations": {"de": {"name": "Aufräumen"}}})
|
||||
.to_string();
|
||||
let bytes = wat::parse_str(tpl::returning(&manifest, r#"{"objects":[]}"#)).unwrap();
|
||||
let hash = vectorcraft_plugins::permissions::sha256_hex(&bytes);
|
||||
let data = vectorcraft_format::base64_encode(&bytes);
|
||||
let ask = |h: &mut Window, lang: &str| {
|
||||
crate::i18n::set_current(crate::i18n::Lang::from_code(lang).unwrap());
|
||||
let r = h.state_mut().run("ui.installPlugin", json!({ "dataBase64": data }));
|
||||
let pending = h.state().pending_plugin_install.as_ref().map(|p| (p.message.clone(), p.detail.clone(), p.params["hash"].clone()));
|
||||
crate::i18n::set_current(crate::i18n::Lang::EN);
|
||||
step(h);
|
||||
answer(h, false);
|
||||
assert_eq!(r.unwrap()["pending"], dialogs::plugin::INSTALL_KIND);
|
||||
pending.unwrap()
|
||||
};
|
||||
let (message, detail, shown_hash) = ask(&mut h, "de");
|
||||
assert!(message.contains("Aufräumen") && !message.contains("Tidy"), "{message}");
|
||||
assert!(detail.contains("ID: test.ui.translated_approval"), "{detail}");
|
||||
assert!(detail.contains("Tidy"), "the manifest's own name: {detail}");
|
||||
assert!(!detail.contains("Aufräumen"), "{detail}");
|
||||
assert_eq!(shown_hash, json!(hash));
|
||||
let (message, detail, _) = ask(&mut h, "en");
|
||||
assert_eq!(message, "Install “Tidy”, which asks for these permissions?");
|
||||
assert_eq!(detail.lines().next(), Some("ID: test.ui.translated_approval"));
|
||||
assert_eq!(detail.lines().nth(1), Some("Version: 1"), "no second name line: {detail}");
|
||||
assert!(vectorcraft_plugins::registry::get(id).is_none());
|
||||
}
|
||||
|
||||
/// The label of each item of `items`, a submenu's as `name ›` followed by its items'.
|
||||
fn menu_labels(items: &[menus::Node]) -> Vec<String> {
|
||||
items
|
||||
.iter()
|
||||
.flat_map(|it| match it {
|
||||
menus::Node::Item(i) => vec![i.label.clone()],
|
||||
menus::Node::Heading(label) => vec![label.clone()],
|
||||
menus::Node::Submenu { label, children, .. } => std::iter::once(format!("{label} ›")).chain(menu_labels(children)).collect(),
|
||||
_ => Vec::new(),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Object › Plug-ins, Effect › Plug-ins and File › Open With name a plug-in and its commands in the
|
||||
/// UI language when its manifest's `translations` give them: German text in German, `pt` text for
|
||||
/// Brazilian Portuguese without its own, and the manifest's own text in any other language.
|
||||
#[test]
|
||||
fn plugin_menus_show_the_plugins_names_in_the_ui_language() {
|
||||
let mut app = app();
|
||||
let (filter, effect, importer) = ("test.ui.translated.filter", "test.ui.translated.effect", "test.ui.translated.importer");
|
||||
let translations = r#""translations":{"de":{"name":"Aufräumen","commands":{"grow":{"label":"Wachsen"}}},"pt":{"name":"Arrumar"}}"#;
|
||||
let filter_manifest = format!(
|
||||
r#"{{"id":"{filter}","name":"Tidy","kind":"filter","commands":[{{"id":"grow","label":"Grow","params":{{"by":{{"type":"bool"}}}}}}],{translations}}}"#
|
||||
);
|
||||
let effect_manifest = format!(
|
||||
r#"{{"id":"{effect}","name":"Wobble","kind":"effect","params":{{"on":{{"type":"bool"}}}},"translations":{{"de":{{"name":"Wackeln"}}}}}}"#
|
||||
);
|
||||
let importer_manifest =
|
||||
format!(r#"{{"id":"{importer}","name":"Plotter","kind":"importer","extensions":["tpx"],"translations":{{"de":{{"name":"Zeichner"}}}}}}"#);
|
||||
for manifest in [filter_manifest, effect_manifest, importer_manifest] {
|
||||
let module = wat::parse_str(tpl::returning(&manifest, r#"{"objects":[]}"#)).unwrap();
|
||||
app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&module)})).unwrap();
|
||||
}
|
||||
let shown = |lang: &str| {
|
||||
crate::i18n::set_current(crate::i18n::Lang::from_code(lang).expect("language registered"));
|
||||
let effects = dialogs::plugin::effect_menu().map(|m| menu_labels(&[m])).unwrap_or_default();
|
||||
let all = [menu_labels(&dialogs::plugin::object_menu()), effects, menu_labels(&dialogs::plugin::open_with_menu())].concat();
|
||||
crate::i18n::set_current(crate::i18n::Lang::EN);
|
||||
all
|
||||
};
|
||||
let de = shown("de");
|
||||
for label in ["Aufräumen ›", "Aufräumen", "Wachsen…", "Wackeln…", "Zeichner…"] {
|
||||
assert!(de.contains(&label.to_string()), "{label} in German: {de:?}");
|
||||
}
|
||||
// Other tests' plug-ins may be installed meanwhile: only this test's names are checked.
|
||||
for label in ["Tidy ›", "Tidy", "Grow…", "Wobble…", "Plotter…"] {
|
||||
assert!(!de.contains(&label.to_string()), "{label} in German: {de:?}");
|
||||
}
|
||||
let pt_br = shown("pt-br");
|
||||
assert!(pt_br.contains(&"Arrumar ›".to_string()) && pt_br.contains(&"Grow…".to_string()), "pt, then the manifest: {pt_br:?}");
|
||||
for lang in ["en", "fr"] {
|
||||
let other = shown(lang);
|
||||
for label in ["Tidy ›", "Grow…", "Wobble…", "Plotter…"] {
|
||||
assert!(other.contains(&label.to_string()), "{label} in {lang}: {other:?}");
|
||||
}
|
||||
}
|
||||
// A German item is still the plug-in's own name, not text a catalog translates, and Keyboard
|
||||
// Shortcuts lists the filter and its command as the menu does, in the language it is shown in.
|
||||
let grow = format!("plugin.{filter}.grow");
|
||||
let rows = |lang: &str| {
|
||||
crate::i18n::set_current(crate::i18n::Lang::from_code(lang).unwrap());
|
||||
let names = menus::shows_a_name("effect.dialog", "Wackeln…");
|
||||
let row = |key: &str| crate::shortcut_editor::entry(key).map(|e| (e.label.clone(), e.group.clone()));
|
||||
let rows = (names, row(&grow), row(&format!("plugin:{filter}")));
|
||||
crate::i18n::set_current(crate::i18n::Lang::EN);
|
||||
rows
|
||||
};
|
||||
let (names, command, own) = rows("de");
|
||||
assert!(names);
|
||||
assert_eq!(command, Some(("Wachsen".to_string(), "Object › Plug-ins › Aufräumen".to_string())));
|
||||
assert_eq!(own.map(|r| r.0), Some("Aufräumen".to_string()));
|
||||
let (_, command, _) = rows("en");
|
||||
assert_eq!(command, Some(("Grow".to_string(), "Object › Plug-ins › Tidy".to_string())));
|
||||
// Last Effect names the effect as Effect › Plug-ins does.
|
||||
app.last_effect = Some((vectorcraft_plugins::effect::effect_id(effect), json!({})));
|
||||
let last = |lang: &str| {
|
||||
crate::i18n::set_current(crate::i18n::Lang::from_code(lang).unwrap());
|
||||
let shown = (menus::display_label(&app, "effect.last", "Last Effect…"), menus::dynamic_label(&app, "effect.last", "Last Effect…"));
|
||||
crate::i18n::set_current(crate::i18n::Lang::EN);
|
||||
shown
|
||||
};
|
||||
let (de, de_dynamic) = last("de");
|
||||
assert!(de.contains("Wackeln…") && de_dynamic == "Last Effect: Wackeln…", "{de} / {de_dynamic}");
|
||||
assert_eq!(last("en"), ("Last Effect: Wobble…".to_string(), "Last Effect: Wobble…".to_string()));
|
||||
app.last_effect = None;
|
||||
for id in [filter, effect, importer] {
|
||||
app.run("plugin.remove", json!({"id": id})).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
/// A command placed in another menu shows its label and its plug-in's name in the UI language there
|
||||
/// and in Keyboard Shortcuts, and the manifest's own text in a language the plug-in does not
|
||||
/// translate.
|
||||
#[test]
|
||||
fn a_placed_plugin_command_shows_the_plugins_translation() {
|
||||
let mut app = app();
|
||||
let id = "test.ui.translated.placed";
|
||||
let manifest = format!(
|
||||
r#"{{"id":"{id}","name":"Ridge","api":2,"version":"1","kind":"filter","commands":[{{"id":"low","label":"Low Area","menu":{{"path":["Object","Clipping Mask"]}}}}],"translations":{{"de":{{"name":"Grat","commands":{{"low":{{"label":"Tiefe Fläche"}}}}}}}}}}"#
|
||||
);
|
||||
let module = wat::parse_str(tpl::returning(&manifest, r#"{"objects":[]}"#)).unwrap();
|
||||
app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&module)})).unwrap();
|
||||
let low = vectorcraft_engine::cmd::plugin::command_id(id, "low");
|
||||
let shown = |app: &VectorcraftApp, lang: &str| {
|
||||
crate::i18n::set_current(crate::i18n::Lang::from_code(lang).unwrap());
|
||||
let item = menus::menu_entries(app).into_iter().find(|e| e.command.as_deref() == Some(low.as_str())).map(|e| (e.path, e.label));
|
||||
let row = crate::shortcut_editor::entry(&low).map(|e| (e.group, e.label));
|
||||
crate::i18n::set_current(crate::i18n::Lang::EN);
|
||||
(item, row)
|
||||
};
|
||||
let (de, en) = (shown(&app, "de"), shown(&app, "en"));
|
||||
app.run("plugin.remove", json!({"id": id})).unwrap();
|
||||
// Other tests count the items of Select and View: this one places its command in a menu no other test uses.
|
||||
let menu = || vec!["Object".to_string(), "Clipping Mask".to_string()];
|
||||
assert_eq!(de.0, Some((menu(), "Tiefe Fläche (Grat)".to_string())));
|
||||
assert_eq!(de.1, Some(("Object › Clipping Mask".to_string(), "Tiefe Fläche (Grat)".to_string())));
|
||||
assert_eq!(en.0, Some((menu(), "Low Area (Ridge)".to_string())));
|
||||
assert_eq!(en.1, Some(("Object › Clipping Mask".to_string(), "Low Area (Ridge)".to_string())));
|
||||
}
|
||||
|
||||
/// Last Effect shows a live-effect plug-in's translated name as the plug-in gives it, even where it
|
||||
/// matches text the app translates: "Open" in German stays "Open".
|
||||
#[test]
|
||||
fn last_effect_leaves_a_plugins_translated_name_as_it_gives_it() {
|
||||
let mut app = app();
|
||||
let effect = "test.ui.translated.last_effect";
|
||||
let manifest = format!(r#"{{"id":"{effect}","name":"Unseal","kind":"effect","translations":{{"de":{{"name":"Open"}}}}}}"#);
|
||||
let module = wat::parse_str(tpl::returning(&manifest, r#"{"objects":[]}"#)).unwrap();
|
||||
app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&module)})).unwrap();
|
||||
app.last_effect = Some((vectorcraft_plugins::effect::effect_id(effect), json!({})));
|
||||
let de = crate::i18n::Lang::from_code("de").unwrap();
|
||||
crate::i18n::set_current(de);
|
||||
let shown = menus::display_label(&app, "effect.last", "Last Effect…");
|
||||
crate::i18n::set_current(crate::i18n::Lang::EN);
|
||||
app.last_effect = None;
|
||||
app.run("plugin.remove", json!({"id": effect})).unwrap();
|
||||
assert_ne!(crate::i18n::tr(de, "Open"), "Open", "German translates the app's Open");
|
||||
assert_eq!(shown, crate::i18n::fmt(crate::i18n::tr(de, "Last Effect: {name}"), &[("name", "Open")]));
|
||||
}
|
||||
|
||||
/// Keyboard Shortcuts shows a plug-in command's label and its plug-in's name as the plug-in gives
|
||||
/// them, even where they match text the app translates: in German, a command labeled "Open" of a
|
||||
/// plug-in named "Close" keeps both, as in its menu.
|
||||
#[test]
|
||||
fn keyboard_shortcuts_leave_a_plugin_commands_text_as_the_plugin_gives_it() {
|
||||
let mut app = app();
|
||||
let id = "test.ui.untranslated.command";
|
||||
let manifest = format!(r#"{{"id":"{id}","name":"Close","kind":"filter","commands":[{{"id":"go","label":"Open"}}]}}"#);
|
||||
let module = wat::parse_str(tpl::returning(&manifest, r#"{"objects":[]}"#)).unwrap();
|
||||
app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&module)})).unwrap();
|
||||
crate::i18n::set_current(crate::i18n::Lang::from_code("de").unwrap());
|
||||
let shown = crate::shortcut_editor::entry(&format!("plugin.{id}.go")).map(|e| crate::shortcut_editor::shown_name(&e));
|
||||
let expected = format!("{} › {} › Close › Open", crate::i18n::t("Object"), crate::i18n::t("Plug-ins"));
|
||||
assert_ne!((crate::i18n::t("Open"), crate::i18n::t("Close")), ("Open", "Close"), "German translates both as app text");
|
||||
crate::i18n::set_current(crate::i18n::Lang::EN);
|
||||
app.run("plugin.remove", json!({"id": id})).unwrap();
|
||||
assert_eq!(shown, Some(expected));
|
||||
}
|
||||
|
||||
/// A filter's and an importer's menu item show their names as prompts do, a right-to-left override
|
||||
/// escaped, as a filter with commands already showed its submenu.
|
||||
#[test]
|
||||
fn plugin_menu_items_escape_bidirectional_characters() {
|
||||
let mut app = app();
|
||||
let (filter, importer) = ("test.ui.bidi.filter", "test.ui.bidi.importer");
|
||||
// The override as a JSON escape in the manifest.
|
||||
let rlo = format!("\\u{:04X}", 0x202E);
|
||||
for manifest in [
|
||||
format!(r#"{{"id":"{filter}","name":"Flip{rlo}txt.exe","kind":"filter"}}"#),
|
||||
format!(r#"{{"id":"{importer}","name":"Read{rlo}fdp.exe","kind":"importer","extensions":["rdx"]}}"#),
|
||||
] {
|
||||
let module = wat::parse_str(tpl::returning(&manifest, r#"{"objects":[]}"#)).unwrap();
|
||||
app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&module)})).unwrap();
|
||||
}
|
||||
let labels = [menu_labels(&dialogs::plugin::object_menu()), menu_labels(&dialogs::plugin::open_with_menu())].concat();
|
||||
assert!(labels.contains(&"Flip\\u{202E}txt.exe".to_string()), "{labels:?}");
|
||||
assert!(labels.contains(&"Read\\u{202E}fdp.exe…".to_string()), "{labels:?}");
|
||||
assert!(!labels.iter().any(|l| l.contains('\u{202E}')), "{labels:?}");
|
||||
for id in [filter, importer] {
|
||||
app.run("plugin.remove", json!({"id": id})).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -192,7 +192,7 @@ fn only_js_and_jsx_files_are_taken() {
|
||||
let mut app = app();
|
||||
for name in ["a.txt", "a.jsxbin", "a"] {
|
||||
let e = menus::run_ui_command(&mut app, "ui.runScript", &json!({ "path": name })).unwrap().unwrap_err();
|
||||
assert!(e.contains(".js or .jsx"), "{name}: {e}");
|
||||
assert!(e.contains(".js, .mjs or .jsx"), "{name}: {e}");
|
||||
}
|
||||
assert!(!app.any_dialog_open());
|
||||
assert!(!is_open::<RunQuestion>(&app));
|
||||
@@ -247,6 +247,17 @@ fn a_picked_script_goes_to_the_warning() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_web_pick_of_a_mjs_file_runs_as_a_module() {
|
||||
let mut app = app();
|
||||
app.session.prefs.show_external_script_warning = false;
|
||||
// `export` is a syntax error outside a module, and `this` is undefined at a module's top.
|
||||
let module = format!("export var a = 1;\nif (this !== undefined) throw new Error('not a module');\n{DRAW}");
|
||||
script_run::picked_script(&mut app, Picked::Contents(vec![("Picked.MJS".into(), module.into_bytes())])).unwrap();
|
||||
finish(&mut app);
|
||||
assert_eq!(objects(&app), 2, "{}", app.ui.status);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_web_pick_that_is_not_text_is_reported() {
|
||||
let mut app = app();
|
||||
|
||||
+59
-8
@@ -2773,12 +2773,12 @@ the included files too.
|
||||
vectorcraft-cli run --cmd script.check --params '{"path": "Tidy Layers.jsx"}'
|
||||
```
|
||||
|
||||
`script.run {path? | source?, name?, args?, answers?, maxFuel?}` runs a JavaScript file against the open documents.
|
||||
`script.run {path? | source?, module?, name?, args?, answers?, maxFuel?}` runs a JavaScript file against the open documents.
|
||||
|
||||
In an ES2015 realm, `Symbol.for` lookups and insertions take fuel for the key's code units. A registered description
|
||||
shares the key's existing string buffer.
|
||||
Block-scoped declaration checks retain one copy of each `var` declaration name through nested blocks.
|
||||
File › Scripts › Other Script… (Cmd+F12) picks a `.js` or `.jsx` file and runs it the same way; the help page
|
||||
File › Scripts › Other Script… (Cmd+F12) picks a `.js`, `.mjs` or `.jsx` file and runs it the same way; the help page
|
||||
https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/install-and-run-scripts.html
|
||||
describes that menu item. Its warning before the run lists what `script.check` finds the script reaches outside
|
||||
the document, read without running it: each `outside` category of the report (files it writes, moves or deletes,
|
||||
@@ -2789,7 +2789,7 @@ says when the script is too large to check, compiled or not a script, when the c
|
||||
short at its limit. The listing does not stop the run. Run checks the script again, and when the report has changed
|
||||
since the warning opened, nothing runs and the warning opens again with the new report. A script from the Scripts
|
||||
folder runs without the warning.
|
||||
Pass exactly one of `path` and `source`. A `path` must end in `.js` or `.jsx`, in any
|
||||
Pass exactly one of `path` and `source`. A `path` must end in `.js`, `.mjs` or `.jsx`, in any
|
||||
case. A `.jsxbin` file or text that starts with `@JSXBIN@` is compiled and ends with an error, as does text that is
|
||||
not UTF-8. The language is ES5.1, except that identifiers take the characters Unicode's `ID_Start` and
|
||||
`ID_Continue` properties allow, as later editions define them, and may use `\u{...}` escapes. A `path` that ends in
|
||||
@@ -2835,23 +2835,71 @@ throws a `TypeError`, since that engine was made without the ECMAScript 2015 bui
|
||||
an engine that `#targetengine` keeps reads each run the way that run's script does. A
|
||||
`.jsx` file and a `source` string read ES5.1 only, and the ECMAScript 2015 forms are syntax errors there; there
|
||||
`yield` is a name like any other. A `.js` file
|
||||
`.jsx` file and a `source` string read ES5.1 when run as scripts. With `module: true`, they run as modules and
|
||||
accept the ECMAScript 2015 forms listed here. A `.js` file
|
||||
also reads two ECMAScript 2020 forms (https://262.ecma-international.org/11.0/): optional chains (`a?.b`, `a?.[key]`,
|
||||
`f?.(args)`), which give `undefined` and skip the rest of the chain when the value before `?.` is `undefined` or
|
||||
`null`, and `??`, which evaluates its right side only when its left side is `undefined` or `null`. Mixing `??` with `&&`
|
||||
or `||` without parentheses, and assigning to an optional chain, are syntax errors. In a `.jsx` file and a `source`
|
||||
string, `?.` and `??` are syntax errors. Which files read these forms is VectorCraft's own rule. Every script, `.js`,
|
||||
`.jsx` or `source`, also reads ECMAScript for XML (E4X, ECMA-357, 2nd edition,
|
||||
string that runs as a script, `?.` and `??` are syntax errors. Which files read these forms is VectorCraft's own rule.
|
||||
Every script, `.js`, `.jsx` or `source`, also reads ECMAScript for XML (E4X, ECMA-357, 2nd edition,
|
||||
https://ecma-international.org/publications-and-standards/standards/ecma-357/): XML and XMLList literals, the `..`,
|
||||
`.@`, `.*`, `.()` and `::` selectors, `for each`, `default xml namespace`, and the global `XML`, `XMLList`,
|
||||
`Namespace`, `QName`, `isXMLName` and `setDefaultXMLNamespace`, as the XML object pages describe them
|
||||
(https://extendscript.docsforadobe.dev/integrating-xml/the-xml-object/). A script run from a `.js` file also has
|
||||
`Promise` (described below); a `.jsx` file and a script given as `source` do not, except that a named engine
|
||||
(`#targetengine`) has `Promise` from the first `.js` run that names it and keeps it for every later run, as it keeps
|
||||
(https://extendscript.docsforadobe.dev/integrating-xml/the-xml-object/). A script run from a `.js` file or a module also has
|
||||
`Promise` (described below); a `.jsx` file and a script given as `source` that runs as a script do not, except that a named engine
|
||||
(`#targetengine`) has `Promise` from the first `.js` or module run that names it and keeps it for every later run, as it keeps
|
||||
its globals. An ES5.1 script does not have `Map`, `Set`, `WeakMap`, `WeakSet`, `ArrayBuffer`, `DataView` or the
|
||||
typed arrays; the JavaScript engine's ECMAScript 2015 mode (`Options::es2015` in `vectorcraft-js`) adds them, as
|
||||
`docs/target-app-parity.md` describes. The collector retains tagged-template cache entries only while the site's code
|
||||
is reachable. The script reaches the app through the global object `vc`, and writes to the Script Console and runs
|
||||
other files through `$`:
|
||||
`Promise` (described below); a `.jsx` file and a `source` string that runs as a script do not, except that a named engine
|
||||
(`#targetengine`) has `Promise` from its first `.js` or module run and keeps it for every later run, as it keeps its globals.
|
||||
|
||||
A `path` that ends in `.mjs` (in any case) runs as an ECMAScript 2015 module
|
||||
(https://262.ecma-international.org/6.0/#sec-modules): strict mode code with the forms above (optional chains and `??`
|
||||
included), and `import` and
|
||||
`export` declarations at its top level. Module source reserves `await` as an identifier. A module namespace has an
|
||||
own `Symbol.toStringTag` property with value `"Module"` that is nonwritable, nonenumerable and nonconfigurable.
|
||||
`import` and `export` are syntax errors in a `.js` or `.jsx` script.
|
||||
`module` (true or false) chooses this for any `path` or `source`; it defaults to true for a `path` that ends in
|
||||
`.mjs` and false otherwise. The app passes `module: true` for a `.mjs` file picked on the web, where the script
|
||||
arrives as `source`. A `source` that runs as a module imports no files: each import ends the run with an error that
|
||||
names the specifier.
|
||||
|
||||
- A specifier is a path relative to the file that imports it. It starts with `./` or `../`, separates names with
|
||||
`/` and names a `.mjs` or `.js` file, which is read as a module. A bare name such as `'lib'`, a URL, an absolute
|
||||
path, and a specifier with `\`, `:` or a control character end the run with a `SyntaxError` that names the
|
||||
specifier.
|
||||
- Modules are read through the script's own file scope: only from the script's folder and the folders below it.
|
||||
A specifier whose `..` names lead above the script's folder, and a link that leads out of it, end the run with an
|
||||
error that names the specifier. A missing file ends the run with an error that names the specifier.
|
||||
- Every module is read, parsed and linked before any of them runs. A syntax error, a missing or refused file, an
|
||||
import of a name the module does not export, and an import of a name that two `export *` declarations give from
|
||||
different modules end the run with no code run, at the file, line and column of the module they are in.
|
||||
- Each module runs once in a run, after the modules it imports, in the order it imports them. In a cycle of imports
|
||||
a module does not wait for a module that is still waiting for its own imports, so it can run before that module
|
||||
has initialized its bindings. Two paths to one file
|
||||
(a link, `sub/../x.mjs`, or names that differ only in letter case in a Windows folder that ignores case) are one
|
||||
module, and a module's relative imports are read from the folder the file is in, whichever path reached it first. An import reads
|
||||
the exporting module's binding each time, so it sees later assignments, and reading it before that module has
|
||||
initialized it (in a cycle of imports) throws a `ReferenceError`. Assigning to an import throws a `TypeError`.
|
||||
- `import * as ns` gives a namespace object: not extensible, with no prototype, its export names in code unit order
|
||||
as properties that cannot be written or deleted, and `[object Module]` from `Object.prototype.toString`.
|
||||
Export redefinitions use the ECMAScript 2020 rule, which accepts a descriptor only when it leaves the current
|
||||
export unchanged (https://262.ecma-international.org/11.0/#sec-module-namespace-exotic-objects-defineownproperty-p-desc).
|
||||
`export *` passes on every name but `default`, and `export * as ns from` passes on a namespace.
|
||||
- A module's top-level names stay in the module, `this` is `undefined` at its top, it has no preprocessor lines,
|
||||
and `import()` is a syntax error. `vc`, `$` and the other globals are there as in a script.
|
||||
- In the host API, `Realm::run_module` drains queued Promise jobs before returning, as sliced module execution does.
|
||||
`Realm::start_module` and `Realm::run_module` end a paused or waiting run before loading replacement source,
|
||||
including when that source fails to compile. Existing globals remain available.
|
||||
- Module files count against the limits of `#include` files: 8 MiB a file, 32 MiB of source in all, 64 files
|
||||
besides the script, imports 16 deep and 1,024 paths looked up. These limits are VectorCraft's own.
|
||||
|
||||
The script reaches the app through the global object `vc`, and writes to the Script Console and runs other files
|
||||
through `$`:
|
||||
|
||||
- `vc.run(id, params)` runs a command and returns its result. A command that fails throws an error the script can
|
||||
catch. The documents and the session state the command changed, preferences included, go back, and any file it
|
||||
@@ -15093,6 +15141,9 @@ The preference `pluginInstructionBudget` (`normal`, the default, or `large`; `pr
|
||||
sets the instructions every object filter run gets: Large gives a light filter 250 M instructions instead of 50 M,
|
||||
plus 4,000 per input byte either way, with its 60 s time budget unchanged; a heavy filter keeps its own budget with
|
||||
either value. The next `plugin.run` or plug-in command uses the value set ([plug-ins](plugins.md#instruction-budget-preference)).
|
||||
A manifest's `translations` ([plug-ins](plugins.md#translations)) change only the text the app shows: `plugin.list`,
|
||||
`plugin.info` and plug-in command entries keep the manifest's own names and labels, and `plugin.inspect` and
|
||||
`plugin.info`'s `manifest` give `translations` as declared.
|
||||
A plug-in whose manifest lists permissions (`permissions` in its `plugin.inspect` entry, with `needsApproval: true`)
|
||||
needs a person's approval too, and `plugin.install` refuses `grant: [permission]` from a request. With a desktop
|
||||
app connected, `ui.installPlugin` opens the approval dialog and returns `{pending: "pluginInstall"}`; `answer_dialog`,
|
||||
|
||||
+50
-2
@@ -375,8 +375,8 @@ an importer an import's). Each of its runs gets 1 G instructions (20 times a lig
|
||||
and 300 s (`vectorcraft_plugins::{HEAVY_FUEL, HEAVY_WALL_TIME_MS}`). Its output can't add to the budget: the host learns
|
||||
how much there is only once the run has ended.
|
||||
|
||||
- **Installing asks first.** Install Plug-in… and File › Open show what the filter asks for, and install it once the
|
||||
user clicks OK (see [Permissions](#permissions) for who can). `plugin.install` refuses it without `allowHeavy: true`,
|
||||
- **Installing asks first.** Install Plug-in… and File › Open show what the filter asks for, with its ID and file
|
||||
SHA-256, and install it once the user clicks OK (see [Permissions](#permissions) for who can). `plugin.install` refuses it without `allowHeavy: true`,
|
||||
and refuses `allowHeavy` from a request except in a session started with `vectorcraft-cli --allow-plugin-grants`
|
||||
(`plugin.inspect` shows the budget beforehand). A filter kept in the `Plug-ins` folder was agreed to and is installed
|
||||
again at startup. The Additional Plug-ins Folder skips heavy filters with a note in its report, since loading a folder
|
||||
@@ -929,6 +929,7 @@ the module's start function, in a run that isn't a filter's run on a document, o
|
||||
it): the ids of the commands the filter may [call](#command-calls), at most 256, each once (`"commandAllowlist":
|
||||
["select.all", "object.move"]`). An id is 1–128 characters from `A-Z a-z 0-9 . _ -` that starts with a letter, with
|
||||
no empty part between dots. A malformed list is refused when the module is installed, and the error names the id.
|
||||
- `translations`: the plug-in's text in other languages ([Translations](#translations)).
|
||||
- `params`: in dialog order. Names are `[A-Za-z0-9_]`, not starting with `_`, and not `id`, `ids`, `params` or
|
||||
`preview`. The host validates the user's values before calling: missing values take the default, numbers are
|
||||
clamped to `min..max` (ints rounded), a wrong type or an unknown choice is an error. Numeric defaults are also clamped
|
||||
@@ -961,6 +962,53 @@ A hidden parameter still goes to the plug-in with its value: what the dialog sho
|
||||
filter, live-effect and exporter dialogs use all of these keys. The Appearance panel's editor of a plug-in effect's
|
||||
parameters uses `label`, `unit`, `help`, `visibleWhen` and `widget`, and lists the parameters without sections or
|
||||
help buttons.
|
||||
Dialogs and menus show plug-in text with control and bidirectional characters escaped (`\u{202E}`).
|
||||
|
||||
#### Translations
|
||||
|
||||
`translations` gives the plug-in's text in other languages, keyed by language code. The app shows the text for its
|
||||
interface language (Preferences › User Interface). Text a language leaves out comes from the same code without its
|
||||
last part (`pt-BR`, then `pt`; `zh-Hant-TW`, then `zh-Hant`, then `zh`) and then from the manifest's own text. Codes
|
||||
match without regard to case.
|
||||
|
||||
```json
|
||||
"translations": {
|
||||
"de": {
|
||||
"name": "Pfade aufräumen",
|
||||
"params": {"mode": {"label": "Modus", "help": "Weich rundet die Ecken.", "options": {"soft": "Weich", "hard": "Hart"}}},
|
||||
"groups": {"Shape": "Form"},
|
||||
"commands": {"grow": {"label": "Vergrößern", "params": {"by": {"label": "Um"}}}}
|
||||
},
|
||||
"pt": {"name": "Arrumar caminhos"},
|
||||
"pt-BR": {"name": "Organizar caminhos"}
|
||||
}
|
||||
```
|
||||
|
||||
| Key | What it translates |
|
||||
|---|---|
|
||||
| `name` | The plug-in's name in Object › Plug-ins, Effect › Plug-ins, File › Open With, Edit › Keyboard Shortcuts, the command palette, the Appearance panel and dialog headings (1–64 characters). |
|
||||
| `params` | By parameter name: its `label` (also for a parameter that gives none), `help` (only where the parameter gives one; line breaks allowed) and `options`, the label of each choice by the value it passes (1–64 characters each). |
|
||||
| `groups` | By the `group` the parameters give: the section's heading. The section stays the same section in every language. |
|
||||
| `commands` | By command id: its `label` and its parameters' text, as `params` gives it. |
|
||||
|
||||
The text is only shown. Command ids, parameter names and choice values are the same in every language, the plug-in
|
||||
is given the values it declared, and `plugin.list`, `plugin.info` and errors use the manifest's own `name` and labels;
|
||||
`plugin.inspect` and `plugin.info` give `translations` as declared. The install approval names the plug-in in the UI
|
||||
language and, when that name is a translation, also shows the manifest's own name under its ID; what the approval
|
||||
grants is still bound to the ID and file hash it shows.
|
||||
|
||||
A manifest gives at most 16 languages, inside its 64 KiB limit. Installing refuses the following, with an error that
|
||||
names the key (such as `translations.de.params.mode.label`):
|
||||
|
||||
- a code that is not a language of 2 or 3 letters followed by parts of 2–8 letters and digits after a `-` (at most 35
|
||||
characters), or a language given twice;
|
||||
- text longer than the field it translates allows, empty text, or text with a control character (a line break
|
||||
outside `help`), a character that changes the direction text runs in (`U+202A`–`U+202E`, `U+2066`–`U+2069`,
|
||||
`U+200E`, `U+200F`, `U+061C`) or a line or paragraph separator;
|
||||
- a parameter, choice value, group or command the manifest doesn't declare, `options` on a parameter that isn't a
|
||||
choice, two options of a choice with the same label, or a key not listed above.
|
||||
|
||||
Hosts from before `translations` ignore it and show the manifest's own text.
|
||||
|
||||
### Input
|
||||
|
||||
|
||||
@@ -55,6 +55,8 @@ Block-scoped declaration checks keep each `var` declaration name in the current
|
||||
|
||||
- Fold Preview orders overlapping coplanar panels by their fold tree, draws distinct planes and crossing panels by depth, and calculates poses relative to the blank's center. Each plane uses one comparison depth, and every member of a plane group must match every other member. A hinge uses its longest line across all split pieces. Tests cover flat, near-flat, nested and offset folds in `crates/three-d/src/fold/tests.rs` and `crates/three-d/src/fold/raster/tests.rs`.
|
||||
- `addon.packaging.setFoldAngle` stores or resets individual fold angles for editable Crease, Partial Cut, and Perforation lines. The fold commands read those angles, and role queries report their shared value and stored-angle counts. Engine tests cover validation, locked compound members, one-step undo, native save, and SVG exports.
|
||||
Synchronous module execution through `Realm::run_module` drains queued Promise jobs before returning. Both module entry points end a paused or waiting run before loading new source and preserve existing globals. Module namespaces expose an immutable own `Symbol.toStringTag` property with value `"Module"`, and module source rejects `await` identifiers before dependencies execute. `crates/js/src/module_tests.rs` compares resolution and rejection callbacks with sliced execution and covers paused-script replacement with valid and invalid module source, namespace properties and reserved identifiers.
|
||||
|
||||
`vectorcraft-js` ends a paused or waiting run before `Realm::run` or `Realm::start` compiles new source. Its globals remain available. The earlier run's remaining code and queued jobs do not run. Regressions in `crates/js/src/host_tests.rs` cover paused scripts, Promise reactions, waiting host calls, invalid replacement source, and deferred language settings.
|
||||
|
||||
Scripts: `Promise.prototype[Symbol.toStringTag]` is `"Promise"` when Symbols are available, with a configurable, non-enumerable, non-writable descriptor. Promise instances report `[object Promise]` in engines without Symbols. Test: `promise_prototype_has_a_configurable_string_tag` in `crates/js/src/promise_tests.rs`.
|
||||
@@ -1186,10 +1188,11 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- `vectorcraft-js` parses JavaScript as ECMAScript 5.1 defines it, with the legacy octal forms, block functions and lenient regular expressions of Annex B, into a syntax tree with source spans. A comma may follow the last argument of a call or `new` expression and the last parameter of a function other than a setter, as ECMAScript 2017 allows (https://tc39.es/ecma262/2017/#sec-left-hand-side-expressions, https://tc39.es/ecma262/2017/#sec-function-definitions); `f(,)` and `f(1,,)` give a `SyntaxError`. It reads the `#target`, `#include` and other preprocessor lines as directives without running them, and a script that breaks the grammar or an early-error rule gives a `SyntaxError` with its line and column. Nesting past the parser's depth limit (`Options::max_depth`, 200 by default) gives a `SyntaxError` instead of exhausting the stack. `cargo xtask test262` fetches the conformance suite at a pinned commit and parses its ES5 tests: 5,411 of 5,418 runs pass (the 7 others use `let` and `const`). This entry covers parsing; the next entry covers running scripts. Tests: `crates/js/src/tests.rs`, `crates/engine/tests/it/js_lexer_vs_scriptcheck.rs`.
|
||||
- `vectorcraft-js` identifiers, written out or as `\uXXXX` and `\u{...}` escapes, take the characters Unicode's `ID_Start` and `ID_Continue` properties allow (https://www.unicode.org/reports/tr31/), plus `$` and, at the start, `_`, as later ECMAScript editions define them (https://tc39.es/ecma262/#sec-names-and-keywords). `Other_ID_Start` characters such as U+2118 and `Other_ID_Continue` characters such as U+00B7 and the zero width non-joiner and joiner are accepted, and no `Pattern_Syntax` or `Pattern_White_Space` character is. Letter categories come from Unicode 17.0, so U+088F starts an identifier and U+1ACF may follow its first character; characters assigned after Unicode 17.0 are not yet identifier characters. Tests: `crates/js/src/tests.rs` (`identifier_characters_are_unicode_17_id_start_and_id_continue`, which checks every code point, `identifiers_take_the_characters_unicode_17_assigned`, `identifiers_take_the_other_id_start_and_continue_characters`, `identifiers_refuse_pattern_syntax_surrogates_and_bad_escapes`, `no_pattern_syntax_or_white_space_character_is_an_identifier_character`).
|
||||
- `vectorcraft-js`'s `Realm` runs ECMAScript 5.1 scripts: the parsed script compiles to verified bytecode that a non-recursive interpreter runs, with closures, `this`, `arguments`, `with`, direct and indirect `eval`, `new Function`, `try`/`catch`/`finally`, labeled `break` and `continue`, and `for`-`in` in insertion order, over a mark-and-sweep heap, with the built-ins the next two entries list. Every run is bounded by fuel, heap bytes, frames, nested host calls and an interrupt flag (smaller defaults in the wasm build), and a run that reaches a limit stops with a limit error that `try` cannot catch. `cargo xtask test262` also runs the suite's ES5 language tests that need only the built-ins present: 4,676 of 4,682 runs pass (4 of the others expect the completion values of later editions, and 2 expect a configurable function `length`). The app does not call it yet. Tests: `crates/js/src/interp_tests.rs`, `crates/js/tests/test262.rs`.
|
||||
- With `Options::es2015`, `vectorcraft-js` also reads and runs these ECMAScript 2015 forms (https://262.ecma-international.org/6.0/): `let` and `const` with block scope and their temporal dead zone (a read or write before the declaration runs throws a `ReferenceError`, and a write to a `const` throws a `TypeError` in any code), a new `let` binding for each iteration of a `for` or `for`-`in` loop, function declarations scoped to their block, arrow functions with the `this` and `arguments` of the code around them and no `prototype`, template literals and tagged templates with one frozen strings object for each site, default and rest parameters with an `arguments` object that does not follow the parameters, and spread in array literals, calls and `new`. Spread uses the iterator protocol (see the `for`-`of` line below). Spread and template objects take fuel for each element and count against the heap limit, and nested arrows and templates count against `Options::max_depth`. `script.run` sets the option for a `.js` file, and `eval`, `Function`, `#include` files and `$.evalFile` read code the way the script does; a `.jsx` file and a `source` string stay ES5.1. Modules are still syntax errors. `cargo xtask test262` reads the suite's tests of these forms without and with the option: when these forms were added, 390 of 390 negative parse runs and 565 of 589 other runs passed with it (373 and 27 without it), and the 24 failing runs expected function `name` properties, a configurable function `length` and the `caller` and `arguments` restrictions. The object-literal line below adds function names and configurable lengths; the `caller` and `arguments` restrictions are still not implemented. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`.
|
||||
- With `Options::es2015`, `vectorcraft-js` also reads and runs these ECMAScript 2015 forms (https://262.ecma-international.org/6.0/): `let` and `const` with block scope and their temporal dead zone (a read or write before the declaration runs throws a `ReferenceError`, and a write to a `const` throws a `TypeError` in any code), a new `let` binding for each iteration of a `for` or `for`-`in` loop, function declarations scoped to their block, arrow functions with the `this` and `arguments` of the code around them and no `prototype`, template literals and tagged templates with one frozen strings object for each site, default and rest parameters with an `arguments` object that does not follow the parameters, and spread in array literals, calls and `new`. Spread uses the iterator protocol (see the `for`-`of` line below). Spread and template objects take fuel for each element and count against the heap limit, and nested arrows and templates count against `Options::max_depth`. `script.run` sets the option for a `.js` file, and `eval`, `Function`, `#include` files and `$.evalFile` read code the way the script does; a `.jsx` file and a `source` string stay ES5.1 when run as scripts. With `module: true`, they run as modules and accept these ECMAScript 2015 forms. `import` and `export` outside a module are syntax errors (the modules entry below). `cargo xtask test262` reads the suite's tests of these forms without and with the option: when these forms were added, 390 of 390 negative parse runs and 565 of 589 other runs passed with it (373 and 27 without it), and the 24 failing runs expected function `name` properties, a configurable function `length` and the `caller` and `arguments` restrictions. The object-literal line below adds function names and configurable lengths; the `caller` and `arguments` restrictions are still not implemented. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`.
|
||||
The collector retains tagged-template cache entries only while the site's code is reachable.
|
||||
- With `Options::es2015`, `vectorcraft-js` also reads and runs classes (https://262.ecma-international.org/6.0/#sec-class-definitions): declarations, scoped to their block like `let`, and expressions, with `extends`, `static` members, getters and setters, generator methods, and computed method names, Symbols included; class code is strict mode code, methods are not enumerable and cannot be constructed, and calling a class without `new` throws a `TypeError`. A derived constructor's `this` is unusable until `super(…)` returns (a `ReferenceError`), and its own default constructor passes its arguments on. `super.name` and `super[key]` read, call and write through the prototype of the method's home object with `this` as the receiver, in class methods and in methods and accessors written in object literals, which are enumerable, computed names included. A class takes its own name, or the name it is assigned to, and each method takes the name of its key (`get ` or `set ` before an accessor's, a Symbol's description in brackets). `new.target` names the constructor `new` was applied to, in functions and the arrow functions inside them. A class can extend `null`, a function, a class, or the built-in constructors `Object`, `Function`, `Array`, `String`, `Number`, `Boolean`, `RegExp`, `Date` and the error types; a class can name another built-in constructor in `extends`, but `new` on that class throws a `TypeError` when it reaches the built-in constructor, a rule that is VectorCraft's own. Each class and method takes fuel, and deep chains of constructors stop at the frame limit. `new.target` in code given to direct `eval` inside a function, or inside an arrow function within one, reads that function's `new.target`, and outside a function it is a `SyntaxError`; `super` in code given to direct `eval` is not supported yet. `cargo xtask test262` runs the `class`, `super` and `new.target` tests with the other ES2015 forms. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`.
|
||||
- `Options::es2015` also reads and runs two ECMAScript 2020 forms (https://262.ecma-international.org/11.0/): optional chains (`a?.b`, `a?.[key]`, `f?.(args)` and the accesses and calls after them), which evaluate their base once and give `undefined` without evaluating the rest of the chain when a value before `?.` is `undefined` or `null`, keep the object as `this` for `a?.b()` and `a.b?.()`, make `eval?.(code)` an indirect eval and make `delete a?.b` true when `a` is `undefined` or `null`; and `??`, which keeps any left side other than `undefined` and `null`. `?.` before a digit reads as `?` and a number (`a?.5:1`). Mixing `??` with `&&` or `||` without parentheses, assigning to or updating an optional chain, a tagged template after one and `new a?.b()` are syntax errors. A skipped part of a chain takes no fuel, and a chain of any length compiles without recursion. Using the ECMAScript 2015 option for them, so `.js` files read them and `.jsx` files and `source` strings do not, is VectorCraft's own rule. With the suite's `expressions/optional-chaining` and `expressions/coalesce` tests that need only the forms above, `cargo xtask test262` reads 426 of 426 negative parse runs and 591 of 782 other runs as passing with the option (409 and 27 without it). Of the 191 failing runs, 175 are those the entry above names, and 16 do not parse because the tests also use method definitions, classes, `for`-`of` or `new.target`. Tests: `crates/js/src/es2020_tests.rs`, `crates/js/tests/test262.rs`.
|
||||
- `vectorcraft-js` runs ECMAScript 2015 modules (https://262.ecma-international.org/6.0/#sec-modules): `parse_module` reads `import` and `export` declarations, with their early errors, and `Realm::start_module` and `Realm::run_module` load a module and the modules it imports through the host, link every import before any module runs, and run each module once, after the modules it imports; in a cycle of imports a module does not wait for a module that is still waiting for its own imports, so it can run before that module has initialized its bindings. An import reads the exporting module's binding each time, and a read before that binding is initialized throws a `ReferenceError`; `import * as ns` gives a namespace object that is not extensible and takes no writes. `export * as ns from` (ECMAScript 2020) is read too; `import()` is a syntax error. Parsing takes fuel for each code unit, and the host bounds how many modules a run loads and how deep its imports go. `script.run` runs a `.mjs` file as a module by default; `module: false` runs it as a script. Any script run with `module: true` runs as a module: specifiers are `./` and `../` paths to `.mjs` and `.js` files, read only in the script's folder and the folders below it through the script's file scope; a bare name or a URL is a `SyntaxError` that names it, and module files count against the limits of `#include` files. File › Scripts lists `.mjs` files and Other Script… opens them, on the web too. `cargo xtask test262` runs the suite's module tests under `test/language/module-code`, `import` and `export` whose feature tags it reads: 232 of 263 pass as modules (154 as scripts). Tests: `crates/js/src/module_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_modules.rs`.
|
||||
- `vectorcraft-js` provides the ECMAScript 5.1 built-ins `Object` with its property-descriptor functions, `create`, `keys`, `seal` and `freeze` (section 15.2), `Function.prototype.bind` (15.3.4.5), `Array` with every ES5 method (15.4), `Boolean`, which converts a value when called and makes a Boolean object with `new` (15.6), the error types (15.11), `Math` (15.8), `JSON` with revivers, replacers and indentation (15.12), and the global functions with Annex B's `escape` and `unescape` (15.1, B.2). The array methods work on array-like objects. A method visits only the indices that exist when its range is longer than 4,096 indices and more than 8 times the properties on the object and its prototypes, so `new Array(4294967295).join("")` ends at once; a shorter range is visited index by index, holes included, and each index takes fuel. `join` writes a cycle back to an array as an empty string, `JSON.stringify` throws a `TypeError` on a cycle, and deep `JSON` nesting uses no native stack. Every loop takes fuel and every result is checked against the heap limit. `cargo xtask test262` runs the suite's ES5 built-in tests that need only these built-ins: 7,000 of 7,070 runs pass (the 35 failing tests expect rules of later editions). It also fetches the `json2.js` polyfill at a pinned commit and checks that its `stringify` and `parse` agree with the built-in `JSON`. Tests: `crates/js/src/builtins_tests.rs`, `crates/js/tests/test262.rs`, `crates/js/tests/json2.rs`.
|
||||
- `vectorcraft-js` has `String`, `Number`, `RegExp` and `Date` as ECMAScript 5.1 defines them (sections 15.5, 15.7, 15.9 and 15.10, https://262.ecma-international.org/5.1/), with Annex B's `substr`, `getYear`, `setYear` and `toGMTString`. `toFixed`, `toExponential` and `toPrecision` format a number from its exact decimal value, and `toString(radix)` writes any base from 2 to 36. Regular expressions (flags `g`, `i` and `m`) run on a backtracking matcher whose choice points and capture state count against the heap limit and which takes fuel for every step, so a catastrophic pattern stops at the fuel limit and 50,000 nested groups give a `SyntaxError` at the default depth limit. A string method that would build a string past the heap limit stops before it allocates. `Date` reads the clock and time zone the host sets (`Realm::set_clock`, `Realm::set_time_zone`; local time is UTC by default). `cargo xtask test262` runs the suite's `built-ins` tests for the four (https://github.com/tc39/test262): of the runs of the ES5 tests that need only the built-ins present, 1,421 of 1,453 pass for `String`, 304 of 304 for `Number`, 962 of 996 for `RegExp` and 8 of 8 for `Date`. The others expect later editions' rules (built-in functions whose `length` can be deleted, flags given with a RegExp object, a negative `lastIndex`, `RegExp.prototype` as a plain object, and `RegExp.prototype`'s `global`, `ignoreCase` and `multiline` properties that can be deleted). Tests: `crates/js/src/text_tests.rs`, `crates/js/tests/test262.rs`.
|
||||
- `cargo xtask test262` also reads the suite's Annex B tests (https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), whichever edition they name. It parses the 819 tests under `test/annexB/language` without a feature tag in the modes their flags give, so a `for`-`in` variable with an initializer must parse in sloppy code and give a `SyntaxError` in strict code (682 of 843 runs pass), and it runs those tests and the `test/annexB/built-ins` tests for `String`, `Date`, `RegExp` and `Function` that need only the built-ins present (263 of 667 runs pass for the language tests and 56 of 252 for the built-ins). Failures go to `annexb-parse-failures.txt`, `annexb-language-failures.txt` and `annexb-builtins-failures.txt` beside the suite. A conformance failure does not fail the tests, but an interpreter panic fails `annex_b_runs`, so `cargo xtask test262` exits non-zero. A folder or file the runner cannot read also fails the test that reads it. The runner reads only regular files inside the suite, up to 8 MiB each, and does not follow symbolic links. Tests: `crates/js/tests/test262.rs`.
|
||||
@@ -1283,7 +1286,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- The status bar translates the plug-in host's other errors (manifest, module and run checks, the output an importer, exporter or effect returns, and the approval a plug-in's permissions need) in every language that translates every message. A JSON object or array inside a message stays as written, and a message that wraps another one, such as `plug-in manifest: {0}`, is matched by its own row before a row that starts with a placeholder. The reasons inside these errors (what is wrong with a parameter's spec or dialog keys, the value a parameter needs, what is wrong with an object, stroke, paint or effect in a plug-in's output) are translated with them, and the untranslated-strings report lists the reasons the plug-in host's error helpers take (`plugin_messages_are_translated_in_every_complete_catalog`, `plugin_errors_translate_with_their_values`, `plugin_error_reasons_are_translated_with_the_error`, `message_scan_reads_plugin_helpers`, `templates_that_start_with_text_match_first`).
|
||||
- The status bar translates the errors of Object › Plug-ins › Cutting Tools › Banner Hems and Grommets… and the line for a recovery copy that fails in a store with no folder to name (`{saving} failed: {e}`) in every language that translates every message. The untranslated-strings report also lists the messages a status takes from a local variable, such as the recovery folder errors (`banner_and_recovery_messages_are_translated_in_every_complete_catalog`, `message_scan_reads_locals_given_to_a_status`).
|
||||
- The status bar translates `script.run`'s refusals of `answers` in every language that translates every message: a value that is not a list, more than 10,000 answers, more than 1 MiB, an answer at an index that is not an object, does not have exactly `kind` and `value`, has a `value` its kind of dialog does not take, holds a prompt's text longer than 16 KiB or has an unknown `kind`, and `answers` given to a run in the app. The index, the counts and the code names are shown as they are, and the command's error stays in English. The untranslated-strings report also lists the refusals of `script.run`'s parameters (`script_answers_errors_are_translated`, `message_scan_reads_script_run_param_refusals`).
|
||||
- The status bar also translates `script.run`'s other refusals of its parameters in every language that translates every message: a `maxFuel` outside 1 to 100,000,000,000, `args` nested more than 64 levels deep (with the place in `args`), `args` that is not an object or is larger than 1 MiB, an empty `path`, a `source` given with `installed`, a `path` that does not name a .js or .jsx file, and neither or both of `path` and `source`. The code names, the place in `args`, the file suffixes and the limits are shown as they are, and the command's error stays in English (`script_run_param_errors_are_translated`).
|
||||
- The status bar also translates `script.run`'s other refusals of its parameters in every language that translates every message: a `maxFuel` outside 1 to 100,000,000,000, `args` nested more than 64 levels deep (with the place in `args`), `args` that is not an object or is larger than 1 MiB, an empty `path`, a `source` given with `installed`, a `path` that does not name a .js, .mjs or .jsx file, and neither or both of `path` and `source`. The code names, the place in `args`, the file suffixes and the limits are shown as they are, and the command's error stays in English (`script_run_param_errors_are_translated`).
|
||||
- The Japanese catalog (`crates/ui-egui/src/i18n/ja.tsv`) has 3,562 `@msg` rows and 49 `@msgplural` rows (counted 2026-11-14). The untranslated report (`untranslated_report`) lists 98 status and error messages in the sources that have no Japanese row: 77 that every complete-message language lacks, and 21 more. Open #7211 translates 34 of them, among them the composite font errors, and open #7116 translates the justification order error. The status bar does not use the rows for ``unknown parameter `{within}{key}`; {why}`` and `{name} must be {lo}–{hi}{unit} (got {v})`, because a message with two placeholders in a row cannot be matched (`Template::parse` in `crates/ui-egui/src/i18n/catalog.rs`). A native speaker has not reviewed the wording.
|
||||
- A status or error message whose braces are literal, such as a plug-in's `expected {"objects": [...]}` or a command's `quotes must be {double?, single?}`, is translated only when the whole message matches its row: the row writes those braces doubled and has no placeholder, so it no longer replaces a different message that starts with the same words, such as a JSON reason `expected value at line 1 column 1`, which stays in English. A row without placeholders is found at any message length (`plain_message_keys_double_their_braces`, `literal_brace_rows_match_only_their_message`).
|
||||
- Every complete-message catalog translates five more messages with literal braces through such a row: the composite font errors `each font must be {name, parts}` and `give fonts: [{name, parts}…]`, `select.font`'s `` `scope` must be "document", {artboards: [index, …]} or {layers: [id, …]} ``, the script regular expression error `numbers out of order in {} quantifier` and `the paint is not a freeform gradient (apply one with paint.editGradient {kind: "freeform"})`. Each translation keeps the braced example as written, and no catalog keeps the older rows with a placeholder in place of the braces, which also translated other text with the same start and end (`literal_brace_messages_have_exact_rows_in_complete_languages`).
|
||||
@@ -2821,6 +2824,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
|
||||
- **Plug-in parameters as their manifest presents them (G17):** each parameter may have a `label`, a `unit` shown after its value, `help` on its label and a `helpUrl` page opened from a button, a `group` (sections that fold, after the parameters outside any group) and a `visibleWhen` that shows it only while the checkboxes and choices it names have one of the listed values (a hidden parameter still goes to the plug-in). `string` and `numberList` parameters join number, int, bool and choice, and a plug-in declares up to 256 parameters, at most 64 outside groups. The filter, live-effect and exporter dialogs use these keys, and the Appearance panel's effect editor the labels, units, help and conditions; hosts from before them ignore them. Regressions: `crates/plugins/src/dialog.rs`, `crates/plugins/src/manifest.rs`, `crates/ui-egui/src/dialogs/tests_plugin_fields.rs`, `crates/ui-egui/src/panels/appearance.rs`. Scores and hours unchanged.
|
||||
- **Plug-in int parameters as sliders (G17):** an `int` parameter with `"widget": "slider"` shows a slider over its range with its number field, in the filter, live-effect and exporter dialogs and in the Appearance panel's effect editor; the manifest is refused at install when the parameter cannot have one. Regressions: `crates/plugins/src/dialog.rs`, `crates/ui-egui/src/dialogs/tests_plugin_fields.rs`. Scores and hours unchanged.
|
||||
- **Plug-in text in the UI language:** a manifest's `translations` give the plug-in's name, its commands' labels, its parameters' labels, help and choice labels, and its group headings in up to 16 languages, by language code (`de`, `pt-BR`). Object › Plug-ins, Effect › Plug-ins, File › Open With, Edit › Keyboard Shortcuts, the command palette, the plug-in dialogs and the Appearance panel show the text for the UI language, then for the language without its region (`pt-br`, then `pt`), then the manifest's own; command ids, parameter names, choice values and `plugin.list` keep the manifest's own text, and the install approval shows the manifest's own name under the ID when the name it asks with is a translation. An unknown code, a repeated language, text a source field couldn't hold, a control, direction or line-separator character, or a key the manifest doesn't declare is refused at install with an error naming the key, inside the 64 KiB manifest limit. Filter and importer menu items and plug-in dialog labels, help, groups and choices now escape bidirectional characters as command labels already did, and so does the refusal of a heavy filter. Regressions: `crates/plugins/src/translations.rs`, `crates/ui-egui/src/tests/plugins.rs`, `crates/ui-egui/src/dialogs/tests.rs`, `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged.
|
||||
- **Live-effect plug-ins read their object's paints (G17):** a live effect is given the object's `fills` and `strokes` as a filter gets them, read only, and `_context.item` (`"object"`, or the fill or stroke whose own effects hold it); the result is cached by paint too, so a change of paint runs it again. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/plugins/src/effect.rs`. Scores and hours unchanged.
|
||||
- **Live-effect plug-ins before a fill's or stroke's own 3D effect:** a live effect listed before a fill's or stroke's own Extrude & Bevel, Inflate or Rotate effect is given `_context.item` for that fill or stroke (`{"fill": i}` or `{"stroke": i}`), not `"object"`, in the drawn art, in the 3D meshes and in Expand as Wireframes; a deferred stage there is listed at that fill's or stroke's place. Regressions: `crates/effects/src/tests/solidcontext.rs`. Scores and hours unchanged.
|
||||
- **Filter plug-ins set effects and stroke styles (G17):** a filter is given each object's effect records and its strokes' `join`, `cap` and `miterLimit`, and may return them; the records are admitted as `effect.apply` admits them (a known effect or installed live-effect plug-in, parameters it takes, one 3D effect that fits, no texture read from a file), and one refused refuses the output. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/plugins/src/objects/tests.rs`. Scores and hours unchanged.
|
||||
|
||||
Reference in new issue
Block a user