Design / version 0.4.0

Shelly scripts, checked before upload and verified after start.

shelly-forge builds TypeScript automations for Shelly devices with scripting support, checks their generated JavaScript, provides a local test runtime and device emulator, and verifies startup after deployment.

The CLI runs on Node.js 22.12 or newer. The automation runs on the device, where JavaScript support and available resources are different. Local checks reduce avoidable failures; the target model and firmware still need testing.

Develop

Check the code that will run

Use the device types, test with a virtual clock, then check the final ES5 artifact. check runs the build pipeline without writing artifacts.

Deploy

Check startup on the device

Upload, start, and poll status. On startup or health failure, restore a different saved last-good version when one exists. The failed deployment still returns a nonzero exit code.

Debug

Inspect through the CLI

Read status and bounded logs, evaluate code in a script, or call device RPC. People and agents use the same commands.

The device is not Node.js

Shelly's scripting interpreter has an ES5-era language subset. It does not provide Node.js or browser APIs. Promises, Node timers, and many array methods do not belong in device code. The runtime profile allows 5 timers, 5 event handlers, 5 status handlers, and 5 in-flight RPC calls per script. The upload limit is 65,535 UTF-8 bytes.

Transpiling syntax is not enough. A bundle can still call a missing built-in, retain an environment lookup, or create too many timers. An edit, upload, and log-reading loop finds these mistakes late.

Before 0.4.0What changed
The deploy command skipped missing artifacts and could return "No scripts were deployed" instead of failing.Deploy builds by default. --no-build requires an artifact and matching manifest entry; missing or mismatched inputs fail with exit 3.
The build command bundled, transpiled, and minified without a TypeScript diagnostic pass or artifact rules.Build checks the project types and the final bundle before writing output.
The device upload path returned after Script.Start, without polling script health.Deploy checks Script.GetStatus after start and keeps a local last-good copy for rollback.
Logs launched npm run wscat through a shell. Both branches returned before the error-handler and cleanup code.The CLI owns its WebSocket streams. Logs can stop after a duration or a count of matching lines.

The previous behavior is visible in the pre-0.4.0 build, deploy, logs, and device-upload implementations. Current limits live in src/core/runtime-profile.ts.

Source to device

A configured script is one build entry and one named script on a device. Imports become part of its bundle, including shared helpers and workspace dependencies outside the project directory. Build does not need device credentials or resolve device environment references.

