@aiquants/plugin-settings 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,53 @@
1
+ # Changelog
2
+
3
+ All notable changes to `@aiquants/plugin-settings` are documented here.
4
+ Headings are version numbers. Unreleased changes go under `## Unreleased`; a release renames that heading to its version and publish date (`## 0.1.0 (YYYY-MM-DD)`).
5
+
6
+ ## 0.2.0 (2026-11-16)
7
+
8
+ ### Breaking changes
9
+
10
+ - **The React entry's peers** (`./react`): `@aiquants/console-ui` ^0.8.0 (it was ^0.7.0) and `@aiquants/auth-core` ^0.9.0 (it was ^0.8.0), optional as before, so a host that loads `./react` installs those releases with this one. The name the React parts import from auth-core (`accessFailureKindOfStatus`) and the names they import from console-ui do not change: console-ui 0.7.1 and 0.7.2 only add (`useFailureOccurrence`, `SegmentedControl`'s `density`), and 0.8.0 only raises its own auth-core floor to `^0.9.0`.
11
+ auth-core's changelog lists its own breaking changes (the access failure policy's required `signedIn`, the catalog key `signInRequired` renamed to `pageSignInRequired`, and a linked group's unlinked upstream members carried as their addresses by reason in place of their counts) for a host that uses those names itself: a host whose settings screens are behind a sign-in builds its presenter's policy with `signedIn: true`, and its notices stay the same. The React-free entry does not change.
12
+
13
+ ### Changed
14
+
15
+ - The test root's presenter (`tests/support/render.tsx`) builds the policy as `{ signedIn: true, keepsWork: true }`, and the design specification (1.6) names the new peer ranges.
16
+
17
+ ## 0.1.0 (2026-11-14)
18
+
19
+ The first release: the neutral base a console declares, checks and configures its plugins with, and the React parts that draw a plugin's settings on `@aiquants/console-ui`.
20
+
21
+ ### Added
22
+
23
+ - **The vocabulary** (`.`): the field types, the comparisons each condition value type allows, the condition matches, the option lists, the selection modes and what became of a chosen item, the ability, audit and check terms, the rule tags with their fixed English sentences, the keys and hard bounds of the tenant limits, and every size the base checks, read from one JSON table that a server-side implementation of the same checks reads too.
24
+ - **The descriptor** (`.`): `PluginDescriptorSchema` (a kind's labels, settings fields, abilities, connection-check steps and selection modes, with the rules across them), `PluginDescriptorFields` with `checkPluginDescriptor` for a layer that narrows `kind`, `filterFieldsOf` and `optionFieldsOf`.
25
+ - **The settings fields** (`.`): fourteen field types (`text`, `multiline`, `code`, `integer`, `duration_ms`, `boolean`, `date`, `datetime`, `choice`, `level`, `destination`, `secret_ref`, `rows`, `condition`), the columns of a rows field and the filter fields of a condition. A choice field declares how its list is closed and never lists its options.
26
+ - **The settings check** (`.`): `validateSettings` returns the canonical settings a save stores or every refusal with its place, reading every field; `settingsValuesOf` reads a draft (`partial`); `settingsSizeProblems` checks the tenant's size limits. The canonical form trims texts and destinations, reads integers, durations, dates and instants from the widths a person types (full-width digits, `2026/1/5`, `2026年1月5日`), and never coerces a value of the wrong kind.
27
+ A destination is read by the one URL grammar the Python base (`aiquants_platform_core.destination`) shares, which refuses a host name whose last label is a number unless it is a dotted IPv4 address of four decimal parts without a leading zero (a resolver reads `0300.0.2.1` as 192.0.2.1).
28
+ - **The condition check** (`.`): `checkedCondition` returns a flat condition (terms joined by `all` or `any`) in its canonical form, or every refusal, counting a condition's terms and values against the tenant's limits; `ConditionSchema` reads the shape of a canonical condition a host answers.
29
+ - **The selection** (`.`): `checkedSelection` (and `selectionOf` inside a larger value) returns what a caller chose of a source in its canonical form (everything, items by their keys, or a condition over the kind's filter fields), or every refusal located from the selection's root, reading the mode first and counting the items against the tenant's limit before any key is read;
30
+ `PluginSelectionSchema` reads a kept selection, `ItemResolutionSchema` and `itemResolutionsSchemaOf` read what became of each asked key, and `SelectionPreviewCountsSchema` reads a preview's counts, which a layer widens with counts of its own (`SelectionPreviewCountsFields`, `checkSelectionPreviewCounts`, `PreviewCountSchema`).
31
+ - **Labels** (`.`): `LabelTextSchema` (a name or sentence in one language) and `LocalizedTextSchema` (one in every language), refused by the rule a settings text breaks (`forbidden_character` before `empty`, one function both share), with the rule's fixed sentence and no position. A layer narrows a label with `.pipe(…)`.
32
+ - **Refusals** (`.`): `Checked`, `Problem` (`{ loc, msg, type }`), `Loc`, `ProblemsDetailSchema`, `ruleOfIssue`, `isRuleTag`, and `problem` and `refuseRule` for a layer's own checks to refuse as the base does.
33
+ - **Options** (`.`): the option query (a page by prefix and cursor, or a lookup of up to `LOOKUP_MAX_KEYS` keys), its page, the states of a value among its options (`named`, `unselected`, `pending`, `unavailable`, `failed`) with their words, and `choiceQueriesOf` / `conditionQueriesOf` (the lookups that name the keys a value holds).
34
+ - **Option batches** (`.`): `optionBatchesOf` asks every wanted query once per target; `optionBatchRequestSchemaOf` and `optionBatchAnswerOf` read a batch and its answer against it; the instance references of a saved registration and of a draft, with `pluginInstanceTargetKeyOf`.
35
+ - **Check results, audit records and limits** (`.`): `CheckResultSchema` (how one connection-check step ended: `passed`, `warned`, `failed` or `skipped`, where a failed or warned step names its reason as a rule tag and a warning does not stop the later steps), `checkResultsSchemaOf` (every declared step once, in order: passes and warnings, then at most one failure, then skips), `PluginAuditEventSchema` and `PluginLimitsSchema`.
36
+ - **Words** (`.`): the Japanese and English catalogs (`resolvePluginSettingsLabels`), a field's title, help and example (`describeField`), and a plugin's abilities in words (`abilityTermsOf`).
37
+ - **`PluginOptionsProvider` and `useOptionLabelOf`** (`./react`): a console's option answers, seeded with the loader's answers (read as the browser's, so a broken answer leaves its batch unreadable) and completed from the browser in batches gathered per commit, each query asked once, released queries aborted, failures shown with a reload, and a breach of the host's contract thrown to the nearest error boundary; a value's state among its options, looked up alone when nothing answers it yet.
38
+ A 401 or a 403 is an access failure, which a field hands to the presenter of console-ui's root instead of drawing a sentence: a 403 with the field's denied sentence and no reload, a 401 with the reload as the retry after signing in again.
39
+ - **`PluginFieldsProvider`** (`./react`): the host's levels, duration ceiling, tenant limits and filter fields, checked once per change, for the fields and the condition builder that need them.
40
+ - **`SettingsFieldInput`** (`./react`): one settings field drawn with console-ui by its type, in the language of console-ui's root. A value is handed up as typed or chosen; the part states the form the save's check will store, computed with the check's own readers (none for a text the type's own rules refuse), and the check alone normalizes.
41
+ A value of the wrong kind is shown and described, and a field whose type is outside the vocabulary throws. A field's caller description, help, example, required note, declared and host rules, saved form and the value's own sentence (not text, or its state among the options) are its one description; `errorAt` draws the check's refusals at their place inside a rows or condition field.
42
+ - **Rows fields** (`./react`): one group per row with a part per column and a toolbar to move and remove it; add is unavailable, with the reason, at the tenant's row limit.
43
+ - **`ConditionBuilder`** (`./react`): the match (no default), each condition's field, comparison and value part by the comparison's value shape (a value held by a comparison that takes none, one value, a list for `in`, the two ends of `between`, a day count for `within_last_days`), with the tenant's limits on conditions and values counted as the check counts them: an edit never raises the values past their limit, and one that keeps or lowers a count already past it is handed up.
44
+ A field, comparison or match the descriptor does not allow is shown and never chosen for the user, and a refusal at a place with no part of its own is drawn on the group around it, naming the place.
45
+ - **Edits that take effect when the caller takes them** (`./react`): rows, conditions and typed list values keep stable keys; focus moves and the edit is announced only when the edited list comes back, so a caller that keeps the value as it was keeps focus and the live region as they were. Focus held by an item or a value part that leaves for any reason is kept by the same rule.
46
+
47
+ - **The React entry's peers** (`./react`): `@aiquants/console-ui` ^0.7.0 and `@aiquants/auth-core` ^0.8.0, optional like React and React DOM (the React-free entry loads none of them). console-ui's root takes the host's presenter of access failures (an `AccessFailurePresenter` of auth-core), and a field tells an access failure apart with auth-core's `accessFailureKindOfStatus`.
48
+
49
+ ### Not in this release
50
+
51
+ - The combo box for open option lists and for closed lists longer than `RADIO_MAX_OPTIONS` or paged: such a choice field throws while rendering.
52
+ - Unavailable check boxes past the values limit: the boxes of a choice list stay pressable, and a choice past the limit is not handed up and is announced.
53
+ - The parts that build on these: a whole connect form with its save, the connection-check results and the selection builder.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 AI Quants
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,215 @@
1
- # Temporary Holding Version
1
+ # @aiquants/plugin-settings
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The neutral base of a console that registers and configures plugins (a data source, a tool, a model provider): what a plugin kind declares (its descriptor: settings fields, abilities, connection-check steps and selection modes), the checks that turn a plugin's settings and conditions into their canonical form or refuse them with every refusal located, the option queries a console asks its host in batches, the words of abilities and option states in Japanese and English, and the React parts that draw a plugin's settings on `@aiquants/console-ui`.
4
+
5
+ The rules are data wherever they can be: the field types, the comparisons each value type allows, the rule tags and their fixed sentences, the hard bounds of the tenant limits and every size are read from one JSON table that a server-side implementation of the same checks reads too, so the two implementations change together.
6
+
7
+ ## Prerequisites
8
+
9
+ - Node.js >= 18.0.0
10
+ - zod ^3.25.0 (a peer dependency of both entries)
11
+ - For `@aiquants/plugin-settings/react` only: React >= 19, React DOM >= 19, `@aiquants/console-ui` ^0.8.0 and `@aiquants/auth-core` ^0.9.0 (optional peer dependencies; the React-free entry loads none of them). console-ui's root takes the host's presenter of access failures (an `AccessFailurePresenter` of auth-core), and the parts tell an access failure apart with auth-core's `accessFailureKindOfStatus`
12
+
13
+ ## Installation
14
+
15
+ ```bash
16
+ pnpm add @aiquants/plugin-settings zod
17
+ # the React parts
18
+ pnpm add @aiquants/console-ui @aiquants/auth-core react react-dom
19
+ ```
20
+
21
+ ## Entry Points
22
+
23
+ | Import path | Contents |
24
+ | --- | --- |
25
+ | `@aiquants/plugin-settings` | React-free: the vocabulary, JSON values and localized texts, the descriptor and its fields, the settings, condition and selection checks with their refusals, what became of chosen items and a preview's counts, the option queries and batches, check results and audit records, the tenant limits and the word catalogs. Servers, loaders and hosts import it without loading React. |
26
+ | `@aiquants/plugin-settings/react` | The React parts, built on `@aiquants/console-ui` and drawn in the language of console-ui's root: `PluginOptionsProvider` and `useOptionLabelOf` (a console's option answers and a value's state among its options), `PluginFieldsProvider` (the host's values some fields need), `SettingsFieldInput` (one settings field drawn by its type) and `ConditionBuilder` (a condition over a descriptor's filter fields), with their props types (`PluginOptionsProviderProps`, `PluginFieldsProviderProps`, `SettingsFieldInputProps`, `ConditionBuilderProps`), the host values' type (`PluginFieldValues`) and the type of the function `useOptionLabelOf` returns (`OptionLabelOf`). |
27
+
28
+ The build emits the code both entries reach as one shared chunk per module format (ESM / CommonJS), so a host that imports both paths in the same format holds one instance of every schema and catalog.
29
+
30
+ The React-free entry exports:
31
+
32
+ - **Vocabulary**: `FIELD_TYPES`, `OPTION_LISTS`, `CONDITION_VALUE_TYPES`, `CONDITION_OPERATORS`, `CONDITION_OPERATORS_BY_VALUE_TYPE`, `NULL_OPERATORS`, `NULL_SATISFIES`, `CONDITION_MATCHES`, `SELECTION_MODE_NAMES`, `ITEM_STATES`, `EGRESS_TERMS`, `STORE_TERMS`, `ABILITY_GRAINS`, `AUDIT_VERBS`, `AUDIT_OUTCOMES`, `CHECK_OUTCOMES` and `LANGUAGES`;
33
+ the rule tags (`SETTINGS_RULES`, `OPTION_RULES`, `BATCH_RULES`, `SELECTION_RULES`, the type `RuleTag`) and their fixed English sentences (`RULE_MESSAGES`); the keys and hard bounds of the tenant limits (`PLUGIN_LIMIT_FIELDS`, `PLUGIN_LIMIT_BOUNDS`);
34
+ and the sizes `SAFE_INTEGER_MAX`, `KEY_MAX_UNITS`, `PREFIX_MAX_UNITS`, `CURSOR_MAX_BYTES`, `QUERY_MAX_BYTES`, `LOOKUP_MAX_KEYS` (10), `BATCH_MAX_QUERIES` (32), `BATCH_TARGETS_MAX_BYTES`, `OPTION_NAME_MAX_UNITS`, `OPTION_NAME_ELLIPSIS`, `CLOSED_LIST_MIN_OPTIONS` (2), `RADIO_MAX_OPTIONS` (8) and `CONDITION_DAYS_MAX`. Each list of names has its type (`FieldType`, `ConditionOperator`, …); `NULL_OPERATORS` and `NULL_SATISFIES` hold `ConditionOperator`s.
35
+ - **JSON values and texts**: `JsonValue` and `JsonValueSchema` (`null`, a boolean, a finite number, a string, or an array or plain object of them, checked without recursion), `LabelTextSchema` (a name or sentence in one language: no control character, no unpaired surrogate, not blank; refused as a settings text is, by `forbidden_character` before `empty`, with the rule's fixed sentence and no position; a layer narrows it as `LabelTextSchema.pipe(z.string().max(…))`, since a refined schema has no `.max`), and `LocalizedText` and `LocalizedTextSchema` (one in every language).
36
+ - **The descriptor**: `PluginDescriptorSchema` (what a plugin kind declares, with the rules across its parts); `PluginDescriptorFields` and `checkPluginDescriptor` for a layer that narrows `kind` and keeps the base's rules; `PluginKindSchema`, `PluginLabelsSchema`, `PluginAbilitiesSchema` (`EgressAbilitySchema`, `StoreAbilitySchema`, `AbilityFlagSchema`), `PluginCheckSchema` and `SelectionModeDeclarationSchema` (a selection mode a kind accepts, `SelectionModeDeclaration`);
37
+ `filterFieldsOf(descriptor)` (the fields a condition may compare) and `optionFieldsOf(descriptor)` (every field whose options the plugin answers, by the path a query names it with: a settings field's name, `<rows field>.<column>`, or a filter field's name).
38
+ - **Fields**: `SettingsFieldSchema` (fourteen types: `text`, `multiline`, `code`, `integer`, `duration_ms`, `boolean`, `date`, `datetime`, `choice`, `level`, `destination`, `secret_ref`, `rows` and `condition`), `ColumnFieldSchema` (a column of a rows field: every type but `rows` and `condition`), `FilterFieldSchema` (a field a condition may compare: its value type, the comparisons it allows, whether its value may be `null`, and for a choice field how its list is closed), `FieldNameSchema` and `FieldOf<T>` (the field of one type, as `FieldOf<"choice">`).
39
+ A choice field never lists its options: it declares whether its list is `closed` or `open` (`option_list`), and the plugin answers its options.
40
+ - **The settings check**: `validateSettings(descriptor, values, context)` (the canonical settings a save stores, or every refusal), `settingsValuesOf(descriptor, values, context, { partial })` (the canonical values of the fields present and the refusals; with `partial: true` a missing required field is not refused), `settingsSizeProblems(values, limits)` and `SettingsValuesSchema`;
41
+ what the check reads from its host: `SettingsContext` (`destinations`, `secrets`, `levels`, `maxDurationMs`, `limits`) with `DestinationPermits` and `SecretBindings`; and the types `SettingsDescriptor` (the parts of a descriptor the check reads: `settings` and `selection_modes`), `SettingsValues` and `SettingsReading` (what `settingsValuesOf` returns: the canonical values of the fields it accepted, and the refusals).
42
+ - **The condition check**: `checkedCondition(raw, filterFields, limits)` (the canonical condition, flat terms joined by `all` or `any`, or every refusal), `ConditionSchema` (the shape of a canonical condition a host answers; whether it fits a kind is `checkedCondition`'s to decide), and the types `Condition`, `ConditionTerm`, `TermValue`, `TermScalar` and `ConditionLimits`.
43
+ - **The selection**: `checkedSelection(raw, descriptor, limits)` (the canonical selection, everything the source holds (`all`), items by their keys (`items`) or what a condition holds for (`filter`), or every refusal) and `selectionOf(raw, descriptor, limits, loc, problems)` (the same inside a larger value), with `SelectionLimits`;
44
+ `PluginSelectionSchema` (`AllSelectionSchema`, `ItemsSelectionSchema`, `FilterSelectionSchema`) and `PluginSelection` (a kept selection a host answers), and `ItemKeySchema` (an item's key by the base's key rule);
45
+ `ItemResolutionSchema`, `ItemResolution` and `itemResolutionsSchemaOf(keys)` (what became of each asked key, in the asked order: `present`, `redirected` with the key it moved to, or `gone`);
46
+ and `SelectionPreviewCountsSchema` and `SelectionPreviewCounts` (a preview's counts), with `SelectionPreviewCountsFields`, `checkSelectionPreviewCounts` and `PreviewCountSchema` for a layer that adds counts of its own.
47
+ - **Refusals**: `Checked<T>` (`{ ok: true, value }` or `{ ok: false, problems }`), `Problem` and `ProblemSchema` (`{ loc, msg, type }`: where the refusal is, the rule's fixed sentence and the rule's tag), `Loc` (field names and list positions from the refused value's root), `ProblemsDetail` and `ProblemsDetailSchema` (a host's `{ "errors": [...] }` detail), `ruleOfIssue(issue)` (the base rule a zod issue reports, or `null`) and `isRuleTag(value)`.
48
+ For a layer's own checks to refuse as the base does: `problem(loc, rule)` (one base rule's refusal at a place) and `refuseRule(ctx, rule, path)` (a base rule's fatal refusal in a zod refinement, which `ruleOfIssue` reads back).
49
+ - **Options**: `OptionQuerySchema` (a page by prefix and cursor, or a lookup of keys), `OptionPageSchema`, `OptionItemSchema`, `OptionLabelsSchema`, `OptionLabelState` (`named`, `unselected`, `pending`, `unavailable` or `failed`), `choiceQueriesOf(field, value, filterFields)` and `conditionQueriesOf(value, filterFields)` (the lookups that name the keys a value holds), and `optionLabelWords(state, labels)`.
50
+ - **Option batches**: `optionBatchesOf(entries, targetKeyOf)` (the batches that ask every entry once), `optionBatchRequestSchemaOf(target)` and `optionBatchAnswerOf(request)` (a batch, and its answer read against the batch), `OptionBatchQuerySchema`, `OptionAnswerSchema`, `OptionFailureSchema` and `OptionBatchAnswerSchema`;
51
+ the types `OptionEntry`, `OptionBatchRequest`, `OptionBatchOutcome`, `AnsweredOptionBatch` and `ResolveOptions`; and the instance references `savedInstanceSchemaOf(key)`, `DraftInstanceSchema`, `DraftSettingsSchema`, `pluginInstanceTargetSchemaOf(key)` and `pluginInstanceTargetKeyOf(target)`, with their types `SavedInstance`, `DraftInstance`, `DraftSettings` and `PluginInstanceTarget`.
52
+ - **Check results and audit records**: `CheckResultSchema`, `checkResultsSchemaOf(descriptor)` and `PluginAuditEventSchema`.
53
+ - **Tenant limits**: `PluginLimitsSchema` (every limit, each an integer within its hard bounds).
54
+ - **Words**: `PLUGIN_SETTINGS_LABEL_CATALOGS`, `resolvePluginSettingsLabels(locale)` and `PluginSettingsLabels` (every key required in every language), `describeField(field, labels)` (a field's title, help and example in one language, `FieldWords`, from the texts a field holds in every language, `FieldText`), and `abilityTermsOf(abilities, rows, kindNoun, labels)` (a plugin's abilities in words: an `AbilityTerm` for each row asked, an `AbilityRow`).
55
+
56
+ ## Usage
57
+
58
+ ### Checking settings on save
59
+
60
+ ```ts
61
+ import { type SettingsContext, validateSettings } from "@aiquants/plugin-settings"
62
+
63
+ const context: SettingsContext = {
64
+ destinations: { permits: (url) => egressPolicy.allows(url) },
65
+ secrets: { binds: (secret, destination) => secretTable.binds(secret, destination) },
66
+ levels: hostLevels,
67
+ maxDurationMs: hostMaxDurationMs,
68
+ limits: tenantLimits,
69
+ }
70
+
71
+ const checked = validateSettings(descriptor, request.settings, context)
72
+ if (!checked.ok) {
73
+ return reply(400, { errors: checked.problems })
74
+ }
75
+ await save(checked.value)
76
+ ```
77
+
78
+ Every field is read, so one answer carries every refusal, each with its `loc` (`["retries"]`, `["routes", 2, "url"]`, `["scope", "terms", 0, "value"]`). The canonical form is what is stored: a `text` or `destination` without its surrounding white space, an `integer` or `duration_ms` as a JSON number, a `date` as `YYYY-MM-DD` and a `datetime` as `YYYY-MM-DDTHH:MM:SS[.fraction]±HH:MM` (typed widths such as `1,234`, `2026/1/5` and `2026年1月5日` are read). A value of the wrong kind is refused, never coerced, and `null` is a wrong kind, not an absent value.
79
+ A `destination` is read by the one grammar it shares with the Python base (`aiquants_platform_core.destination`), narrower than RFC 3986 on purpose so both read every URL the same way: ASCII only, a lower-case scheme, no user information (`userinfo_in_url`), a host name or a bracketed IPv6 address, an optional port of 1 to 65535, then an optional path and query of RFC 3986's characters with well-formed percent escapes, and no fragment; anything else off the grammar is `invalid_url`.
80
+ A host name whose last label is a number (decimal digits, or hexadecimal ones after `0x`) must be a dotted IPv4 address of four decimal parts without a leading zero: a resolver reads `0300.0.2.1` (octal) as 192.0.2.1 and `192.513` as 192.0.2.1, so such a name would reach an address other than the one it shows.
81
+
82
+ ### Checking a selection before sending it
83
+
84
+ ```ts
85
+ import { checkedSelection, PluginSelectionSchema } from "@aiquants/plugin-settings"
86
+
87
+ const checked = checkedSelection(draft, descriptor, tenantLimits)
88
+ if (!checked.ok) {
89
+ return show(checked.problems)
90
+ }
91
+ await send(checked.value)
92
+ const kept = PluginSelectionSchema.parse(await readKept())
93
+ ```
94
+
95
+ The mode is read first, as it decides the object's keys: a value without a mode the kind declares is refused at `["mode"]` alone (`missing`, `wrong_type`, `unknown_value` or `mode_not_allowed`). Then each missing and unknown key is refused, the items are counted against the tenant's `selection_max_items` before any key is read (`empty`, `too_many_items`), and each key is refused at its place (`["items", 3]`: `wrong_type`, `invalid_key` or `duplicate_item`);
96
+ a filter's condition is checked as `checkedCondition` checks it, over the kind's filter fields (`["condition", "terms", 0, "value"]`). The host checks the selection again when it receives it, and builds a preview's question from it with its own clock, so a console never sends a clock.
97
+
98
+ A layer that adds counts to a preview keeps the base's counts and their rule: `SelectionPreviewCountsFields.extend({ kept_outside: PreviewCountSchema }).superRefine(checkSelectionPreviewCounts)`.
99
+
100
+ ### Drawing a plugin's settings
101
+
102
+ ```tsx
103
+ import { ConsoleUiRoot } from "@aiquants/console-ui"
104
+ import { describeField, filterFieldsOf, pluginInstanceTargetKeyOf, resolvePluginSettingsLabels } from "@aiquants/plugin-settings"
105
+ import { PluginFieldsProvider, PluginOptionsProvider, SettingsFieldInput } from "@aiquants/plugin-settings/react"
106
+
107
+ // accessFailure: the host's presenter of access failures, with one identity (see console-ui's README, Wrapping a console)
108
+ <ConsoleUiRoot locale={locale} formatLocale={formatLocale} timeZone={timeZone} accessFailure={accessFailure} testId="console">
109
+ <PluginFieldsProvider levels={levels} maxDurationMs={maxDurationMs} limits={limits} filterFields={filterFieldsOf(descriptor)}>
110
+ <PluginOptionsProvider answered={loaderAnswers} resolveOptions={resolveOptions} targetKeyOf={pluginInstanceTargetKeyOf}>
111
+ {descriptor.settings.map((field) => (
112
+ <SettingsFieldInput
113
+ key={field.name}
114
+ target={target}
115
+ field={field}
116
+ value={draft[field.name]}
117
+ onValueChange={(value) => setDraft((draft) => ({ ...draft, [field.name]: value }))}
118
+ legend={describeField(field, resolvePluginSettingsLabels(locale)).title}
119
+ error={errorOf([field.name])}
120
+ errorAt={(loc) => errorOf([field.name, ...loc])}
121
+ testId={`settings-${field.name}`}
122
+ />
123
+ ))}
124
+ </PluginOptionsProvider>
125
+ </PluginFieldsProvider>
126
+ </ConsoleUiRoot>
127
+ ```
128
+
129
+ - The parts take their language from console-ui's root (`useConsoleUi().locale`) and have no language prop of their own; their DOM hooks are `data-testid` attributes derived from `testId`.
130
+ - `SettingsFieldInput` takes `target` (the instance the field belongs to: what its option queries ask), `field`, `value` (`undefined` when the field has none), `onValueChange`, `legend` (the field's label), `description` (the caller's, placed first), `error` (the caller's error for the whole field), `errorAt(loc)` (the error at a place inside a rows or condition field, `loc` being the check's `loc` without the field's name; one-value fields do not read it) and `testId`.
131
+ - A value is handed up exactly as typed or chosen. Only the save's check normalizes it: a part states the form the check will store (`Saved as “…”.`) when it differs from what was typed, computed with the check's own readers, and never applies it. No form is stated for a text the type's own rules refuse (a forbidden character, a blank text, a destination off the URL grammar or holding user information); the field's bounds (length, URI schemes, range) are left to the check.
132
+ - A value of another kind (a number in a text field, `null`, a list where one value belongs) is shown as JSON. A type that holds text (`text`, `destination`, `secret_ref`, `multiline`, `code`) says the value is not text and a save refuses it, and a boolean field checks nothing and says the value cannot be chosen now;
133
+ a number, duration, date or date-time field says nothing more, since its reader reads a number and its text alike or refuses both (and no saved form is stated for a value it refuses). An edit that writes into such a value replaces it.
134
+ - A field's description is one text, in this order: the caller's description, the field's help, its example, whether a save needs a value, the declared rules (length, code language, range, URI schemes), the host's rules (the duration ceiling), the saved form, and the value's own sentence (that a value is not text, or the value's state among its options). A required field is described, not marked `required`, so a draft can still be saved.
135
+
136
+ | Field type | Drawn as | Value handed up |
137
+ | --- | --- | --- |
138
+ | `text`, `destination`, `secret_ref` | a text input | the typed text |
139
+ | `multiline`, `code` | a text area | the typed text |
140
+ | `integer`, `duration_ms` | a text input (numeric keyboard for `duration_ms` and for an `integer` whose minimum is 0 or more) | the typed text |
141
+ | `date`, `datetime` | a text input (so `YYYY/M/D` and `YYYY年M月D日` can be typed) | the typed text |
142
+ | `boolean` | required: a yes / no radio group with neither checked while there is no value; optional: one checkbox named by the field's title. A value that is not a boolean checks nothing | `true` / `false` |
143
+ | `choice` | a radio group for a closed list whose first page holds every option, at most `RADIO_MAX_OPTIONS` | the option's key |
144
+ | `level` | a radio group for up to `RADIO_MAX_OPTIONS` host levels, else a select | the level's key |
145
+ | `rows` | one group per row with a part per column, and move up / move down / remove in one toolbar per row | the rows |
146
+ | `condition` | `ConditionBuilder` | the condition object |
147
+
148
+ A choice field whose list is open, or closed but longer than `RADIO_MAX_OPTIONS` or paged, throws while rendering: the combo box it needs is not part of this version. A field whose type is outside the vocabulary (one built without `SettingsFieldSchema`) throws a `TypeError` while rendering instead of drawing nothing.
149
+
150
+ ### Rows and conditions
151
+
152
+ `SettingsFieldInput` draws a `rows` field and a `condition` field itself; `ConditionBuilder` draws a condition on its own (for a selection by filter) with the same props but `field`, inside `PluginFieldsProvider` like a `condition` field (it reads the filter fields and the limits from there).
153
+
154
+ - **Edits**: writing a cell writes one key of one row and keeps the row's other keys, undeclared ones included (the check refuses those, and the part describes them first). Removing the last row hands up `[]`, and removing the last condition hands up the condition with an empty `terms` (its match and undeclared keys kept: `{ "match": "all", "terms": [] }` once a match is chosen);
155
+ the check refuses an empty list (`empty`), so mapping either to "no value" for an optional field is the form's decision.
156
+ - **Conditions**: the match (`all` or `any`) has no default. Choosing another field keeps the comparison and the value when the new field allows the comparison and has the same value type, except that between two choice fields the value of a comparison that takes one is dropped (keys belong to one list; the `null` of a comparison that takes none stays).
157
+ Choosing another comparison keeps the value when its shape stays the same and sets `null` for a comparison that takes no value. A field the descriptor does not declare and a comparison the field does not allow are not chosen for the user: the part shows them as the current choice, labelled as not available, and choosing that label again hands nothing up.
158
+ A match outside the vocabulary checks neither radio, and the description says so.
159
+ - **Values**: the value part follows the comparison's value shape, read with the check's own function: none (`is_null`, `is_not_null`: nothing is drawn while the value is `null`; any other value, or no value key, is described as refused on save, with an action that clears it to `null`), one value (a text input; yes / no for a boolean;
160
+ the option picker for a choice), a list for `in` (text inputs with add and remove for a text field; checkboxes for a choice field, keeping a value that is not among the options), the two ends of `between` (start and end) and a day count for `within_last_days` (1 to `CONDITION_DAYS_MAX`). Each typed value states the form the check stores, and a text value that is not text is described as refused on save.
161
+ - **Limits**: add (a row, a condition, a typed value) is unavailable, with the reason, at `settings_max_rows` rows, `condition_max_terms` conditions and `condition_max_values` values; adding a condition is unavailable while the values are at their limit too (only a value completes a condition), with both reasons when both limits are reached.
162
+ An edit that would raise the values past their limit (choosing a comparison, ticking an option) is not handed up, and the limit is announced; a choice list's description states the limit while it is reached. Choosing another field never raises the count. An edit that keeps or lowers a count already past the limit (a condition saved before the limit was lowered) is handed up.
163
+ A condition's values are counted as the check counts a valid term's values: a list counts its length (none while the value is not a list), `between` counts 2, any other chosen comparison counts 1 (one that takes no value too), and a term without a comparison counts none.
164
+ - **Errors at a place**: `errorAt` receives `[i]` (a row) and `[i, column]` (a cell) in a rows field, and `["match"]`, `["terms"]`, `["terms", i]`, `["terms", i, "field" | "op" | "value"]` and `["terms", i, "value", j]` (a value of a list, or an end of `between`) in a condition; the error for `["terms"]` is joined to the caller's error for the whole condition.
165
+ A place with no part of its own is drawn on the group around it, naming the place: an undeclared key (`[key]`, `["terms", i, key]`: “Key “k”: …”), an undeclared column of a row (`[i, column]`: “Column “n”: …”), the value of a condition whose field or comparison is not chosen (`["terms", i, "value"]`: “Value: …”) and one value of a choice list (`["terms", i, "value", j]`: “Value N (“x”): …”).
166
+ - **Keys, focus and announcements**: every row, condition and typed list value keeps a stable React key, so an item keeps its parts, its focus and its option queries when items before it are added, removed or moved.
167
+ An edit takes effect when the caller takes it: the part records the list it hands up, and only when that list comes back (the same JSON, so a caller that copies the value takes it too) does it apply the edit's keys, move focus and announce the edit. A caller that does not take the change leaves the list, focus and the live region as they were, as a controlled input keeps its value;
168
+ any other change of the list drops the waiting edit and keys the items by place. After an addition focus moves to the new item's title, after a removal to the item now at that place (else the one before it, else the add action), and after a move to the same action of the moved row (the opposite one once it reaches an end).
169
+ Additions of rows and conditions, and every removal and move, are announced through console-ui's live region. A move past an item of the same content leaves the list as it was, so it is taken only when the very list handed up comes back (a copy cannot be told from the list as it was).
170
+ - **Focus kept**: when an item's region leaves while it holds focus, whatever removed it (a caller that replaced the value, say), focus moves by the removal's rule from the region's place, unannounced; a condition's value part sits in a region per value type and shape, and hands focus to the condition's comparison when it leaves or changes kind. A part hidden and shown again (`<Activity>`) does not repeat the focus move or the announcement of an edit it already carried.
171
+ - **Layout**: each row, condition, list, pair of ends and value of a comparison that takes none sits in a group named by its title (`role="group"` with `aria-labelledby`), described by its description and then its error, which come before its fields; the title takes focus from code and is not in the Tab order. The spaces follow console-ui's 4 px lattice and double at each level out: 8 px inside a group, 16 px between the parts of a row or condition, 32 px between rows, conditions and the outer sections.
172
+
173
+ ### Options
174
+
175
+ `PluginOptionsProvider` holds the option answers of every part inside it.
176
+
177
+ - `answered` takes the answers the page's loader already read (`AnsweredOptionBatch[]`), read as the browser's answers are (`optionBatchAnswerOf`: an answer that breaks the options contract leaves every query of its batch unreadable). Pass the same array while the answers are the same: a new array is the loader's new answers, and replaces the held answer of each of its queries, one the browser read included.
178
+ `resolveOptions(request, signal)` sends one batch from the browser and resolves to an `OptionBatchOutcome` (it rejects only when `signal` aborts). `targetKeyOf` tells two targets apart (`pluginInstanceTargetKeyOf` for the base's instance references).
179
+ - Parts name the queries they need after each commit and release them when they leave. The names of one commit are gathered in one microtask, and only the queries with no answer are asked, batched with `optionBatchesOf`; an answer is kept and reused, and a query is never asked twice. When every query of a batch is released, its signal is aborted: an awaited query is dropped (a later name asks it again), and a failed query that a reload was asking again keeps its failure, no longer busy (only a reload asks it again).
180
+ Unmounting the provider aborts every batch.
181
+ - A batch that resolves to `{ ok: false }`, or whose answer does not match its request, leaves each of its queries unreadable: the field shows console-ui's `ResourceFailed` with a reload button that asks the field's failed queries again. A query's own failure (`{ error }`) is kept as its answer and described the same way, with the status its business code is answered with. The browser never asks again on its own.
182
+ A 401 or a 403 is an access failure, which `ResourceFailed` hands to the presenter of console-ui's root instead of drawing a sentence: a 403 with the field's denied sentence (`「<title>」の選択肢を読む権限がありません。`, `You may not read the options of “<title>”.`) and no reload, a 401 with the reload as the retry after signing in again.
183
+ - In a choice field, the status line is placed empty when the field is drawn and says that the options are being read in the next drawing (a live region reads only the changes made after it is in place). A first page with no option says there is none. Focus that leaves the reload or the presenter's notice goes to the first option, else to the sentence that there is no option, else to the failure. A value no option shown holds stays and is described, by the name a lookup gives it when one does; a list that holds a value more than once says so (the checkboxes show it once).
184
+ - A breach of the host's contract (`resolveOptions` throws, resolves to something that is not an outcome (neither `{ ok: true, value }` nor `{ ok: false, status, reason }` with a number or `null` status and a text reason: a `TypeError`), or rejects for another reason than the abort; a target that is not a JSON value; one target key given to two different targets while a query waits) is the caller's error, not a field's state: the provider throws the first one while rendering, so the nearest error boundary receives it.
185
+
186
+ `useOptionLabelOf()` returns `(target, field, value) => OptionLabelState`, callable any number of times while rendering. A value is `named` when an answered page of its list names its key; `unavailable` when a lookup of the key answered without it, or when an answer holds the whole list (a first page with no next cursor); `pending` while a lookup of the key waits;
187
+ and `failed` when that lookup could not be read (a failed lookup is not asked again on its own: it stays `failed` until a loader's answers replace it or a choice field's reload asks it again). Otherwise the call names a lookup of that one key and answers `pending`. A field with no value (`undefined`) is `unselected`, and a value that is not a valid key is `unavailable`.
188
+
189
+ ### Host values
190
+
191
+ `PluginFieldsProvider` hands the parts the host's levels (`levels`: keys with a name in every language), the duration ceiling (`maxDurationMs`), the tenant limits (`limits`) and the descriptor's filter fields (`filterFields`), checked once per change. Only `level`, `duration_ms`, `rows` and `condition` fields and `ConditionBuilder` read them; any of them outside the provider throws while rendering, and so does a `level` field when the host has no levels (a `RangeError`).
192
+
193
+ ### Errors thrown while rendering
194
+
195
+ Each of these is a caller's error and reaches the nearest error boundary: a part outside console-ui's `ConsoleUiRoot`; a choice field or `useOptionLabelOf` outside `PluginOptionsProvider`; a `level`, `duration_ms`, `rows` or `condition` field or a `ConditionBuilder` outside `PluginFieldsProvider`; host values that break their schema (a `ZodError`); a `level` field with no host levels (a `RangeError`); a choice field or a condition's choice value that needs the combo box (see above);
196
+ a field whose type is outside the vocabulary (a `TypeError`); and a breach of the option host's contract.
197
+
198
+ ### Accessibility
199
+
200
+ The parts are drawn with console-ui's components, so the 44 px targets, the AAA contrast pairs of both schemes and the focus ring are console-ui's; the package has no stylesheet of its own. Every control has a name, every description and error is tied to its control (`aria-describedby`, `aria-invalid`), the option states waiting for an answer are a status line that never takes focus, and the tests check every part with axe and console-ui's colour-role scan in jsdom.
201
+
202
+ ## Development
203
+
204
+ ```bash
205
+ pnpm --filter @aiquants/plugin-settings run build # dist/index.*, dist/react.*, shared dist/chunk-*
206
+ pnpm --filter @aiquants/plugin-settings run typecheck
207
+ pnpm --filter @aiquants/plugin-settings run check # Biome
208
+ pnpm --filter @aiquants/plugin-settings run test:coverage # exits non-zero below 100 % statements / branches / functions / lines
209
+ ```
210
+
211
+ The React specs run in jsdom (each starts with a `@vitest-environment jsdom` docblock); the rest run in Node.
212
+
213
+ ## License
214
+
215
+ MIT