Skip to content

Latest commit

 

History

History
215 lines (160 loc) · 19.6 KB

extensions.md

File metadata and controls

215 lines (160 loc) · 19.6 KB

Declarative Blockly extensions

Status: proposed design, 2026-12-02. Not implemented. Schema and API names below are provisional until validated against existing blocks.

Goals and principles

Make external Python APIs available as blocks without requiring authors to write a JavaScript generator for every block. Use the same mechanism for built-in hardware APIs where practical. Ultimately every toolbox contribution should be registrable through a common interface; this does not require every language primitive or dynamic interaction to be expressible in JSON.

  • Static first, dynamic only when necessary. Reuse Blockly's native block and toolbox JSON instead of creating another block DSL.
  • Keep the bridge a small independent ES module, with no dependency on PyBlocks project storage, UI, networking, device detection or deployment.
  • Keep Python runtime behavior in Python libraries. The bridge binds APIs, not application policies; it must not fabricate hardware capabilities.
  • Derive abstractions from actual blocks. Do not promise complete declarative coverage or freeze a public specification before testing complex cases.
  • Preserve the universal toolbox and program-first workflow described in design.md.

Prior art

System Mechanism Lesson
Blockly Native JSON block definitions; toolbox JSON; language-specific generator functions Reuse the first two directly; bridge the third.
MakeCode Static TypeScript signatures and annotation metadata mapped to blocks Bind real APIs; one compiler rather than bespoke generators for each API.
Scratch VM Extension metadata plus opcode implementations executed by the VM Separate registration and runtime semantics; a common extension interface.
mBlock 5 Transcoding templates, argument substitution and program sections Templates can cover nested code and shared setup; arbitrary JS evaluation is not required for the initial bridge.
openHAB Blockly Custom block libraries and generator metadata Investigate its template and name-handling approach before extending the schema.

These are design references, not dependencies or a claim that their formats are mutually compatible.

Terminology and responsibilities

An extension provides editor-side block definitions, toolbox contributions and generator rules. A dependency supplies Python source required on the target runtime. An extension may require zero, one or many dependencies; a dependency need not have an extension, and multiple extensions may share a dependency. Never upload the extension descriptor itself to the device.

The bridge converts a validated extension descriptor into registration artifacts. The host loads descriptors, manages ownership, dependencies, persistence, localization and workspace lifecycle. Blockly remains responsible for rendering, connections, serialization and traversing blocks. The Python generator remains responsible for generating the complete program.

Descriptor

Name a standalone file <name>.extension.json, or use extension.json as the entry of a directory containing related sources. It is the extension definition, not merely a package manifest. No archive format, central marketplace or package resolver is needed for the first version.

Proposed top-level fields:

Field Required Meaning
schemaVersion yes Integer descriptor format version, initially 1. Independent of extension release.
id yes Stable, unique, namespaced identifier (e.g. org.example.led).
name yes Human-readable display name. Initially a plain string.
version yes Extension release identifier, not a dependency-solving range.
dependencies no Required runtime library references; empty by default.
blocks yes Native Blockly JSON definition array.
toolbox no Native Blockly toolbox item array, including categories, block references and shadows. Empty means registered but not shown.
generators yes Mapping from block type to declarative generator rule.

Optional description, localization and compatibility metadata may be added after real cases establish requirements. Keep the descriptor JSON-only. Do not introduce a second representation of Blockly input fields, connections or toolbox shadows. Blockly's custom extension/mutator names in a descriptor may reference only explicitly approved host registrations; they are not downloadable scripts.

Complete minimal example

A board-independent LED/pin read block using MicroPython's built-in machine module (no downloaded library):

{
  "schemaVersion": 1,
  "id": "org.example.pin",
  "name": "Pin",
  "version": "0.1.0",
  "dependencies": [],
  "blocks": [
    {
      "type": "org.example.pin_read",
      "message0": "read pin %1",
      "args0": [
        { "type": "input_value", "name": "PIN", "check": "Number" }
      ],
      "output": "Number",
      "colour": 155
    }
  ],
  "toolbox": [
    {
      "kind": "category",
      "name": "Pin",
      "contents": [
        {
          "kind": "block",
          "type": "org.example.pin_read",
          "inputs": {
            "PIN": { "shadow": { "type": "math_number", "fields": { "NUM": 16 } } }
          }
        }
      ]
    }
  ],
  "generators": {
    "org.example.pin_read": {
      "kind": "expression",
      "imports": ["import machine"],
      "code": "machine.Pin(${PIN}, machine.Pin.IN).value()",
      "inputs": {
        "PIN": { "source": "value", "required": true }
      },
      "order": "FUNCTION_CALL"
    }
  }
}

With the default shadow the generator emits machine.Pin(16, machine.Pin.IN).value() and includes the import once. This example describes input configuration as well as reading, not a read from an already-configured object. It does not assume GPIO16 is an LED or prescribe a board.

Block types are globally unique, stable serialized identifiers. New types should be namespaced; existing IDs remain unchanged when migrating built-ins. Reject collisions with native or previously installed definitions rather than silently overwriting them.

Bridge interface

Proposed pure compilation interface (illustrative JavaScript):

const contribution = compileExtension(descriptor);
// { id, name, version, blocks, toolbox, generators, dependencies }

// Host owns registration, not compileExtension:
Blockly.common.defineBlocksWithJsonArray(contribution.blocks);
Object.assign(pythonGenerator.forBlock, contribution.generators);
workspace.updateToolbox({
  ...baseToolbox,
  contents: [...baseToolbox.contents, ...contribution.toolbox]
});

The compiler returns actual generator functions but performs no global registration or I/O. The host validates all contributions and conflicts before calling Blockly. Use the current Blockly 13 API and inject or import the Python generator utilities at the adapter boundary; do not create a new workspace or invoke generation in the compiler. A language-specific Python adapter is acceptable initially; do not generalize to all languages prematurely.

Generator contract

First support a small template grammar: literal Python text and named placeholders of the form ${NAME}. Placeholder bindings are explicit:

  • value: use generator.valueToCode with the appropriate precedence. For simple standalone argument slots use Order.NONE; for embedded operators or receiver expressions use an explicit order or conservative parentheses. Never substitute raw Blockly JSON.
  • variable: use generator.getVariableName with the stored variable ID, not its display name. Reserve imported and helper identifiers so variable allocation cannot shadow them.
  • field: serialize according to an explicit approved kind (string via Python quoting, validated number, boolean, or finite enum token). Never treat arbitrary text as a Python identifier or token.
  • statement (later): use generator.statementToCode and preserve indentation, with a documented empty-suite policy.

An expression returns Blockly's [code, order] pair; a statement returns code with a trailing newline. Require rule kind to match the block connection contract. Map precedence names to the installed Python Order enum, rejecting unknown names. Reject missing or unknown placeholders and binding mismatches; require an explicit fallback if an input is optional. Do not silently generate zero or None for a required missing input.

Imports use the generator's definitions mechanism, with deterministic keys and deduplication. Reserve names before workspace generation, validate conflicts between aliases and other generated definitions, and keep output deterministic across repeated generation. The first prototype can constrain imports to simple import/from-import forms, with no arbitrary import-time statements. Python templates remain potentially executable device code: they are not a sandbox or a guarantee of safety.

Examples of follow-on needs: keyword arguments, finite dropdown mappings, named object creation, method calls, property access, helper functions, multiline suites, await expressions, and code contributions outside the immediate block. Add a feature only when representative real blocks establish its semantics. Do not use eval, Function, embedded JavaScript expressions or an unrestricted template language.

Dynamic native behavior (mutators, context checks, dynamic flyouts, procedure handling and event registration) can later use explicitly trusted host functions or native ES modules through the same contribution contract. Do not support loading arbitrary remote JS in V1.

Loading and registration

Sources: bundled descriptors, user-selected local JSON, and public HTTPS JSON URLs accessible through browser CORS. They converge on one staged pipeline. No backend and no CORS proxy. Limit bytes, nesting, collection sizes and template length; use strict UTF-8 and JSON validation. Display source, id, name and version before enabling an external extension.

flowchart TD
  A[Bundled JSON / Local file / HTTPS URL] --> B[Read and parse JSON]
  B --> C[Validate schema, ID, types, toolbox references and rules]
  C --> D[Compile bridge contribution]
  D --> E[Resolve and stage runtime dependencies]
  E --> F[Check conflicts and confirm install]
  F --> G[Register native block definitions]
  G --> H[Register Python generators]
  H --> I[Merge toolbox and update workspace]
  I --> J[Persist project extension snapshot]
  J --> K[Drag blocks and generate Python]
  K --> L[Explicit upload/run deploys Python and libraries]
Loading
  1. Read the descriptor: id identifies it; name is used in the extension manager. Nothing is registered or executed yet.
  2. Validate all descriptors, block IDs and referenced toolbox types against the complete proposed registry (including existing native types and shadow types). Compile generator functions without mutating globals.
  3. Stage dependency imports with the existing library planner, showing source and any conflicts. Confirm before project or registry mutation. Missing dependencies may be shown as unresolved, but must block upload when required; for the first installation flow prefer completing staging before activation.
  4. Register blocks first, generators second. Registered blocks can be instantiated or restored even without a toolbox entry.
  5. Merge toolbox contributions into the canonical base toolbox and call workspace.updateToolbox. Toolbox references determine visibility and ordering; they do not define blocks. Preserve existing Files/Libraries panels, native dynamic categories and custom icon groups; external descriptors use standard category items initially. Rebuild on language or theme changes without losing contributions.
  6. Persist the enabled descriptor and source metadata with the project. Commit only after validation and activation succeed, restore prior state on error, and avoid saving a partially restored workspace. Provide a recoverable error if storage fails. Do not imply registration alone is equivalent to deployment.
  7. On ordinary generation, Blockly walks the workspace and calls the registered generators. Upload uses the existing device path; only generated Python and runtime files are transferred.

Blockly registries and generator tables are shared within an editor page, not per workspace. Track ownership explicitly, never unregister built-in definitions, and do not allow old project definitions to leak into new projects. V1 may require a controlled editor reload for project replacement/removal rather than implement fragile global unregister behavior. Stage and validate before replacing the old workspace; preserve the original project until successful load. Do not remove a definition while a live workspace needs it.

Project persistence and dependency integration

Current src/project/storage.js stores format v1, workspace, manualCode, libraries and dependencies. Libraries are portable source snapshots; dependency groups refer to installed file paths. Preserve .pyblocks.json and the JSON project format. Add an optional extension snapshot list for new editors; old projects without it must still load.

Proposed record: extensions: [{ descriptor, source: { kind, url? } }]. descriptor is the full validated JSON, not merely a URL. Source is informational; remote URL is optional for a local snapshot. Resolve relative references at initial import, and store enough provenance to reproduce a deliberate update. Opening, exporting or uploading must not automatically refetch or upgrade extension definitions.

The descriptor's dependency requirements and the project's installed dependency groups are different things. For V1 reuse existing supported sources (MicroPython index, curated packages, local source imports) and exact release/file references where possible. A provisional requirement can be { "source": "micropython", "name": "package-name", "version": "exact-version" }; check actual importer capabilities before accepting a source. Do not invent recursive dependency resolution. Local dependencies can be manually supplied and validated against required paths. Persist the installed Python source in libraries; no duplication inside the descriptor. Share files between extensions and retain dependencies on extension removal unless explicitly removed after checking remaining references.

Update createProject, parseProject, editor and manager import/export, duplicate, autosave and validation CLI together so the optional field is not silently discarded. Existing editors reconstruct known fields only and therefore cannot safely round-trip extension projects; choose a project version bump or a clear compatibility gate before shipping. Do not claim old-editor compatibility just because a new field is optional.

On opening a project: parse metadata and snapshots, validate and compile all extensions, register all definitions and generators, then deserialize the workspace and generate code. On missing/invalid extension data or unknown block types, preserve the original serialized state and offer recovery/export; never silently delete blocks or overwrite the project with an empty workspace. Apply the same rules to project import and headless validation. Backpack/snippets may reference extension block types; diagnose missing extensions rather than auto-install unknown code.

UI and lifecycle

Keep an Extensions entry beside Libraries in the toolbox's existing panel style. Show installed id/name/version/source, import from file or URL, and explicit remove/update. The new extension's toolbox categories appear after registration. No connected board is required. A separate marketplace is not necessary.

If an extension is used in a workspace, block removal until affected blocks are removed or explicitly migrated. Same id/version with identical content is idempotent; different content at the same version is a conflict. No automatic upgrade or replacement. Stable IDs matter more than display names. Updates must verify existing saved block compatibility; defer general block migration until concrete need.

Treat JSON, toolbox labels and Python templates as untrusted. No remote script execution, HTML injection, credentials in fetch, or arbitrary extension/mutator hooks. Validate type and resource limits and reject unsafe object keys/prototype pollution. Show provenance of third-party Python; only explicit Upload and run executes it on hardware. The descriptor cannot silently connect to a device, install firmware, or upload anything.

Integration and validation plan

Current touchpoints: src/blocks/index.js imports native implementations, src/editor/toolbox.js creates the toolbox, src/editor/app.js applies project serialization and generation, src/project/storage.js validates project JSON, src/project/libraries.js validates runtime file groups. Reuse those interfaces. Suggested initial bridge location: src/extensions/bridge.js, with schema validation alongside it; keep host loading/persistence outside the bridge. File names are proposals, not a mandatory new module hierarchy.

Case Capability to validate
ADC, timing, GPIO imports, functions, expression/statement distinction, defaults
PWM, servo, buzzer object variables, methods, keyword parameters, finite dropdown mappings, helpers
I2C/SPI/UART, display nested expressions, constants, multiple parameters and runtime libraries
Wi-Fi/MQTT/HTTP shared imports/helpers, dependency ownership, returned objects
SPIKE await, context validation, runloop constraints
Loops and exceptions nested statement suites, indentation and empty bodies
Functions and events names, scope, cross-block state, deferred definitions and dynamic flyouts
Variables and mutators workspace-dependent interactions; identify native fallback needs

Compare generated Python with existing behavior (not necessarily whitespace-identical), verify serialization round-trip, safe names, no duplicated imports, deterministic generation, headless and browser registration, toolbox shadows and reloading, multiple projects, conflict rejection, remove/update, offline reopen, missing extensions, failed fetch/CORS, invalid templates, and blocked untrusted JS. Test deployment with the existing library mechanism and physical devices separately. Measure coverage by actual block types and capabilities, not by category count.

Phase 1: compile minimal static rules, demonstrate one built-in-like extension and one external Python-backed extension end to end. Phase 2: portable project snapshots, loading UI, lifecycle and dependency integration; verify offline and headless use. Phase 3: progressively migrate representative native API blocks and expand templates based on evidence. Phase 4: decide whether trusted native contributions and a separate reusable bridge package are justified. Keep existing built-ins working throughout; no mass rewrite.

Non-goals and open questions

No ZIP project conversion, marketplace, arbitrary JS evaluation, Python package solver, remote native modules, new Blockly renderer, general programming DSL or forced migration of all built-ins in the first iteration. No compatibility claims before testing.

Provisional decisions to validate: placeholder syntax and precedence handling, exact dependency reference shape, localization, optional toolbox placement, registry lifetime, schema/project version gate, helper and async semantics. The acceptance direction is universal toolbox contribution registration with maximal practical declarative coverage, not JSON expressiveness at any cost.