Skip to content

Rules editor: imports typed against the controller's module files (ES modules) - #1220

Draft
evgeny-boger wants to merge 3 commits into
rules-editor-typescriptfrom
rules-editor-esm
Draft

Rules editor: imports typed against the controller's module files (ES modules)#1220
evgeny-boger wants to merge 3 commits into
rules-editor-typescriptfrom
rules-editor-esm

Conversation

@evgeny-boger

@evgeny-boger evgeny-boger commented Aug 28, 2026

Copy link
Copy Markdown
Member

Что происходит; кому и зачем нужно:
В шаблоны MR и MRWM добавлена опция "Установить выход согласно состоянию входа" для "Действий в безопасном режиме".


Что поменялось для пользователей:
См выше


Как проверял/а:
Запускал шаблон на MR6C v2.


Дополнение: привязка опции к версии прошивки

Опция появилась в прошивке 1.27.0 wb-mr (WB-MR3, WB-MR6C, WB-MR6C/NC, WB-MR6C v.3, WB-MRM2-mini) и 1.26.0 wb-mrwm (WB-MRWM2). Старая прошивка отвергает значение 2 своим валидатором: запись проходит без ошибки Modbus, но регистр остаётся прежним — то есть без привязки к прошивке пользователь выбирал бы вариант, который молча ничего не делает.

Поэтому вместо безусловного расширения enum использованы fw-варианты (wb-mqtt-serial 2.269.0, #1243):

  • параметр out<N>_safety_behaviour объявлен дважды — базовое объявление с enum: [0, 1] и объявление с fw прошивки и enum: [0, 1, 2];
  • примечание про «применим только для режима "Переключатель с фиксацией"» — описание fw-варианта группы, поэтому показывается один раз над группой и только на поддерживающей прошивке (раньше описание группы показывалось всегда). Группа объявляется дважды целиком, как и сам параметр рядом: действующий вариант используется целиком, а id, group и order берутся из первого объявления. Выбор варианта группы по версии прошивки добавлен в Show a device template group description by the device firmware #1242, отсюда Breaks: wb-mqtt-homeui (<< 2.255.0~~);
  • parameters в семи шаблонах переведены в массив: в объектной форме два объявления одного id невозможны. Отрендеренные параметры при этом не изменились, меняется только порядок записи параметров в устройство — по порядку шаблона вместо алфавитного;
  • в шаблоне WB-MRM2-mini-NC выходные параметры объявлялись по разу на каждый вход (цикл был вложен в цикл по входам): в объектной форме дубли молча перетирались, в массиве стали бы дублями id. Исправлено отдельным коммитом.

Проверка на стенде (WB-MR6C slave 62, драйвер 2.272.0, homeui из #1242): все семь шаблонов проходят валидацию драйвера, device/Load отдаёт по одному регистру на параметр, запись значения 2 на 1.27.0 доезжает до регистра, на 1.26.5 — нет. В интерфейсе на 1.26.5 нет ни опции, ни примечания; после обновления на 1.27.0 появляются оба.


ИИ: раздел «Дополнение» и правки к нему подготовил ИИ-агент. Разделы выше — текст автора PR.
Модель: claude-opus-5[1m] · Harness: Claude Code CLI 2.1.263
Запустил и отвечает за содержимое: @pgasheev

wb-rules now runs rule files with import/export as ES modules. The
editor's language service knew nothing about the imported files, so every
import fell to the `declare module "*"` wildcard: everything any, a type
import an error, no completions for a module's exports.

The service now resolves a rule's import specifiers through the engine's
own resolution (the new Editor.ResolveModule RPC: relative next to the
file, bare in the module directories, absolute as is), fetches the module
sources transitively (bounded: 50 files, depth 8, 5 s) and places them in
the virtual FS where TypeScript resolves them - relative ones next to the
rule's path, bare ones under /wb-rules-modules mapped by a paths wildcard.
An import added while typing is fetched (debounced) and the lint pass
re-run when it lands, through the lint refresher. Compiler options follow
the engine: module "preserve", allowImportingTsExtensions. Firmware without
the RPC keeps the previous behaviour.

module-resolution.ts: specifier scan, placement, transitive prefetch
(createImportSet); import-refresh.ts: the view plugin; editor-proxy:
ResolveModule; the edit page passes the resolver when the method is
advertised; wb-rules.d.ts re-synced (ImportMeta); changelog.

Tests: module-resolution (scan, placement, bounded prefetch, failure),
ts-language-service-imports (bare import typed including a type import,
relative .ts import, a module's own relative import followed,
unresolvable stays any, refreshImports after an edit); the page test's
expected loadTsEditorSupport arguments gain the resolver.
From a from-scratch review of the import typing:
- a comment inside a multi-line import clause hid the import from the
  specifier scan (a quote or `;` in it broke the clause regex): comments are
  blanked before the scan, which also stops commented-out imports from
  costing a lookup; specifiers come back in document order;
- a reused environment fetched a rule's new imports but never re-linted:
  the reuse path no longer pre-consumes the refresh, the view's refresh
  plugin (which re-lints) does it;
- the ResolveModule advertisement check no longer gates the language
  service (a negative answer takes the full advertisement timeout - 3 s on
  today's firmware): it is folded into the resolver, so only a file with
  imports pays it, bounded by the prefetch deadline;
- the prefetch deadline is a real wall-clock bound: each resolver call is
  raced against what is left of it, so a hung controller cannot hold the
  editor; a malformed reply (no absolute path) is treated as unresolved;
- an import cycle back to the rule never replaces the edited buffer with
  the on-disk copy.
Tests: import-refresh view plugin (creation run, debounced edit, re-lint
on arrival, disabled, destroyed mid-flight), the page-level ResolveModule
gate, comment cases, document order, deadline, malformed replies, the
cycle guard, an unresolvable relative import.
The engine now loads .mjs/.mts (ES modules by name) and .cjs/.cts (classic
scripts by name) next to .js/.ts. The editor treats them as rule files:
TypeScript language mode for .mts/.cts, rename and copy keep the file's
own extension instead of collapsing it to .js/.ts.
@codacy-production

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 95 complexity · 0 duplication

Metric Results
Complexity 95
Duplication 0

View in Codacy

NEW Get contextual insights on your PRs based on Codacy's metrics, along with PR and Jira context, without leaving GitHub. Enable AI reviewer
TIP This summary will be updated as you push new changes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant