diff --git a/AGENTS.md b/AGENTS.md index caad039b..ea811a38 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -8,7 +8,7 @@ WebFront is a C++23 header-only library for serving a browser UI from a C++ appl - C++ calls browser functions with `ui.jsFunction(name)(arguments...)`, which is fire-and-forget and ignores the result, or with `ui.jsFunction(name)(arguments...)`, which returns a `std::future`. Only the untyped C++ form is fire-and-forget. - `webFront.ready` resolves after the WebSocket handshake acknowledgement and rejects if the initial connection fails or closes. -WebFront also ships a standalone developer environment (`NativeApp::bootstrap("developer")`): a terminal whose `wf` commands (`init`, `create`, `install`, `restore`, `run`, `exec`, `check`, `test`, `build`, `dev`, `preview`, `embed`, `list`, `help`) manage a project manifest and lock, compile TS/TSX, type-check, run Jasmine specs and generate the application's embedded provider, with no JavaScript runtime or package manager on the developer's machine. It is not a sandbox. See `docs/DEVELOPER_ENVIRONMENT.md`. +WebFront also ships a standalone developer environment (`NativeApp::bootstrap("developer")`): a terminal whose `wf` commands (`init`, `create`, `install`, `restore`, `run`, `exec`, `check`, `test`, `build`, `dev`, `preview`, `embed`, `list`, `why`, `info`, `help`) manage a project manifest and lock, compile TS/TSX, type-check, run Jasmine specs and generate the application's embedded provider, with no JavaScript runtime or package manager on the developer's machine. It is not a sandbox. See `docs/DEVELOPER_ENVIRONMENT.md`. The README introduces WebFront through the Game of Life walkthrough, demonstrating the developer bootstrap, reactive TypeScript UI and embedded distribution. The minimal `HelloWorld` example remains available under `examples/hello-world/`. Native modules and the bridge are covered by the Jasmine browser integration test. The optional `ui.document()` API provides per-connection DOM islands, batched writes, events (callbacks or awaitable `node.next(name)`) and grouped sender reads; see `docs/DOM.md`. The optional React store and `Island` adapter, including its support policy and coordinated unmount contract, is described in `docs/REACT.md`; `examples/life/react/` demonstrates it. Application coroutines use `webfront::Task` and `app.spawn(task)`/`ui.spawn(task)`; retain a `TaskHandle` to request individual cancellation. WebFront owns and drains these tasks. Spawn is callable from any thread while the application lives; a call rejected during shutdown returns a stopped handle. Destructors wait for outstanding operations; explicit shutdown reports a stalled join. Typed C++ sender calls support local cancellation; futures and JavaScript Promises do not expose cancellation. diff --git a/README.md b/README.md index 1c63b763..050c107d 100644 --- a/README.md +++ b/README.md @@ -169,7 +169,7 @@ app.bootstrap("developer"); app.show(); ``` -The project directory gives the application access to its development files. `bootstrap("developer")` opens the integrated terminal and loads the version-pinned developer environment, checking its SHA-512 integrity. Downloads are cached, so later launches work offline. The terminal runs `wf` commands; no system shell is exposed and nothing is installed on your machine. +The project directory gives the application access to its development files. `bootstrap("developer")` opens the integrated terminal and loads the version-pinned developer environment, checking its SHA-512 integrity. Downloads are cached, so later launches work offline. The terminal runs `wf` commands on the project and has `ls`, `cat`, `tree` and `mounts` to look at it; no system shell is exposed and nothing is installed on your machine. The build you made above is enough. Start the example from the `build` directory: diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 62bb16ff..b7a6e3d2 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -10,8 +10,13 @@ these entries stays in the GitHub releases and the Git history. ## Unreleased +### Breaking + +- Reserve more command names for the terminal: an application command named `ls`, `cat`, `tree`, `mounts`, `cd`, `pwd`, `cp`, `mv`, `rm`, `mkdir`, `rmdir`, `touch`, `edit`, `find`, `grep`, `head`, `tail`, `less`, `stat`, `du` or `df` is now refused by `webfront::Commands::add` and must be renamed (#575, ADR-023). + ### Added +- Look at the project from the terminal with `ls`, `cat`, `tree` and `mounts` (read-only), and at the installed packages with `wf list --tree`, `wf why ` and `wf info `; a `wf` command typed without its prefix answers with the line to type. The `wf` prefix stays (#575, ADR-023, `docs/DEVELOPER_ENVIRONMENT.md`). - Add WebFront to an application that keeps its own loop: `app.start()` opens the system browser and returns at once, `app.requestClose()` ends an embedded window's `show()` from any thread, and `webfront::UIThread` runs an application on a secondary thread where the frontend allows it (WebView2). New `WebFrontHostLoop` example (#567, `docs/HOST_INTEGRATION.md`, ADR-007). - Tell an agent at first contact how an application is developed (C++ with a TypeScript/TSX interface in `ui/`, `wf dev`) and that it can run `wf` itself in JSON or MCP: a README section before the tutorial, `webfront_write_agent_guide()`, and notices at configuration, in the terminal and at startup (#561, `docs/DEVELOPING_WITH_AGENTS.md`). - Add the `app` starter (`wf create app`: a minimal TypeScript interface without dependency), `wf help ` and `wf help agents`, and make a missing manifest, a missing entry and an unknown starter answer with the next steps. Environment 0.9.2 (#561, `docs/DEVELOPER_ENVIRONMENT.md`). diff --git a/docs/DEVELOPER_ENVIRONMENT.md b/docs/DEVELOPER_ENVIRONMENT.md index 7ff422b8..f7d90e79 100644 --- a/docs/DEVELOPER_ENVIRONMENT.md +++ b/docs/DEVELOPER_ENVIRONMENT.md @@ -20,8 +20,14 @@ commands of the terminal operate on it: | `wf check` | type-check with the locked TypeScript compiler | | `wf test` | run Jasmine specs in the application's window | | `wf run`, `wf exec` | run a manifest script or a package's executable entry | +| `wf list [--tree]`, `wf why `, `wf info ` | list the installed packages, show them under the dependencies that bring them, explain or describe one | | `wf embed` | generate the C++ provider of the application's resources | +The terminal also has commands of its own, without prefix, that only read the project: `ls`, `cat`, `tree` and `mounts` +(see [the terminal](#the-terminal-and-the-applications-commands)). Project commands keep the `wf` prefix, which leaves +their names (`test`, `run`, `build`, `list`...) free for the commands of your application +([ADR-023](adr/ADR-023-espace-de-noms-des-commandes-du-terminal.md)). + **Agents.** A WebFront interface is TypeScript/TSX in `ui/`, developed with `wf dev`, and an agent runs every command of this page itself in JSON or MCP: see [developing with an agent](DEVELOPING_WITH_AGENTS.md). @@ -428,9 +434,56 @@ the same layout; `workspace: false` keeps the page as it is. The terminal of the environment (developer distribution 0.5.0, #308) is the only WebFront terminal; it is served from the environment archive with xterm.js, never from a C++ header. It runs `wf` commands, the application's C++ -commands and its own: `help`, `clear` (screen and scrollback), `history` (`history -c` clears it) and -`exit [code]`, which ends the session and closes the window; when the browser keeps a window that a script did not -open, Enter starts a new session. No system shell is exposed. +commands and its own: `help`, `clear` (screen and scrollback), `history` (`history -c` clears it), +`exit [code]`, which ends the session and closes the window, and the file commands below; when the browser keeps a +window that a script did not open, Enter starts a new session. No system shell is exposed. + +**Why `wf` stays.** A bare name belongs to the terminal or to your application; `wf` is the namespace of the project +(manifest, lock, packages, build). Without it the verbs of `wf` would be names your application could not use, and +every verb added later would take one more. A `wf` command typed without its prefix is not run: the error gives the +line to type (`Unknown command: install. Did you mean: wf install react?`). + +**File commands** (environment 0.9.3) read the project directory and never write it. Paths are relative +to the project and cannot leave it; there is no working directory, no glob and no pipe. Options combine (`-la`, `-aL 2`, +`-L2`), and `--` ends them so that a name may start with a dash (`cat -- -notes.txt`). + +Names, file contents and what a package declares about itself are not trusted: every control character they contain (C0, +DEL and the 8-bit C1 controls) is shown, `^[` for ESC or `\x9b` for an 8-bit CSI, and never sent to the terminal. This +holds for `ls`, `cat`, `tree`, `wf list`, `wf why` and `wf info`. + +| Command | Purpose | +| --- | --- | +| `ls [-l] [-a] [path]` | the entries of a directory; `-a` adds the hidden ones; `-l` adds type, size in bytes, modification time and what `wf` knows of the entry: `[manifest]`, `[lock]`, `[entry main]`, `[spec]`, `[script icons]`, `[generated provider LifeUI]`, and under `.webfront/` the package cache, the publications and the history | +| `cat [file...]` | the text of UTF-8 files, at most 1 MiB each; a binary file is refused | +| `tree [-a] [-L ] [path]` | a directory as a tree, three levels deep by default and at most 2000 entries; `.webfront/` is listed with `-a` but opened only when the path names it; a file is refused with the `cat` line that prints it | +| `mounts` | what the application answers to the browser, in the order it looks (resources embedded in the executable, the publications of `.webfront/developer/`, the application's own providers), and what the commands read: manifest, lock, cache, environment and registry. The sources of the project are never served | + +`ls -l` needs a library that has the `webfront.developer.entries` callback (added with these commands); with an older +one it says so, and `ls`, `cat`, `tree` and `mounts` still work. + +The usual file commands that the terminal does not provide are reserved all the same: `cd`, `pwd`, `cp`, `mv`, `rm`, +`mkdir`, `rmdir`, `touch`, `edit`, `find`, `grep`, `head`, `tail`, `less`, `stat`, `du`, `df`. Each answers with what to +do instead (edit the files in your editor while `wf dev` rebuilds), and a later environment can provide one without +taking a name from an application. + +**Dependencies.** `wf list` names the locked packages; `wf list --tree` shows them under the dependencies of the +manifest, each with the range that asks for it (`peer` for a peer, `deduped` where a package already shown comes again); +`wf why ` gives the chains of requirements from the manifest to a package, for each locked version; +`wf info ` (a name or `name@version`) gives its license, integrity, files, dependencies, dependents and +`wf exec` entries. They read the lock only: no network, nothing written. + +```text +> wf list --tree +react@19.3.1 (^19.3.1) +react-dom@19.3.1 (^19.3.1) +├── react@19.3.1 (peer ^19.3.1) +└── scheduler@0.28.0 (^0.28.0) + +2 roots, 3 packages +> wf why scheduler +scheduler@0.28.0 + react-dom@19.3.1 (root, ^19.3.1) > scheduler@0.28.0 (^0.28.0) +``` `wf help` lists the `wf` commands; `wf help ` gives the usage and purpose of one, and `wf help agents` (or `wf help --agents`) the model, the sequence for a new interface and the `webfront-agent` commands that run it in JSON or @@ -449,7 +502,8 @@ it comes from the library's embedded loader, not from the environment. pages on the same project keep each other's lines. A history file that cannot be read is never replaced. - **Typing ahead and paste:** keys typed or pasted while a command runs are applied after it, line by line; a last line without a line break waits on the prompt. Ctrl+C drops the keys still waiting. -- **Completion (Tab):** command names, `wf` subcommands, the manifest's scripts after `wf run`, its entries and +- **Completion (Tab):** command names, `wf` subcommands, the manifest's scripts after `wf run`, the installed packages after + `wf why` and `wf info`, its entries and entries/providers after `wf build`, `wf dev`, `wf preview` and `wf embed`, and project paths, also when the word is escaped (`my\ dir/`) or quoted (`"my dir/`); the completion is written the same way and closes the quote. Several candidates are completed to their common prefix, or listed. @@ -497,8 +551,9 @@ of its browser with `webfront.commands.start`. In C++, the command is spawned li A second `webfront::Commands` on the same application throws `std::logic_error` and registers nothing. A copy of a `Context` may outlive its command (a detached task): its stop token stays valid and its writes are dropped once the -browser is gone. The names `wf`, `clear`, `exit`, -`help` and `history` are reserved. `context.write` has no flow control: a command +browser is gone. The names the terminal handles itself are reserved (`webfront::commands::reservedNames`): `wf`, +`clear`, `exit`, `help`, `history`, `ls`, `cat`, `tree`, `mounts` and the file commands listed above; `commands.add` +throws `std::invalid_argument` for one of them. `context.write` has no flow control: a command writing large output with it, faster than the browser reads, grows the connection's write queue; use `context.print` for such output. diff --git a/docs/DEVELOPING_WITH_AGENTS.md b/docs/DEVELOPING_WITH_AGENTS.md index ca570ea9..2f26b0fc 100644 --- a/docs/DEVELOPING_WITH_AGENTS.md +++ b/docs/DEVELOPING_WITH_AGENTS.md @@ -137,7 +137,7 @@ The JSON column completes `webfront-agent --attach DIRECTORY`; the MCP column is - **`wf dev` has no agent operation.** It is a watch for a person at the window. An agent edits the files with its own tools and runs `preview` again; a person's `wf dev` may stay running meanwhile, and both use the same window. -- `install` takes one package per operation. `wf run`, `wf exec` and `wf list` have no operation: there is no shell, no +- `install` takes one package per operation. `wf run`, `wf exec`, `wf list`, `wf why` and `wf info` have no operation, nor have the terminal's `ls`, `cat`, `tree` and `mounts`: there is no shell, no script execution and no JavaScript evaluation for an agent. - A result is JSON with a `state` and `result.exitCode`; compiler and type errors come as `diagnostics` with file, line and column. A failed operation is not a verification. `inspect` returns the visible elements that have an `id`, which is why diff --git a/docs/PROJECT_STATUS.md b/docs/PROJECT_STATUS.md index e01d59c0..71bcb455 100644 --- a/docs/PROJECT_STATUS.md +++ b/docs/PROJECT_STATUS.md @@ -29,7 +29,7 @@ WebFront is a header-only C++23 HTTP/WebSocket core plus a standalone developer window. See [host integration](HOST_INTEGRATION.md). - **Developer environment.** `NativeApp::bootstrap("developer")` loads the verified, pinned environment selected by `DeveloperReleaseData.hpp`. Its terminal provides `wf init`, `create`, - `install`, `restore`, `run`, `exec`, `check`, `test`, `build`, `dev`, `preview`, `embed`, `list` and `help`. The manifest and lock describe + `install`, `restore`, `run`, `exec`, `check`, `test`, `build`, `dev`, `preview`, `embed`, `list`, `why`, `info` and `help`, beside the terminal's own read-only `ls`, `cat`, `tree` and `mounts` (ADR-023). The manifest and lock describe dependencies, entries, providers, scripts and permissions. TypeScript/TSX compilation uses esbuild-wasm; type checking uses the project's locked TypeScript. Application commands use `webfront::Commands`. From environment 0.9.1, a project that has a preview opens diff --git a/docs/adr/ADR-023-espace-de-noms-des-commandes-du-terminal.md b/docs/adr/ADR-023-espace-de-noms-des-commandes-du-terminal.md new file mode 100644 index 00000000..f2df6909 --- /dev/null +++ b/docs/adr/ADR-023-espace-de-noms-des-commandes-du-terminal.md @@ -0,0 +1,137 @@ +# ADR-023 : Espace de noms des commandes du terminal développeur + +## Versions + +| Version | Date | État | Auteur | Évolution | Révision Git | +| --- | --- | --- | --- | --- | --- | +| 1.0 | 2026-11-14 | Acceptée | Ambroise Leclerc | Décision initiale (#575), avant la 1.0 : le préfixe `wf` est conservé ; le terminal reçoit des commandes de fichiers en lecture seule (`ls`, `cat`, `tree`, `mounts`) et réserve le vocabulaire de fichiers qu'il ne fournit pas ; `wf list --tree`, `wf why` et `wf info` montrent le graphe des dépendances. | À renseigner après intégration. | + +## État et chronologie + +**Acceptée** le **2026-11-14** par le propriétaire du projet, comme dernière décision d'architecture avant la 1.0. Elle +est mise en œuvre par la même modification : les noms réservés de `webfront::Commands`, le callback +`webfront.developer.entries` et l'environnement qui porte les commandes. + +## Contexte + +Le terminal de l'environnement développeur ([ADR-016](ADR-016-bootstrap-comme-socle.md)) route une ligne vers trois +familles de commandes : + +- `wf ` : les commandes du projet (`init`, `create`, `install`, `restore`, `run`, `exec`, `check`, `test`, `build`, + `dev`, `preview`, `embed`, `list`, `help`) ; +- les commandes du terminal lui-même (`help`, `clear`, `history`, `exit`) ; +- les commandes C++ que l'application ajoute avec `webfront::Commands`, sous le nom qu'elle choisit. + +Les noms que le terminal traite lui-même sont refusés à l'application (`webfront::commands::reservedNames`, et la même +liste dans `commands.mjs`, comparées par le test `CommandNamesAgree`). Cette liste est un contrat public : un nom qui y entre +après la 1.0 casse l'application qui l'utilisait. + +Deux questions se posaient. Taper `wf` devant chaque commande paraît répétitif : le préfixe est-il nécessaire ? Et le +terminal ne montrait rien du projet sur lequel il agit : ni ses fichiers, ni ce que l'application sert au navigateur, ni +les relations entre les paquets installés, dont `wf list` ne donnait que la liste. + +## Décision + +### 1. Le préfixe `wf` est conservé + +Les noms nus appartiennent au terminal et à l'application ; `wf` est l'espace de noms du projet : son manifeste, son +lock, ses paquets et sa construction. + +- **Les verbes de wf sont des mots courants.** Sans préfixe, `test`, `run`, `build`, `check`, `list`, `install`, + `create` ou `help` seraient interdits aux commandes de l'application, qui sont justement celles qu'une application + nomme ainsi. Avec le préfixe, la réserve ne contient que `wf` et le vocabulaire du terminal. +- **wf doit pouvoir grandir après la 1.0.** Un nouveau verbe (`wf why`, `wf info` dans cette décision même) n'ajoute + aucun nom réservé. Sans préfixe, chaque verbe ajouté serait une rupture pour une application qui le porte. +- **`wf` n'est pas qu'une convention de saisie.** Le premier mot `wf` distingue, dans les scripts du manifeste, une + commande d'un module (`"build": "wf embed LifeUI"`) ; c'est le nom du pilote non interactif (`webfront-wf`) et celui + que citent la documentation, le guide des agents et les messages d'erreur (« run wf install »). Une ligne citée se + copie telle quelle dans le terminal, dans un script ou dans une documentation. +- **Un gestionnaire de paquets se nomme.** `install`, `list`, `why`, `info` n'ont de sens que rapportés à un outil, + comme pour les gestionnaires de paquets usuels. `wf list` (les paquets) et `ls` (les fichiers) ne se confondent pas. + +Une commande nue inconnue qui est un verbe de wf n'est pas exécutée : l'erreur donne la ligne à taper +(`Unknown command: install. Did you mean: wf install react?`). Elle n'est pas résolue implicitement, car le sens d'une +ligne dépendrait alors des commandes de l'application. + +### 2. Des commandes de fichiers en lecture seule + +Le terminal fournit, sous des noms nus et dans le vocabulaire habituel : + +| Commande | Rôle | +| --- | --- | +| `ls [-l] [-a] [chemin]` | les entrées d'un répertoire du projet ; `-l` ajoute le type, la taille, la date et la *nature* de l'entrée pour wf (manifeste, lock, entrée, spec, script, provider généré, cache et publications sous `.webfront/`) | +| `cat ...` | le texte UTF-8 de fichiers du projet, 1 Mio au plus chacun ; les caractères de contrôle sont affichés, pas envoyés au terminal | +| `tree [-a] [-L n] [chemin]` | l'arbre d'un répertoire, trois niveaux par défaut, 2000 entrées au plus ; `.webfront/` n'est ouvert que s'il est nommé | +| `mounts` | ce que l'application sert au navigateur, couche par couche et dans l'ordre où elle cherche, et ce que les commandes lisent | + +Elles lisent le répertoire du projet par les callbacks qu'utilise wf (`developer::Store`) : les chemins sont relatifs au +projet et n'en sortent pas. Ce qu'elles affichent n'est pas de confiance : un dépôt cloné choisit ses noms de fichiers +et leur contenu, un paquet npm son `package.json`. Tout caractère de contrôle (C0, DEL et les C1 sur 8 bits, dont le CSI +U+009B) est donc rendu visible avant d'atteindre le terminal, dans ces commandes comme dans `wf list`, `wf why` et +`wf info`. `mounts` répond à la question de la nature du système de fichiers : les ressources embarquées +dans l'exécutable, les publications de `.webfront/developer/` (`environment`, `preview`, `test`), les providers propres +à l'application, et le fait que les sources du projet ne sont jamais servies. Les couches sont décrites, pas énumérées : +un `fs::Provider` n'a que `open()`, et lui ajouter une énumération aurait étendu l'API publique du cœur. + +`ls -l` s'appuie sur un callback ajouté, `webfront.developer.entries`. C'est un ajout : la version d'API de +l'environnement reste 1, et un environnement récent chargé par une bibliothèque qui ne l'a pas le dit pour `ls -l` et +fonctionne pour le reste. + +### 3. Les noms de fichiers non fournis sont réservés dès maintenant + +`cd`, `pwd`, `cp`, `mv`, `rm`, `mkdir`, `rmdir`, `touch`, `edit`, `find`, `grep`, `head`, `tail`, `less`, `stat`, `du` et +`df` sont réservés sans être fournis. Chacun répond par une erreur qui dit quoi faire : il n'y a pas de répertoire +courant ; le terminal ne modifie pas les fichiers, qui s'éditent dans l'éditeur du développeur pendant que `wf dev` +reconstruit. + +Réserver un nom sans fournir la commande a un coût immédiat et certain : une application ne peut plus appeler une de +ses commandes `find`, `stat`, `edit` ou `head`, et `commands.add` lève `std::invalid_argument` pour celles qui le +faisaient. Ce coût est accepté pour trois raisons. Il se paie une seule fois, avant la 1.0, quand aucune application +publiée n'a de contrat à faire respecter ; la même réserve décidée après la 1.0 serait une rupture à chaque commande +ajoutée, donc ne serait jamais décidée, et le terminal resterait figé à quatre commandes. Les noms retenus sont ceux +qu'un développeur tape par réflexe dans un terminal : une application qui les prendrait pour autre chose tromperait +son utilisateur, et le terminal ne pourrait plus dire pourquoi `rm` ne fait rien. Enfin la liste est fermée et +limitée au vocabulaire des fichiers : les mots du domaine d'une application (`status`, `echo`, `print`, `count`…) +restent libres, et une commande nue future ne peut venir que de cette réserve. + +`echo` n'est pas réservé : ce n'est pas une commande de fichiers, et c'est un nom naturel pour une commande +d'application. + +Le terminal n'est toujours pas un shell : aucun processus n'est lancé, il n'y a ni tube, ni redirection, ni motif, ni +variable, ni répertoire courant. La mention « No system shell is exposed » reste exacte. + +### 4. Le graphe des dépendances se lit avec wf + +Le lock enregistre déjà, pour chaque paquet, le paquet exact auquel chacune de ses dépendances et chacun de ses pairs +satisfaits a été résolu. Trois commandes le lisent, sans réseau ni écriture : + +- `wf list --tree` : les paquets sous les racines du manifeste, avec la plage qui les demande ; un paquet déjà ouvert + est marqué `deduped`. `wf list` seul reste la liste plate. +- `wf why ` : les chaînes d'exigences qui amènent un paquet depuis les racines, pour chacune de ses versions. +- `wf info ` : licence, intégrité, fichiers, dépendances, dépendants et entrées exécutables d'un paquet verrouillé. + +Elles n'ont pas d'opération d'automatisation, comme `wf list` : un agent lit le lock lui-même. + +## Options écartées + +| Option | Pourquoi | +| --- | --- | +| Supprimer le préfixe | Réserve quatorze mots courants, rend chaque nouveau verbe incompatible, rompt les scripts de manifeste, le pilote, la documentation et les environnements publiés. | +| Préfixe facultatif (`test` exécute `wf test` si l'application n'a pas de commande `test`) | Le sens d'une ligne dépend de l'application ; une commande ajoutée par l'application change silencieusement ce qu'une ligne exécutait. | +| Commandes de fichiers sous `wf` (`wf ls`) | Mêle l'inspection générique de fichiers au vocabulaire du projet, et prive des noms que tout le monde tape. | +| Écriture depuis le terminal (`cp`, `mv`, `rm`, `mkdir`) | `rm` et `mv` demandent des callbacks destructifs nouveaux ; aucune n'est nécessaire au développement, que l'éditeur et wf couvrent. Les noms sont réservés pour pouvoir y revenir. | +| Éditeur intégré (`edit`) | Un chantier à part entière, sans rapport avec une décision de nommage ; le nom est réservé. | +| Énumérer le système de fichiers servi | Étend le concept `fs::Provider` et les providers générés par `wf embed` juste avant la 1.0, pour une information que `mounts` donne déjà. | + +## Conséquences + +- **Contrat :** `webfront::commands::reservedNames` compte 26 noms. Une application qui enregistrait une commande sous + l'un des nouveaux (`ls`, `cat`, `tree`, `mounts` ou un nom de fichiers réservé) doit la renommer : c'est la rupture + que cette décision choisit de faire avant la 1.0 plutôt qu'après. +- **Règle pour la suite :** une commande qui lit ou modifie le manifeste, le lock, les paquets ou la construction entre + sous `wf` ; une commande nue nouvelle ne peut venir que de la réserve. +- **Dégradation :** l'environnement reconnaît une bibliothèque sans `webfront.developer.entries` au texte d'erreur du + bridge pour un callback non enregistré ; le parcours navigateur vérifie ce texte sur le vrai bridge. +- **Preuves :** specs Jasmine `files-specs.mjs` et `dependencies-specs.mjs`, scénarios Catch2 de `Store::entries` et + des noms réservés, test `CommandNamesAgree`, et le parcours navigateur `developer_integration` qui exécute les commandes + dans le terminal. diff --git a/docs/adr/README.md b/docs/adr/README.md index 7c91e923..cda5332b 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -65,6 +65,7 @@ verification evidence remain in [PROJECT_STATUS](../PROJECT_STATUS.md). | [ADR-020](ADR-020-services-systeme.md) | System services (files, clipboard, shell, notifications…) through optional C++ portals with per-connection backends, granting handles rather than paths | Proposed | 2026-10-31 | 1.8 — 2026-11-09 | | [ADR-021](ADR-021-publication-de-l-environnement-developpeur.md) | Simplifying the publication of the developer environment: automate the release, keep pinned hashes, no dedicated server | Accepted (domain delivered; phase 1 to implement) | 2026-11-02 | 1.0 — 2026-11-02 | | [ADR-022](ADR-022-profils-et-niveaux-de-support.md) | Compiler profiles, GCC 13 S2 minimum, exit clause and LTS build tools | Accepted | 2026-11-11 | 1.1 — 2026-11-11 | +| [ADR-023](ADR-023-espace-de-noms-des-commandes-du-terminal.md) | Terminal command names: `wf` stays the prefix of project commands, read-only file commands (`ls`, `cat`, `tree`, `mounts`), file command names reserved ahead, dependency graph with `wf list --tree`, `wf why`, `wf info` | Accepted | 2026-11-14 | 1.0 — 2026-11-14 | Numbering follows the reading topics; milestones and individual file histories provide the chronology, which does not follow the numerical order. @@ -110,7 +111,7 @@ Do not replace historical dates with the date of an editorial change to the docu Keep previous rows and update the current version in the index. - Use one `ADR-NNN-description.md` file per decision and one row in this index. The next number - is **ADR-022**. Retain historical numbers and files. + is **ADR-024**. Retain historical numbers and files. - For a new decision that has not been integrated, use **Proposée** (Proposed), its actual proposal date and validation criteria; do not assign an artificial historical commit date. - After integration, record the date and supporting commits, the accepted negative diff --git a/include/webfront/Commands.hpp b/include/webfront/Commands.hpp index 691a59c0..0129c6e0 100644 --- a/include/webfront/Commands.hpp +++ b/include/webfront/Commands.hpp @@ -39,8 +39,12 @@ inline constexpr std::size_t maxPendingOutput = 32; /// Exit code of a command stopped by Ctrl+C, a disconnection or the application's shutdown. inline constexpr int interruptedExitCode = 130; -/// Names the terminal itself handles, which an application cannot register. -inline constexpr std::array reservedNames{"wf", "clear", "exit", "help", "history"}; +/// Names the terminal itself handles, which an application cannot register: wf, the terminal's own commands (help, +/// clear, history, exit, ls, cat, tree, mounts) and the usual file commands it keeps for itself without providing +/// them, so that a later environment can add one without taking a name from an application (ADR-023). +inline constexpr std::array reservedNames{"wf", "clear", "exit", "help", "history", "ls", "cat", "tree", "mounts", + "cd", "pwd", "cp", "mv", "rm", "mkdir", "rmdir", "touch", "edit", + "find", "grep", "head", "tail", "less", "stat", "du", "df"}; namespace detail { diff --git a/include/webfront/DeveloperApp.hpp b/include/webfront/DeveloperApp.hpp index 97463688..26ccffcc 100644 --- a/include/webfront/DeveloperApp.hpp +++ b/include/webfront/DeveloperApp.hpp @@ -113,6 +113,8 @@ class BasicDeveloperApp : public BasicWF("webfront.developer.read"); expose<&Store::list, Bytes, std::string>("webfront.developer.list"); + // Added after API 1 was published: an environment looks for it and does without (ls -l) when it is missing. + expose<&Store::entries, Bytes, std::string>("webfront.developer.entries"); expose<&Store::beginReplacing, std::string, std::string, bool>("webfront.developer.begin"); expose<&Store::beginNew, std::string, std::string, bool>("webfront.developer.beginNew"); expose<&Store::write, void, std::string, std::string, std::uint64_t, Bytes>("webfront.developer.write"); diff --git a/include/webfront/system/DeveloperStore.hpp b/include/webfront/system/DeveloperStore.hpp index 5890218e..29512a7b 100644 --- a/include/webfront/system/DeveloperStore.hpp +++ b/include/webfront/system/DeveloperStore.hpp @@ -72,30 +72,33 @@ class Store { /// be read, is omitted; only a directory that cannot be read fails the listing. std::vector list(std::string directory) const { std::scoped_lock lock(mutex); - const auto source = directory.empty() ? root : projectPath(root, directory); - std::error_code error; - if (!std::filesystem::is_directory(source, error)) - throw std::runtime_error("Cannot list project directory: " + directory); - std::vector names; - std::filesystem::directory_iterator entries(source, error); - for (; !error && entries != std::filesystem::directory_iterator{}; entries.increment(error)) { - const auto name = entries->path().filename().generic_string(); - if (auto listed = listedName(directory, name)) { - if (names.size() == maxListedEntries) - throw std::length_error("Project directory has more than 4096 entries: " + directory); - names.push_back(std::move(*listed)); - } - } - if (error) - throw std::runtime_error("Cannot list project directory: " + directory); - std::ranges::sort(names); - std::string text = "["; - for (const auto& name : names) + std::string text = "["; + for (const auto& name : listedNames(directory)) text += (text.size() > 1 ? "," : "") + json::quote(name); text += "]"; return {text.begin(), text.end()}; } + /// The entries list() names, as a JSON array of {"name", "type", "size", "modified"} sorted like it: the name has + /// no final '/', "type" is "directory" or "file" (a link inside the project reads as its target), "size" is in + /// bytes (0 for a directory) and "modified" in milliseconds since the Unix epoch, both 0 when they cannot be read. + std::vector entries(std::string directory) const { + std::scoped_lock lock(mutex); + std::string text = "["; + for (auto name : listedNames(directory)) { + const bool isDirectory = name.ends_with('/'); + if (isDirectory) + name.pop_back(); + const auto path = projectPath(root, directory.empty() ? name : directory + "/" + name); + std::error_code error; + const auto size = isDirectory ? std::uintmax_t{} : std::filesystem::file_size(path, error); + text += (text.size() > 1 ? "," : "") + ("{\"name\":" + json::quote(name)) + ",\"type\":\"" + (isDirectory ? "directory" : "file") + + "\",\"size\":" + std::to_string(error ? std::uintmax_t{} : size) + ",\"modified\":" + std::to_string(modifiedMilliseconds(path)) + "}"; + } + text += "]"; + return {text.begin(), text.end()}; + } + std::string begin(std::string destination, bool directory, bool replace = true) { std::scoped_lock lock(mutex); expireAbandoned(); @@ -239,6 +242,40 @@ class Store { } private: + // The sorted names of list(): directories end with '/'. + std::vector listedNames(const std::string& directory) const { + const auto source = directory.empty() ? root : projectPath(root, directory); + std::error_code error; + if (!std::filesystem::is_directory(source, error)) + throw std::runtime_error("Cannot list project directory: " + directory); + std::vector names; + std::filesystem::directory_iterator entries(source, error); + for (; !error && entries != std::filesystem::directory_iterator{}; entries.increment(error)) { + const auto name = entries->path().filename().generic_string(); + if (auto listed = listedName(directory, name)) { + if (names.size() == maxListedEntries) + throw std::length_error("Project directory has more than 4096 entries: " + directory); + names.push_back(std::move(*listed)); + } + } + if (error) + throw std::runtime_error("Cannot list project directory: " + directory); + std::ranges::sort(names); + return names; + } + + // The last write of an entry on the system clock; the file clock's epoch is not portable, so the time is taken + // relative to now on both clocks. 0 when it cannot be read. + static std::int64_t modifiedMilliseconds(const std::filesystem::path& path) { + std::error_code error; + const auto written = std::filesystem::last_write_time(path, error); + if (error) + return 0; + const auto age = std::filesystem::file_time_type::clock::now() - written; + const auto at = std::chrono::system_clock::now() - std::chrono::duration_cast(age); + return std::chrono::duration_cast(at.time_since_epoch()).count(); + } + // The listed form of one entry, or nothing when it leaves the project or its type cannot be read. std::optional listedName(const std::string& directory, const std::string& name) const { std::error_code error; diff --git a/js/developer/environment/bundles.json b/js/developer/environment/bundles.json index 1e32cb08..01ab3f38 100644 --- a/js/developer/environment/bundles.json +++ b/js/developer/environment/bundles.json @@ -17,14 +17,16 @@ "js/developer/environment/packages.mjs": "37fe2a410e211264cfeaedbff3df50f7e62b02f8088130127d94f92081e2a5ad", "js/developer/environment/starter.mjs": "fd43db1861121577c48a0327436ce39cb9076d7cad0e9e273d40955747cc6a48", "js/developer/environment/paths.mjs": "3b6114df78eb193161c5c84499dda084cb7ff91c56a4496371c30295d00880e3", - "js/developer/environment/runtime.mjs": "0b41bf7e7e5ae308597468d51b22b736a785a4914827e0b48b4827af3459da07", + "js/developer/environment/runtime.mjs": "7275da57703d8a9d06991d4dffc2bed2976bcfa78329171d99deeb522bced5b1", "js/developer/environment/automation.mjs": "79405c89ba7025c1774bc13c9b78d814a07592755dcde018c8659a8015c4b8ed", "js/developer/environment/development.mjs": "1f32f911610c72ad3e935de1c2b138fa275ce9eda04bb63c824d5e09923305a6", "js/developer/environment/testing.mjs": "aeb584505fab5957b9c02e78536e12f7d7f3d12f8adb2e17f1a1a6e395e43f3c", - "js/developer/environment/terminal.mjs": "7ffcf7ac6ef63c35cdf5ef70284b384525b13ba18422af069289e53b6c4f6be1", + "js/developer/environment/terminal.mjs": "1d81a28a6e6cfd5bdb1ff8854e17a273b7bcfebf2c97d469b8706db636f3799e", "js/developer/environment/workspace.mjs": "4fe794b140515579c4f80a226d8b1beca254a3488e2e4d9f6ba580e077a11558", "js/developer/environment/tarball.mjs": "1c1e1aea067910e1fec74e85b4bf9fbefed9b38187a04d8d2764f0b9a96fca39", - "js/developer/environment/commands.mjs": "8de20c01f02f33c0566f204fcf1ee2382a23344d2103581fe2914469ec570531", + "js/developer/environment/commands.mjs": "a759f48584b78aed79e9965fd202d2ec108a6948ef6f1b8d689fed87a458b265", + "js/developer/environment/files.mjs": "199336f7f3d23f6370da352993bf4686738b1f394b79aa9883769d19824540e0", + "js/developer/environment/dependencies.mjs": "4857eb7dfb9f099266c27021ee07a8d9d9a529a8344f3e134d22d7f8b7166e2e", "js/developer/environment/compiler.mjs": "0158931132aa9b43b7bbbd01de6fa4fc34fce8c65515d593dd494930f7a1910f", "js/developer/environment/bundler.mjs": "48658151aae4fa5ad54c9fa3386ef4095b793de0f3ad242f95e8e5de0cd0ce4d", "js/developer/environment/entry.mjs": "b2b942443e3c74ae2c008392ba244d9b7e91db70ba1b4ebbe1357c455ebf51bb", @@ -43,11 +45,11 @@ "js/developer/starters/agent-guide.md": "a4ace796863308f9239825389cc3ddd0f29dcc6f45cd0b2af65767411fc723ce", "js/developer/starters/app/main.ts": "3bc27323c1170089c53dec4ffcc8632ed3db66c45e73d75fa6d2d9ff2752652e", "js/developer/starters/app/style.css": "1d4dccf54c21d56cd99bf72de181be095e196263767848ac52721ea94520dc5d", - "js/developer/tools/distribution.json": "1f2934587eeed1c88630e1693f7ddc91c65315d08a151b6427a3edac36368690", + "js/developer/tools/distribution.json": "42daedcec878dce14463c3523b5e136c61f0a7d7e4a38073aed5e6df2a021665", "js/developer/tools/archive.mjs": "da63bb9d796ddfd24ed945b15c53f66a0400eb177886fd4f1c8fd10cafb5a91b", "js/developer/tools/distribution.mjs": "43dfdccc912693db46fd095fd78ae79325abab672d99f89fd569914ef3499cad", "js/developer/scripts/build.mjs": "a577f4396ab867096bc6fe6876e16e5220121ec8e8dd234fa1e4819d0a1173e1", - "js/developer/webfront.project.json": "4694000d9a8b921548ddcd1d832824cec63c366031acabb87210175014ce60f6", + "js/developer/webfront.project.json": "a31b7313bedc47bd437fe68decb23e0788dcaa9903c4c5c2a31841b296a40776", "js/core/bootstrap/bootstrap.bundle.mjs": "bd78d70acb13a492e510ef0982e982f652ea1558f37071d0adb3e717611367e8", "js/developer/environment/packages.bundle.mjs": "5598a590a9e859a4128075387a6c32963b2246ca120c2d7775851c780ad437f2", "include/webfront/system/DeveloperReleaseData.hpp": "06fe92e4b4f78ebe96a97be84f4b59e2754e0165e1d28af75d0b5aef8dcf1e4b" diff --git a/js/developer/environment/commands.mjs b/js/developer/environment/commands.mjs index 7e0c618e..5509321d 100644 --- a/js/developer/environment/commands.mjs +++ b/js/developer/environment/commands.mjs @@ -1,8 +1,13 @@ // The application's C++ commands (webfront::Commands): discovered through the bridge and run in this browser's session. // Their output streams in through fire-and-forget calls; Ctrl+C cancels them in C++ without waiting for them to end. -/** Names the terminal itself handles; webfront::commands::reservedNames refuses them to C++ commands. */ -export const reservedNames = ['wf', 'clear', 'exit', 'help', 'history']; +/** + * Names the terminal itself handles; webfront::commands::reservedNames refuses them to C++ commands. After wf and the + * terminal's own commands come the usual file commands it keeps without providing them (files.mjs: withheld), so that + * a later environment can add one without taking a name from an application. + */ +export const reservedNames = ['wf', 'clear', 'exit', 'help', 'history', 'ls', 'cat', 'tree', 'mounts', 'cd', 'pwd', 'cp', 'mv', 'rm', + 'mkdir', 'rmdir', 'touch', 'edit', 'find', 'grep', 'head', 'tail', 'less', 'stat', 'du', 'df']; const running = new Map(); // command number -> {write, exit} let lastId = 0; diff --git a/js/developer/environment/dependencies.mjs b/js/developer/environment/dependencies.mjs new file mode 100644 index 00000000..41810310 --- /dev/null +++ b/js/developer/environment/dependencies.mjs @@ -0,0 +1,127 @@ +// The installed packages as a graph, read from the lock alone: wf list --tree, wf why and wf info. The lock records, for +// every package, the exact package each of its dependencies and satisfied peers resolved to. +import {packageRoot} from './paths.mjs'; +import {inline} from './terminal.mjs'; + +const byName = (a, b) => a < b ? -1 : a > b ? 1 : 0; +// Everything shown comes from the lock, so from the package.json of packages: control characters are made visible. +const idOf = node => inline(`${node.name}@${node.version}`); + +// How a package asks for one of its dependencies: the range of its package.json, marked when it is a peer. +function request(node, name) { + const manifest = node.manifest ?? {}; + if (manifest.dependencies?.[name] !== undefined) return inline(manifest.dependencies[name]); + if (manifest.optionalDependencies?.[name] !== undefined) return inline(`optional ${manifest.optionalDependencies[name]}`); + if (manifest.peerDependencies?.[name] !== undefined) return inline(`peer ${manifest.peerDependencies[name]}`); + return ''; +} +const requested = range => range ? ` (${inline(range)})` : ''; +const edges = node => Object.entries(node.dependencies ?? {}).sort(([a], [b]) => byName(a, b)); + +/** + * The locked graph as a tree under the roots of the manifest, each with the range it was requested with. A package + * is opened once: where it comes again, "deduped" stands for the dependencies already shown. + */ +export function dependencyTree(lock) { + const roots = Object.entries(lock?.roots ?? {}).sort(([a], [b]) => byName(a, b)); + if (!roots.length) return 'No installed packages.'; + const lines = [], opened = new Set(); + const children = (id, prefix) => { + const node = lock.packages[id]; + const list = edges(node); + list.forEach(([name, child], index) => { + const last = index === list.length - 1; + const childNode = lock.packages[child]; + const again = opened.has(child) && edges(childNode).length > 0; + lines.push(`${prefix}${last ? '└── ' : '├── '}${idOf(childNode)}${requested(request(node, name))}${again ? ' deduped' : ''}`); + if (opened.has(child)) return; + opened.add(child); + children(child, prefix + (last ? ' ' : '│ ')); + }); + }; + for (const [, root] of roots) { + const again = opened.has(root.id) && edges(lock.packages[root.id]).length > 0; + lines.push(`${idOf(lock.packages[root.id])}${requested(root.requested)}${again ? ' deduped' : ''}`); + if (opened.has(root.id)) continue; + opened.add(root.id); + children(root.id, ''); + } + const count = Object.keys(lock.packages).length; + lines.push('', `${roots.length} ${roots.length === 1 ? 'root' : 'roots'}, ${count} ${count === 1 ? 'package' : 'packages'}`); + return lines.join('\n'); +} + +/** The locked packages a word designates: every version of a name, or the one "name@version". Throws when none is. */ +export function selectPackages(lock, spec) { + const found = Object.entries(lock?.packages ?? {}).filter(([, node]) => node.name === spec || `${node.name}@${node.version}` === spec) + .sort(([, a], [, b]) => byName(idOf(a), idOf(b))); + if (!found.length) throw new Error(`${inline(spec)} is not installed (wf list names the installed packages)`); + return found; +} + +const rootsOf = (lock, id) => Object.entries(lock.roots ?? {}).filter(([, root]) => root.id === id); +const dependents = (lock, id) => Object.entries(lock.packages) + .flatMap(([parent, node]) => edges(node).filter(([, child]) => child === id).map(([name]) => ({parent, node, name}))) + .sort((a, b) => byName(idOf(a.node), idOf(b.node))); + +export const chainLimit = 20; + +// The chains of dependents from a package up to the roots, each written from its root down. +function chains(lock, target) { + const found = []; + const climb = (id, below, seen) => { + if (found.length >= chainLimit) return; + for (const [, root] of rootsOf(lock, id)) + found.push([`${idOf(lock.packages[id])} (root${root.requested ? `, ${inline(root.requested)}` : ''})`, ...below]); + for (const {parent, node, name} of dependents(lock, id)) { + if (seen.has(parent)) continue; // a cycle of peers: the chain through it was already taken + climb(parent, [`${idOf(lock.packages[id])}${request(node, name) ? ` (${request(node, name)})` : ''}`, ...below], new Set([...seen, parent])); + } + }; + climb(target, [], new Set([target])); + return found.slice(0, chainLimit); +} + +/** wf why : why each locked version of it is installed, as chains from the roots of the manifest. */ +export function why(lock, spec) { + return selectPackages(lock, spec).map(([id, node]) => { + const found = chains(lock, id); + const lines = found.map(chain => ` ${chain.join(' > ')}`); + if (!found.length) lines.push(' nothing requires it: wf install --update resolves the manifest again'); + if (found.length === chainLimit) lines.push(` ... only the first ${chainLimit} chains are shown`); + return [idOf(node), ...lines].join('\n'); + }).join('\n'); +} + +// "license" is a string; older packages have {type} or a "licenses" array of them. Anything else is not a declaration. +function license(manifest) { + const names = [manifest?.license, manifest?.licenses].flat() + .map(value => typeof value === 'string' ? value : value?.type).filter(value => typeof value === 'string' && value); + return names.length ? inline(names.join(', ')) : 'not declared'; +} +function executables(node) { + const bin = node.manifest?.webfront?.bin; + if (typeof bin === 'string') return [inline(node.name.split('/').pop())]; + return bin && typeof bin === 'object' && !Array.isArray(bin) ? Object.keys(bin).map(inline) : []; +} + +/** wf info : what the lock records of each locked version of it. */ +export function info(lock, spec) { + return selectPackages(lock, spec).map(([id, node]) => { + const roots = rootsOf(lock, id); + const needs = edges(node).map(([name, child]) => `${idOf(lock.packages[child])}${request(node, name) ? ` (${request(node, name)})` : ''}`); + const neededBy = [...new Set(dependents(lock, id).map(({node: parent}) => idOf(parent)))]; + const bins = executables(node); + const rows = [ + ['root', roots.length ? `yes, requested ${roots.map(([, root]) => inline(root.requested)).join(', ')}` : 'no, installed for another package (wf why)'], + ...(typeof node.manifest?.description === 'string' && node.manifest.description ? [['description', inline(node.manifest.description)]] : []), + ['license', license(node.manifest)], + ['integrity', inline(node.integrity)], + ['files', `${node.files.length} in ${packageRoot}/${inline(node.key)}/`], + ['dependencies', needs.join(', ') || 'none'], + ['dependents', neededBy.join(', ') || 'none'], + ...(bins.length ? [['executables', bins.map(name => `wf exec ${inline(node.name)}${bins.length > 1 ? `:${name}` : ''}`).join(', ')]] : []), + ]; + return [idOf(node), ...rows.map(([label, value]) => ` ${label.padEnd(12)} ${value}`)].join('\n'); + }).join('\n'); +} diff --git a/js/developer/environment/files.mjs b/js/developer/environment/files.mjs new file mode 100644 index 00000000..9fd6e1e7 --- /dev/null +++ b/js/developer/environment/files.mjs @@ -0,0 +1,289 @@ +// The terminal's file commands: ls, cat, tree and mounts. They only read the project directory, through the callbacks +// that wf uses; paths are relative to the project and never leave it. They are not a shell: no working directory, no +// glob, no pipe, and nothing is written (ADR-023). +import {call, blockSize} from './io.mjs'; +import {isUnsafe} from './paths.mjs'; +import {manifestPath, lockPath} from './manifest.mjs'; +import {printable, inline} from './terminal.mjs'; + +const decoder = new TextDecoder(); +const usage = { + ls: 'ls [-l] [-a] [--] [path]', cat: 'cat [--] [file...]', tree: 'tree [-a] [-L ] [--] [path]', mounts: 'mounts'}; +/** One line per file command, for the terminal's help. */ +export const fileCommandHelp = { + ls: 'List a project directory; -l adds size, date and what wf knows of each entry, -a the hidden entries', + cat: 'Print text files of the project', + tree: 'Show a project directory as a tree (3 levels; -L , -a for the hidden entries)', + mounts: 'Describe what the application serves to the browser, and from where', +}; + +const usageError = name => new Error(`Usage: ${usage[name]}`); + +/** A project path as the callbacks take it: '' for the project itself, no "./" prefix, no final "/". */ +export function projectPath(argument = '') { + let path = argument; + while (path.startsWith('./')) path = path.slice(2); + path = path.replace(/\/+$/, ''); + if (path === '' && argument.startsWith('/')) throw new Error(`${argument}: paths are relative to the project directory`); + if (path === '' || path === '.') return ''; + if (path.startsWith('/') || isUnsafe(path)) throw new Error(`${argument}: paths are relative to the project directory and stay inside it`); + return path; +} + +// Splits arguments into single-letter flags (-la is -l -a) and the other words. A `valued` flag takes the rest of its +// word (-L3) or the next word (-L 3, -aL 3). After "--" every word is a path, so that a name may start with "-". +function parseArguments(name, args, allowed, valued = '') { + const flags = new Map(), words = []; + for (let index = 0; index < args.length; ++index) { + const word = args[index]; + if (word === '--') { words.push(...args.slice(index + 1)); break; } + if (!word.startsWith('-') || word === '-') { words.push(word); continue; } + for (let position = 1; position < word.length; ++position) { + const flag = word[position]; + if (!allowed.includes(flag)) throw usageError(name); + if (!valued.includes(flag)) { flags.set(flag, true); continue; } + const attached = word.slice(position + 1); + if (!attached && index + 1 === args.length) throw usageError(name); + flags.set(flag, attached || args[++index]); + break; + } + } + return {flags, words}; +} + +const join = (directory, name) => directory ? `${directory}/${name}` : name; +const listNames = async (bridge, directory) => JSON.parse(decoder.decode(await call(bridge, 'list', directory))); +const visible = (names, all) => all ? names : names.filter(name => !name.startsWith('.')); + +// What wf keeps under .webfront/: the longest prefix describes an entry. +const managed = [ + ['.webfront/developer/packages', 'package cache (wf install, wf restore)'], + ['.webfront/developer/environment', 'developer environment, served to the browser'], + ['.webfront/developer/preview', 'interface built by wf dev and wf preview, served to the browser'], + ['.webfront/developer/test', 'files of a wf test run, served to the browser'], + ['.webfront/developer/build', 'output of wf build'], + ['.webfront/developer/staging', 'publications in progress'], + ['.webfront/developer/history.json', 'terminal history'], + ['.webfront', 'managed by wf'], +]; +const firstWord = text => String(text).trim().split(/\s+/)[0]; + +/** + * What wf knows of a project path: the manifest, the lock, what it manages under .webfront/, and the entries, specs, + * scripts and generated providers that the manifest declares. An empty string for the project's other files. + */ +export function nature(path, manifest = null) { + if (path === manifestPath) return 'manifest'; + if (path === lockPath) return 'lock'; + const kept = managed.find(([prefix]) => path === prefix || path.startsWith(prefix + '/')); + if (kept) return kept[1]; + const named = (section, value, label) => Object.entries(Object(manifest?.[section] ?? {})) + .filter(([, declared]) => value(declared) === path).map(([name]) => `${label} ${name}`); + const roles = [ + ...named('entries', entry => entry, 'entry'), + ...named('providers', provider => provider?.output, 'generated provider'), + ...named('scripts', script => firstWord(script) === 'wf' ? null : firstWord(script), 'script'), + ...(Array.isArray(manifest?.test?.specs) && manifest.test.specs.includes(path) ? ['spec'] : []), + ]; + return roles.join(', '); +} + +/** Names laid out in columns read downwards, for a terminal `width` cells wide. */ +export function columns(names, width = 80) { + if (!names.length) return ''; + const cell = Math.max(...names.map(name => name.length)) + 2; + const rows = Math.ceil(names.length / Math.max(1, Math.floor(width / cell))); + return Array.from({length: rows}, (_, row) => + names.filter((_, index) => index % rows === row).map(name => name.padEnd(cell)).join('').trimEnd()).join('\n'); +} + +const two = number => String(number).padStart(2, '0'); +function timestamp(milliseconds) { + if (!milliseconds) return '-'.padEnd(16); + const date = new Date(milliseconds); + return `${date.getFullYear()}-${two(date.getMonth() + 1)}-${two(date.getDate())} ${two(date.getHours())}:${two(date.getMinutes())}`; +} + +/** The lines of ls -l: type, size in bytes, modification time, name, and the entry's nature when wf knows one. */ +export function longListing(entries, directory, manifest) { + const width = Math.max(1, ...entries.map(entry => String(entry.size).length)); + return entries.map(entry => { + const isDirectory = entry.type === 'directory'; + const role = nature(join(directory, entry.name), manifest); + const size = (isDirectory ? '-' : String(entry.size)).padStart(width); + return `${isDirectory ? 'd' : '-'} ${size} ${timestamp(entry.modified)} ${inline(entry.name)}${isDirectory ? '/' : ''}${role ? ` [${inline(role)}]` : ''}`; + }).join('\n'); +} + +/** Whether an error of the bridge says that the application has no such webfront.developer.* callback (an older library). */ +export const isMissingCallback = (error, name) => String(error?.message).includes(`C++ function 'webfront.developer.${name}' was not found`); + +async function describedEntries(bridge, directory) { + try { return JSON.parse(decoder.decode(await call(bridge, 'entries', directory))); } + catch (error) { + if (isMissingCallback(error, 'entries')) + throw new Error('ls -l needs a more recent WebFront library in the application; ls and tree work with this one'); + throw error; + } +} + +// A path that is not a directory is listed as the one entry of its directory, when it is there. +async function listing(bridge, path, read) { + try { return {directory: path, items: await read(path)}; } + catch (error) { + if (!path || !/Cannot list project directory/.test(error?.message)) throw error; + const cut = path.lastIndexOf('/'); + const directory = path.slice(0, Math.max(cut, 0)), name = path.slice(cut + 1); + const items = (await read(directory).catch(() => [])).filter(item => (item.name ?? item) === name); + if (!items.length) throw new Error(`${path}: no such file or directory in the project`); + return {directory, items, single: true}; + } +} + +/** ls [-l] [-a] [path]. context.manifest() resolves with the manifest for the natures, or null. */ +export async function ls(args, {bridge, manifest = async () => null, width = 80}) { + const {flags, words} = parseArguments('ls', args, 'la'); + if (words.length > 1) throw usageError('ls'); + const path = projectPath(words[0]); + const all = flags.has('a'); + if (!flags.has('l')) { + const {items, single} = await listing(bridge, path, directory => listNames(bridge, directory)); + return columns((single ? items : visible(items, all)).map(inline), width); + } + const {directory, items, single} = await listing(bridge, path, target => describedEntries(bridge, target)); + const shown = single || all ? items : items.filter(entry => !entry.name.startsWith('.')); + return longListing(shown, directory, await manifest().catch(() => null)); +} + +export const catLimit = 1024 * 1024; + +async function readText(bridge, path, signal) { + const chunks = []; + let size = 0; + for (;;) { + signal?.throwIfAborted(); + let chunk; + try { chunk = await call(bridge, 'read', path, size); } + catch (error) { + if (/Cannot read project file/.test(error?.message)) throw new Error(`${path}: no such file in the project`); + throw error; + } + chunks.push(chunk); + size += chunk.length; + if (size > catLimit) throw new Error(`${path} is larger than 1 MiB: open it in your editor`); + if (chunk.length < blockSize) break; + } + const bytes = new Uint8Array(await new Blob(chunks).arrayBuffer()); + if (bytes.includes(0)) throw new Error(`${path} is not a text file`); + try { return new TextDecoder('utf-8', {fatal: true}).decode(bytes); } + catch { throw new Error(`${path} is not UTF-8 text`); } +} + +/** cat [file...]: the text of project files, at most 1 MiB each. */ +export async function cat(args, {bridge, signal}) { + const {words} = parseArguments('cat', args, ''); + if (!words.length) throw usageError('cat'); + let output = ''; + for (const word of words) { + const path = projectPath(word); + if (!path) throw new Error(`${word} is a directory`); + const text = printable(await readText(bridge, path, signal)); + output += text && !text.endsWith('\n') ? text + '\n' : text; + } + return output; +} + +export const treeLimit = 2000; +const defaultDepth = 3; + +/** + * tree [-a] [-L ] [path]. Hidden entries need -a, and even then .webfront/ is not opened unless the path names + * it: its package cache would hide the project. The tree stops after treeLimit entries. + */ +export async function tree(args, {bridge, signal}) { + const {flags, words} = parseArguments('tree', args, 'aL', 'L'); + if (words.length > 1) throw usageError('tree'); + const depth = flags.has('L') ? Number(flags.get('L')) : defaultDepth; + if (!Number.isInteger(depth) || depth < 1 || depth > 32) throw new Error('tree -L expects a depth from 1 to 32'); + const root = projectPath(words[0]); + const all = flags.has('a'); + const lines = [root ? inline(root) + '/' : '.']; + let directories = 0, files = 0, cut = false; + let rootNames; + try { rootNames = await listNames(bridge, root); } + catch (error) { + if (!/Cannot list project directory/.test(error?.message)) throw error; + const cutAt = root.lastIndexOf('/'); + const siblings = await listNames(bridge, root.slice(0, Math.max(cutAt, 0))).catch(() => []); + throw new Error(siblings.includes(root.slice(cutAt + 1)) ? `${root} is a file: cat ${root} prints it` : `${root}: no such directory in the project`); + } + // A directory that cannot be listed below the root (removed meanwhile, or unreadable) is shown without content. + const namesOf = directory => directory === root ? rootNames : listNames(bridge, directory).catch(error => { + if (/Cannot list project directory/.test(error?.message)) return []; + throw error; + }); + const walk = async (directory, prefix, level) => { + signal?.throwIfAborted(); + const names = visible(await namesOf(directory), all); + for (const [index, name] of names.entries()) { + if (lines.length > treeLimit) { cut = true; return; } + const last = index === names.length - 1; + const isDirectory = name.endsWith('/'); + const path = join(directory, isDirectory ? name.slice(0, -1) : name); + const closed = isDirectory && (level === depth || (path === '.webfront' && root !== '.webfront')); + lines.push(`${prefix}${last ? '└── ' : '├── '}${inline(name)}${closed && level < depth ? ' [managed by wf: tree .webfront]' : ''}`); + isDirectory ? ++directories : ++files; + if (isDirectory && !closed) await walk(path, prefix + (last ? ' ' : '│ '), level + 1); + if (cut) return; + } + }; + await walk(root, '', 1); + if (cut) lines.push(`... more than ${treeLimit} entries: name a subdirectory or lower -L`); + lines.push('', `${directories} ${directories === 1 ? 'directory' : 'directories'}, ${files} ${files === 1 ? 'file' : 'files'}`); + return lines.join('\n'); +} + +const published = [ + ['environment', 'the developer environment, verified against its SHA-512'], + ['preview', 'the interface built by wf dev and wf preview'], + ['test', 'the files of a wf test run'], +]; + +/** + * mounts: what the developer application answers to the browser, in the order it looks, and what the project + * commands read. The layers are those of fs::DeveloperFS; the application's own providers are not enumerable. + */ +export async function mounts(args, {bridge, config = {}}) { + if (args.length) throw usageError('mounts'); + const present = async name => (await listNames(bridge, `.webfront/developer/${name}`).catch(() => [])).length > 0; + const rows = [ + ['/WebFront.js, /webfront-bootstrap.html, /webfront-bootstrap.mjs', 'embedded in the executable: the bridge and the loader'], + ]; + for (const [name, purpose] of published) + rows.push([`/webfront/developer/${name}/`, `.webfront/developer/${name}/ of the project (${await present(name) ? 'published' : 'empty'}): ${purpose}`]); + rows.push(['/index.html, /favicon.ico, /webfront-dom.mjs, /webfront-fallback.mjs', 'embedded in the executable: the fallback page and its modules'], + ['other paths', "the application's own providers, if it has some; else 404"]); + const width = Math.max(...rows.map(([url]) => url.length)); + return ['Served to the browser, the first that answers:', + ...rows.map(([url, source]) => ` ${url.padEnd(width)} ${source}`), + 'The sources of the project are never served: wf compiles them into a publication, and wf embed into a C++ provider.', + '', + 'Read by the commands of this terminal (ls, cat, tree, wf): the project directory given to the application.', + ` manifest ${manifestPath}`, + ` lock ${lockPath}`, + ' wf cache .webfront/ (packages, publications, history)', + ...(config.environment ? [` environment ${config.environment}`] : []), + ...(config.integrity ? [` integrity ${config.integrity}`] : []), + ...(config.registry ? [` registry ${config.registry}${config.registryExplicit ? ' (chosen by the application)' : ''}`] : []), + ].join('\n'); +} + +/** The file commands the terminal keeps for itself without providing them (commands.mjs: reservedNames). */ +export const withheld = ['cd', 'pwd', 'cp', 'mv', 'rm', 'mkdir', 'rmdir', 'touch', 'edit', 'find', 'grep', 'head', 'tail', 'less', 'stat', 'du', 'df']; +const reading = new Set(['find', 'grep', 'head', 'tail', 'less', 'stat', 'du', 'df']); +/** Why a withheld command does nothing, and what to use instead. */ +export function withheldReason(name) { + if (name === 'cd' || name === 'pwd') return `${name} is not provided: there is no working directory, every path is relative to the project (ls, tree, mounts)`; + if (reading.has(name)) return `${name} is not provided: this terminal has ls, cat and tree; use your own tools for the rest`; + return `${name} is not provided: this terminal does not change files; edit the project in your editor (wf dev rebuilds on every save)`; +} diff --git a/js/developer/environment/runtime.mjs b/js/developer/environment/runtime.mjs index 2b7fe478..218bf2b8 100644 --- a/js/developer/environment/runtime.mjs +++ b/js/developer/environment/runtime.mjs @@ -1,6 +1,6 @@ import {Terminal} from '@xterm/xterm'; import {FitAddon} from '@xterm/addon-fit'; -import {LineEditor, tokenize, wordAtEnd, unicodeProvider, clearScreen, historyLimit} from './terminal.mjs'; +import {LineEditor, tokenize, wordAtEnd, unicodeProvider, clearScreen, historyLimit, inline} from './terminal.mjs'; import {manifestPath, setManifestDirectory} from './manifest.mjs'; import {discoverCommands, runCommand, reservedNames} from './commands.mjs'; export {discoverCommands, reservedNames}; @@ -19,6 +19,8 @@ import {typescriptPackage, parseCheckOptions, checkHost} from './typecheck.mjs'; import {pinnedStarters} from './bootstrap.mjs'; import {createWorkspace, isManaged} from './workspace.mjs'; import {connectAutomation as connectAgent, clipText, automationHelp, onAutomationNotice} from './automation.mjs'; +import {ls, cat, tree, mounts, fileCommandHelp, withheld, withheldReason} from './files.mjs'; +import {dependencyTree, why as whyInstalled, info as packageInfo} from './dependencies.mjs'; const encoder = new TextEncoder(); const decoder = new TextDecoder(); @@ -280,18 +282,30 @@ async function test(args, {bridge, signal, write = () => {}, createFrame, onRepo } } -async function list(_args, {bridge}) { +// wf list [--tree]: the locked packages, or their graph under the roots of the manifest. +async function list(args, {bridge}) { + if (args.length > 1 || (args.length && args[0] !== '--tree')) throw new Error(`Usage: ${usage.list}`); const project = await loadProject(bridge); - const names = Object.keys(project.lock?.packages ?? {}).sort().join('\n'); + if (args.length) return syncNotice(project) + dependencyTree(project.lock); + const names = Object.keys(project.lock?.packages ?? {}).sort().map(inline).join('\n'); return syncNotice(project) + (names || 'No installed packages.'); } +// wf why and wf info : read from the lock, like wf list. +const lockQuery = (name, answer) => async (args, {bridge}) => { + if (args.length !== 1 || args[0].startsWith('-')) throw new Error(`Usage: ${usage[name]}`); + const project = await loadProject(bridge); + return syncNotice(project) + answer(project.lock, args[0]); +}; +const why = lockQuery('why', whyInstalled); +const info = lockQuery('info', packageInfo); + const availableStarters = config => starterNames(config).length ? ` (starters: ${starterNames(config).join(', ')})` : ''; const usage = { init: 'wf init [name]', create: 'wf create [directory]', install: 'wf install [--update] [[@range] ...]', restore: 'wf restore [--offline]', run: 'wf run [--timeout ]