The local build pipeline TypeScript source goes through type checking, an esbuild bundle at target esnext, TypeScript ES5 lowering, and UTF-8 normalization with optional esbuild minification. Artifact rules inspect the unminified ES5 bundle and size rules measure shipped code. Only passing builds write JavaScript and a manifest. Check writes nothing. LOCAL / BUILD AND CHECK TypeScript source configured entry + local imports Type check tsconfig.json device type lib Bundle esnext / IIFE public env values Lower + minify TypeScript / ES5 UTF-8 / minify Artifact checks unminified ES5 errors stop build Write output dist/*.js manifest.json check stops before writing output. --strict makes warnings fail the build or check.
Build checks project types once. With a selector, only diagnostics in selected entries and their imported inputs, plus global and configuration errors, can fail the build. Ignored diagnostic counts appear at debug level. The generated project's tsconfig.json supplies the device library.

esbuild bundles at target esnext, then TypeScript lowers syntax to ES5. TypeScript's __assign and __rest helpers detect missing built-ins; esbuild's earlier lowering used helpers that required Object.getOwnPropertyDescriptors. A final esbuild pass normalizes raw UTF-8 even with --no-minify, which keeps the ES5 bundle readable.

The schema 1 manifest records source and artifact sizes and hashes, build settings, findings, and each script's inputs as project-relative paths with SHA-256 hashes. Input paths may contain ../ for imports outside the project directory, but cannot be absolute or contain backslashes or NUL. Entry source and artifact paths must stay inside the project. The build validates the merged manifest before writing any artifacts. publicEnvSha256 hashes sorted public name/value pairs without storing the values. Selected builds merge entries by deployId, retain other configured scripts, and drop removed entries. runtime.bundleTarget is esnext; readers also accept es2015.

build --no-typecheck and build --no-check bypass separate checks; they are not fixes for reported errors. Neither type checking nor artifact checking executes a test suite. Run npm test separately.

Deployment, startup verification, and rollback After preflight and a cache check that requires a running script, deployment finds or creates the script, stops it, uploads chunks, configures it, and starts it. Every returned status must be healthy and at least one poll must complete within the verification window before the cache and last-good artifact are recorded. A later deadline-aborted request or late healthy response does not cancel an earlier healthy result. Startup or health failure can re-upload a different saved last-good artifact and verify it. The failed deployment returns exit 5 even after restoration. DEVICE / DEPLOY PASS STARTUP / HEALTH FAILURE RETRY Preflight + cache targets / size / hash skip requires running Upload and start find or create / stop / Script.PutCode set name + boot setting / Script.Start Verify startup Script.GetStatus healthy completed polls Restore last-good code only if saved code exists and differs re-upload / start / verify again original deploy still fails / exit 5 Record locally deploy-cache.json last-good JavaScript SOLID: NORMAL PATH DASHED: CONDITIONAL RECOVERY
Upload chunks normally contain 1,024 JavaScript string code units, adjusted to avoid splitting a surrogate pair. The first chunk replaces existing code; later chunks append. An ambiguous DEVICE_UNREACHABLE chunk failure restarts the entire upload with replace mode, at most twice. An explicit RPC rejection does not trigger a restart.

The last Script.PutCode response's numeric len must equal the artifact's UTF-8 byte length. Only when len is absent, the CLI falls back to Script.GetCode {id, offset: 0, len: 1} and adds the sample's byte count to left. A replacement character from a partial multibyte character counts as one sampled byte. An invalid len or a length mismatch fails the upload. The artifact limit is measured in UTF-8 bytes, not string length.

Verification polls immediately after start, then waits up to 500 ms between polls across the full 3,000 ms window. At least one healthy poll must complete within the window. Every returned status must report running: true without errors or error_msg, including responses after the deadline. Any unhealthy response fails immediately with those details. After an earlier healthy poll, a later request cut off by the deadline or a late healthy response does not fail verification. Other failed status requests still fail. This checks startup, not behavior after the window.

deploy and dev accept --verify-timeout <ms> to change the window. The value must be an integer from 1 to 4294967295. Invalid values return USAGE, exit 2, before building or starting a watcher.

The first Ctrl+C cancels before stop or after start, not between stop, upload, configuration, and start. It also defers cancellation during rollback's replacement sequence. Cancellation alone therefore does not leave a script stopped. An upload error still can. A second Ctrl+C forces exit 130 and can interrupt any step.

The cache is keyed by host and target script name. A skip also requires a matching artifact hash, device script ID, boot setting, and running: true. A skip does not read back device code or repeat the health window. Use status to inspect health and deploy --force to upload again after out-of-band edits. Last-good filenames include 12 hexadecimal characters of the target name's SHA-256 hash so names differing only in case remain distinct on case-insensitive filesystems.

An upload failure can leave a stopped, partially written script and returns exit 4. Run deploy again to send the complete artifact. Rollback applies to startup or health failure, not partial upload. --no-verify skips the startup check and does not save a new cache entry or last-good copy. --no-rollback disables restoration.

deploy --dry-run builds by default and reports create, update, or skip plans. Its device requests are limited to Script.List. It does not upload, start a script, or prove that a deployment would run.

deploy --no-build validates the artifact, entry source, imported inputs, and public environment hashes against the manifest. Missing or changed inputs report their path. Older manifests without input or public environment hashes require rebuilding. Prefer the default build-then-deploy path.

Deployment reuses an authenticated RPC client only for the same normalized host and password during upload, verification, and rollback. Entries with different passwords do not share a client. HTTP 429 waits 2,000 ms before retrying, at most twice. Malformed responses include their HTTP status; HTTP 404 adds a hint to check for a Gen2+ device or the wrong host.

Implementation: build pipeline, manifest validation, deployer, script RPC operations.

Where failures are caught

CheckWhat it can catchWhat it does not prove
Editor and project type checkInvalid types, missing declared APIs, and unsupported array methods when using the device library.Types do not measure resource use or execute callbacks.
Artifact checksKnown hazards left in the final JavaScript, including unsupported free globals and oversized code.Rules are not a complete implementation of the device interpreter. Some checks are heuristics.
Simulator testsBehavior under supplied inputs, virtual time, RPC outcomes, and enforced resource limits.The simulator is Node's VM, not device firmware. It does not reproduce CPU, memory, or radio behavior.
Emulator end-to-end testsCLI builds, deployment, logs, authentication, and recovery over local HTTP and WebSocket connections.The emulator shares the simulator's Node VM engine. Its timing and resource fields do not measure device behavior.
Deploy verificationA newly started script that is not running or reports errors during the verification window.A healthy window does not prove long-running correctness. Cached skips do not repeat this check.

Rules on the ES5 bundle

AST rules inspect the unminified ES5 bundle, equal to build --no-minify output. Finding line and column numbers refer to that bundle, even when shipped code is minified. For minified builds and check, text locations include (unminified) and JSON artifact findings include bundle: "unminified". build --no-minify writes the matching file and omits that marker. AST messages include a short code excerpt because check writes no artifact. Size rules measure shipped code. The default severities below come from artifact-check.ts. --strict promotes warnings to errors.

Rule IDSeverityReported condition
size-limitErrorMore than 65,535 UTF-8 bytes.
size-budgetWarningAbove 80% of the size limit, without exceeding the limit.
unresolved-envErrorA remaining process.env lookup. Only set SHELLY_PUBLIC_* values are inlined at build time.
unsupported-globalError or warningFree references to Promise, Node timers, setImmediate, queueMicrotask, fetch, XMLHttpRequest, require, or process are errors. Symbol, Proxy, Reflect, WeakMap, and WeakSet are warnings. Local bindings are excluded.
async-functionErrorTypeScript __awaiter or __generator helpers.
dynamic-codeErrorFree eval references or calls and construction through the global Function.
use-before-declarationErrorA reference evaluated before its function declaration in the same execution scope, including a callback passed to Timer.set. References inside a nested function body are allowed.
unicode-escapeErrorA \u escape in string literal source. Use raw UTF-8 characters instead; a literal escaped backslash is allowed.
unsupported-array-methodWarningCallback-taking map, forEach, filter, reduce, reduceRight, some, every, find, findIndex, or flatMap calls with a function or identifier as the first argument. Free Object, JSON, Math, String, Number, and Array receivers and declared object methods are excluded. Non-callback methods rely on the type checker.
class-inheritanceError or warningclass X extends Y fails because TypeScript's ES5 output relies on function hoisting. Use composition or plain objects. Other __extends and Object.setPrototypeOf findings remain warnings.
callback-nestingWarningFunction expressions passed as call arguments nested deeper than two levels. The top-level IIFE is not counted.
non-asciiWarningNon-ASCII characters in string literals. Device string indexing and length operate on bytes.

Type diagnostics use the typescript rule; bundling failures use bundle. A missing tsconfig.json produces a missing-tsconfig warning and skips type checking. In strict mode, that warning fails the check.

Testing without hardware

shelly-forge/testing executes bundled code in a Node VM with simulated device APIs. Tests control time and inputs instead of waiting for timers or contacting a device.

The simulator and the test process A Vitest test loads source or an artifact into a Node VM. The bundle uses simulated Shelly, KVS, Timer, MQTT, HTTP, and BLE APIs. A virtual clock orders timers and deferred RPC callbacks. The runtime profile removes unsupported built-ins and enforces resource limits. Tests inspect calls, logs, KVS values, and published messages. NODE:VM / SIMULATED DEVICE Vitest test loadScript / loadArtifact advance / inject inputs Assertions calls / logs / KVS mqtt.published Your bundled JavaScript loadScript bundles without minification / loadArtifact reads a built file Shelly + KVS RPC / component state events / handlers Virtual clock + Timer ordered timers deferred RPC callbacks MQTT / HTTP / BLE injected messages requests / adverts Runtime profile / unsupported built-ins removed / resource limits enforced
advance(ms) runs due timers in order and delivers pending RPC callbacks before and between timer steps. flush() delivers pending RPC callbacks without advancing time. The first uncaught script failure throws ShellyScriptError, sets runtime.crashed, and stops the runtime.

Test the generated example

This test belongs beside the generated src/example/hello.ts. That script increments example.hello.count once per minute. The host test may use async functions; the device script uses named callbacks.

import { fileURLToPath } from 'node:url';
import { expect, test } from 'vitest';
import { createShellyRuntime } from 'shelly-forge/testing';

const scriptPath = fileURLToPath(new URL('./hello.ts', import.meta.url));

test('persists the first counter value', async () => {
  const runtime = createShellyRuntime();
  await runtime.loadScript(scriptPath, {
    env: { SHELLY_PUBLIC_GREETING: 'Hello' },
  });

  runtime.advance(60000);

  expect(runtime.kvs.get('example.hello.count')).toBe('1');
  expect(runtime.logs).toEqual(['Hello example/hello 1']);
});

Tests can set component status, emit events, inject MQTT messages, call HTTP endpoints, and supply RPC handlers. The default strict mode removes unsupported globals and array methods from the VM, not from the host test process. It also removes undeclared modern APIs such as String.prototype.startsWith, padStart, Object.assign, Object.entries, Array.from, Number.isInteger, and newer Math methods. TypeScript's feature-detecting helpers still work. strictBuiltins: false retains those native APIs for test convenience.

In both modes, String.prototype.at returns a numeric character code or undefined outside the string. It uses Node's character indexing, not the device's UTF-8 byte indexing.

An uncaught top-level or callback error clears timers, pending RPC work, event/status handlers, MQTT subscriptions, HTTP endpoints, and BLE activity. Later advance() and flush() do nothing, including no clock advancement. Calls, logs, completed KVS writes, and published messages remain inspectable. Loading again throws the same stored error; create a new runtime to restart. A caught script error does not crash the runtime.

Host calls to setStatus and emitEvent copy their input before entering the script. Inputs that JSON cannot serialize, such as circular references or BigInt, throw TypeError to the caller without crashing the runtime, changing state, invoking handlers, or clearing queued work. Errors inside script handlers still crash the runtime.

The simulator enforces 5 timers, 5 event handlers, 5 status handlers, 5 pending RPC calls, 10 MQTT subscriptions, and 5 HTTP endpoints. KVS allows 50 keys, with at most 42 UTF-8 bytes per key and 253 bytes per value. Non-string values use their serialized JSON size.

The simulator is not a security boundary for untrusted scripts. Unhandled RPC methods return error -114 with method not simulated: <name>; supply a handler when a test needs them. BLE GAP parsing is not simulated, HTTP responses must be sent synchronously, and virtual component handles return null. Node's string behavior and execution engine are not the device interpreter.

Read the testing guide for fixtures and RPC failure examples. To test the exact minified output, build first and load its file with loadArtifact.

Local device emulator

shelly-forge emulate runs a local device server for development, debugging, and end-to-end CLI tests in CI. The existing device clients call its HTTP RPC and WebSocket endpoints without a separate emulator client.

CLI requests and logs through the local emulator The CLI sends requests to the RPC router through /rpc. The router manages script engines and shared device state. Script engines also use that state. Print output and crashes pass through the log broadcaster to the CLI over /debug/log. Each script engine runs in Node vm, not the device interpreter. EMULATOR / 127.0.0.1:8080 /rpc DEVICE CALLS PRINT / CRASH WS /debug/log Shelly Forge CLI deploy / rpc / eval status / logs / dev RPC router Script.* lifecycle Shelly / Sys / Switch / KVS Script engines one Node vm per script real-time clock ticks Shared device state switch components KVS values status / events Log broadcaster {ts, level, data} src/emulator uses the script engine and DeviceState in src/testing
The server shares switch and KVS state across running scripts. A callback crash stops only its script. Debug logging starts disabled; logs enables it by default. Optional mDNS requires a non-loopback bind and a password.

Start npx shelly-forge emulate and set DEVICE_HOSTNAME=127.0.0.1:8080 in the client project's .env. The default binding is loopback. --port 0 selects a free port. Set SHELLY_EMULATOR_PASSWORD for server authentication and the same value as SHELLY_PASSWORD for the client. Ctrl+C closes the server and discards its in-memory state.

A non-loopback bind requires a nonempty server password or exits 2. An empty password means no authentication. --mdns requires a non-loopback bind, such as --bind 0.0.0.0; it exits 2 on loopback. The server rejects requests with an Origin header and non-local Host headers on loopback.

Scripts can use Shelly.call for the emulator's Shelly.*, Sys.*, and Script.* methods. Unknown methods return 404 No handler for <Method>.

Node-side tests can import startEmulator from shelly-forge/emulator, then call close() in cleanup. The API defaults to a free port and exposes status and event injection. See the emulator reference for options, supported RPC methods, log frames, and an API example.

Node vm is not a security boundary. Only run code you trust. Top-level code, each callback, and eval have a 1000 ms synchronous execution limit. A timeout crashes the script; eval instead returns an error. Memory, CPU, timing, and engine quirks differ from hardware. Script resource fields are zero placeholders. Keep the emulator local and verify behavior on the target hardware.

See CONTRIBUTING.md for the regular emulator end-to-end suite and the opt-in npm run test:device workflow with SHELLY_E2E_HOST and optional SHELLY_E2E_PASSWORD.

Implementation: public API, server, RPC router, script engine, shared device state.

Deploy and debug

Use dev <selector> for an interactive edit loop. It watches src/, solutions.config.json, tsconfig.json, and .env. It debounces changes for 300 ms and serializes builds and deployments.

Commands around a running device Dev builds and deploys edited code to a Shelly device. Logs receives the device-wide debug WebSocket stream, while debug toggles that setting. Status reads script health and resource metrics. Eval executes code in a running script, and rpc calls a device method. INTERACTIVE DEVELOPMENT AND EXPLICIT INSPECTION Edit and deploy dev example/hello watch / build / verify Shelly device named script / component state HTTP RPC / debug WebSocket target model + firmware Read device logs logs / debug on|off ws://host/debug/log Inspect script health status example/hello running / errors / memory / CPU Inspect or change state eval / Script.Eval rpc / device methods
dev reuses the build and deploy code. A build or check failure prevents that cycle's deployment. A newer edit observed during a build supersedes that build; failures are reported and the watcher continues.

Dev enables debug logging, including with --no-logs. On Ctrl+C it closes watchers and streams and turns debug off only on devices where it enabled it. --keep-debug preserves that setting. Standalone logs enables debug by default and leaves it enabled; use --no-enable-debug to avoid that change.

The first log connection failure per device outage emits a warning with its DNS, refusal, HTTP, or close reason. Repeats in the same outage use debug-level diagnostics. A successful connection resets warning suppression, so a later outage warns again. When a WebSocket upgrade returns a digest challenge, the stream reuses that header instead of making another request; it fetches a challenge only when the header is missing.

npx shelly-forge --json status example/hello
npx shelly-forge --json logs example/hello --duration 15 --lines 100
npx shelly-forge --json eval example/hello 'Shelly.getUptimeMs()'
npx shelly-forge --json rpc Shelly.GetDeviceInfo --script example/hello

Logs are device-wide. A selector chooses the device and output label, not a server-side script filter. --grep <pattern> filters message text with a regular expression; --lines counts matching lines. eval and rpc can change device state, depending on the supplied code or method.

Exit codes are part of the interface

ExitError codes or resultNext step
0The command completed with no reported failure.Read the result. Dry-runs, cache skips, and explicitly unverified deployments are not health proofs.
1INTERNAL, NOT_IMPLEMENTED, or no CLI arguments.Inspect the message and use --verbose for error details. No arguments prints help to stderr; explicit --help prints to stdout and exits 0.
2USAGE, CONFIGFix arguments, selectors, config, or required environment values.
3BUILD, CHECKFix diagnostics or regenerate the artifact and manifest.
4DEVICE_UNREACHABLE, DEVICE_AUTH, DEVICE_RPC, DEPLOYCheck the host, credentials, and RPC error. Retry a partial upload with deploy.
5UNHEALTHY; status can also return 5 with result data.Inspect status and bounded logs. Read whether rollback succeeded.
130A second SIGINT forces the process to exit.Inspect the device if deployment was interrupted.

Status returns 5 for a missing script or reported runtime errors, and 4 for a device request error. A stopped script without reported errors does not by itself make status fail. In a long-running dev session, failed cycles are events; do not rely only on the final process exit code.

Implementation: error codes, dev, status, logs.

Working with agents

The agent workflow uses packaged skills and the same CLI that a person runs. The MCP server was removed in 0.4.0. Skills carry the device rules and workflow examples; the CLI executes commands and reports results.

First, install the skills with the Skills CLI, which requires Node.js 22.20 or newer:

npx skills add mslavov/shelly-forge --skill shelly-forge shelly-scripting

Then ask the agent to create the project, write and run tests, and check the code. Require your confirmation before it makes changes to a real device. Shelly Forge itself requires Node.js 22.12 or newer.

shelly-scripting covers device code. shelly-forge covers testing, deployment, and debugging. Keeping these instructions with the package makes them available in an initialized project without a separate server.

Machine-readable does not mean unattended mutation

--json puts result envelopes on stdout. logs and dev emit newline-delimited JSON events before their final envelope. Progress uses stderr. Every result envelope includes exitCode, and ok is true only when it is 0. Thrown failures include an error object with a code and message; optional hint and details fields add context.

Always check the process exit code as well as the data. Status can return result data with ok: false and exitCode: 4 or 5, without an error object.

Use bounded logs in non-interactive work, not a persistent dev process. Confirm the intended device before deploy, debug changes, or state-changing eval and RPC calls. The generated project's AGENTS.md asks for that confirmation; the CLI does not enforce an approval prompt.

Installer: skills.ts. Output contract: command.ts. Command reference: CLI guide.

Project and configuration

The generated project separates device code from Node.js tests. create <solution> <script> adds both files and a config entry. It refuses to replace existing files.

src/example/hello.ts         Device automation
src/example/hello.test.ts    Vitest test in Node.js
solutions.config.json       Entries and device targets
tsconfig.json               Device types, no default library
tsconfig.test.json          Node.js types for tests
.env                        Local values, ignored by Git
.agents/skills/             Installed agent instructions
AGENTS.md                   Generated project guide
dist/                       Built JavaScript and manifest
.shelly-forge/               Logs, deploy cache, last-good copies

tsconfig.json uses noLib: true and types: [], includes the two packaged device declaration files, and excludes test files. tsconfig.test.json uses ES2022 and Node.js types. Both set moduleDetection: "force", so scripts can share top-level names without an empty export. Project-wide interface extensions use declare global. The template's npm run typecheck checks both configurations.

{
  "$schema": "./node_modules/shelly-forge/schema/solutions.config.schema.json",
  "example": {
    "hello": {
      "src": "src/example/hello.ts",
      "device": "${DEVICE_HOSTNAME}",
      "enableOnBoot": true
    }
  }
}

The canonical selector is example/hello. example-hello, a unique script name, or a unique targetScriptName also works. Ambiguous selectors fail and list the matching IDs. The device name defaults to the script name; targetScriptName overrides it. deploy and dev reject duplicate host and target-name pairs involving the selection.

The CLI loads .env from the project directory without overriding existing environment values. --cwd <dir> sets that directory. Copy .env.example before the first build; the example expects SHELLY_PUBLIC_GREETING to be set.

The deploy cache and last-good files live in this project, not on a remote service. Removing them loses the local skip and recovery history. The CLI cannot restore a previous version it has never saved.

See the README for setup and commands, the template guide for the generated project, and the configuration schema for accepted fields.

Further reading

Use the package

Maintain the package

Check device behavior