interpreter

package
v0.0.0-...-5365fac Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 23, 2026 License: MIT Imports: 55 Imported by: 0

Documentation

Index

Constants

View Source
const (
	MatchStatusNone     = "НеНайдено"
	MatchStatusOne      = "НайденаОдна"
	MatchStatusMultiple = "НайденоНесколько"
)

Статусы safe-match API (ПроверитьСовпадениеПоРеквизиту): кладутся в поле Статус результата, чтобы прикладной код мог явно различать create/update/conflict.

View Source
const (
	MaxEmailRecipientBytes        = 512
	MaxEmailSubjectBytes          = 256
	MaxEmailBodyBytes             = 16 << 20
	MaxEmailAttachmentBytes       = 25 << 20
	MaxEmailAttachmentsTotalBytes = 50 << 20
	MaxEmailAttachmentCount       = 20
	MaxEmailAttachmentNameBytes   = 255
)
View Source
const (
	MaxUntrustedExpressionBytes       = 128 << 10
	MaxUntrustedExpressionTokens      = 1024
	MaxUntrustedExpressionSyntaxDepth = 128
)

These limits keep recursive expression parsing bounded for text supplied at runtime. They are exported so API/UI validation and report formulas can use exactly the same pre-parse gate as the interpreter.

Variables

View Source
var ErrDivisionByZero = errors.New("деление на ноль")

ErrDivisionByZero помечает ошибку деления на ноль. Доступна через errors.Is(err, ErrDivisionByZero) по цепочке DSLError.Unwrap. Нужна, чтобы контексты, где деление на ноль — это «неопределённое значение» (компоновка отчётов: пустая ячейка, как в 1С), отличали его от настоящих runtime-ошибок; при этом обычное исполнение DSL по-прежнему возбуждает явную ошибку.

View Source
var ErrRowAccessDenied = errors.New("доступ к данным запрещён правами текущего пользователя")

ErrRowAccessDenied — отказ прав доступа к данным. Текст читает пользователь: он всплывает в интерфейсе как результат обработки, и «row access denied» говорило ему только то, что что-то сломалось. Сравнения идут через errors.Is по идентичности, так что формулировка ни на что не влияет.

View Source
var ErrTransactionLeftOpen = errors.New("DSL-обработчик оставил открытую транзакцию; она отменена")

ErrTransactionLeftOpen is returned when a DSL procedure exits successfully while still owning a transaction or savepoint. The scope is rolled back before this error is returned.

Functions

func AmountInWords

func AmountInWords(amount decimal.Decimal, currency string) string

AmountInWords форматирует денежную сумму вида «1234.56» как «Одна тысяча двести тридцать четыре рубля 56 копеек». currency: "rub" (по умолчанию) | "usd" | "eur" — для будущего расширения, сейчас только rub полностью локализован.

func BindNamedArgs

func BindNamedArgs(decl *ast.ProcedureDecl, values map[string]any) []any

BindNamedArgs связывает именованные значения (параметры обработки) с одноимёнными аргументами объявленной процедуры.

