Files
Reims-Go/internal/plugin/rules.go
Dnyo666 ceeec602be feat(i18n,plugin): implement end-to-end i18n & L10n v2 architecture and language pack protocol
- Build single-source-of-truth 7-domain locale catalog (`locales/{zh-CN,en-US}/*.json`, 1,100+ keys) and `cmd/i18ngen` generator emitting Go catalogs and eager/lazy-split TypeScript domain modules (`core`/`vm` eager; `wizard`/`settings`/`plugins` lazy)
- Add zero-dependency ICU MessageFormat subset (`{var}`, `{n, number}`, CLDR `plural`, `select`), 8-hop cycle-free regional fallback (`zh-HK/zh-MO -> zh-Hant -> zh-TW -> zh-CN`), `auto` OS display-language preference, and `en-XA` pseudo-localization across Go and TypeScript
- Introduce `CodedError` supportability with `[E_CODE]` badges, collapsible `[detail]` diagnostics, and automatic SMC OSK / SMBIOS serial / MAC / token redaction
- Add Host × Guest macOS dual-terminology annotation (`FormatGuestTerm`) across 6 official Apple guest UI locales and localize Win32 system tray, file pickers, and DPI-adaptive `installguide` overlays with CJK font fallback probing
- Upgrade L1–L4 plugin localization to dual-track v2: Track A full language packs (`files`, WOFF2 `fonts`, cross-plugin `pluginOverrides`), Track B plugin-scoped `l10n` bundles (`HasUIMessages` isolation), live `plugin/localeChanged` notifications, `< 2ms` static CLI pack loading, and `reims-go plugin locale init|check` translator toolchain with `zh-TW` and `ja-JP` reference packs
- Harden security, WCAG 2.1 AA token contrast, `< 768px` responsive drawer & form layouts, and RTL logical properties; add backend security/locale regression tests and frontend `node --test` static/runtime guard suite in CI

# Conflicts:
#	frontend/src/i18n.ts
#	internal/cli/cli.go
#	internal/i18n/i18n.go
2026-11-30 14:56:19 +08:00

203 lines
5.6 KiB
Go

