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.
Design / version 0.4.0
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
Use the device types, test with a virtual clock, then check the final ES5 artifact. check runs the build pipeline without writing artifacts.
Deploy
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
Read status and bounded logs, evaluate code in a script, or call device RPC. People and agents use the same commands.
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.0 | What 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.
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.
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.
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.
--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.
| Check | What it can catch | What it does not prove |
|---|---|---|
| Editor and project type check | Invalid types, missing declared APIs, and unsupported array methods when using the device library. | Types do not measure resource use or execute callbacks. |
| Artifact checks | Known 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 tests | Behavior 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 tests | CLI 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 verification | A 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. |
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 ID | Severity | Reported condition |
|---|---|---|
size-limit | Error | More than 65,535 UTF-8 bytes. |
size-budget | Warning | Above 80% of the size limit, without exceeding the limit. |
unresolved-env | Error | A remaining process.env lookup. Only set SHELLY_PUBLIC_* values are inlined at build time. |
unsupported-global | Error or warning | Free 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-function | Error | TypeScript __awaiter or __generator helpers. |
dynamic-code | Error | Free eval references or calls and construction through the global Function. |
use-before-declaration | Error | A 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-escape | Error | A \u escape in string literal source. Use raw UTF-8 characters instead; a literal escaped backslash is allowed. |
unsupported-array-method | Warning | Callback-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-inheritance | Error or warning | class 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-nesting | Warning | Function expressions passed as call arguments nested deeper than two levels. The top-level IIFE is not counted. |
non-ascii | Warning | Non-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.
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.
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.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.
-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.
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.
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.
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.
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.
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 | Error codes or result | Next step |
|---|---|---|
| 0 | The command completed with no reported failure. | Read the result. Dry-runs, cache skips, and explicitly unverified deployments are not health proofs. |
| 1 | INTERNAL, 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. |
| 2 | USAGE, CONFIG | Fix arguments, selectors, config, or required environment values. |
| 3 | BUILD, CHECK | Fix diagnostics or regenerate the artifact and manifest. |
| 4 | DEVICE_UNREACHABLE, DEVICE_AUTH, DEVICE_RPC, DEPLOY | Check the host, credentials, and RPC error. Retry a partial upload with deploy. |
| 5 | UNHEALTHY; status can also return 5 with result data. | Inspect status and bounded logs. Read whether rollback succeeded. |
| 130 | A 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.
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.
init <name> copies the template, including AGENTS.md and CLAUDE.md, and installs bundled skills unless --no-skills is set. Non-interactive use requires a project name.skills install copies skills to .agents/skills/ and stamps each with the package version. It creates relative .claude/skills/ symlinks, with a copy fallback if symlinks fail. It does not create AGENTS.md in an existing project.--force is explicit. Managed installations at a different version are replaced; same-version installations are skipped by default.--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.
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.
${NAME} in a device or password config field resolves when a device command needs it. deploy and each dev cycle resolve selected entries strictly. A missing or empty reference in a selected entry is a config error. Unresolved unselected entries do not block either command, but other resolvable entries still participate in duplicate-target checks.process.env.SHELLY_PUBLIC_* values enter the bundle. They are public in the generated JavaScript. An empty greeting uses the example's fallback; an unset greeting remains unresolved and fails artifact checks.password field takes precedence over SHELLY_PASSWORD. Neither should use the public prefix. Authentication uses the admin username.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.