From 4c7e9bf6de33e2ab6de8acc1215cb57cec9e0b71 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sat, 14 Nov 2026 14:54:57 +0100 Subject: [PATCH 1/3] Keep the wf prefix, add read-only file commands and the dependency graph to the terminal (#575) The terminal gains ls, cat, tree and mounts, which only read the project, and reserves the usual file command names it does not provide. wf list --tree, wf why and wf info read the graph of the lock. A wf command typed without its prefix answers with the line to type. Store::entries and the webfront.developer.entries callback give ls -l sizes and dates. Environment 0.9.3. --- include/webfront/Commands.hpp | 8 +- include/webfront/DeveloperApp.hpp | 2 + include/webfront/system/DeveloperStore.hpp | 75 ++++-- js/developer/environment/bundles.json | 10 +- js/developer/environment/commands.mjs | 9 +- js/developer/environment/dependencies.mjs | 120 +++++++++ js/developer/environment/files.mjs | 274 ++++++++++++++++++++ js/developer/environment/runtime.mjs | 48 +++- js/developer/tools/bundle-inputs.json | 2 + js/developer/tools/distribution.json | 2 +- js/developer/webfront.project.json | 2 + test/developer/memory-bridge.mjs | 7 + test/developer/specs/dependencies-specs.mjs | 113 ++++++++ test/developer/specs/files-specs.mjs | 234 +++++++++++++++++ test/unit/CommandsTests.cpp | 6 + test/unit/DeveloperTests.cpp | 50 +++- test/web/developer-specs.mjs | 34 +++ 17 files changed, 958 insertions(+), 38 deletions(-) create mode 100644 js/developer/environment/dependencies.mjs create mode 100644 js/developer/environment/files.mjs create mode 100644 test/developer/specs/dependencies-specs.mjs create mode 100644 test/developer/specs/files-specs.mjs 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..7d182a0a 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": "b7392bb63438422a1c4da7fe0f0e075af972cc048e9c51c344403a7b3ecab15f", "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/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": "2d4a0f184acf0862ecf66a3c8c6ba30ce114b818b771a2ac27f15b0763b3c415", + "js/developer/environment/dependencies.mjs": "a414f36433f3ecc6b56979fbb8f5a2a9d4ed6fe0a9f7a1db8047c8fa0c608564", "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..75186341 --- /dev/null +++ b/js/developer/environment/dependencies.mjs @@ -0,0 +1,120 @@ +// 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'; + +const byName = (a, b) => a < b ? -1 : a > b ? 1 : 0; +const idOf = node => `${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 manifest.dependencies[name]; + if (manifest.optionalDependencies?.[name] !== undefined) return `optional ${manifest.optionalDependencies[name]}`; + if (manifest.peerDependencies?.[name] !== undefined) return `peer ${manifest.peerDependencies[name]}`; + return ''; +} +const requested = range => range ? ` (${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 || idOf(node) === spec) + .sort(([, a], [, b]) => byName(idOf(a), idOf(b))); + if (!found.length) throw new Error(`${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 ? `, ${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'); +} + +const license = manifest => typeof manifest?.license === 'string' ? manifest.license : manifest?.license?.type ?? 'not declared'; +function executables(node) { + const bin = node.manifest?.webfront?.bin; + if (typeof bin === 'string') return [node.name.split('/').pop()]; + return bin && typeof bin === 'object' && !Array.isArray(bin) ? Object.keys(bin) : []; +} + +/** 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]) => root.requested).join(', ')}` : 'no, installed for another package (wf why)'], + ...(node.manifest?.description ? [['description', node.manifest.description]] : []), + ['license', license(node.manifest)], + ['integrity', node.integrity], + ['files', `${node.files.length} in ${packageRoot}/${node.key}/`], + ['dependencies', needs.join(', ') || 'none'], + ['dependents', neededBy.join(', ') || 'none'], + ...(bins.length ? [['executables', bins.map(name => `wf exec ${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..00f9611c --- /dev/null +++ b/js/developer/environment/files.mjs @@ -0,0 +1,274 @@ +// 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'; + +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; `valued` flags take the next word. +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.startsWith('-') || word === '-') { words.push(word); continue; } + for (const flag of word.slice(1)) { + if (!allowed.includes(flag)) throw usageError(name); + if (!valued.includes(flag)) { flags.set(flag, true); continue; } + if (word.length !== 2 || index + 1 === args.length) throw usageError(name); + flags.set(flag, args[++index]); + } + } + 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)} ${entry.name}${isDirectory ? '/' : ''}${role ? ` [${role}]` : ''}`; + }).join('\n'); +} + +async function describedEntries(bridge, directory) { + try { return JSON.parse(decoder.decode(await call(bridge, 'entries', directory))); } + catch (error) { + if (/C\+\+ function 'webfront\.developer\.entries' was not found/.test(error?.message)) + 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), 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; + +// Control characters would drive the terminal: they are shown in caret notation, except tabs and line breaks. +const printable = text => text.replace(/\r\n/g, '\n').replace(/[\x00-\x08\x0b-\x1f\x7f]/g, + char => char === '\x7f' ? '^?' : '^' + String.fromCharCode(char.charCodeAt(0) + 64)); + +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}) { + if (!args.length || args.some(word => word.startsWith('-') && word !== '-')) throw usageError('cat'); + let output = ''; + for (const word of args) { + 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 ? root + '/' : '.']; + let directories = 0, files = 0, cut = false; + const walk = async (directory, prefix, level) => { + signal?.throwIfAborted(); + const names = visible(await listNames(bridge, 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 ? '└── ' : '├── '}${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; + } + }; + try { await walk(root, '', 1); } + catch (error) { + if (/Cannot list project directory/.test(error?.message)) throw new Error(`${root}: no such directory in the project`); + throw error; + } + 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..21d2288f 100644 --- a/js/developer/environment/runtime.mjs +++ b/js/developer/environment/runtime.mjs @@ -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); + if (args.length) return syncNotice(project) + dependencyTree(project.lock); const names = Object.keys(project.lock?.packages ?? {}).sort().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 ]