package plugin
import (
"context"
"fmt"
"strings"
)
// RuleCondition is a declarative, non-Turing-complete predicate over host, VM,
// and runtime facts (§5.4).
type RuleCondition struct {
Fact string `json:"fact"` // e.g. "host.needs_cold_reboot", "host.whpx", "vm.driver", "runtime.kind", "runtime.capabilities"
Operator string `json:"operator"` // "eq" | "neq" | "contains" | "not_contains" | "exists"
Value any `json:"value,omitempty"`
}
// RuleAction is a constrained action emitted when all conditions match (§5.4).
type RuleAction struct {
Kind string `json:"kind"` // "append_args" | "set_env" | "warn" | "post_start"
Key string `json:"key,omitempty"` // fragment key for append_args
Tokens []string `json:"tokens,omitempty"` // QEMU arg tokens
Env map[string]string `json:"env,omitempty"` // env overrides
Message LocalizedText `json:"message,omitempty"` // localized warning text (accepts string or {"zh-CN":..., "en-US":...})
Action string `json:"action,omitempty"` // post_start kind
Params map[string]any `json:"params,omitempty"`
}
// RuleHook is an L1 declarative hook rule contributed via plugin.json (§5.4).
type RuleHook struct {
ID string `json:"id"`
Event string `json:"event"` // "vm.beforeStart" | "host.preflight"
Priority int `json:"priority,omitempty"`
Conditions []RuleCondition `json:"conditions,omitempty"`
Actions []RuleAction `json:"actions"`
}
// EvaluateRuleConditions checks whether all declarative conditions hold against facts.
func EvaluateRuleConditions(conds []RuleCondition, facts map[string]any) bool {
for _, c := range conds {
val, exists := facts[c.Fact]
switch strings.ToLower(strings.TrimSpace(c.Operator)) {
case "exists":
if !exists || val == nil {
return false
}
case "eq", "==":
if !exists || !factEquals(val, c.Value) {
return false
}
case "neq", "!=":
if exists && factEquals(val, c.Value) {
return false
}
case "contains":
if !exists || !factContains(val, c.Value) {
return false
}
case "not_contains":
if exists && factContains(val, c.Value) {
return false
}
default:
return false
}
}
return true
}
func factEquals(actual, expected any) bool {
return strings.EqualFold(fmt.Sprint(actual), fmt.Sprint(expected))
}
func factContains(actual, needle any) bool {
sNeedle := strings.ToLower(fmt.Sprint(needle))
switch v := actual.(type) {
case []string:
for _, item := range v {
if strings.EqualFold(item, sNeedle) {
return true
}
}
return false
case []any:
for _, item := range v {
if strings.EqualFold(fmt.Sprint(item), sNeedle) {
return true
}
}
return false
default:
return strings.Contains(strings.ToLower(fmt.Sprint(actual)), sNeedle)
}
}
func (r *Registry) registerRuleHooks(sc *Scope, pluginID string, rules []RuleHook) {
for _, rule := range rules {
rl := rule
switch rl.Event {
case EventVMBeforeStart:
r.hooks.Subscribe(sc, HookRegistration{
PluginID: pluginID,
Event: EventVMBeforeStart,
Priority: rl.Priority,
Handler: func(_ context.Context, raw any) (any, error) {
p, ok := raw.(BeforeStartPayload)
if !ok {
return nil, nil
}
facts := buildStartFacts(p)
if !EvaluateRuleConditions(rl.Conditions, facts) {
return nil, nil
}
return buildRuleStartIntent(pluginID, rl, string(r.currentLocale())), nil
},
})
case EventHostPreflight:
r.hooks.Subscribe(sc, HookRegistration{
PluginID: pluginID,
Event: EventHostPreflight,
Priority: rl.Priority,
Handler: func(_ context.Context, raw any) (any, error) {
p, ok := raw.(PreflightPayload)
if !ok {
return nil, nil
}
if !EvaluateRuleConditions(rl.Conditions, p.HostFacts) {
return nil, nil
}
var res PreflightResult
loc := string(r.currentLocale())
for _, act := range rl.Actions {
if act.Kind == "warn" {
if msg := act.Message.Get(loc); msg != "" {
res.Warnings = append(res.Warnings, msg)
}
}
}
return res, nil
},
})
}
}
}
func buildStartFacts(p BeforeStartPayload) map[string]any {
facts := make(map[string]any, len(p.HostFacts)+8)
for k, v := range p.HostFacts {
facts[k] = v
}
facts["vm.name"] = p.VMName
facts["vm.driver"] = p.DriverID
facts["vm.capabilities"] = p.VMCaps
facts["vm.state"] = p.State
facts["vm.has_installer"] = p.HasInstaller
facts["runtime.kind"] = p.RuntimeKind
facts["runtime.capabilities"] = p.RuntimeCaps
return facts
}
func buildRuleStartIntent(pluginID string, rule RuleHook, loc string) StartIntent {
intent := StartIntent{PluginID: pluginID}
for i, act := range rule.Actions {
switch act.Kind {
case "append_args":
if len(act.Tokens) == 0 {
continue
}
key := act.Key
if key == "" {
key = fmt.Sprintf("%s:%s:%d", pluginID, rule.ID, i)
}
intent.Args = append(intent.Args, ArgFragment{
PluginID: pluginID,
Key: key,
Tokens: append([]string(nil), act.Tokens...),
Priority: rule.Priority,
})
case "set_env":
if len(act.Env) > 0 {
if intent.Env == nil {
intent.Env = make(map[string]string, len(act.Env))
}
for k, v := range act.Env {
intent.Env[k] = v
}
}
case "warn":
if msg := act.Message.Get(loc); msg != "" {
intent.Warnings = append(intent.Warnings, msg)
}
case "post_start":
if act.Action != "" {
intent.PostStart = append(intent.PostStart, PostStartAction{
PluginID: pluginID,
Kind: act.Action,
Params: act.Params,
})
}
}
}
return intent
}