diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index dc33c46ab1..67d6556bbe 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -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 { "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, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt)}] (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), 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; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message, title, errorIcon (alert), noAsDefault (confirm), preset (prompt), answer: \"ok\" | true | false | text | null | \"stop\" | \"missing\"}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", + "{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), 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, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt)}] (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), 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; vc.args is args. A .mjs file runs as an ECMAScript 2015 module: strict code whose import and export declarations at its top name other modules by a path relative to the importing file, starting with ./ or ../ and naming a .mjs or .js file, read in the script's folder and the folders below it (a bare name, a URL or a path that leads above the script's folder ends the run with an error naming it); every module is read, parsed and linked before any runs, so a syntax error, a missing file or an import of a name a module does not export ends the run with no code run; each module runs once, after the modules it imports, and an import reads the exporting module's binding as it is at that moment; its top-level names stay in the module, this is undefined, it has no preprocessor lines, and import() is a syntax error; module files count against the limits of included files. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message, title, errorIcon (alert), noAsDefault (confirm), preset (prompt), answer: \"ok\" | true | false | text | null | \"stop\" | \"missing\"}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", always, run ), @@ -86,7 +86,7 @@ pub fn specs() -> Vec { "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 ), @@ -188,7 +188,7 @@ fn run(s: &mut Session, p: &Value) -> Result { 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)?; diff --git a/crates/engine/src/script/folder.rs b/crates/engine/src/script/folder.rs index d071195df6..8226fa0711 100644 --- a/crates/engine/src/script/folder.rs +++ b/crates/engine/src/script/folder.rs @@ -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 @@ -256,7 +256,7 @@ 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 { diff --git a/crates/engine/src/script/include.rs b/crates/engine/src/script/include.rs index a024949a35..8de325cb70 100644 --- a/crates/engine/src/script/include.rs +++ b/crates/engine/src/script/include.rs @@ -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,57 @@ pub(crate) struct Files { frames: Vec, /// 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>, + /// The key of each module path read, below the script's folder. + module_paths: HashMap, } /// 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 path, in lowercase on Windows, +/// whose file names ignore letter case. +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()); + } + } + let shown = display(real).to_string(); + if cfg!(windows) { shown.to_lowercase() } else { shown } +} + +/// 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, 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 +375,76 @@ 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(), } } + /// 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()); + 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, |p, name| p.join(name)); + let (real, bytes) = match self.scope.read(&candidate, crate::script::MAX_SOURCE_BYTES) { + 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}"))), + }; + if self.bytes.saturating_add(bytes.len()) > MAX_TOTAL_BYTES { + return Err(LoadError::Range("script source limit reached (32 MiB)".to_string())); + } + self.bytes += bytes.len(); + let key = module_key(&real); + self.module_paths.insert(relative, key.clone()); + if self.module_dirs.contains_key(&key) { + return Ok((key, None)); + } + if self.files >= MAX_FILES { + return Err(LoadError::Range(format!("module file limit ({MAX_FILES}) reached"))); + } + self.files += 1; + let text = decode(&bytes, specifier).map_err(LoadError::Other)?; + path.pop(); + self.module_dirs.insert(key.clone(), path); + 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, ..Options::default() } diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index a01453a627..e318c0abb6 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -62,7 +62,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::{ @@ -1575,6 +1576,19 @@ 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 { + let (key, read) = host.files.borrow_mut().module(referrer, specifier)?; + let source = read.map(|(text, map)| { + host.eval_maps.borrow_mut().push(map); + host.disk.borrow_mut().saw_code(&text.encode_utf16().collect::>()); + 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>) { let (kind, message) = match f.kind { @@ -1937,7 +1951,16 @@ 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); + // A `.mjs` script is a module, with no preprocessor lines; `module_key` names it among the + // modules it imports. + let (expanded, module_key) = if include::module_script(request.file.as_deref()) { + 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, @@ -2083,7 +2106,13 @@ impl Session { .and_then(|()| if fresh { dialogs::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()); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index e524d1c63c..cfaf6649ba 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -176,6 +176,7 @@ mod script_engines; mod script_folder; mod script_include; mod script_io; +mod script_modules; mod script_run; mod scripts; mod select_effects; diff --git a/crates/engine/src/tests/script_modules.rs b/crates/engine/src/tests/script_modules.rs new file mode 100644 index 0000000000..9727abb927 --- /dev/null +++ b/crates/engine/src/tests/script_modules.rs @@ -0,0 +1,227 @@ +//! `.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/` in `base`, with the text `text`. +fn run_file(base: &Path, file: &str, text: &str) -> (Result, 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 { + 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); +} diff --git a/crates/engine/tests/script_corpus.rs b/crates/engine/tests/script_corpus.rs index 870bfbabc2..b4ad5c5a61 100644 --- a/crates/engine/tests/script_corpus.rs +++ b/crates/engine/tests/script_corpus.rs @@ -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] diff --git a/crates/js/src/ast.rs b/crates/js/src/ast.rs index c015e3fa38..a5d39c0b06 100644 --- a/crates/js/src/ast.rs +++ b/crates/js/src/ast.rs @@ -471,6 +471,58 @@ pub struct Program { pub(crate) es2015: bool, } +/// 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 { + pub specifier: String, + 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, + pub imports: Vec, + pub exports: Vec, +} + +/// 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) { diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index f2c02bdf4c..b85780cdc5 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -433,7 +433,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 { let k = interp.to_key(&arg(args, 0))?; let o = interp.to_object(&this)?; - Ok(Value::Bool(interp.get_own_property(o, &k)?.is_some())) + Ok(Value::Bool(interp.own_property(o, &k)?.is_some())) } fn is_prototype_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { @@ -452,7 +452,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 { let k = interp.to_key(&arg(args, 0))?; let o = interp.to_object(&this)?; - Ok(Value::Bool(interp.get_own_property(o, &k)?.is_some_and(|p| p.enumerable()))) + Ok(Value::Bool(interp.own_property(o, &k)?.is_some_and(|p| p.enumerable()))) } // ---- Function ---- diff --git a/crates/js/src/builtins/object.rs b/crates/js/src/builtins/object.rs index af41bb7782..419fbe57c5 100644 --- a/crates/js/src/builtins/object.rs +++ b/crates/js/src/builtins/object.rs @@ -130,7 +130,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_key(&arg(args, 1))?; - match interp.get_own_property(o, &k)? { + match interp.own_property(o, &k)? { Some(p) => from_prop(interp, &p), None => Ok(Value::Undefined), } @@ -265,7 +265,7 @@ fn locked(interp: &mut Interp, v: &Value, frozen: bool) -> JsResult { let o = *o; for k in interp.own_keys(o)? { interp.use_fuel()?; - let Some(prop) = interp.get_own_property(o, &k)? else { continue }; + let Some(prop) = interp.own_property(o, &k)? else { continue }; if prop.configurable() || (frozen && matches!(prop, Prop::Data { flags, .. } if flags & WRITABLE != 0)) { return Ok(Value::Bool(false)); } @@ -294,7 +294,7 @@ fn keys(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult, 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) -> CResult> { + let mut c = FnCompiler::new(&program.ast, source, CodeKind::Eval, true, 0); + c.es2015 = 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). diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index 0750204403..f158f45a0f 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -246,6 +246,9 @@ pub(crate) enum Class { }, /// A `.( )` filter in progress. XmlFilter(Box), + /// 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), } /// What an XML value is. @@ -322,6 +325,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", } } } @@ -353,17 +358,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()) } } @@ -674,6 +711,16 @@ fn trace_object(o: &Object, work: &mut Vec, strings: &mut StringSizes) -> u extra = BOUND_ARG_BYTES * args.len(); } Class::Arguments(map) => work.push(map.env.0), + 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) { @@ -730,6 +777,10 @@ fn trace_env(e: &Env, work: &mut Vec, 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() } diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index dc0e678e91..ae755f3aa3 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -24,8 +24,8 @@ use crate::ast::BinaryOp; use crate::bytecode::{Code, CodeKind, 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::string_builtins::flat_charged; use crate::value::{Str, Value, array_index, index_key, number_to_str, string_to_number, to_int32, to_uint32}; @@ -184,6 +184,10 @@ pub(crate) struct Frame { completion: Value, /// Returning from this frame returns from the Rust call that pushed it. boundary: bool, + /// 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. + chained: bool, } /// Where the exception being thrown was raised: the code and the instruction. @@ -949,7 +953,11 @@ impl Interp { } let Some(frame) = self.frames.pop() else { return Err(Abrupt::Throw(v)) }; self.stack.truncate(frame.base); - 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)); } @@ -983,6 +991,9 @@ impl Interp { if frame.boundary { return Ok(Some(v)); } + if frame.chained { + return Ok(None); + } self.push(v)?; Ok(None) } @@ -1245,6 +1256,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")) @@ -1257,6 +1277,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)), @@ -1276,6 +1304,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)) => { @@ -1464,11 +1498,38 @@ impl Interp { return Ok(Some(Prop::Data { value: self.binding_value(map.env, name)?, flags })); } } + 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> { + self.check_namespace_export(id, k)?; + self.get_own_property(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> { let mut cur = Some(id); @@ -1492,6 +1553,9 @@ impl Interp { /// [[Get]] starting at `start`, with `receiver` as `this` for a getter. pub(crate) fn get_from(&mut self, start: ObjId, k: &[u16], receiver: &Value) -> JsResult { + // A module's export read before the module ran is in its temporal dead zone (ECMA-262 + // 2015 section 9.4.6.8). + self.check_namespace_export(start, k)?; match self.find_property(start, k)? { None | Some(Prop::Accessor { get: None, .. }) => Ok(Value::Undefined), Some(Prop::Data { value, .. }) => Ok(value), @@ -1600,10 +1664,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.6): only a + /// descriptor that leaves an export as it is (enumerable, writable, not configurable, its + /// current value) succeeds, and it changes nothing. + fn define_namespace_export(&mut self, id: ObjId, k: &[u16], desc: &Desc, throw: bool) -> JsResult { + 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") } + } + fn reject_bool(&mut self, throw: bool, k: &[u16], why: &str) -> JsResult { if throw { let key = String::from_utf16_lossy(k); @@ -1768,6 +1848,10 @@ impl Interp { /// [[Put]] (section 8.12.5). pub(crate) fn put(&mut self, id: ObjId, k: Key, v: Value, throw: bool) -> JsResult<()> { + // 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 { @@ -2586,7 +2670,14 @@ 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 reads each one (ECMA-262 2015 section 9.4.6.5). let keys = self.enumerable_keys(o).and_then(|keys| { + for k in &keys { + self.check_namespace_export(o, k)?; + } + Ok(keys) + }); + let keys = keys.and_then(|keys| { let bytes = keys.iter().map(|k| string_bytes(k.len())).sum::(); self.reserve_heap(bytes)?; self.heap.bytes = self.heap.bytes.saturating_add(bytes); @@ -2862,6 +2953,7 @@ impl Interp { construct, completion: Value::Undefined, boundary, + chained: false, }); Ok(()) } @@ -3135,6 +3227,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, 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 { @@ -3316,10 +3424,96 @@ impl Interp { construct: None, completion: Value::Undefined, boundary, + chained: 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) -> JsResult<(EnvId, EnvId)> { + self.charge_code(code, 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 { + [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 { + let bytes = exports.iter().map(|(k, _)| binding_bytes(k.len()).saturating_mul(2)).sum::(); + self.reserve_heap(OBJECT_BYTES.saturating_add(bytes))?; + let mut object = Object::new(Class::ModuleNamespace(Box::default()), None); + 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 })); + Ok(self.heap.alloc_object(object)) + } + + /// 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, 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; + } + } + 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() + } + + /// 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. /// diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index f1fa58730f..8f99275192 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -55,8 +55,14 @@ //! 12.3.7), default and rest parameters (section 14.1) and spread in array literals, calls and //! `new` (sections 12.2.5 and 12.3.6.1). Spread reads arrays by index, reading the length again //! before each element, strings and `String` objects by code point, and objects with a `length` by -//! index; other values are a `TypeError`. Destructuring, `for … of`, classes, -//! generators and modules stay syntax errors. +//! index; other values are a `TypeError`. Destructuring, `for … of`, classes and generators 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. +//! Dynamic `import()` is a syntax error. #![forbid(unsafe_code)] pub mod ast; @@ -71,6 +77,7 @@ mod heap; mod host; mod interp; mod lexer; +mod module; mod number; mod number_builtins; mod parser; @@ -86,13 +93,15 @@ mod xml_builtins; mod xpath; pub use ast::{ - AssignOp, Ast, BinaryOp, CatchClause, Expr, ExprId, ForInTarget, ForInit, Function, FunctionId, FunctionKind, LexKind, LogicalOp, Name, Program, - Property, PropertyKey, PropertyValue, Stmt, StmtId, SwitchCase, TemplatePiece, UnaryOp, UpdateOp, VarDecl, XmlNamePart, XmlPart, XmlQualifier, + AssignOp, Ast, BinaryOp, CatchClause, DEFAULT_BINDING, ExportEntry, Expr, ExprId, ForInTarget, ForInit, Function, FunctionId, FunctionKind, + ImportEntry, ImportName, LexKind, LogicalOp, 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 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, RunError, RunErrorKind, SourceLocator, UNKNOWN_SOURCE}; pub use token::{Directive, DirectiveName, Keyword, Punct, Span, Token, TokenKind}; @@ -140,6 +149,34 @@ pub fn parse_utf16(source: &[u16], options: &Options) -> Result 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, 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() } +} + /// The tokens of `source`, in order, as the parser reads them: preprocessor lines included, and /// each `/` read as division or as the start of a regular expression literal as the grammar /// decides. The source must be a valid script. @@ -227,6 +264,8 @@ mod host_tests; #[cfg(test)] mod interp_tests; #[cfg(test)] +mod module_tests; +#[cfg(test)] mod tests; #[cfg(test)] mod text_tests; diff --git a/crates/js/src/module.rs b/crates/js/src/module.rs new file mode 100644 index 0000000000..b706c280f5 --- /dev/null +++ b/crates/js/src/module.rs @@ -0,0 +1,448 @@ +//! 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; +use std::rc::Rc; + +use crate::ast::{ExportEntry, ImportName, ModuleInfo}; +use crate::bytecode::Code; +use crate::heap::{Binding, 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, +} + +/// 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 + '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; + +/// A loaded module. +struct Record { + key: String, + info: ModuleInfo, + code: Rc, + tag: u32, + /// The module each of `info.requests` names, by index. + requested: Vec, + /// The environment its code runs in and the outer one, once instantiated. + envs: Option<(EnvId, EnvId)>, + namespace: Option, +} + +/// 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, + by_key: HashMap, + 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, 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 { + let interp = &mut *self.interp; + interp.prepare_source(source.len()).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))), + }; + self.records.push(Record { key: key_name.clone(), info, code, tag, requested: Vec::new(), envs: None, namespace: None }); + 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, u32)> = self.records[i].info.requests.iter().map(|r| (r.specifier.clone(), r.span.start)).collect(); + let depth = depths.get(i).copied().unwrap_or(0); + for (specifier, offset) in requests { + self.interp.use_fuel().map_err(LinkFail::Run)?; + 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); + } + 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); + } + Ok(()) + } + + /// The module the request `request` of module `m` names. + fn target(&self, m: usize, request: usize) -> Option { + 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 Vec<(usize, String)>) -> Result, Ambiguous>, LinkFail> { + if seen.iter().any(|(sm, sn)| *sm == m && sn == name) { + return Ok(Ok(None)); + } + if seen.len() >= 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.push((m, name.to_string())); + let exports = self.records.get(m).map(|r| r.info.exports.clone()).unwrap_or_default(); + for e in &exports { + match e { + ExportEntry::Local { export_name, local, .. } if export_name == name => { + return Ok(Ok(Some(Resolution::Binding { module: m, name: local.clone() }))); + } + ExportEntry::Indirect { export_name, request, import, .. } if export_name == name => { + 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; + for e in &exports { + let ExportEntry::Star { request, .. } = e else { continue }; + let Some(t) = self.target(m, *request) else { continue }; + 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, names: &mut Vec) -> Result<(), LinkFail> { + if visited.contains(&m) { + return Ok(()); + } + visited.push(m); + let exports = self.records.get(m).map(|r| r.info.exports.clone()).unwrap_or_default(); + for e in &exports { + self.interp.use_fuel().map_err(LinkFail::Run)?; + match e { + ExportEntry::Local { export_name, .. } | ExportEntry::Indirect { export_name, .. } => { + if !(star && export_name == "default") && !names.contains(export_name) { + names.push(export_name.clone()); + } + } + ExportEntry::Star { request, .. } => { + if let Some(t) = self.target(m, *request) { + self.exported_names(t, true, visited, names)?; + } + } + } + } + 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 { + 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)?; + let mut resolved = Vec::new(); + for name in names { + if let Ok(Some(r)) = self.resolve_export(m, &name, &mut Vec::new())? { + 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 Vec::new())? { + 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 Vec::new())? { + 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)); + } + }, + }; + 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 { + 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, 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 + } +} diff --git a/crates/js/src/module_tests.rs b/crates/js/src/module_tests.rs new file mode 100644 index 0000000000..26f453b652 --- /dev/null +++ b/crates/js/src/module_tests.rs @@ -0,0 +1,419 @@ +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 +} + +/// 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 + use<> { + let map: HashMap = 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, 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 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_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'), () => { for (var k in ns) {} }, () => Object.isSealed(ns), () => Object.isFrozen(ns), + () => Object.seal(ns), () => Object.freeze(ns), () => Object.defineProperties({}, ns), () => JSON.stringify(ns)]; + tries.forEach(function (f) { try { f(); out.push('no error'); } catch (e) { out.push(e.name); } }); + out.push('a' in 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(12); + assert_eq!(realm.run("out.join('|')"), Ok(JsValue::String(format!("{errors}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 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)]); + let r = realm.run_module( + "main.mjs", + "import * as ns from './m.mjs'; import { f } from './m.mjs'; out.push(ns.f(), f());", + ModuleLimits::default(), + &mut load, + ); + assert_eq!(r, Ok(JsValue::Undefined)); + realm.collect_garbage(); + assert_eq!(realm.run("out.join('|')"), Ok(JsValue::String("kept|kept".into()))); +} diff --git a/crates/js/src/parser.rs b/crates/js/src/parser.rs index edc6b22c9a..28b7cd5f72 100644 --- a/crates/js/src/parser.rs +++ b/crates/js/src/parser.rs @@ -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 xml; use std::collections::{HashMap, HashSet}; @@ -101,6 +102,9 @@ pub(crate) struct Parser<'s> { es2015: bool, /// The scopes open around the current token, outermost first (only with `es2015`). scopes: Vec, + /// Read a module ([`Parser::parse_module`]): its top-level function declarations are lexical + /// declarations (ECMA-262 2015 section 15.2.1.11). + module: bool, } impl<'s> Parser<'s> { @@ -125,6 +129,7 @@ impl<'s> Parser<'s> { e4x: options.e4x, es2015: options.es2015, scopes: if options.es2015 { vec![Scope { function: true, ..Scope::default() }] } else { Vec::new() }, + module: false, }; parser.tok = parser.next_significant()?; Ok(parser) @@ -342,6 +347,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) = self.ast.function(id).and_then(|f| f.name.clone()) 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) { diff --git a/crates/js/src/parser/module.rs b/crates/js/src/parser/module.rs new file mode 100644 index 0000000000..ec39092afb --- /dev/null +++ b/crates/js/src/parser/module.rs @@ -0,0 +1,299 @@ +//! 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::HashSet; + +use super::{Parser, Result, describe}; +use crate::ast::{ + 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, +} + +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)> { + self.module = true; + let mut info = ModuleInfo::default(); + 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)?; + } else if self.at_keyword(Keyword::Export) { + if let Some(stmt) = self.export_declaration(&mut info, &mut clause)? { + 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 }; + 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. + fn module_specifier(&mut self, info: &mut ModuleInfo) -> Result { + 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)))); + }; + let Ok(specifier) = String::from_utf16(units) else { + return Err(self.error_at_token(&self.tok, "a module specifier must be valid text")); + }; + let span = self.bump()?.span; + if let Some(i) = info.requests.iter().position(|r| r.specifier == specifier) { + return Ok(i); + } + info.requests.push(ModuleRequest { specifier, span }); + 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) -> 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)?; + 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)?; + 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) -> Result> { + 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)?; + 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)?; + 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)?; + 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 = match self.ast.stmt(stmt) { + Some(Stmt::Var(decls) | Stmt::Lexical(_, decls)) => decls.iter().map(|d| d.name.clone()).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 { + 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 name = Name { name: DEFAULT_BINDING.into(), span: start }; + let stmt = self.ast.push_stmt(Stmt::Lexical(LexKind::Const, vec![VarDecl { name, 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 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)?; + 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 import becomes a re-export of what it imports (section 15.2.1.16.1; a namespace + /// import as ECMA-262 2020 reads `export * as ns from`). + fn finish_exports(&self, info: &mut ModuleInfo, clause: Vec) -> Result<()> { + 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 = info.imports.iter().find(|i| i.local.name == c.local); + let entry = match imported { + Some(i) => ExportEntry::Indirect { export_name: c.export_name, request: i.request, import: i.import.clone(), span: c.span }, + None => 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(()) + } +} diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index 728839949c..1765d6d9d1 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -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)] @@ -255,6 +260,75 @@ impl Realm { /// Compiles `source` and readies the realm for a run. fn compile(&mut self, source: &str) -> Result, RunError> { + 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. + pub fn start_module(&mut self, key: &str, source: &str, limits: ModuleLimits, load: &mut ModuleLoader<'_>) -> Result<(), RunError> { + 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()); + 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); + 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`]) and returns + /// `undefined`. + pub fn run_module(&mut self, key: &str, source: &str, limits: ModuleLimits, load: &mut ModuleLoader<'_>) -> Result { + self.start_module(key, source, limits, load)?; + let result = self.interp.execute(); + 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; let interp = &mut self.interp; if let Some(message) = &interp.install_error { @@ -274,20 +348,7 @@ impl Realm { interp.finally_marks.clear(); interp.finally_sites.clear(); interp.error_mark = None; - 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. diff --git a/crates/js/tests/test262.rs b/crates/js/tests/test262.rs index 32790b3125..3e3472d634 100644 --- a/crates/js/tests/test262.rs +++ b/crates/js/tests/test262.rs @@ -30,7 +30,10 @@ //! //! A fifth test reads the ECMAScript 2015 subset that `Options::es2015` covers (`let`, `const`, //! arrow functions, templates, default and rest parameters) 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`. //! //! Two more tests read the Annex B trees, where tests name any edition's section: one parses every //! test under `test/annexB/language/` without a feature tag the same way as the ES5 parse subset @@ -46,7 +49,9 @@ 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, Punct, Realm, RunErrorKind, Token, TokenKind, parse, tokenize, tokenize_module, +}; /// A test file's metadata, from its `/*--- … ---*/` block. #[derive(Default)] @@ -427,6 +432,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], 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()), @@ -793,6 +804,163 @@ 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 { + 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. A `negative_type` is the error the run must end with: thrown, +/// or, for a `SyntaxError`, also a module that does not parse. +fn run_module_one(dir: &Path, prelude: &str, rel: &str, source: &str, negative_type: Option<&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 }) + }; + match (realm.run_module(rel, source, ModuleLimits::default(), &mut load), negative_type) { + (Ok(_), None) => Ok(()), + (Ok(_), Some(t)) => Err(format!("completed; a {t} was expected")), + (Err(e), Some("SyntaxError")) if 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(); + 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 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_type.as_deref(), &options)) { + Ok(r) => r, + Err(_) => 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!(!failures.contains("PANIC"), "the interpreter panicked; see {}", report.display()); +} + #[test] fn annex_b_runs() { let Some(dir) = suite_dir() else { diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index c3dbf78293..ff97bd9a3e 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -2029,13 +2029,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`: `name`, `script`, `dontShow`); without a file pick one (the web opens the browser's file picker)", + "{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`: `name`, `script`, `dontShow`); without a file pick one (the web opens the browser's file picker)", ), ( "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", + "{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", ), ( "ui.checkScript", diff --git a/crates/ui-egui/src/dialogs/script_run.rs b/crates/ui-egui/src/dialogs/script_run.rs index f8baa7b7de..f281431dc5 100644 --- a/crates/ui-egui/src/dialogs/script_run.rs +++ b/crates/ui-egui/src/dialogs/script_run.rs @@ -3,7 +3,7 @@ //! asks while a script runs, and the dialogs a script opens with `alert`, `confirm` and `prompt`. //! //! `ui.runScript {path? | source?, name?}` shows the warning for that script; without either it -//! asks for a `.js` or `.jsx` file (the web opens the browser's file picker). With Preferences › +//! asks for a `.js`, `.mjs` or `.jsx` file (the web opens the browser's file picker). With Preferences › //! General › Show External Script Warning off, the chosen script runs at once. Warning fields: //! `name`, `script` (`script.run`'s params) and `dontShow` (true: turn the warning off). //! @@ -145,7 +145,7 @@ pub(crate) fn command(app: &mut VectorcraftApp, p: &Value) -> Result Result { 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 app.run("script.run", params); diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e4271f7926..0150154359 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6427,7 +6427,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 @@ -6597,7 +6597,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 diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 488df173c3..08fa462557 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -5235,7 +5235,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í @@ -5382,7 +5382,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 diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 302ab6aa69..6ea9ba8e12 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -53,7 +53,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 @@ -241,7 +241,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} diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9482345f18..b915221d20 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -4820,7 +4820,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 @@ -8434,7 +8434,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 diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 434d0cc0b8..3fdba11d4c 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2624,7 +2624,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 εκτελείται ένα σενάριο: διακόψτε το ή περιμένετε να τελειώσει @@ -2795,7 +2795,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 Η αναφορά του σεναρίου αντιγράφηκε diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3f83e928e4..b2e9ad14bd 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -4899,7 +4899,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 @@ -5069,7 +5069,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 diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a4d85b23e8..b715bbc2ec 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5140,7 +5140,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 @@ -5310,7 +5310,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 diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8f56486157..ca239421f1 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -4881,7 +4881,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 @@ -5027,7 +5027,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 diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index e9509d9202..65579ccc22 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -7573,7 +7573,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 एक स्क्रिप्ट चल रही है: उसे रोकें या पूरा होने की प्रतीक्षा करें @@ -7744,7 +7744,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 स्क्रिप्ट रिपोर्ट diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 87f050ef0d..f1b34e6842 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5752,7 +5752,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 @@ -5900,7 +5900,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 diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 924d3d80b5..cdb530f77c 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -53,7 +53,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 @@ -148,7 +148,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} diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5f47e3f117..8362a90183 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4958,7 +4958,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 @@ -8475,7 +8475,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 diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 9a1b5f6354..0655c91562 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5784,7 +5784,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 スクリプトの実行中です: 停止するか、終了するまでお待ちください @@ -5931,7 +5931,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 スクリプトのレポートをコピーしました diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8eeacee621..ff7f6aa9a0 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -2135,7 +2135,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` წარმოადგენს @@ -8453,7 +8453,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 სკრიპტი მუშაობს: შეაჩერეთ ან დაელოდეთ დასრულებას diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 57e0b8be10..423ade9b5c 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5713,7 +5713,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 스크립트 실행 중: 중지하거나 끝날 때까지 기다리세요 @@ -5860,7 +5860,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 스크립트 보고서를 복사했습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 5ed5cdc3e0..982e687887 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -53,7 +53,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 @@ -219,7 +219,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} diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 74029133dc..85ecad038e 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5063,7 +5063,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 @@ -8678,7 +8678,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 diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a1747af0b2..94b7580994 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6102,7 +6102,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 @@ -9047,7 +9047,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 diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ca0c8d5145..48468148a6 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -4934,7 +4934,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 выполняется скрипт: остановите его или дождитесь завершения @@ -5091,7 +5091,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 Отчёт о сценарии скопирован diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c26474cf93..556baff641 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4796,7 +4796,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 @@ -4967,7 +4967,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 diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 2ca2c76e03..762714fd4d 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -5848,7 +5848,7 @@ fn script_run_param_errors_are_translated() { "`args` is larger than 1 MiB", "`path` is empty", "`installed` takes a `path`, not a `source`", - "`path` must name a .js or .jsx file", + "`path` must name a .js, .mjs or .jsx file", "give exactly one of `path` and `source`", ]; let scanned = message_literals(); @@ -5876,7 +5876,7 @@ fn script_run_param_errors_are_translated() { (json!({"source": "1", "args": {"x": "x".repeat(1 << 20)}}), Some("`args` is larger than 1 MiB".into())), (json!({"path": ""}), Some("`path` is empty".into())), (json!({"source": "1", "installed": true}), Some("`installed` takes a `path`, not a `source`".into())), - (json!({"path": "notes.txt"}), Some("`path` must name a .js or .jsx file".into())), + (json!({"path": "notes.txt"}), Some("`path` must name a .js, .mjs or .jsx file".into())), (json!({}), Some("give exactly one of `path` and `source`".into())), (json!({"path": "a.js", "source": "1"}), Some("give exactly one of `path` and `source`".into())), (json!({"path": 1}), Some("`path` must be a string".into())), diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 82186ebcdd..370480f94f 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4648,7 +4648,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 @@ -4803,7 +4803,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ı diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index de3329ef10..07182972fa 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -4942,7 +4942,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 виконується скрипт: зупиніть його або дочекайтеся завершення @@ -8634,7 +8634,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` має бути індексом монтажної області документа diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 675143a8d6..f24dd20ba4 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5420,7 +5420,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 @@ -5590,7 +5590,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 diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 57f6a4403b..fa282f2150 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5449,7 +5449,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 脚本正在运行:请停止它或等待其完成 @@ -8684,7 +8684,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` 必须是文档中某个画板的索引 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9834c17ea6..8f2aa2eafb 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2795,7 +2795,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 指令碼正在執行:請停止它或等待其完成 @@ -2942,7 +2942,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 已複製指令碼報告 diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index d2c72aae40..33986b055a 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -2030,13 +2030,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`: `name`, `script`, `dontShow`); without a file pick one (the web opens the browser's file picker)", + "{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`: `name`, `script`, `dontShow`); without a file pick one (the web opens the browser's file picker)", ), ( 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", + "{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", ), ( "ui.checkScript", diff --git a/crates/ui-egui/src/tests/script_run.rs b/crates/ui-egui/src/tests/script_run.rs index fee27caa13..f8d3d4c39e 100644 --- a/crates/ui-egui/src/tests/script_run.rs +++ b/crates/ui-egui/src/tests/script_run.rs @@ -94,7 +94,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.ui.dialog.is_none()); } diff --git a/docs/mcp.md b/docs/mcp.md index ec6f2d7f76..b34a4ebed6 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2611,10 +2611,10 @@ 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. -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. Pass exactly one of `path` and `source`. A `path` must end in `.js` 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 +describes that menu item. 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 `.js` (in any case) also reads these ECMAScript 2015 forms (https://262.ecma-international.org/6.0/): `let` and @@ -2625,8 +2625,36 @@ before each element, strings and `String` objects by code point, and objects wit throws a `TypeError` for any other value; that rule is VectorCraft's own until iterators are added. `eval`, `Function`, `#include` files and `$.evalFile` read code the way the script does, and 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. The script reaches the -app through the global object `vc`, and writes to the Script Console and runs other files through `$`: +`.jsx` file and a `source` string read ES5.1 only, and the ECMAScript 2015 forms are syntax errors there. + +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, and `import` and +`export` declarations at its top level. `import` and `export` are syntax errors in a `.js` or `.jsx` script. + +- 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; two paths to one file + (a link, `sub/../x.mjs`, or names that differ only in letter case on Windows) are one module. 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 *` 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. +- 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 diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 144b20bd1c..15745fc595 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1079,7 +1079,8 @@ 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; 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,280 of 4,286 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 reads arrays by index, reading the length again before each element, strings and `String` objects by code point, and objects with a `length` property by index, and throws a `TypeError` for any other value; that rule is VectorCraft's own until iterators are added. 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. Destructuring, `for`-`of`, classes, generators and modules are still syntax errors. `cargo xtask test262` reads the suite's tests of these forms without and with the option: 390 of 390 negative parse runs and 533 of 708 other runs pass with it (373 and 27 without it). Of the 175 failing runs, 151 do not parse because the tests also use forms this list leaves out (classes, method definitions, destructuring, `for`-`of`, trailing commas in parameter lists, and a later edition's rule for escapes in tagged templates), and 24 expect function `name` properties, a configurable function `length` and the `caller` and `arguments` restrictions, ECMAScript 2015 rules that `vectorcraft-js` does not implement. 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 reads arrays by index, reading the length again before each element, strings and `String` objects by code point, and objects with a `length` property by index, and throws a `TypeError` for any other value; that rule is VectorCraft's own until iterators are added. 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. Destructuring, `for`-`of`, classes and generators are still syntax errors, and so are `import` and `export` outside a module (next entry). `cargo xtask test262` reads the suite's tests of these forms without and with the option: 390 of 390 negative parse runs and 533 of 708 other runs pass with it (373 and 27 without it). Of the 175 failing runs, 151 do not parse because the tests also use forms this list leaves out (classes, method definitions, destructuring, `for`-`of`, trailing commas in parameter lists, and a later edition's rule for escapes in tagged templates), and 24 expect function `name` properties, a configurable function `length` and the `caller` and `arguments` restrictions, ECMAScript 2015 rules that `vectorcraft-js` does not implement. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.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. 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: 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. `cargo xtask test262` runs the suite's module tests under `test/language/module-code`, `import` and `export` whose feature tags it reads: 233 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), 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: 6,798 of 6,866 runs pass (the 34 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,379 of 1,411 pass for `String`, 298 of 298 for `Number`, 954 of 988 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`. @@ -1161,7 +1162,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The untranslated-strings report reads a message written over two lines with a `\` at the end of the first as one line, the text the program shows, and the Georgian catalog's (`ka`) row for PDF export's warning about knockout groups with too many translucent elements matches that text (`message_scan_joins_a_literal_continued_on_the_next_line`, `untranslated_report`). - 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 `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`).