diff --git a/.gitignore b/.gitignore index 9b388af1d..e13788056 100644 --- a/.gitignore +++ b/.gitignore @@ -62,6 +62,10 @@ web/vendor/tree-sitter-*/*.wasm # And pdf.js, pinned in web/vendor/pdfjs/SHA256SUMS: 1.7 MB of minified API # and worker, the same argument at a smaller size. web/vendor/pdfjs/*.mjs +# And Prettier, which formats JavaScript in the editor on request. +web/vendor/prettier/*.mjs +web/vendor/prettier/THIRD-PARTY-NOTICES.md +web/vendor/prettier-plugins/*.mjs # And the temp file a download in progress writes, which carries none of those # suffixes: a run killed outright leaves one, and it is the same megabytes. web/vendor/*/.*.part diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.md index c402ed862..f09877d3f 100644 --- a/THIRD-PARTY-NOTICES.md +++ b/THIRD-PARTY-NOTICES.md @@ -18,8 +18,9 @@ pinned files with `make verify-vendor`. | [Tree-sitter Python](https://github.com/tree-sitter/tree-sitter-python) | 0.25.0 | MIT | Python grammar | | [Three.js](https://threejs.org/) | 0.185.1 | MIT | Avatar renderer | | [@pixiv/three-vrm](https://github.com/pixiv/three-vrm) | 3.5.5 | MIT | VRM support | +| [Prettier](https://github.com/prettier/prettier) | 3.10.1 | MIT | Editor's Format JS, `standalone.mjs` with the estree and acorn plugins | -The MediaPipe binaries, the Pyodide binaries, pdf.js and Tree-sitter are fetched at build time from +The MediaPipe binaries, the Pyodide binaries, pdf.js, Tree-sitter and Prettier are fetched at build time from the version or commit named in their `FETCH` manifests, and accepted only when they match the adjacent `SHA256SUMS`. The LiveKit client and the three-vrm bundle are committed and pinned in place. @@ -34,6 +35,9 @@ License texts and source details are shipped with the relevant assets: - `web/vendor/avatar/README.md` - `web/vendor/pyodide/README.md` - `web/vendor/pdfjs/README.md` +- `web/vendor/prettier/LICENSE`, `web/vendor/prettier/THIRD-PARTY-NOTICES.md` + (Prettier and what its bundles include, such as acorn and acorn-jsx) and + `web/vendor/prettier/README.md` The build also patches two Rust crates, kept in source form with their licenses: diff --git a/tests/browser/editor-format.test.js b/tests/browser/editor-format.test.js new file mode 100644 index 000000000..9c1a2176e --- /dev/null +++ b/tests/browser/editor-format.test.js @@ -0,0 +1,249 @@ +// Run with: node --test tests/browser/editor-format.test.js +// +// The parts of Shift+Alt+F formatting that need no page: what the formatter +// answers for a buffer and which keystrokes are the chord. +// format-shortcut.test.js drives the same code, through the Format JS button +// and the chord, in a browser. + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import vm from "node:vm"; + +import { createJavaScriptFormatter } from "../../web/format.js"; +import { isFormatKeystroke, shortcutKey } from "../../web/editor.js"; + +const FOUR = " "; +const format = createJavaScriptFormatter(); + +async function formatted(code, caret = 0, indent = FOUR) { + const result = await format(code, caret, indent); + assert.equal(result.ok, true, result.message); + return result; +} + +// Before and after, byte for byte, under the default four-space indentation. +// Each "after" is Prettier 3.10.1's answer; a version bump that moves one is +// a change the pull request has to show. +const FIXTURES = [ + { + name: "a one-line function", + before: "function add(a,b){return a+b}", + after: "function add(a, b) {\n return a + b;\n}\n", + }, + { + name: "comments, line and block, kept where they were", + before: + "// head\nfunction f(x){ /* inner */ return x // tail\n}\n/* end */\n", + after: + "// head\nfunction f(x) {\n /* inner */ return x; // tail\n}\n/* end */\n", + }, + { + name: "a template literal's text untouched, its expressions spaced", + before: "const s=`a b\n c ${ 1+2 }`\n", + after: "const s = `a b\n c ${1 + 2}`;\n", + }, + { + name: "a directive stays first and keeps its quotes", + before: "'use strict'\nlet x=1\n", + after: '"use strict";\nlet x = 1;\n', + }, + { + name: "a long line broken at eighty columns", + before: + "const total = values.map((value) => value * factor).filter((value) => value > threshold).reduce((a, b) => a + b, 0);\n", + after: + "const total = values\n .map((value) => value * factor)\n .filter((value) => value > threshold)\n .reduce((a, b) => a + b, 0);\n", + }, + // Automatic semicolon insertion does not apply before a line that opens + // with "[", so these two lines are one expression. Prettier prints the + // expression the parser saw, which shows the hazard rather than hiding it. + { + name: "a missing semicolon before '[' printed as the one expression it is", + before: "let a = 1\n[1,2].forEach(x=>x)\n", + after: "let a = (1)[(1, 2)].forEach((x) => x);\n", + }, +]; + +for (const { name, before, after } of FIXTURES) { + test(`formats ${name}`, async () => { + assert.equal((await formatted(before)).value, after); + }); + + test(`formatting ${name} a second time changes nothing`, async () => { + assert.equal((await formatted(after)).value, after); + }); +} + +test("an empty or blank buffer formats to empty, with the caret kept in range", async () => { + assert.deepEqual(await format("", 0, FOUR), { + ok: true, + value: "", + cursor: 0, + }); + assert.deepEqual(await format(" \n\n ", 4, FOUR), { + ok: true, + value: "", + cursor: 0, + }); +}); + +test("the caret stays on the token it was on", async () => { + const code = "function f(a,b){return a+b}"; + const caret = code.indexOf("return") + 2; + const { value, cursor } = await formatted(code, caret); + assert.equal(value.slice(cursor - 2, cursor + 4), "return"); +}); + +test("the lobby's indentation is the formatter's", async () => { + const code = "if(a){b()}"; + assert.equal((await formatted(code, 0, " ")).value, "if (a) {\n b();\n}\n"); + assert.equal( + (await formatted(code, 0, FOUR)).value, + "if (a) {\n b();\n}\n", + ); + assert.equal((await formatted(code, 0, "\t")).value, "if (a) {\n\tb();\n}\n"); +}); + +// A formatter that guessed at incomplete code would hand the candidate a +// program they did not write. Acorn refuses it, and the refusal names where. +for (const [code, message] of [ + ["function f(", "Unexpected token at line 1, column 12"], + ["let x = ;", "Unexpected token at line 1, column 9"], + ["if (a) {\n b()\n", "Unexpected token at line 3, column 1"], + ["const s = `open", "Unterminated template at line 1, column 12"], + ["a + b = 1", "Assigning to rvalue at line 1, column 1"], +]) { + test(`incomplete code is refused, not repaired: ${JSON.stringify(code)}`, async () => { + assert.deepEqual(await format(code, 0, FOUR), { ok: false, message }); + }); +} + +// The known exceptions to "only what the runner runs": Prettier's acorn +// parser carries JSX and allows a top-level return. Each is formatted, and +// stays as unrunnable after as it was before, so nothing invalid becomes valid. +test("JSX and a top-level return are formatted rather than refused", async () => { + assert.equal( + (await formatted("const a=
")).value, + "const a = ;\n", + ); + assert.equal((await formatted("return 1")).value, "return 1;\n"); +}); + +// Parsing is not proof: each program prints the same thing before and after, +// run in a fresh context each time. +for (const program of [ + "let a = [3,1,2]\nlet b = a.sort((x,y)=>x-y)\n;[a.length].forEach(n=>out.push(n))\nout.push(b.join(','))", + "function f(){return (\n1+1)}\nout.push(f())", + "const o={a:1,'b-c':2}; out.push(JSON.stringify(o))", + "let i=0\ni++\n++i\nout.push(i)", + "const t=`x${ [1,2].map(n=>n*2) }y`;out.push(t)", + "label: for(const x of [1,2,3]){ if(x===2) continue label; out.push(x) }", +]) { + test(`formatting keeps what a program does: ${JSON.stringify(program.slice(0, 30))}`, async () => { + const run = (code) => { + const out = []; + vm.runInNewContext(code, { out }); + return out; + }; + const after = (await formatted(program)).value; + assert.notEqual(after, program); + assert.deepEqual(run(after), run(program)); + }); +} + +test("a large buffer formats within the budget", async (t) => { + const body = Array.from( + { length: 400 }, + (_, i) => + `function f${i}(a,b){const c=[a,b,${i}].map(x=>x*2).filter(x=>x>1);return c.reduce((s,x)=>s+x,0)}`, + ).join("\n"); + await formatted("let warm=1"); // the import is the first call's cost, not this one's + const started = performance.now(); + const { value } = await formatted(body); + const elapsed = performance.now() - started; + t.diagnostic( + `${body.length} characters, ${value.split("\n").length} lines formatted in ${Math.round(elapsed)} ms`, + ); + // Measured at 245 ms on one machine. The ceiling is twenty times that, so a + // loaded CI shard does not fail it; it catches a formatter that went + // quadratic, not a slow runner. + assert.ok(elapsed < 5000, `${Math.round(elapsed)} ms`); +}); + +test("a formatter that cannot load says so, and the next call loads again", async () => { + let calls = 0; + let online = false; + const flaky = createJavaScriptFormatter((url) => { + calls += 1; + return online + ? import(url.href) + : Promise.reject(new TypeError("Failed to fetch")); + }); + assert.deepEqual(await flaky("let a=1", 0, FOUR), { + ok: false, + message: "The formatter could not be loaded", + }); + online = true; + assert.deepEqual(await flaky("let a=1", 0, FOUR), { + ok: true, + value: "let a = 1;\n", + cursor: 0, + }); + // Three modules each time: the failure was not cached. + assert.equal(calls, 6); +}); + +// A Prettier error with no parser position still says what went wrong. +test("a formatter error without a position is reported as it is", async () => { + const broken = createJavaScriptFormatter(async (url) => + url.pathname.endsWith("standalone.mjs") + ? { + formatWithCursor() { + throw new Error("Comment was not printed\nmore detail"); + }, + } + : {}, + ); + assert.deepEqual(await broken("let a=1", 0, FOUR), { + ok: false, + message: "Comment was not printed", + }); +}); + +const key = (init) => ({ + key: "F", + code: "KeyF", + shiftKey: true, + altKey: true, + ctrlKey: false, + metaKey: false, + isComposing: false, + keyCode: 70, + ...init, +}); + +test("Shift+Alt+F is the chord, on every platform's spelling of it", () => { + assert.equal(isFormatKeystroke(key()), true); + assert.equal(isFormatKeystroke(key({ key: "f" })), true); + // Option+Shift+F on a Mac composes a character; the key's position says F. + assert.equal(isFormatKeystroke(key({ key: "Ï" })), true); +}); + +test("nothing else is the chord", () => { + for (const [why, init] of [ + ["no Shift", { shiftKey: false, key: "f" }], + ["no Alt", { altKey: false }], + ["AltGr, which is Ctrl+Alt on Windows", { ctrlKey: true }], + ["Cmd", { metaKey: true }], + ["another letter", { key: "G", code: "KeyG" }], + ["a composition", { isComposing: true }], + ["an engine that cleared isComposing early", { keyCode: 229 }], + ]) + assert.equal(isFormatKeystroke(key(init)), false, why); +}); + +test("shortcutKey lowercases ASCII, reads a composed character by key position, and keeps named keys", () => { + assert.equal(shortcutKey({ key: "Z", code: "KeyZ" }), "z"); + assert.equal(shortcutKey({ key: "Ω", code: "KeyZ" }), "z"); + assert.equal(shortcutKey({ key: "Enter", code: "Enter" }), "Enter"); +}); diff --git a/tests/browser/format-shortcut.test.js b/tests/browser/format-shortcut.test.js new file mode 100644 index 000000000..a5b215868 --- /dev/null +++ b/tests/browser/format-shortcut.test.js @@ -0,0 +1,769 @@ +// Run with: node --test tests/browser/format-shortcut.test.js +// +// The Format JS button and Shift+Alt+F in a real interview page. What the +// formatter writes is pinned in editor-format.test.js; what can break here is +// the wiring: the button and the chord reaching the formatter in JavaScript +// and no other language, the result landing as one edit that undo takes back +// with the overlay and the gutter in step, and a refusal leaving everything as +// it was. + +import { after, before, test } from "node:test"; +import assert from "node:assert/strict"; + +import { createJavaScriptFormatter } from "../../web/format.js"; +import { + DEFAULT_RUNTIME_CONFIG, + FAKE_SPEECH_CAPTURE, + fakeLiveKit, + launchChromium, + startStaticServer, +} from "./source.js"; + +const PROBLEM = "chargeback-pair-match"; +// A working answer to the problem, written with no formatting at all. +const MESSY = + "function matchDisputedCharge(nums,target){const seen=new Map();for(let i=0;i