Зачем. Параметры обработки инжектировались только как переменные, а `Процедура Выполнить(ModelName = "")` объявляет СВОЙ параметр с тем же именем — он затенял инжектированный и приходил пустым. Ошибки при этом не было: обработка отрабатывала «успешно», просто со значением по умолчанию, и выглядело это как «--set не биндится» (#706). Описать параметры сигнатурой процедуры — естественная привычка (так и в 1С), поэтому ловушку правильнее убрать, а не задокументировать.

Возвращается позиционный список до последнего найденного параметра. Дыры в нём помечаются внутренним sentinel: callUserProc отличает «значение не передали» от явно переданного nil и вычисляет DSL-default только в первом случае. Это позволяет передать второй именованный параметр, не затирая default первого.

func ClampWallClock

func ClampWallClock(ctx context.Context, configured time.Duration) time.Duration

ClampWallClock согласует настроенный лимит времени с дедлайном контекста.

Общая точка для всех серверных входов DSL: сам по себе MaxWallClock не знает про дедлайн HTTP-запроса, а контекст не знает про настройку. Без согласования профиль в 30 секунд пережил бы 10-секундный запрос и продолжил бы держать открытую транзакцию уже после того, как клиент ушёл.

Возвращает 0 («без лимита»), если лимит не настроен: это осознанное значение по умолчанию, а не забытая настройка. Если дедлайн уже истёк, отдаёт минимальную положительную величину, чтобы запуск отрубился сразу, а не оказался бессрочным.

func DecimalWithinSafeBounds

func DecimalWithinSafeBounds(d decimal.Decimal) bool

DecimalWithinSafeBounds reports whether decimal operations can expand d without constructing an unbounded intermediate big.Int. Sandboxed callers that accept data from outside the DSL use the same boundary as division, remainder and numeric builtins instead of duplicating subtly different exponent/coefficient checks.

func DistributeAmount

func DistributeAmount(total float64, weights []float64, scale int) []float64

DistributeAmount распределяет total пропорционально weights, гарантируя что сумма получившихся долей строго равна total после округления до scale знаков. Накопленную ошибку округления отдаёт последней ненулевой доле — это устраняет «прилипающие копейки» на остатках списанных партий (

DistributeAmount(100, []float64{1, 2, 3}, 2) → [16.67, 33.33, 50.00]

При нулевой total или сумме весов == 0 возвращает массив нулей той же длины.

func FinishTxExecution

func FinishTxExecution(state *TxState, runErr error) error

FinishTxExecution closes every transaction/savepoint still owned by state. Cleanup keeps transaction values but is detached from execution cancellation and independently bounded, so timeout/error paths cannot strand a pool connection or a borrowed savepoint.

func FormatUserError

func FormatUserError(err error) string

FormatUserError отдаёт пользовательский текст бизнес-ошибки DSL. Для *DSLError — только Msg; иначе err.Error().

func InjectMaket

func InjectMaket(vars map[string]any, lt *printform.LayoutTemplate)

InjectMaket adds the «Макет» DSL variable to vars when a layout template is present. With a nil layout it is a no-op (the variable is not added, so DSL without a макет behaves exactly as before). Used by all processor run paths (UI, CLI procrun, scheduler) to expose src/<имя>.proc.layout.yaml as Макет.

func JSONValueToDSL

func JSONValueToDSL(v any) any

JSONValueToDSL рекурсивно превращает разобранное JSON-значение (map[string]any/ []any/скаляры из encoding/json) в DSL-значение (*Map/*Array/скаляры) — то же, что получает DSL из ПрочитатьJSON. Экспортировано для приёмки (план 90): конверт события отдаётся обработчику как привычный *Map.

func KnownBuiltinNames

func KnownBuiltinNames() map[string]struct{}

KnownBuiltinNames returns a set of all known callable names (lowercase): platform builtins + runtime-injected functions (HTTP, Email, Tx и т.п.). Used by the syntax checker to validate function calls in modules.

Имена из фабрик (NewHTTPFunctions, NewEmailFunctions, NewTxFunctions, ...) собираются автоматически — добавил builtin в фабрику → имя сразу появилось в чек-листе синтаксиса без правок здесь. Ключи с префиксом `__factory_` (это служебные конструкторы для СоздатьОбъект, не пользовательские функции) исключаются.

Имена, инжектируемые напрямую через buildDSLVars / контекст интерпретатора (Сообщить, ОписаниеОшибки, ТекущийПользователь и т.п.), пока перечислены явно — у них нет общей фабрики. После выделения dslvars в отдельный пакет этот список можно будет заменить на dslvars.Names().

func MarshalDSLValue

func MarshalDSLValue(v any) ([]byte, error)

MarshalDSLValue сериализует произвольное DSL-значение (Структура/Соответствие/ Массив/число/строка/…) в JSON. Используется роутером, когда обработчик вернул «голое» значение вместо HTTPСервисОтвет — тогда оно отдаётся как JSON 200.

func MatchValueString

func MatchValueString(raw any) string

MatchValueString приводит DSL-значение к строке для поиска по реквизиту: у ссылки берётся наименование, числа форматируются без экспоненты (как Строка()). Экспортируется для пути Документы.X в пакете ui.

func NewChartFunctions

func NewChartFunctions() map[string]any

func NewEmailFunctions

func NewEmailFunctions(sender EmailSender, guard NetGuard, resolvers ...EmailFileResolver) map[string]any

NewEmailFunctions returns DSL functions/factories to inject into extraVars. If sender is nil or not configured, functions panic with a user-friendly message.

func NewEquipmentFunctions

func NewEquipmentFunctions() map[string]any

NewEquipmentFunctions возвращает функции и фабрики подключаемого оборудования для инъекции в extraVars интерпретатора (аналогично NewHTTPFunctions).

func NewExecFunctions

func NewExecFunctions(guard ExecGuard, audit ExecAudit, ctxSources ...CtxSource) map[string]any

NewExecFunctions возвращает builtin ВыполнитьКоманду с привязанными guard'ом и (необязательным) аудитом. guard=deny используется песочницей для запрета (см. SandboxProfile.Vars).

func NewFileFunctions

func NewFileFunctions(guard FileGuard) map[string]any

func NewHTMLTemplateObject

func NewHTMLTemplateObject(args []any) any

NewHTMLTemplateObject — конструктор «Новый ШаблонHTML(Текст)».

func NewHTTPFunctions

func NewHTTPFunctions(guard NetGuard, ctxSources ...CtxSource) map[string]any

NewHTTPFunctions returns factories and shorthands to inject into DSL extraVars. guard (может быть nil) проверяется в момент сетевого вызова — предохранитель сети читается свежим, переключение в конфигураторе действует без перезапуска.

func NewLLMFunctions

func NewLLMFunctions(ai AIAssistant) map[string]any

NewLLMFunctions возвращает DSL-функции ИИ-помощника для инъекции в extraVars. При ai == nil (или не настроенном помощнике) функции дают понятную ошибку.

func NewNotifyFunctions

func NewNotifyFunctions(n Notifier) map[string]any

NewNotifyFunctions возвращает DSL-функции публикации уведомлений (ОтправитьУведомление / PublishNotification). Если n == nil — функции остаются тихим no-op (фоновые задания, тесты, не подключённая шина), поэтому конфигурация с вызовом не падает там, где push недоступен.

func NewQueryFactory

func NewQueryFactory(ctx context.Context, db QueryDB, reg QueryRegistry) func(args []any) any

NewQueryProxy создаёт фабрику для инъекции через extraVars. Использование: extraVars["__factory_Запрос"] = interpreter.NewQueryFactory(ctx, db, reg)

func NewQueryFactoryGuarded

func NewQueryFactoryGuarded(ctx context.Context, db QueryDB, reg QueryRegistry, compiler QueryCompiler, guard QueryGuard) func(args []any) any

NewQueryFactoryGuarded additionally attaches a host guard over the result rows — UI uses it for field-level masking (план 88E), so a processing cannot read protected values that the same user would only see masked in a report.

func NewQueryFactoryWithCompiler

func NewQueryFactoryWithCompiler(ctx context.Context, db QueryDB, reg QueryRegistry, compiler QueryCompiler) func(args []any) any

NewQueryFactoryWithCompiler creates a query factory that delegates compilation to the host runtime. UI uses this to inject row-level access filters; callers that pass nil keep the legacy direct query.Compile behavior.

func NewRegexObject

func NewRegexObject(args []any) any

NewRegexObject — конструктор «Новый Регекс(Шаблон[, Флаги])».

func NewServiceFunctions

func NewServiceFunctions() map[string]any

NewServiceFunctions возвращает фабрики и short-hand'ы для инжекта в DSL.

func NewSpreadsheetFunctions

func NewSpreadsheetFunctions() map[string]any

NewSpreadsheetFunctions returns a map of spreadsheet-related functions and factories.

func NewTxFunctions

func NewTxFunctions(state *TxState, db TxDB) map[string]any

NewTxFunctions returns DSL builtins for transaction control. Inject the returned map into interpreter.Run via extraVars. All DSL functions that write to storage must call state.Ctx() to get the current context so they participate in the active transaction.

func RaiseUserError

func RaiseUserError(msg string)

RaiseUserError panics with a DSL user error. Предназначено для внешних пакетов (например ui), которым нужно прервать выполнение DSL из метода объекта (CallMethod) с осмысленным сообщением — оно перехватывается Run/RunWithResult и Попыткой так же, как Error().

func RaiseUserErrorWrap

func RaiseUserErrorWrap(msg string, err error)

RaiseUserErrorWrap — как RaiseUserError, но сохраняет исходную error (i18nerr) в userError.Err → DSLError.Err, чтобы i18nerr.Localize локализовал сообщение по цепочке, а не показывал русский текст не-русскому пользователю.

func ResolveSafePath

func ResolveSafePath(p string) (string, error)

safePathOrRaise возвращает безопасный путь либо прерывает выполнение DSL пользовательской ошибкой (panic userError, перехватывается Попыткой). op — имя операции для сообщения. ResolveSafePath — экспортированная обёртка resolveSafePath для файловых builtins вышестоящих слоёв (ui: вложения из DSL). Уважает ту же песочницу, что и встроенные файловые функции.

func RollbackTxExecution

func RollbackTxExecution(state *TxState)

RollbackTxExecution is a best-effort panic/early-return backstop. Normal execution paths call FinishTxExecution synchronously before continuing.

func SetFileSandbox

func SetFileSandbox(root string)

SetFileSandbox ограничивает файловые builtins каталогом root. Пустой root снимает ограничение. Включается, например, для demo-режима, где обработки исполняет недоверенный пользователь (см. cli.runServer).

func ValidateEmailMessage

func ValidateEmailMessage(to, subject, textBody, htmlBody string, files []EmailAttachment) error

ValidateEmailMessage is the shared fail-closed boundary for DSL senders and the SMTP implementation. It rejects header injection and bounds allocations before MIME message construction.

func ValidateUntrustedExpressionSource

func ValidateUntrustedExpressionSource(expr string) error

ValidateUntrustedExpressionSource performs only iterative work. It must run before ParseStandaloneExpr/ParseProgram, whose recursive descent cannot consult a sandbox deadline while parsing deeply nested input.

Types

type AIAssistant

type AIAssistant interface {
	Ask(req AIRequest) (string, error)
	Configured() bool
}

AIAssistant — минимальный интерфейс ИИ-помощника для DSL-функций. Конкретная реализация (поверх internal/llm) строится в слое обвязки из конфига базы, так что пакет interpreter не зависит от llm/storage.

type AIRequest

type AIRequest struct {
	Task        string // профиль маршрутизации: "анализ" | "документы" | ...
	System      string // системная инструкция
	Prompt      string // пользовательский промпт
	JSON        bool   // запросить строгий JSON
	Temperature float64
	ImageB64    string // base64 изображения/PDF (для vision)
	MimeType    string
}

AIRequest — запрос к ИИ-помощнику из DSL. Если ImageB64 непуст, это мультимодальный (vision) запрос распознавания.

type AccessChecker

type AccessChecker interface {
	// RoleAllows — матрица операций (план 112): разрешает ли роль op над (вид,объект).
	RoleAllows(roleName, kind, entity, op string) (allowed bool, err error)
	// FieldMask — полевой доступ (план 88): применяет маскирование поля при чтении.
	// hasPolicy=true, если поле маскируется/скрывается; masked — результат маски
	// на value (для точной проверки МаскаПоля).
	FieldMask(roleName, kind, entity, field string, value any) (masked any, hasPolicy bool, err error)
	// RowRestriction — строковый доступ (план 79): "denied" | "unrestricted" |
	// "restricted" для чтения/записи роли над объектом.
	RowRestriction(roleName, kind, entity, op string) (state string, err error)
}

AccessChecker резолвит права роли для ассертов доступа. Инжектится раннером тестов (слой ui), чтобы ядро интерпретатора не зависело от пакетов auth/access. Вид/операция — пользовательские слова, реализация их нормализует. Ошибки (неизвестная роль/вид/объект) — чтобы ассерт провалился громко, а не молча.

type AreaParameters

type AreaParameters struct {
	// contains filtered or unexported fields
}

AreaParameters provides dot-notation access to area cell values (R1C1, R1C2, etc.) Used when DSL code accesses Обл.Параметры.R1C1 = "value".

func (*AreaParameters) CallMethod

func (p *AreaParameters) CallMethod(name string, args []any) any

func (*AreaParameters) Get

func (p *AreaParameters) Get(field string) any

func (*AreaParameters) Set

func (p *AreaParameters) Set(field string, v any)

type Array

type Array struct {
	// contains filtered or unexported fields
}

func NewArray

func NewArray(items []any) *Array

NewArray создаёт Массив из готового среза значений. Нужен внешним пакетам (ui), которым требуется вернуть в DSL коллекцию с методами Количество()/ Получить()/итерацией — items не экспортируется.

func (*Array) CallMethod

func (a *Array) CallMethod(name string, args []any) any

func (*Array) Index

func (a *Array) Index(i int) any

func (*Array) Iterate

func (a *Array) Iterate() []any

func (*Array) SetIndex

func (a *Array) SetIndex(i int, val any)

func (*Array) String

func (a *Array) String() string

func (*Array) TypeName

func (a *Array) TypeName() string

type AssertOutcome

type AssertOutcome struct {
	Passed bool
	Desc   string // описание проверки (последний строковый аргумент)
	Detail string // деталь расхождения для отчёта (пусто, если прошла)
}

AssertOutcome — результат одной проверки Утверждать.*.

type AssertRecorder

type AssertRecorder interface {
	RecordAssert(o AssertOutcome)
}

AssertRecorder принимает результаты проверок из объекта Утверждать. Реализуется раннером тестов.

type AssertRoot

type AssertRoot struct {
	// contains filtered or unexported fields
}

AssertRoot — корневой DSL-объект Утверждать.

func NewAssertRoot

func NewAssertRoot(rec AssertRecorder) *AssertRoot

NewAssertRoot создаёт объект для инжекции как DSL-переменную «Утверждать».

func (*AssertRoot) CallMethod

func (a *AssertRoot) CallMethod(method string, args []any) any

func (*AssertRoot) Get

func (a *AssertRoot) Get(string) any

This: у объекта нет доступных членов, только методы. Get/Set — безопасные no-op.

func (*AssertRoot) Set

func (a *AssertRoot) Set(string, any)

func (*AssertRoot) SetAccessChecker

func (a *AssertRoot) SetAccessChecker(rc AccessChecker)

SetAccessChecker включает ассерты доступа (РольМожет/ПолеМаскируется/ СтрокиОграничены и т.п.), подставляя резолвер прав.

type BuiltinFunc

type BuiltinFunc func(args []any, file string, line int) (any, error)

BuiltinFunc is a callable value that can be injected via extraVars (e.g. Сообщить).

func NewNStrFunc

func NewNStrFunc(defaultLang string) BuiltinFunc

NewNStrFunc возвращает НСтр(ИсходнаяСтрока[, КодЯзыка]) — выбор локализованной строки формата "ru = 'Привет'; en = 'Hello'". Если явный КодЯзыка не передан, используется defaultLang; если язык не найден среди сегментов — возвращается первый сегмент. UI-слой (internal/ui) инжектирует НСтр с языком текущего пользователя, чтобы НСтр без кода переводил на язык интерфейса (план 66, п.3); глобальная версия остаётся на "ru".

type CatalogDeleter

type CatalogDeleter interface {
	DeleteCatalogRef(ctx context.Context, entity *metadata.Entity, id uuid.UUID) error
}

CatalogDeleter — хост-путь физического удаления справочника. Подключается ui-слоем и ведёт в entityservice.Delete: хуки ПередУдалением/ПослеУдаления, проверка ссылок (CheckRefs), снятие строк ТЧ и регистрация в планах обмена — те же гарантии, что у удаления из UI и REST. Прямого db.Delete у DSL-пути нет намеренно (у CatalogsDB и метода-то такого нет): «свой» способ удаления обходил бы запреты, написанные в конфигурации, — ровно тот класс дефекта, который ловит delete_chokepoint_test.

type CatalogObjectFactory

type CatalogObjectFactory interface {
	NewCatalogObject(entity *metadata.Entity) any
	LoadCatalogObject(entity *metadata.Entity, uuidStr string) (any, error)
}

CatalogsRoot is the DSL global Справочники / Catalogs. CatalogObjectFactory — необязательная фабрика объектных обёрток справочника. Позволяет вышестоящему слою (ui) подменить объекты, возвращаемые Справочники.X.Создать() и Ссылка.ПолучитьОбъект(), на полнофункциональные — с табличными частями и DSL-хуком ПриЗаписи (как у документов). Без фабрики используется встроенный CatalogRecordWriter (только поля шапки).

type CatalogProxy

type CatalogProxy struct {
	// contains filtered or unexported fields
}

CatalogProxy resolves predefined items, runtime lookups, and record creation.

Справочники.ТипЦен.Закупочная                  → *Ref to predefined item
Справочники.ТипЦен.НайтиПоНаименованию("X")     → *Ref or nil
Справочники.Контрагент.Создать()                → *CatalogRecordWriter

func NewCatalogProxy

func NewCatalogProxy(entity *metadata.Entity, db CatalogsDB, ctxSrc CtxSource) *CatalogProxy

NewCatalogProxy создаёт менеджера справочника для привязки к ссылкам, приходящим из БД (см. enrichHeaderRefs/enrichTPRowsWithRefs в ui). Так Ссылка.Удалить()/ПолучитьОбъект() работают на ссылках реквизитов шапки/ТЧ, а не только на ссылках, созданных через Справочники.X.НайтиПо…

func (*CatalogProxy) CallMethod

func (p *CatalogProxy) CallMethod(method string, args []any) any

CallMethod implements MethodCallable for method-style invocation.

func (*CatalogProxy) DeleteRef

func (p *CatalogProxy) DeleteRef(uuidStr string) error

DeleteRef реализует RefManager — удаление записи справочника по UUID. Физическое удаление делает хост-делетер (entityservice.Delete): там хуки «ПередУдалением»/«ПослеУдаления», проверка ссылок, строки ТЧ и регистрация в планах обмена — тот же путь, что у UI, REST и Документы.X.Удалить(). Раньше здесь стоял прямой db.Delete, и DSL-удаление справочника обходило и хуки (#750 обещал «на всех путях»), и CheckRefs (#774/#801).

func (*CatalogProxy) Get

func (p *CatalogProxy) Get(itemName string) any

Get is called for foo.Bar attribute access — predefined item lookup.

func (*CatalogProxy) LoadObject

func (p *CatalogProxy) LoadObject(uuidStr string) (any, error)

LoadObject реализует RefManager — загружает существующую запись справочника по UUID и возвращает CatalogRecordWriter с предзаполненными полями, так что Ссылка.ПолучитьОбъект().Поле = … → Записать() обновит запись по тому же id. При подключённой фабрике объект строит она (с табличными частями и хуками).

func (*CatalogProxy) Set

func (p *CatalogProxy) Set(_ string, _ any)

func (*CatalogProxy) WithDeleter

func (p *CatalogProxy) WithDeleter(d CatalogDeleter) *CatalogProxy

WithDeleter подключает хост-путь удаления (entityservice) к standalone-прокси. Для цепочки.

func (*CatalogProxy) WithExchangeRegistrar

func (p *CatalogProxy) WithExchangeRegistrar(reg ExchangeRegistrar) *CatalogProxy

WithExchangeRegistrar подключает регистрацию изменений в планах обмена к standalone-прокси (обычно менеджеру ссылки на справочник). Для цепочки.

func (*CatalogProxy) WithFieldSearchChecker

func (p *CatalogProxy) WithFieldSearchChecker(c FieldSearchChecker) *CatalogProxy

WithFieldSearchChecker подключает полевую политику к поиску по реквизиту у standalone-прокси. Для цепочки.

func (*CatalogProxy) WithObjectFactory

func (p *CatalogProxy) WithObjectFactory(f CatalogObjectFactory) *CatalogProxy

WithObjectFactory подключает фабрику объектных обёрток к standalone-прокси (менеджеру ссылки). Для цепочки.

func (*CatalogProxy) WithRowAccessChecker

func (p *CatalogProxy) WithRowAccessChecker(c RowAccessChecker) *CatalogProxy

WithRowAccessChecker attaches host row-level access checks to a standalone catalog proxy, usually one used as a Ref manager for values loaded from DB.

type CatalogRecordWriter

type CatalogRecordWriter struct {
	// contains filtered or unexported fields
}

CatalogRecordWriter — записываемый объект справочника/документа, созданный через Справочники.X.Создать().

Зап = Справочники.Контрагент.Создать();
Зап.Наименование = "ООО Ромашка";
Зап.ИНН = "7701234567";
Ссыл = Зап.Записать();   // → *Ref на записанную запись

func (*CatalogRecordWriter) CallMethod

func (w *CatalogRecordWriter) CallMethod(method string, args []any) any

CallMethod — Записать() / УстановитьЗначение().

func (*CatalogRecordWriter) Fields

func (w *CatalogRecordWriter) Fields() []string

Fields — имена заполненных полей объекта. Позволяет использовать объект как источник в ЗаполнитьЗначенияСвойств(Приёмник, Объект).

func (*CatalogRecordWriter) Get

func (w *CatalogRecordWriter) Get(name string) any

Get — чтение установленного значения поля (case-insensitive).

func (*CatalogRecordWriter) Set

func (w *CatalogRecordWriter) Set(name string, v any)

Set — установка значения поля (Зап.Поле = значение).

type CatalogsDB

type CatalogsDB interface {
	PredefinedDB
	FindCatalogByField(ctx context.Context, entity *metadata.Entity, fieldName, value string) (idStr, display string, ok bool, err error)
	ListCatalogMatchesByField(ctx context.Context, entity *metadata.Entity, fieldName, value string) (ids, displays []string, err error)
	// MatchCatalogByField — safe-match: количество совпадений и (при ровно
	// одном) id/представление найденной записи.
	MatchCatalogByField(ctx context.Context, entity *metadata.Entity, fieldName, value string) (idStr, display string, count int, err error)
	// WriteCatalogRecord upserts a record. idStr пустой →
	// генерируется новый UUID. Возвращает UUID записанной записи.
	WriteCatalogRecord(ctx context.Context, entity *metadata.Entity, idStr string, fields map[string]any) (string, error)
	// GetByID загружает запись по UUID. Возвращает поля шапки (включая
	// id, _version, deletion_mark и т.д.). Используется Ссылка.ПолучитьОбъект()
	// для редактирования существующих записей справочников.
	GetByID(ctx context.Context, entityName string, id uuid.UUID, entity *metadata.Entity) (map[string]any, error)
}

CatalogsDB extends PredefinedDB with field-based lookups and writes. Returns ("", "", false, nil) on not-found so the DSL can compare against nil.

type CatalogsRoot

type CatalogsRoot struct {
	// contains filtered or unexported fields
}

func NewCatalogsRoot

func NewCatalogsRoot(ctxSrc CtxSource, db CatalogsDB, lookup EntityLookup) *CatalogsRoot

NewCatalogsRoot creates the root object for injection as DSL extraVar. ctxSrc — источник живого контекста (staticCtx или *TxState).

func (*CatalogsRoot) Get

func (r *CatalogsRoot) Get(entityName string) any

func (*CatalogsRoot) Set

func (r *CatalogsRoot) Set(_ string, _ any)

func (*CatalogsRoot) WithDeleter

func (r *CatalogsRoot) WithDeleter(d CatalogDeleter) *CatalogsRoot

WithDeleter подключает хост-путь удаления (entityservice). Возвращает себя для цепочки. Без делетера Удалить()/Ссылка.Удалить() отказывает fail-closed.

func (*CatalogsRoot) WithExchangeRegistrar

func (r *CatalogsRoot) WithExchangeRegistrar(reg ExchangeRegistrar) *CatalogsRoot

WithExchangeRegistrar подключает регистрацию изменений в планах обмена для прямых записей справочников из DSL. Возвращает себя для цепочки.

func (*CatalogsRoot) WithFieldSearchChecker

func (r *CatalogsRoot) WithFieldSearchChecker(c FieldSearchChecker) *CatalogsRoot

WithFieldSearchChecker подключает полевую политику к поиску по реквизиту (НайтиПоРеквизиту/НайтиПоНаименованию/НайтиПоКоду/ПроверитьСовпадение…). Возвращает себя для цепочки.

func (*CatalogsRoot) WithManagerCaller

func (r *CatalogsRoot) WithManagerCaller(c ManagerCaller) *CatalogsRoot

WithManagerCaller подключает обработчик пользовательских методов модуля менеджера. Возвращает себя для цепочки.

func (*CatalogsRoot) WithObjectFactory

func (r *CatalogsRoot) WithObjectFactory(f CatalogObjectFactory) *CatalogsRoot

WithObjectFactory подключает фабрику объектных обёрток (см. CatalogObjectFactory). Возвращает себя для цепочки.

func (*CatalogsRoot) WithRowAccessChecker

func (r *CatalogsRoot) WithRowAccessChecker(c RowAccessChecker) *CatalogsRoot

WithRowAccessChecker attaches host row-level access checks to all catalog proxies created from this root.

type Chart

type Chart struct {
	// contains filtered or unexported fields
}

Chart is the main DSL chart object: Новый Диаграмма

func NewChart

func NewChart() *Chart

func (*Chart) CallMethod

func (c *Chart) CallMethod(method string, args []any) any

func (*Chart) Get

func (c *Chart) Get(name string) any

func (*Chart) Set

func (c *Chart) Set(name string, v any)

func (*Chart) ToEChartsOption

func (c *Chart) ToEChartsOption() map[string]any

ToEChartsOption builds the ECharts option map for JSON serialization.

type ChartPoint

type ChartPoint struct {
	// contains filtered or unexported fields
}

func (*ChartPoint) CallMethod

func (p *ChartPoint) CallMethod(method string, args []any) any

func (*ChartPoint) Get

func (p *ChartPoint) Get(name string) any

func (*ChartPoint) Set

func (p *ChartPoint) Set(name string, v any)

type ChartPointsCollection

type ChartPointsCollection struct {
	// contains filtered or unexported fields
}

func (*ChartPointsCollection) CallMethod

func (c *ChartPointsCollection) CallMethod(method string, args []any) any

func (*ChartPointsCollection) Get

func (c *ChartPointsCollection) Get(name string) any

func (*ChartPointsCollection) Set

func (c *ChartPointsCollection) Set(name string, v any)

type ChartSeries

type ChartSeries struct {
	// contains filtered or unexported fields
}

func (*ChartSeries) CallMethod

func (s *ChartSeries) CallMethod(method string, args []any) any

func (*ChartSeries) Get

func (s *ChartSeries) Get(name string) any

func (*ChartSeries) Set

func (s *ChartSeries) Set(name string, v any)

type ChartSeriesCollection

type ChartSeriesCollection struct {
	// contains filtered or unexported fields
}

func (*ChartSeriesCollection) CallMethod

func (c *ChartSeriesCollection) CallMethod(method string, args []any) any

func (*ChartSeriesCollection) Get

func (c *ChartSeriesCollection) Get(name string) any

func (*ChartSeriesCollection) Set

func (c *ChartSeriesCollection) Set(name string, v any)

type ClockRoot

type ClockRoot struct {
	// contains filtered or unexported fields
}

ClockRoot — DSL-объект Часы.

func (*ClockRoot) CallMethod

func (r *ClockRoot) CallMethod(method string, args []any) any

func (*ClockRoot) Get

func (r *ClockRoot) Get(string) any

func (*ClockRoot) Set

func (r *ClockRoot) Set(string, any)

type ConstantsDB

type ConstantsDB interface {
	SetConstant(ctx context.Context, name string, value any) error
}

ConstantsDB — то, что нужно объекту Константы от хранилища.

type ConstantsRoot

type ConstantsRoot struct {
	// contains filtered or unexported fields
}

ConstantsRoot — объект `Константы` в DSL.

Прежде это была обычная карта-снимок (MapThis поверх ListConstants), поэтому присваивание `Константы.Имя = Значение` меняло значение ТОЛЬКО в памяти текущего процесса: код отрабатывал без ошибки, следующее чтение в том же прогоне возвращало новое значение — и всё, в базу не уходило ничего. Ровно на этом молча не работало аварийное отключение интеграции по 401: обработка «выключить» отчитывалась об успехе, а после перезапуска константа снова была включена (#719).

Чтение по-прежнему идёт из снимка, снятого на старте прогона: константы читают часто, и лишний запрос на каждое обращение того не стоит. Запись уходит в базу сразу и обновляет снимок, поэтому в пределах прогона Get после Set видит записанное.

func NewConstantsRoot

func NewConstantsRoot(ctx context.Context, db ConstantsDB, declared []string, values map[string]any) *ConstantsRoot

NewConstantsRoot собирает объект Константы. declared — имена из конфигурации, values — снимок значений из базы.

func (*ConstantsRoot) Get

func (r *ConstantsRoot) Get(name string) any

func (*ConstantsRoot) Set

func (r *ConstantsRoot) Set(name string, v any)

Set записывает константу в базу и обновляет снимок.

Неизвестное имя — ошибка, а не тихое заведение ключа. Прежде опечатка в имени создавала запись в карте, которая жила до конца прогона и никого ни о чём не оповещала; отличить «выключил не ту константу» от «выключил не существующую» было нельзя ничем.

type CtxSource

type CtxSource interface {
	Ctx() context.Context
}

CtxSource предоставляет «живой» контекст. Для обычного запуска это статический контекст; при активной DSL-транзакции — *TxState, чей Ctx() несёт открытую транзакцию — запись справочника из обработки участвует в ней.

func NewStaticCtx

func NewStaticCtx(ctx context.Context) CtxSource

NewStaticCtx wraps a plain context as a CtxSource.

type DSLError

type DSLError struct {
	File string
	Line int
	Msg  string
	// Err — исходная ошибка (если есть), например i18nerr с ключом перевода.
	// Unwrap отдаёт её, чтобы i18nerr.Localize смог локализовать сообщение по
	// цепочке (иначе текст сплющивался бы в строку и перевод терялся).
	Err error
}

DSLError is returned by Error() built-in; stops execution and cancels Save.

func (*DSLError) Error

func (e *DSLError) Error() string

func (*DSLError) Unwrap

func (e *DSLError) Unwrap() error

func (*DSLError) UserMessage

func (e *DSLError) UserMessage() string

UserMessage — текст для пользователя (UI/REST), без пути к модулю и номера строки. Error() по-прежнему отдаёт file:line: msg для check, логов и отладчика.

type DSLPageBuilder

type DSLPageBuilder struct {
	// contains filtered or unexported fields
}

DSLPageBuilder — объект «Страница» в DSL. Реализует This (Get/Set) и MethodCallable (CallMethod).

func NewPageBuilder

func NewPageBuilder() *DSLPageBuilder

NewPageBuilder создаёт пустой построитель страницы (для UI-роутера).

func (*DSLPageBuilder) Blocks

func (b *DSLPageBuilder) Blocks() []PageBlock

Blocks возвращает собранные блоки в порядке добавления (для рендера).

func (*DSLPageBuilder) CallMethod

func (b *DSLPageBuilder) CallMethod(name string, args []any) any

func (*DSLPageBuilder) Get

func (b *DSLPageBuilder) Get(string) any

func (*DSLPageBuilder) Set

func (b *DSLPageBuilder) Set(string, any)

type DSLPageChart

type DSLPageChart struct {
	// contains filtered or unexported fields
}

DSLPageChart — дескриптор графика внутри построителя.

func (*DSLPageChart) CallMethod

func (c *DSLPageChart) CallMethod(name string, args []any) any

func (*DSLPageChart) Get

func (c *DSLPageChart) Get(string) any

func (*DSLPageChart) Set

func (c *DSLPageChart) Set(string, any)

type DSLPageList

type DSLPageList struct {
	// contains filtered or unexported fields
}

DSLPageList — дескриптор списка внутри построителя.

func (*DSLPageList) CallMethod

func (l *DSLPageList) CallMethod(name string, args []any) any

func (*DSLPageList) Get

func (l *DSLPageList) Get(string) any

func (*DSLPageList) Set

func (l *DSLPageList) Set(string, any)

type DSLPageRow

type DSLPageRow struct {
	// contains filtered or unexported fields
}

DSLPageRow — дескриптор строки таблицы. Ячейки адресуются по имени колонки.

func (*DSLPageRow) CallMethod

func (r *DSLPageRow) CallMethod(name string, args []any) any

func (*DSLPageRow) Get

func (r *DSLPageRow) Get(string) any

func (*DSLPageRow) Set

func (r *DSLPageRow) Set(string, any)

type DSLPageTable

type DSLPageTable struct {
	// contains filtered or unexported fields
}

DSLPageTable — дескриптор табличного блока внутри построителя. Мутирует блок по индексу, поэтому добавление других блоков позже его не ломает.

func (*DSLPageTable) CallMethod

func (t *DSLPageTable) CallMethod(name string, args []any) any

func (*DSLPageTable) Get

func (t *DSLPageTable) Get(string) any

func (*DSLPageTable) Set

func (t *DSLPageTable) Set(string, any)

type DSLServiceRequest

type DSLServiceRequest struct {
	// contains filtered or unexported fields
}

DSLServiceRequest — входящий запрос к HTTP-сервису. Экспортирован, чтобы роутер мог его сконструировать (NewServiceRequest). Реализует This (доступ к свойствам Метод/ПараметрыURL/…) и MethodCallable (ПолучитьТелоКакСтроку и т.п.).

func NewServiceRequest

func NewServiceRequest(method, rootURL, path string, pathParams map[string]string, query url.Values, headers http.Header, body []byte) *DSLServiceRequest

NewServiceRequest собирает объект запроса для передачи в DSL-обработчик.

func (*DSLServiceRequest) CallMethod

func (r *DSLServiceRequest) CallMethod(name string, args []any) any

func (*DSLServiceRequest) Get

func (r *DSLServiceRequest) Get(field string) any

func (*DSLServiceRequest) Set

func (r *DSLServiceRequest) Set(field string, val any)

type DSLServiceResponse

type DSLServiceResponse struct {
	// contains filtered or unexported fields
}

DSLServiceResponse — ответ HTTP-сервиса. Создаётся обработчиком через `Новый HTTPСервисОтвет(КодСостояния[, ТипСодержимого])` и возвращается через Возврат. Роутер читает результат экспортированными методами.

func (*DSLServiceResponse) BodyBytes

func (r *DSLServiceResponse) BodyBytes() []byte

func (*DSLServiceResponse) CallMethod

func (r *DSLServiceResponse) CallMethod(name string, args []any) any

func (*DSLServiceResponse) Get

func (r *DSLServiceResponse) Get(field string) any

func (*DSLServiceResponse) HeadersMap

func (r *DSLServiceResponse) HeadersMap() map[string]string

HeadersMap разворачивает Соответствие-заголовки в обычную карту строк.

func (*DSLServiceResponse) Set

func (r *DSLServiceResponse) Set(field string, val any)

func (*DSLServiceResponse) StatusCodeValue

func (r *DSLServiceResponse) StatusCodeValue() int

StatusCodeValue, BodyBytes, HeadersMap — экспортированные аксессоры для роутера.

type DebugHook

type DebugHook interface {
	// HookCheckBreakpoint отвечает, надо ли останавливаться на строке. cond
	// вычисляет условие точки останова в окружении текущего оператора и
	// приводит результат к булеву по правилам `Если`; хук зовёт его только
	// когда на строке есть включённая точка с непустым условием.
	HookCheckBreakpoint(file string, line int, cond func(expr string) (bool, error)) bool
	HookShouldStep(file string, stackDepth int) bool
	HookOnPause(file string, line int, vars map[string]any, evalFn func(string) (any, error), reason string)
	HookPushFrame(procedure string, line int)
	HookPopFrame()
}

DebugHook is the interface the interpreter calls for debugging. When nil on the Interpreter, there is zero overhead. Implemented by debugger.ActiveSession.

type EmailAttachment

type EmailAttachment struct {
	Name     string
	MimeType string
	Data     []byte
}

EmailAttachment — вложение письма (имя файла, MIME-тип, содержимое).

type EmailAttachmentSender

type EmailAttachmentSender interface {
	SendWithAttachments(to, subject, textBody, htmlBody string, files []EmailAttachment) error
}

EmailAttachmentSender — необязательное расширение EmailSender: отправка письма с вложениями. Реализуется mailer.Mailer; проверяется type-assertion в момент отправки, чтобы существующие реализации EmailSender (моки в тестах) не требовали доработки.

type EmailFileResolver

type EmailFileResolver func(path string) (string, error)

EmailFileResolver optionally authorizes and resolves a path before an email attachment is read. UI uses it for RLS-checked attachment-storage paths, which intentionally live outside the ordinary DSL file sandbox.

type EmailSender

type EmailSender interface {
	Send(to, subject, textBody, htmlBody string) error
	Configured() bool
}

EmailSender is the minimal interface required by email DSL functions.

type EntityLookup

type EntityLookup interface {
	GetEntity(name string) *metadata.Entity
}

EntityLookup resolves an entity name (case-insensitive) to its metadata.

type ExchangePlansRoot

type ExchangePlansRoot struct {
	// contains filtered or unexported fields
}

ExchangePlansRoot — корневой DSL-объект ПланыОбмена. Член по имени плана возвращает менеджер конкретного плана.

func NewExchangePlansRoot

func NewExchangePlansRoot(ctx context.Context, store *storage.DB, reg ExchangeRegistry) *ExchangePlansRoot

NewExchangePlansRoot создаёт объект для инъекции в extraVars как «ПланыОбмена».

func (*ExchangePlansRoot) Get

func (r *ExchangePlansRoot) Get(planName string) any

func (*ExchangePlansRoot) Set

func (r *ExchangePlansRoot) Set(_ string, _ any)

func (*ExchangePlansRoot) WithHook

WithHook подключает обработчик правила конфликта hook к загрузке пакетов из DSL (ЗагрузитьПакет). Возвращает тот же объект для цепочечной инициализации.

type ExchangeRegistrar

type ExchangeRegistrar func(ctx context.Context, entity *metadata.Entity, id uuid.UUID, deletion bool) error

ExchangeRegistrar регистрирует изменение объекта в планах обмена (план 86) после прямой записи из DSL (Справочники.X.Создать().Записать()), которая идёт мимо entityservice.Save. nil — обмен не подключён (тесты/headless). Замыкание строит host-слой (ui), где доступны store и реестр планов.

type ExchangeRegistry

type ExchangeRegistry interface {
	GetExchangePlan(name string) *metadata.ExchangePlan
	GetEntity(name string) *metadata.Entity
	GetConstantMeta(name string) *metadata.Constant
	GetInfoRegister(name string) *metadata.InfoRegister
}

ExchangeRegistry — то, что объекту ПланыОбмена нужно от реестра конфигурации. Реализуется *runtime.Registry. Методы метаданных требуются, потому что объект передаётся в exchange.BuildPackage/ApplyPackage как EntityResolver.

type ExecAudit

type ExecAudit func(command string, args []string, code int)

ExecAudit, если задан, вызывается после запуска для записи в журнал.

type ExecGuard

type ExecGuard func() error

ExecGuard вызывается перед запуском команды. nil-ошибка — запуск разрешён, иначе вызов прерывается userError (ловится Попыткой), как checkNet/checkFile.

type FallbackBuiltinFunc

type FallbackBuiltinFunc BuiltinFunc

FallbackBuiltinFunc is an injected platform function that is used only when the application does not declare a procedure with the same name. It is meant for compatibility-sensitive additions to the global DSL namespace: existing common-module and same-file procedures keep their historical meaning, while new configurations can still call the platform function directly.

type FieldSearchChecker

type FieldSearchChecker interface {
	IsFieldSearchDenied(ctx context.Context, entity *metadata.Entity, field string) bool
}

FieldSearchChecker сообщает, что поиск по реквизиту превратил бы полевую маску в оракул перебора: значения пользователь не видит, но подтверждает его по факту попадания — ровно как отбор ГДЕ в запросе, который план 88E закрывает целиком. Проверяющий подключается вышестоящим слоем (ui); nil сохраняет прежнее доверенное поведение для тестов и headless-вызовов.

type FileGuard

type FileGuard func() error

FileGuard вызывается перед каждой файловой операцией. nil → без ограничений.

type Interpreter

type Interpreter struct {
	LookupProc func(name string) *ast.ProcedureDecl
	// LookupSiblingProc resolves a helper procedure defined in the same
	// source file as the currently-executing statement. Used so that
	// `.proc.os` / `.posting.os` / `.rep.os` могут содержать вспомогательные
	// процедуры (см. Optional — может быть nil.
	LookupSiblingProc func(file, name string) *ast.ProcedureDecl
	// LookupModuleProc resolves Module.Proc() namespaced calls, например
	// `Утилиты.ФИФО(...)`. Используется когда object-часть MemberExpr —
	// идентификатор, не разрешённый в env как переменная. См.
	LookupModuleProc func(module, name string) *ast.ProcedureDecl
	// DebugSource выдаёт debug hook для очередного запуска (nil = без отладки).
	// Захватывается один раз на Run/Call/RunWithResult в execCtx запуска.
	// Устанавливается однократно при конфигурировании сервера (как LookupProc);
	// текущее включён/выключен живёт внутри источника (GlobalDebugController),
	// поэтому Interpreter после старта неизменяем и безопасен для конкурентных
	// запусков (план 52: раньше поле DebugHook мутировалось хендлерами на лету).
	DebugSource func() DebugHook
	// MaxRecursionDepth ограничивает глубину вложенных вызовов процедур/функций.
	// 0 = defaultMaxRecursionDepth. Поле (а не глобальная константа), чтобы порог
	// можно было задать per-Interpreter и понизить в тестах стража рекурсии.
	MaxRecursionDepth int
	// MaxEvalDepth ограничивает глубину вложенных Вычислить/Eval, которая не
	// увеличивает MaxRecursionDepth. 0 = defaultMaxEvalDepth.
	MaxEvalDepth int
	// StrictLexicalScope включает opt-in режим, где вызванная процедура видит
	// только свои параметры/локальные переменные и root-env запуска (extraVars,
	// factories, This), но не локальные переменные caller-процедуры.
	StrictLexicalScope bool
}

func New

func New() *Interpreter

func (*Interpreter) Call

func (i *Interpreter) Call(proc *ast.ProcedureDecl, this This, args []any, extraVars ...map[string]any) (result any, err error)

Call executes a procedure with positional arguments and captures the return value. Используется для вызова процедур модуля менеджера через Документы/Справочники.X.Method(args…) — args биндятся на proc.Params через callUserProc (включая обработку дефолтов).

func (*Interpreter) CallSandboxed

func (i *Interpreter) CallSandboxed(proc *ast.ProcedureDecl, this This, args []any, p SandboxProfile, extraVars ...map[string]any) (result any, err error)

CallSandboxed is the argument-passing counterpart of RunSandboxed. It is used for HTTP services and manager calls that need wall-clock limits but still return a value.

func (*Interpreter) EvalExpr

func (i *Interpreter) EvalExpr(expr ast.Expr, this This) any

EvalExpr evaluates a parsed AST expression and returns the result. Public for the debugger console and debug handlers.

func (*Interpreter) Run

func (i *Interpreter) Run(proc *ast.ProcedureDecl, this This, extraVars ...map[string]any) (err error)

Run executes a procedure. Optional extra vars (e.g. {"Движения": collector}) are injected into the top-level environment.

func (*Interpreter) RunSandboxed

func (i *Interpreter) RunSandboxed(proc *ast.ProcedureDecl, this This, p SandboxProfile, result *any, extraVars ...map[string]any) (err error)

RunSandboxed исполняет процедуру с ресурсными лимитами профиля (wall-clock и итерации) и запретами возможностей (сеть/файлы/ИИ). Запреты навязываются автоматически — p.Vars() становится приоритетным immutable overlay, поэтому переоткрыть известную возможность через extraVars, Перем или присваивание нельзя. Произвольный готовый capability-объект под другим именем остаётся ответственностью доверенного Go-вызывающего. Возвращаемое значение — в result.

func (*Interpreter) RunWithResult

func (i *Interpreter) RunWithResult(proc *ast.ProcedureDecl, this This, result *any, extraVars ...map[string]any) (err error)

RunWithResult executes a function procedure and captures its return value.

type KeyValue

type KeyValue struct {
	Key   any
	Value any
}

func (*KeyValue) Get

func (kv *KeyValue) Get(field string) any

func (*KeyValue) Set

func (kv *KeyValue) Set(field string, val any)

func (*KeyValue) TypeName

func (kv *KeyValue) TypeName() string

type ManagerCaller

type ManagerCaller interface {
	CallManager(entityName, method string, args []any) (result any, found bool, err error)
}

ManagerCaller — необязательный «вызыватель» процедур модуля менеджера (X.manager.os). Опционально цепляется к CatalogsRoot через WithManagerCaller — если не задан, CatalogProxy остаётся прежним.

Семантика found: процедура была найдена в модуле менеджера. Если false — proxy продолжает обработку (например, возвращает nil как раньше).

type Map

type Map struct {
	// contains filtered or unexported fields
}

func NewStringMap

func NewStringMap(src map[string]string) *Map

NewStringMap строит Соответствие (Map) из строковых пар — UI-слой передаёт им «Параметры» страницы в обработчик.

func (*Map) CallMethod

func (m *Map) CallMethod(name string, args []any) any

func (*Map) Get

func (m *Map) Get(key any) any

func (*Map) Keys

func (m *Map) Keys() []any

func (*Map) String

func (m *Map) String() string

func (*Map) TypeName

func (m *Map) TypeName() string

type MapThis

type MapThis struct{ M map[string]any }

MapThis wraps map[string]any as a This (used for tablepart rows and register movement records).

func (*MapThis) Get

func (m *MapThis) Get(name string) any

func (*MapThis) Set

func (m *MapThis) Set(name string, v any)

type MethodCallable

type MethodCallable interface {
	CallMethod(method string, args []any) any
}

MethodCallable is implemented by objects that support obj.Method(args) calls.

type MethodLister

type MethodLister interface {
	KnownMethods() (typeName string, methods []string)
}

MethodLister — необязательное дополнение к MethodCallable: объект называет свой тип и список методов, которые понимает.

Нужен потому, что CallMethod не умеет сказать «такого метода нет»: он возвращает одно значение, и «не нашёл» неотличимо от «нашёл и вернул Неопределено». Из-за этого опечатка в имени метода у ~45 реализаций оставалась бесшумной — ровно тот дефект, что закрывали в #718 для Массива, Структуры и Соответствия правкой их собственных switch'ей.

Реализовавшие интерфейс получают тот же честный отказ со списком доступных методов, что и встроенные коллекции, и остаются свободны от зависимости на этот пакет: список — это данные, а не вызов RaiseUserError.

type MockRoot

type MockRoot struct {
	// contains filtered or unexported fields
}

MockRoot — DSL-объект Мок. Его поля Email/Http/ОС/ИИ — живые массивы записей вызовов (`*Array` из `*MapThis`), поэтому в тесте работают и индексация (Мок.Email[0].Кому), и методы массива (Количество/Очистить).

func (*MockRoot) Get

func (m *MockRoot) Get(name string) any

func (*MockRoot) Set

func (m *MockRoot) Set(string, any)

type NetGuard

type NetGuard func() error

NetGuard вызывается перед каждой сетевой операцией. Возвращает ошибку, если сеть заблокирована предохранителем (план 62). nil → без ограничений.

type Notifier

type Notifier interface {
	// Publish доставляет событие по адресу target (логин | "роль:<Имя>" | "*").
	Publish(target, name string, data any)
}

Notifier публикует уведомление в real-time-шину «сервер → браузер» (план 74). Интерфейс объявлен здесь, чтобы пакет interpreter не зависел от internal/realtime; конкретную реализацию (адаптер над *realtime.Hub) инжектирует слой UI/конфигурации через dslvars.

type NumeratorRegistry

type NumeratorRegistry interface {
	GetEntity(name string) *metadata.Entity
}

NumeratorRegistry — доступ к метаданным сущности (её настройке numerator). Реализуется *runtime.Registry.

type NumeratorStore

type NumeratorStore interface {
	// GenerateNumber — ЕДИНАЯ точка выдачи номера (план 117C): период, маски
	// даты и префикс базы считаются там, а не пересобираются по месту. Пока
	// этот объект собирал номер сам, он терял префикс базы (117D): номер,
	// выданный из модуля, отличался от выданного через UI, и в разных базах
	// такие номера совпадали — ровно то, ради предотвращения чего префикс и
	// заведён.
	GenerateNumber(ctx context.Context, entity *metadata.Entity, fields map[string]any) (string, error)
	NextNumber(ctx context.Context, entityName, periodKey string) (int, error)
	NextNum(ctx context.Context, entityName string) (int64, error)
}

NumeratorStore — то, что объекту Нумераторы нужно от хранилища. Реализуется *storage.DB. Обе операции атомарны и безопасны при конкурентных вызовах.

type NumeratorsRoot

type NumeratorsRoot struct {
	// contains filtered or unexported fields
}

NumeratorsRoot — корневой DSL-объект Нумераторы.

func NewNumeratorsRoot

func NewNumeratorsRoot(ctx CtxSource, store NumeratorStore, reg NumeratorRegistry) *NumeratorsRoot

NewNumeratorsRoot создаёт объект для инжекции как DSL extraVar «Нумераторы».

func (*NumeratorsRoot) CallMethod

func (r *NumeratorsRoot) CallMethod(method string, args []any) any

func (*NumeratorsRoot) Get

func (r *NumeratorsRoot) Get(string) any

This: у объекта нет доступных членов, только метод. Get/Set — безопасные no-op.

func (*NumeratorsRoot) Set

func (r *NumeratorsRoot) Set(string, any)

type PageBlock

type PageBlock struct {
	Kind string // heading | paragraph | kpi | table | button | divider | raw

	Text   string // heading/paragraph/button: текст; kpi: подпись не здесь (см. Label)
	URL    string // button: адрес перехода
	Action string // button: имя серверной процедуры-действия (КнопкаДействие); взаимоисключимо с URL
	Label  string // kpi: подпись
	Value  string // kpi: уже отформатированное значение
	Title  string // table: заголовок таблицы

	Columns      []string  // table: КЛЮЧИ колонок — адресация ячеек в Rows (не переводятся)
	ColumnLabels []string  // table: отображаемые заголовки колонок (переводятся i18n)
	Rows         []PageRow // table: строки

	Items []PageListItem // list: пункты списка
	Chart *PageChart     // chart: данные графика

	HTML string // raw: санитизированный HTML (только ДобавитьСыройHTML)
}

PageBlock — один отрендеренный блок страницы. Экспортирован, чтобы UI-слой мог пройтись по результату (PageBuilder.Blocks()). Поля заполняются по Kind.

type PageCell

type PageCell struct {
	Text string
	URL  string
}

PageCell — ячейка таблицы: текст и необязательная ссылка (кликабельная ячейка).

type PageChart

type PageChart struct {
	Kind   string // bar | line | pie
	XAxis  []string
	Series []PageSeries
}

PageChart — данные графика (план 66). Сериализуется в опции ECharts тем же EChartsOption, что и виджеты рабочего стола.

type PageListItem

type PageListItem struct {
	Text string
	URL  string
}

PageListItem — пункт списка: текст и необязательная ссылка.

type PageRow

type PageRow struct {
	Cells map[string]PageCell
}

PageRow — строка таблицы. Ячейки адресуются по имени колонки.

type PageSeries

type PageSeries struct {
	Name string
	Data []float64
}

PageSeries — одна серия графика, выровненная по XAxis.

type PredefinedCatalogProxy

type PredefinedCatalogProxy struct {
	// contains filtered or unexported fields
}

PredefinedCatalogProxy resolves individual predefined items by name. ПредопределённыеЗначения.Валюта.Рубль → UUID string

func (*PredefinedCatalogProxy) Get

func (p *PredefinedCatalogProxy) Get(itemName string) any

func (*PredefinedCatalogProxy) Set

func (p *PredefinedCatalogProxy) Set(_ string, _ any)

type PredefinedDB

type PredefinedDB interface {
	GetPredefinedIDStr(ctx context.Context, entityName, itemName string) (string, error)
}

PredefinedDB is the minimal storage interface for predefined item lookup. Returns the UUID of a predefined item as a string.

type PredefinedRoot

type PredefinedRoot struct {
	// contains filtered or unexported fields
}

PredefinedRoot is the DSL global ПредопределённыеЗначения / PredefinedValues. Each property access (.Валюта) returns a PredefinedCatalogProxy for that entity.

func NewPredefinedRoot

func NewPredefinedRoot(ctx context.Context, db PredefinedDB) *PredefinedRoot

NewPredefinedRoot creates the root object for injection as DSL extraVar.

func (*PredefinedRoot) Get

func (r *PredefinedRoot) Get(entityName string) any

func (*PredefinedRoot) Set

func (r *PredefinedRoot) Set(_ string, _ any)

type QueryCompiler

type QueryCompiler func(ctx context.Context, text string, params map[string]any) (query.Result, error)

type QueryDB

type QueryDB interface {
	QueryAll(ctx context.Context, sql string, args ...any) ([]map[string]any, error)
	Dialect() storage.Dialect
}

QueryDB is the minimal storage interface needed by queryProxy.

type QueryGuard

type QueryGuard func(ctx context.Context, res query.Result, rows []map[string]any) error

QueryGuard проверяет и правит строки результата до того, как они попадут в DSL: полевое маскирование ПДн (план 88E). Ошибка означает, что запрос читать нельзя, — строки в модуль не отдаются.

type QueryRegistry

type QueryRegistry interface {
	Registers() []*metadata.Register
	InfoRegisters() []*metadata.InfoRegister
	AccountRegisters() []*metadata.AccountRegister
	Entities() []*metadata.Entity
}

QueryRegistry is the minimal registry interface needed by queryProxy.

type ReadOnlyBuiltinFunc

type ReadOnlyBuiltinFunc BuiltinFunc

ReadOnlyBuiltinFunc is an explicit opt-in for an injected callback that is safe to invoke from an unattended debugger condition. Ordinary BuiltinFunc values fail closed there: the interpreter cannot infer whether an arbitrary Go closure writes data or performs an external action.

type Ref

type Ref struct {
	UUID string
	Name string
	// Type — имя типа объекта (справочника/документа). Может быть пустым,
	// если ссылка создана вне менеджера.
	Type string
	// Manager — менеджер объекта; задаётся при создании ссылки и позволяет
	// Ссылка.Удалить() работать. nil → метод поднимет понятную ошибку.
	Manager RefManager
	// AttrResolver enables safe host-side single-hop attribute reads such as
	// Ссылка.Артикул. It is optional; bare references still expose only display
	// name, UUID and methods.
	AttrResolver RefAttrResolver
}

Ref represents a DSL reference value: UUID for identity/SQL, Name for display. Строка(ref) returns Name; SQL parameter expansion uses UUID.

func (*Ref) CallMethod

func (r *Ref) CallMethod(method string, args []any) any

CallMethod реализует MethodCallable для ссылки. Без этого вызов любого метода на ссылке молча возвращал nil.

func (*Ref) Get

func (r *Ref) Get(field string) any

Get обеспечивает доступ к полям ссылки: ссылка.Наименование / ссылка.Имя возвращают наименование объекта, ссылка.УникальныйИдентификатор — UUID. Прочие реквизиты объекта недоступны без его загрузки (ссылка несёт только UUID и наименование).

func (*Ref) GetRefUUID

func (r *Ref) GetRefUUID() string

func (*Ref) String

func (r *Ref) String() string

func (*Ref) TypeName

func (r *Ref) TypeName() string

type RefAttrResolver

type RefAttrResolver interface {
	ResolveRefAttr(ref *Ref, field string) (any, bool)
}

RefAttrResolver is an optional, host-provided resolver for object attributes addressed through a reference value. It deliberately lives in interpreter to avoid importing ui/storage here; concrete implementations are supplied by callers that know how to read metadata-backed objects.

type RefManager

type RefManager interface {
	DeleteRef(uuidStr string) error
	LoadObject(uuidStr string) (any, error)
}

RefManager — менеджер объекта (справочника/документа), к которому привязана ссылка. Реализуется CatalogProxy и docProxy; позволяет методам ссылки Удалить()/ПолучитьОбъект() работать без явного указания менеджера.

LoadObject загружает существующий объект по UUID и возвращает изменяемый writer (*CatalogRecordWriter для справочника, *docWriter для документа). any в сигнатуре — потому что *docWriter живёт в пакете ui и не виден из interpreter; DSL вызывает у возвращённого значения Get/Set/CallMethod через рефлексию, конкретный тип ему не важен.

type RowAccessChecker

type RowAccessChecker interface {
	CheckRowAccess(ctx context.Context, entity *metadata.Entity, op string, id uuid.UUID, fields map[string]any) error
	IsRowAccessRestricted(ctx context.Context, entity *metadata.Entity, op string) bool
	AutoFillRowAccess(ctx context.Context, entity *metadata.Entity, op string, fields map[string]any) error
}

RowAccessChecker is provided by the host runtime to make DSL data proxies respect the same row-level access decisions as UI/REST. A nil checker keeps legacy trusted/server-code behavior for tests and headless callers.

type SandboxProfile

type SandboxProfile struct {
	Context      context.Context // optional cancellation source for the whole DSL run
	DenyNet      bool            // запретить сеть: HTTP-клиент, email, ИИ-запросы
	DenyFile     bool            // запретить файловые builtins (и чтение в РаспознатьДокумент)
	DenyExec     bool            // запретить команды ОС (ВыполнитьКоманду, план 67) недоверенному коду; secure-by-default обычного режима даёт флаг базы exec.enabled
	MaxWallClock time.Duration   // 0 = без лимита времени
	MaxLoopIters int             // 0 = дефолт (maxWhileIter)
	// MaxDecimalExpansion bounds decimal exponents, coefficients and explicit
	// precision accepted by builtins during this sandbox run. Wall-clock checks
	// cannot interrupt one shopspring/decimal rescale or strconv formatting call,
	// so untrusted expressions need a memory bound at those sinks as well.
	// 0 keeps the ordinary trusted-DSL behavior unchanged.
	MaxDecimalExpansion int32
	// MaxStringExpansion bounds total string/byte input and output and
	// preflights multiplicative replace/join/template expansion. 0 keeps the
	// ordinary trusted-DSL behavior unchanged.
	MaxStringExpansion int
}

SandboxProfile описывает ограничения одного запуска DSL. Deny-семантика: нулевое значение = «ничего не запрещено» = поведение по умолчанию (без регрессии). RunSandboxed применяет запреты профиля безусловно (см. Vars), поэтому, чтобы запретить возможность, явно выставь соответствующий флаг.

func RestrictedProfile

func RestrictedProfile() SandboxProfile

RestrictedProfile — строгий профиль для недоверенного кода (ИИ/marketplace): запрещены сеть и файлы, заданы лимиты времени и итераций.

func (SandboxProfile) Vars

func (p SandboxProfile) Vars() map[string]any

Vars возвращает известные имена возможностей, которые должен закрыть профиль (сеть/email/файлы/ИИ). RunSandboxed и CallSandboxed помещают их в неизменяемый overlay запуска: обычные vars, Перем и присваивания не могут затенить deny. Возможности без выставленного запрета не трогаются — остаются обычные функции (с глобальным предохранителем сети, план 62). Для нулевого профиля карта пуста.

Это защита известных глобальных имён, а не object-capability membrane: доверенный Go-вызывающий не должен передавать уже готовый сетевой/файловый объект под произвольным новым именем. Такие объекты остаются его trust boundary.

type SpreadsheetDocument

type SpreadsheetDocument struct {
	Doc *sheet.Document
	// contains filtered or unexported fields
}

SpreadsheetDocument — DSL-обёртка над sheet.Document. Данные и рендеры — в Doc; здесь — диспетчер DSL-методов и именованные области (DSL-уровень).

func NewSpreadsheetDocument

func NewSpreadsheetDocument() *SpreadsheetDocument

NewSpreadsheetDocument creates a new empty spreadsheet document.

func (*SpreadsheetDocument) CallMethod

func (d *SpreadsheetDocument) CallMethod(name string, args []any) any

func (*SpreadsheetDocument) Get

func (d *SpreadsheetDocument) Get(field string) any

Get обеспечивает чтение свойств страницы из DSL (ТабДок.ОриентацияСтраницы). Метод также делает SpreadsheetDocument реализацией This — на диспетчер методов (CallMethod) это не влияет (методы идут через MethodCallable).

func (*SpreadsheetDocument) HTMLString

func (d *SpreadsheetDocument) HTMLString() string

HTMLString returns the full HTML representation of the document.

func (*SpreadsheetDocument) Set

func (d *SpreadsheetDocument) Set(field string, v any)

Set обеспечивает запись свойств страницы из DSL (план 64, этап 2):

  • ОриентацияСтраницы = "Портрет"/"Ландшафт" (и англ. Portrait/Landscape);
  • РазмерСтраницы = "A4"/"A5"/"Letter" и т.п. либо кастомный "Ш×В" в мм ("229x162mm") — литеральный размер бланка (конверты, ярлыки);
  • ПоляПечати = число мм (все четыре поля) ЛИБО Массив [верх,низ,лево,право] мм.

func (*SpreadsheetDocument) SetBackURL

func (d *SpreadsheetDocument) SetBackURL(url string)

BackURL делегирует одноимённое поле модели (используется handlers_print.go).

type SpreadsheetDocumentArea

type SpreadsheetDocumentArea struct {
	Area *sheet.Area
	// contains filtered or unexported fields
}

SpreadsheetDocumentArea — DSL-обёртка над sheet.Area (прямоугольная область- шаблон с собственными ячейками в относительных координатах). Данные — в Area.

func (*SpreadsheetDocumentArea) CallMethod

func (a *SpreadsheetDocumentArea) CallMethod(name string, args []any) any

func (*SpreadsheetDocumentArea) Get

func (a *SpreadsheetDocumentArea) Get(field string) any

Get allows accessing cells via dot notation (Area.R1C1) or properties (Area.Параметры).

func (*SpreadsheetDocumentArea) Set

func (a *SpreadsheetDocumentArea) Set(field string, v any)

Set allows setting cells via dot notation (Area.R1C1 = "value") or area properties.

type SpreadsheetDocumentCell

type SpreadsheetDocumentCell = sheet.Cell

SpreadsheetDocumentCell — псевдоним модельной ячейки. Используется maket.go при материализации областей из макета (доступ к полям напрямую).

func NewSpreadsheetDocumentCell

func NewSpreadsheetDocumentCell(text string) *SpreadsheetDocumentCell

NewSpreadsheetDocumentCell создаёт ячейку с дефолтным форматированием.

type SpreadsheetDocumentCellWrapper

type SpreadsheetDocumentCellWrapper struct {
	// contains filtered or unexported fields
}

SpreadsheetDocumentCellWrapper provides direct access to a single cell.

func (*SpreadsheetDocumentCellWrapper) CallMethod

func (w *SpreadsheetDocumentCellWrapper) CallMethod(name string, args []any) any

func (*SpreadsheetDocumentCellWrapper) Get

func (*SpreadsheetDocumentCellWrapper) Set

func (w *SpreadsheetDocumentCellWrapper) Set(field string, v any)

type Struct

type Struct struct {
	// contains filtered or unexported fields
}

func NewMatchResultStruct

func NewMatchResultStruct(ref *Ref, count int) *Struct

NewMatchResultStruct собирает результат safe-match в Структуру с полями Статус / Ссылка / Количество. ref задаётся только при ровно одном совпадении. Экспортируется, чтобы тем же результатом пользовался путь Документы.X в ui.

func NewStructFromMap

func NewStructFromMap(m map[string]any) *Struct

NewStructFromMap creates a Struct from a string map.

func (*Struct) CallMethod

func (s *Struct) CallMethod(name string, args []any) any

func (*Struct) Fields

func (s *Struct) Fields() []string

func (*Struct) Get

func (s *Struct) Get(field string) any

func (*Struct) Set

func (s *Struct) Set(field string, v any)

func (*Struct) String

func (s *Struct) String() string

func (*Struct) TypeName

func (s *Struct) TypeName() string

type TestClock

type TestClock struct {
	// contains filtered or unexported fields
}

TestClock — источник времени с возможностью заморозки. nil frozen = реальное время. Раннер сбрасывает его между тестами.

type TestProfile

type TestProfile struct {
	// contains filtered or unexported fields
}

TestProfile объединяет часы и моки одного прогона тестов.

func NewTestProfile

func NewTestProfile() *TestProfile

NewTestProfile создаёт профиль для раннера тестов.

func (*TestProfile) Reset

func (p *TestProfile) Reset()

Reset очищает рекордеры и сбрасывает часы — вызывать перед каждым тестом, чтобы Мок.* и время не протекали между тестами.

func (*TestProfile) Vars

func (p *TestProfile) Vars() map[string]any

Vars — переменные тест-профиля для инъекции в прогон (поверх стандартных). Переопределяют встроенные функции даты/сети/ОС/ИИ рекордерами и добавляют объекты Часы и Мок. Инъекция идёт последней, поэтому перекрывает штатные функции окружения.

type This

type This interface {
	Get(name string) any
	Set(name string, v any)
}

This is implemented by runtime.Object; defined here to avoid import cycles.

type TxDB

type TxDB interface {
	BeginTx(ctx context.Context) (storage.Tx, context.Context, error)
	Exec(ctx context.Context, sql string, args ...any) (storage.CommandTag, error)
}

TxDB is the minimal storage interface needed for DSL transactions. Satisfied by *storage.DB.

type TxState

type TxState struct {
	// contains filtered or unexported fields
}

TxState is a mutable context holder for DSL transaction management. All DSL builtins that write to storage should call Ctx() to get the current context — it carries the active transaction if one is open.

func NewTxState

func NewTxState(ctx context.Context) *TxState

NewTxState creates a TxState with the given base context.

func (*TxState) Ctx

func (s *TxState) Ctx() context.Context

Ctx returns the current context (contains the active transaction if any).

func (*TxState) HasOpen

func (s *TxState) HasOpen() bool

HasOpen reports whether the DSL execution still owns an open transaction or savepoint. Execution boundaries use it to prevent a procedure that forgot to commit/rollback from leaking a connection past the request.

func (*TxState) InTransaction

func (s *TxState) InTransaction() bool

InTransaction reports whether the current execution context is already in a transaction, including one borrowed from an outer service/test boundary. HasOpen alone cannot see that borrowed transaction before the first explicit DSL BeginTransaction creates its savepoint.

func (*TxState) RollbackOpen

func (s *TxState) RollbackOpen(ctx context.Context) error

RollbackOpen unwinds every transaction/savepoint still owned by the DSL, from the innermost level to the outermost one. The supplied context should be detached from the execution cancellation (and bounded by the caller), while retaining the transaction values from Ctx().

Database rollback/release is always attempted before the corresponding hook scope is discarded. The state is cleared even when cleanup fails, and all cleanup errors are returned instead of panicking.

type ValueTable

type ValueTable struct {
	// contains filtered or unexported fields
}

ValueTable — in-memory таблица значений (ТаблицаЗначений), аналог типа 1С. Строки хранятся как map[ключ_в_нижнем_регистре]значение; наружу строка отдаётся как *MapThis, поэтому Стр.Колонка читается/пишется и edits отражаются в таблице (общая ссылка на map).

func NewValueTable

func NewValueTable(_ []any) *ValueTable

NewValueTable создаёт пустую ТаблицуЗначений (Новый ТаблицаЗначений).

func (*ValueTable) CallMethod

func (t *ValueTable) CallMethod(name string, args []any) any

func (*ValueTable) Get

func (t *ValueTable) Get(name string) any

func (*ValueTable) IterateRows

func (t *ValueTable) IterateRows() []map[string]any

IterateRows реализует контракт цикла «Для Каждого» (см. ForEachStmt): каждая строка оборачивается в *MapThis.

func (*ValueTable) Set

func (t *ValueTable) Set(_ string, _ any)

func (*ValueTable) String

func (t *ValueTable) String() string

func (*ValueTable) TypeName

func (t *ValueTable) TypeName() string

type Макет

type Макет struct {
	// contains filtered or unexported fields
}

Макет wraps a LayoutTemplate as a DSL-accessible object. DSL code uses it: Макет.Область("Заголовок") → returns SpreadsheetDocumentArea.

func NewMaket

func NewMaket(lt *printform.LayoutTemplate) *Макет

NewMaket creates a Макет DSL object from a layout template.

func (*Макет) CallMethod

func (m *Макет) CallMethod(name string, args []any) any

CallMethod handles method calls on the макет.

func (*Макет) Get

func (m *Макет) Get(field string) any

Get allows property access: Макет.Заголовок → same as Макет.Область("Заголовок").

func (*Макет) Set

func (m *Макет) Set(field string, v any)

Set is not supported on макет.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL