Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/DeveloperDistribution.yml
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ jobs:
echo "::notice::Sources build $building; DeveloperReleaseData.hpp still pins the published $pinned."
node js/developer/tools/pin-check.mjs
fi
node --test js/developer/tools/check.mjs js/developer/tools/distribution-check.mjs js/developer/tools/manifest-check.mjs js/developer/tools/restore-check.mjs
node --test js/developer/tools/check.mjs js/developer/tools/distribution-check.mjs js/developer/tools/manifest-check.mjs js/developer/tools/restore-check.mjs js/developer/tools/scripts-check.mjs
- name: Check the dedicated release tag
if: startsWith(github.ref, 'refs/tags/developer-v')
env:
Expand Down
8 changes: 8 additions & 0 deletions docs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,14 @@
print it with its origin. A reproducible local npm registry fixture (`js/developer/tools/registry-fixture.mjs`)
serves the tests.

- `wf run [--timeout <s>] <script>` and `wf exec <package>[:<entry>]` (developer distribution 0.5.0): WebFront
scripts (JS/TS bundled by esbuild-wasm, `default async function (context)`) run in a dedicated Worker with the
`context` API (`args`, `signal`, `console`, `project.read/readText/list/write`, `packages.resolve`, `fetch`,
`exit`) under the manifest `permissions`. `wf exec` runs only `webfront.bin` entries, never npm's `bin`. Node.js
imports are refused while loading. Ctrl+C or the time limit aborts `context.signal`, then terminates the Worker
after a 2 s grace period; staged writes are aborted, committed ones complete. Exit codes reach the terminal.
New bridge callback `webfront.developer.list` (`developer::Store::list`).

### Changed

- `DeveloperBootstrapOptions::registry` is now `std::optional<std::string>`: unset, the manifest's registry
Expand Down
57 changes: 54 additions & 3 deletions docs/DEVELOPER_ENVIRONMENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -161,9 +161,9 @@ A project has one manifest, the equivalent of `package.json`, which every `wf` c

Only `format`, `name` and `version` are required. Validation is strict: an unknown key, a format
newer than the environment reads, a path leaving the project, a non-HTTPS registry or origin and an
unknown permission are errors printed in the terminal, never silently ignored. `scripts`, `test` and
`permissions` are validated here and used by the later commands (#307, #310); permissions will only
frame the operations of the `context` API of authorized scripts, they are not a sandbox.
unknown permission are errors printed in the terminal, never silently ignored. `scripts` and `permissions` are
used by `wf run` and `wf exec` (below); `test` is validated here and used by `wf test` (#310). Permissions only frame
the operations of the `context` API of scripts; they are not a sandbox.

- `wf init [name]` writes `webfront.project.json` at the project root, the manifest every `wf` command
reads; it never replaces an existing one. When a lock already exists (a project installed before
Expand Down Expand Up @@ -240,6 +240,57 @@ and tarballs from the application (`fs::NativeDebugFS` or an application provide
`registry`, then run `wf restore`; or copy `.webfront/developer/packages/` from another machine and check it with
`wf restore --offline`. The environment archive is provisioned the same way (see below).

## Scripts (`wf run`, `wf exec`)

WebFront scripts replace npm scripts and `npx` for producing a project's resources, without Node.js:

```json
{
"scripts": {"icons": "tools/icons.ts --size 64", "build": "wf embed LifeUI"},
"permissions": {"files": ["assets"], "publish": ["generated"], "fetch": ["https://api.example.org"]}
}
```

- `wf run [--timeout <seconds>] <script> [args...]` runs a script of the manifest. A script whose first word is `wf`
runs that wf command (up to four nested levels); otherwise its first word is the project path of a JS or TS module
and the other words, then the command's arguments, are its `context.args`. No shell is involved.
- `wf exec [--timeout <seconds>] <package>[:<entry>] [args...]` runs an executable WebFront entry of an installed
package: the field `webfront.bin` of its `package.json`, a path or an object naming paths. npm's `bin` is never run:
a package with only a `bin` (a Node.js program) is refused, as is a browser package without `webfront.bin`.

The module is bundled by esbuild-wasm with its locked dependencies (JSX with the automatic runtime, as for previews)
and runs in a dedicated Worker; only the package files it imports are read from the cache. It exports
`default async function (context)`, where `context` offers:

| Member | Behavior |
| --- | --- |
| `args` | The arguments, as an array of strings. |
| `signal` | An `AbortSignal` aborted by Ctrl+C and by the time limit. |
| `console` | `log`/`info`/`debug` and `warn`/`error`, streamed to the terminal; the Worker's global `console` too. |
| `project.read(path)`, `readText(path)` | A project file as bytes or text, under `permissions.files` or `publish`. |
| `project.list(path = '')` | The names in a project directory (directories end with `/`). A readable directory is listed whole; the root and the directories leading to granted paths list only the entries leading to them. |
| `project.write(path, data)` | Publishes a string or `Uint8Array` with `developer::Store`, under `permissions.publish`. |
| `packages.resolve(name)` | `{name, version, integrity}` of a locked package, or `null`. |
| `fetch(input, init)` | `fetch` of a URL or a `Request` to an origin listed in `permissions.fetch`; a refusal rejects. Redirects are not followed, since their target could be any origin: the promise rejects and the script requests the final URL. |
| `exit(code)` | Ends the run with an exit code from 0 to 255; it throws, so the statements after it do not run, and nothing the script does afterwards reaches the page. |

A `context` operation outside the permissions rejects with an explicit error. The manifest, the lock and
`.webfront/` are never written by a script, whatever the permissions. **The permissions frame only the `context`
API**: the Worker keeps its own capabilities (global `fetch`, `importScripts`, WebSocket...), and nothing here is a
security boundary. Node.js modules (`fs`, `child_process`, `node:*`...) are refused while the script is loaded,
unless a locked package of that name is a dependency of the importer; `process` does not exist and no polyfill is
provided.

Ctrl+C first aborts `context.signal`; a script still running two seconds later (the grace period) is terminated with
`worker.terminate()`, which also stops a loop that never returns to the event loop. The time limit (`--timeout`,
600 seconds by default, from 1 to 3600) applies the same sequence; it also bounds the scripts that the script runs
through `wf` commands, whatever their own limit. The terminal stays usable. Each write is a transaction of its own:
at a stop, one still staging is aborted and leaves the file unchanged, and one whose commit was already sent
completes atomically; the terminal lists the publications applied and abandoned. When a script ends by itself, the
writes it did not await complete first; if one of them fails, the run ends with code 1 and names it. A script that
returns ends with code 0, a thrown error with 1, `exit(code)` with that code, Ctrl+C with 130 and the time limit with
124; a non-zero code is an error carrying `exitCode`.

## Dependencies, storage and limitations

- `wf install` accepts exact versions, registry tags and semver ranges, resolves ordinary
Expand Down
3 changes: 2 additions & 1 deletion docs/PROJECT_STATUS.md
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,8 @@ Status snapshot: 2026-07-19. Optional mddlog integration note: 2026-10-02. Newco
those public-path headers and ran both applications offline with developer callbacks absent.
Pages returned HTTP 200, CORS `*` and byte-identical pinned environment data on 2026-10-20.
- Browser packages only: no installation scripts, native modules, Node API shims, optional
dependencies or TypeScript type checking. Peers require explicit compatible roots/direct
dependencies or TypeScript type checking. `wf run`/`wf exec` (#307) run WebFront scripts in a Worker under the
manifest permissions, which frame the `context` API only and are not a sandbox. Peers require explicit compatible roots/direct
dependencies. Automatic rebuild/watch is future work. `wf restore [--offline]` (0.5.0, #306) rebuilds or checks
the cache from the lock, from the application's registry option, else the manifest's, else npmjs.
See [DEVELOPER_ENVIRONMENT](DEVELOPER_ENVIRONMENT.md) for exact commands and limits.
Expand Down
1 change: 1 addition & 0 deletions include/webfront/DeveloperApp.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ class BasicDeveloperApp : public BasicWF<NetProvider, fs::Multi<fs::DeveloperFS,
return config;
});
expose<&Store::read, Bytes, std::string, std::uint64_t>("webfront.developer.read");
expose<&Store::list, Bytes, std::string>("webfront.developer.list");
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");
Expand Down
1 change: 1 addition & 0 deletions include/webfront/system/DeveloperFiles.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ namespace webfront::developer {
inline constexpr std::size_t chunkSize = 256 * 1024;
inline constexpr std::uint64_t maxTransactionBytes = 256 * 1024 * 1024;
inline constexpr std::size_t maxTransactions = 8;
inline constexpr std::size_t maxListedEntries = 4096;
/// A transaction untouched for this long is abandoned: its browser reloaded or disconnected.
inline constexpr std::chrono::minutes defaultAbandonedAfter{10};
/// Staging left by a crashed process is removed at startup once it is this old.
Expand Down
47 changes: 47 additions & 0 deletions include/webfront/system/DeveloperStore.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@

#include "DeveloperFiles.hpp"
#include "DeveloperJournal.hpp"
#include "../utils/Json.hpp"

#include <algorithm>
#include <cctype>
#include <optional>
#include <set>

namespace webfront::developer {
Expand Down Expand Up @@ -50,6 +52,35 @@ class Store {
return bytes;
}

/// The names in a project directory as a sorted JSON array of strings; a directory's name ends with '/'. An
/// empty path lists the project root. An entry that a link would take out of the project, or whose type cannot
/// be read, is omitted; only a directory that cannot be read fails the listing.
std::vector<std::uint8_t> 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<std::string> 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)
text += (text.size() > 1 ? "," : "") + json::quote(name);
text += "]";
return {text.begin(), text.end()};
}

std::string begin(std::string destination, bool directory, bool replace = true) {
std::scoped_lock lock(mutex);
expireAbandoned();
Expand Down Expand Up @@ -193,6 +224,22 @@ class Store {
}

private:
// The listed form of one entry, or nothing when it leaves the project or its type cannot be read.
std::optional<std::string> listedName(const std::string& directory, const std::string& name) const {
std::error_code error;
try {
const auto resolved = projectPath(root, directory.empty() ? name : directory + "/" + name);
const bool isDirectory = std::filesystem::is_directory(resolved, error);
if (error && error != std::errc::no_such_file_or_directory)
return std::nullopt;
return isDirectory ? name + "/" : name;
} catch (const std::invalid_argument&) {
return std::nullopt;
} catch (const std::filesystem::filesystem_error&) {
return std::nullopt;
}
}

static std::vector<std::string> lines(const std::string& text) {
std::vector<std::string> result;
std::istringstream stream{text};
Expand Down
2 changes: 1 addition & 1 deletion js/core/WebFrontAssets.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ function(webfront_add_embedded_assets)
find_program(WEBFRONT_NODE_EXECUTABLE NAMES node nodejs REQUIRED)
add_test(NAME DeveloperJavaScript COMMAND "${WEBFRONT_NODE_EXECUTABLE}"
--test "${root}/js/developer/tools/check.mjs" "${root}/js/developer/tools/distribution-check.mjs"
"${root}/js/developer/tools/manifest-check.mjs" "${root}/js/developer/tools/restore-check.mjs")
"${root}/js/developer/tools/manifest-check.mjs" "${root}/js/developer/tools/restore-check.mjs" "${root}/js/developer/tools/scripts-check.mjs")
set_tests_properties(DeveloperJavaScript PROPERTIES TIMEOUT 30)
add_test(NAME EmbeddedAssetGenerator COMMAND ${CMAKE_COMMAND} -E env
"WEBFRONT_TEST_CMAKE=${CMAKE_COMMAND}" "${WEBFRONT_NODE_EXECUTABLE}"
Expand Down
64 changes: 60 additions & 4 deletions js/developer/environment/bundler.mjs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Virtual project/npm filesystem for esbuild's browser API. No Node.js shims or network imports.
import {normalize, packageEntry} from './entry.mjs';
import {resolveImport} from './resolve.mjs';
import {packageRoot} from './paths.mjs';
export {normalize, packageEntry};

const decoder = new TextDecoder();
Expand All @@ -17,11 +18,20 @@ async function probe(read, namespace, candidate) {
}
}

function createFinder(packages, readProject, loaded) {
// Package files come from `packages` (id -> path -> bytes) or, without it, are read from the cache when resolved.
export function createFinder(packages, readProject, loaded, lock) {
const files = new Map();
const cached = (id, path) => {
const node = lock?.packages?.[id];
if (!node) return undefined;
if (!files.has(id)) files.set(id, new Set(node.files));
return files.get(id).has(path) ? readProject(`${packageRoot}/${node.key}/${path}`) : undefined;
};
const read = async (namespace, path) => {
if (namespace === 'project') return readProject(path);
const slash = path.indexOf('/');
return packages[path.slice(0, slash)]?.get(path.slice(slash + 1));
const [id, file] = [path.slice(0, slash), path.slice(slash + 1)];
return packages ? packages[id]?.get(file) : cached(id, file);
};
const find = async (namespace, path) => {
for (const suffix of extensions) {
Expand All @@ -36,8 +46,11 @@ function createFinder(packages, readProject, loaded) {
}

export function virtualPlugin(lock, packages, readProject) {
const loaded = new Map();
const {read, find} = createFinder(packages, readProject, loaded);
return virtualPluginWith(lock, packages, readProject, new Map());
}

function virtualPluginWith(lock, packages, readProject, loaded) {
const {read, find} = createFinder(packages, readProject, loaded, lock);
const load = namespace => async args => {
const bytes = loaded.get(`${namespace}:${args.path}`) ?? await read(namespace, args.path);
const loader = loaders.get(args.path.split('.').pop());
Expand All @@ -58,3 +71,46 @@ export async function bundle(esbuild, {entry, lock, packages, readProject}) {
plugins: [virtualPlugin(lock, packages, readProject)]});
return new Map(result.outputFiles.map(file => [file.path.replace(/^\/output\//, ''), file.contents]));
}

// Node.js built-in modules: a script importing one fails while it is loaded, unless a locked package of that name
// (an npm polyfill such as "events") is a dependency of the importer.
const nodeBuiltins = new Set(['assert', 'async_hooks', 'buffer', 'child_process', 'cluster', 'console', 'constants', 'crypto',
'dgram', 'diagnostics_channel', 'dns', 'domain', 'events', 'fs', 'http', 'http2', 'https', 'inspector', 'module', 'net',
'os', 'path', 'perf_hooks', 'process', 'punycode', 'querystring', 'readline', 'repl', 'stream', 'string_decoder', 'sys',
'timers', 'tls', 'trace_events', 'tty', 'url', 'util', 'v8', 'vm', 'wasi', 'worker_threads', 'zlib']);

// Every specifier that may name a built-in module, digits included (http2, v8).
export const nodeImport = /^(?:node:|[a-z_][a-z0-9_]*(?:\/|$))/;

export function nodeBuiltin(specifier) {
if (specifier.startsWith('node:')) return specifier.slice(5).split('/')[0];
const name = specifier.split('/')[0];
return nodeBuiltins.has(name) ? name : null;
}

const nodeError = name => `"${name}" is a Node.js API, which WebFront scripts do not provide (no fs, child_process or process; use the context API)`;

// The script's entry is given as {namespace, path}: a project module, or a file of a locked package for wf exec.
function scriptPlugin(entry, lock, find) {
return {name: 'webfront-script', setup(build) {
build.onResolve({filter: /^webfront-script-entry$/}, () => find(entry.namespace, entry.path));
build.onResolve({filter: nodeImport}, async args => {
const name = nodeBuiltin(args.path);
if (!name) return undefined;
if (args.path.startsWith('node:')) return {errors: [{text: nodeError(name)}]};
try { return await resolveImport(args, lock, find); }
catch { return {errors: [{text: nodeError(name)}]}; }
});
}};
}

/** One ES module for a script Worker: TS/JS of the project or of a locked package, with the locked dependencies. */
export async function bundleScript(esbuild, {entry, lock, packages, readProject}) {
const loaded = new Map();
const {find} = createFinder(packages, readProject, loaded, lock);
const result = await esbuild.build({entryPoints: ['webfront-script-entry'], bundle: true, write: false,
outfile: '/output/script.js', format: 'esm', platform: 'browser', target: 'es2022', jsx: 'automatic', legalComments: 'inline',
define: {'process.env.NODE_ENV': '"production"'},
plugins: [scriptPlugin(entry, lock, find), virtualPluginWith(lock, packages, readProject, loaded)]});
return new Map(result.outputFiles.map(file => [file.path.replace(/^\/output\//, ''), file.contents]));
}
Loading
Loading