Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Typed Preferences on the Wire
Status: In Progress — all three phases (A declarations and generator, B contract, C enforcement) in one pull request, one commit series per phase
Target: Spree 6.0
Depends on: 6.0-json-preferences.md (JSON storage, decimals as exact strings, tiers as a list, secret_preferences), 6.0-money-correctness.md (money and rate string formats)
Author: Damian + Claude
Last updated: 2026-10-09 (open questions settled, implementation started)
Tracking: Linear V-3739 · GitHub spree/spree#14850
Summary
Preferences reach the API in two ways, and both expose the Ruby preferences DSL instead of a contract. Settings on concrete resources (store, channel, seller profile) appear as preferred_* fields: the prefix is the DSL's method name, not a word an API client should see. Configurable subtypes (promotion rules and actions, calculators, payment methods, integrations, delivery method rules, commission rules, order routing rules, price rules, seller requirements, imports) send type plus an untyped preferences: Record<string, unknown>. They also carry a preference_schema written in Ruby type names (decimal, password, array, hash). The real behaviour lives in code no client can see: the parse_on_set lambdas decode prefixed IDs and normalize country codes, an unknown key raises NoMethodError, and :array preferences declare no item type. This plan renames the preferred_* fields to plain names. It compiles every preference declaration to JSON Schema and publishes each family as a discriminated union in OpenAPI and the SDKs. It also validates every preferences write against that schema. The declarations stay the only source: no second schema is written by hand. The result is a configuration contract that the dashboard, plugin authors, AI agents and any non-Ruby implementation can read, type-check and validate in the same way.
Key Decisions (do not deviate without discussion)
The preference declarations remain the single source (continuing
6.0-json-preferences.md). The JSON Schema, the OpenAPI components, the SDK types, the/…/typesresponses and write validation are all generated frompreference :name, :type, …. Nothing is maintained by hand.Declarations become complete.
:arrayrequiresof:.:hashrequireskeys:andvalues:. An ID list declaresof: :id, model:, scope:, which replaces itsparse_on_setdecoding lambda. Money values declare the:moneytype. Fixed vocabularies declarechoices:. Domain formats (:currency,:iso_country,:date,:timezone) declareformat:. A declaration the generator cannot compile fails a spec, not production.:anyis removed. No production declaration uses it any more (the three counted by6.0-json-preferences.mdare gone); only specs did, and they move to real types.Type mapping:
Declaration JSON Schema :string,:textstring(textaddsx-spree-widget: textarea):booleanboolean:integerinteger:decimalstring, canonical decimal pattern:moneystring, canonical decimal pattern,format: money(the money plan's preference type):array, of:arraywith typeditems;of: :idgivesformat: prefixed-idandx-spree-prefix:hash, keys:, values:objectwithpropertyNamesandadditionalProperties:passwordstring,writeOnly: true,x-spree-secret: true:datestring,format: datechoices:enumformat: :currency/:iso_countrystring,format: currency/format: iso-country(drives the dashboard's currency select and country combobox)Defaults become
default, except for secrets, which never carry one.Families are open unions. Each family is published as
oneOfwithdiscriminator: { propertyName: type }. It has one member per built-in subtype, and one final fallback member:{ type: string, preferences: object }. The SDK type isItemTotalRule | CountryRule | … | UnknownPromotionRule. Narrowing ontypetypespreferencesfor built-in subtypes, while a plugin subtype still type-checks. This respects the existing rule that registry-driventypevalues cannot be closed enums: registries fill after serializers load.Built-in subtypes are static and every subtype is discoverable. OpenAPI and the SDKs carry the subtypes Spree ships. The
/…/typesendpoints return{ type, label, schema }for every registered subtype, plugins included, from the same generator.schemareplacespreference_schema.preference_schemaleaves resource rows. It describes a class, not a record. Today it is repeated on every serialized rule, action and integration. Clients read it from/…/types.Writes are validated before assignment. Admin and Seller controllers validate
preferencesagainst the subtype's schema withjson_schemer. An unknown key, a wrong type, a malformed or foreign ID, or a value outsidechoicesreturns 422invalid_preferences, with a JSON pointer per failure (/preferences/channel_ids/1). A non-Ruby implementation validates the same schema with Ajv or Zod, so the two cannot drift.ID decoding becomes declarative.
format: prefixed-idwithx-spree-prefixtells the server which values to decode, and to decode only those. Controllers that skipnormalize_paramsto protect opaque provider values (Admin::PaymentMethodsController) no longer need that exception for preferences.The secret round trip is specified, not just implemented. A secret reads back masked (
"••••1234"). Writing the masked value back leaves the secret unchanged.nullclears it. Any other string replaces it. This lives in the contract (x-spree-secret) and in the conformance spec, not only inSpree::Preferences::Masking.masked?.preferred_*fields are renamed. On resources whose settings are a fixed set (store, channel, seller profile and any other serializer exposingpreferred_*), the wire name drops the prefix:preferred_guest_checkoutbecomesguest_checkout, andpreferred_timezonebecomestimezone. The model owns the bridge, following the existing read/write symmetry rule:Preferablegainsexposes_preferences :guest_checkout, :timezone, …, which defines plain readers and writers. Serializers and controllers use only the plain names. Typed by the same mapping above.order.preferred_stock_location_idis not renamed. It is an association whose domain name is "preferred stock location", not a preference.One calculator shape. Delivery methods move from flat
calculator_typepluscalculator_preferencesto the nestedcalculator: { type, preferences }used by promotion actions, on both read and write.The
preferencesfield name stays. It is plain English, not a Ruby term. The leaks were the untyped values and thepreferred_prefix.Breaking in 6.0, for every v3 API. Consistent with the Ruby-class-name change (#14837). Every renamed field and every removed
preference_schemais listed in the upgrade guide. Inventory (2026-10-09) found the Store API unaffected: the cart's onlypreferred_*field ispreferred_stock_location_id, which stays, and the sellerprofilebelongs to the Seller API.One pull request, one commit series per phase (decided 2026-10-09). The three phases below are delivered together so every breaking 6.0 change is reviewed and released at once.
storefront_urlis the store setting's plain name; its reader keeps the fallback (decided 2026-10-09, narrowed the same day in review). Dropping the prefix collides withStore#storefront_url. The setting takes the name on the wire and in the model, no second method is introduced, and the model's reader still answers the first non-loopback allowed origin and then the store's own URL when nothing is set, so customer emails and the product feed never get an empty base URL. The API'sstorefront_urlfield returns the stored setting (nullwhen unset), whileurlkeeps returning the effective address: review found that serving the fallback made the dashboard show a "View store" link for stores without a storefront, and save the fallback back as if the merchant had typed it.Incomplete declarations warn in 6.0 and raise in 6.1 (decided 2026-10-09). An
:arraywithoutof:, a:hashwithoutkeys:/values:, or:anylogs a deprecation naming the missing option, and its schema accepts any value for that key, so an un-updated plugin keeps working. Every declaration Spree ships is complete, and a spec enforces it.exposes_preferencesdoes not grant write access to anyone (decided 2026-10-09). It defines the plain model reader and writer only. Each API keeps its own permitted list, and Seller controllers keep usingadditional_seller_permitted_attributes, so exposing a setting never makes it seller-writable.
Settled during implementation (2026-10-09)
- An id list names its model, not its prefix.
of: :id, model: 'Spree::Channel', scope: ->(rule) { … }. The prefix (x-spree-prefix) is read from the model, and the model is needed anyway to check that every id exists insidescope.model:takes a class name or a block (-> { Spree.customer_class }), so a declaration never loads another class.normalize_id_preferencestays one release as a deprecated bridge. - The SDK narrows through a map, not a union with a catch-all member. TypeScript does not narrow on
typewhen one member'stypeisstring, so the plan'sItemTotalRule | … | UnknownPromotionRulewould type nothing. Each family ships<Family>PreferencesMap(an interface, so an extension adds its types by declaration merging, as withWebhookEventMap) andTyped<Family>, the resource narrowed bytype. The generated resource type keepspreferences: Record<string, unknown>, which is what a plugin type reads as. - OpenAPI carries the family union on
preferences, without adiscriminator. The specs are OpenAPI 3.0.3, andtypesits outside thepreferencesobject, so a discriminator cannot apply. Each family is ananyOfof its subtypes plus a plain object, withx-spree-preferences-by-typemapping eachtypeto its component. Nullable types usenullable: true;propertyNamesbecomesx-spree-property-names. - Secrets are not
writeOnly. They read back masked, so the property is in responses;x-spree-secretmarks them. A secret is always nullable, because an unset one reads asnull. - Defaults computed at read time are not in the schema. A default given as a block (the default store's currency) differs per store and needs the database, so it is left out and does not make the value nullable. The schema can then be generated without a database.
- Internal preferences are refused on write. They are not in the schema, so sending one is an unknown key (422), not a silent no-op.
- An id that is well formed but outside the store, or missing, is a 422
invalid_preferences, with the pointer of the list, rather than a 404. normalize_paramsleavespreferencesalone. It decoded every*_idsvalue inside nested hashes, which would have turned valid prefixed ids into integers before the schema saw them.- Old
preferred_*keys are still accepted on write for one release (found in review), with a deprecation warning, on the store, channel and import endpoints; responses use only the plain names. Without it a 5.x client's change was silently dropped with a 200.preferred_auto_captureandpreferred_auto_capture_on_dispatchstay accepted until 6.1, as already promised. - Deprecated preferences stay writable until their removal (found in review). They are in the schema with
deprecated: true, so a write is accepted with the existing deprecation warning; forms and reads leave them out. - The old delivery-method calculator parameters are bridged too (found in review):
calculator_typeandcalculator_preferencesare still accepted on write until 6.1, with a deprecation warning. - An id list declared without
of:still has its prefixed ids decoded in 6.0, as the API did for every*_idskey before, so an extension that has not completed its declarations keeps working until 6.1. - A calculator is attached only after its settings are accepted (found in review). On a saved delivery method, assigning a new calculator replaces the stored one at once, so a refused update used to leave a free rate behind.
/payment_methods/typeslists every provider, withinstalled. An installed provider's edit form reads its schema from that list now that rows no longer carry one, so the list may not leave it out; pickers filter oninstalled. Reading it needs read access, not create.- A failure inside a nested payload names its row:
/rules/1/preferences/channel_ids/0,/actions/0/calculator/preferences/amount,/calculator/preferences/amount. - Values stored before the declarations were typed read back in the declared form, so a delivery method saved with numeric
amountscan be re-saved unchanged. - Validation errors on an exposed setting use its plain name. A model validates
preferred_<name>; the API reports the error as<name>. preference_attributes Model, :name, …in serializers types each exposed setting from its declaration, so the generated SDK types follow the model. Store decimal settings are now exact strings.- Money is the money plan's
:moneytype, not amoney:option (settled 2026-10-09 when rebasing onto the money changes):preference :amount, :moneycompiles toformat: money, and reads keep that plan's formatting in the calculator's currency. - Calculators are typed in the SDKs' generated resource types (decided 2026-10-09 with the author):
calculatorisTypedDeliveryCalculator | nullandTypedPromotionCalculator | null, generated through the serializers' type hints. Each settings shape is emitted as atyperather than aninterface, so it stays assignable to theRecord<string, unknown>that generic forms take. - Aligned with Rails 8.2's
has_jsonwhere it costs little (decided 2026-10-09 with the author). Storage is already the same flat JSON object; strings, integers and booleans now cast throughActiveModel::Type, ashas_jsondoes; andexposes_preferencesdefines the reader, writer and?predicatehas_delegated_jsonwould. No migration tohas_jsonis planned: it covers only those three types, with no decimals, lists, secrets, nullability or published schema. ItemTotal'soperator_min/operator_maxdeclare nochoices:yet. Their defaults are>/<while the code compares againstgt/gte; fixing that needs a data upgrade for stored rules and is left for a follow-up.
Design Details
Declaration additions
preference :amount_min, :money
preference :channel_ids, :array, of: :id, model: 'Spree::Channel', scope: ->(rule) { rule.store.channels }, default: []
preference :country_codes, :array, of: :string, format: :iso_country, default: []
preference :match_policy, :string, choices: %w[any all none], default: 'any'
preference :amounts, :hash, keys: :currency, values: :money, default: {}
preference :tiers, :array, of: :object, properties: { threshold: :money, value: :decimal }, default: []
preference :secret_key, :password
parse_on_set stays available for normalization a schema cannot express. It may not change the type, and the generator ignores it.
Generator
Spree::PreferenceSchema::JsonSchema.for(klass) compiles a class's declarations (deprecated and internal preferences excluded, as today) into a JSON Schema object with additionalProperties: false. It is memoized per class, like preference_schema. It is used by:
- The OpenAPI components.
swagger_helperregisters one component per built-in subtype (PromotionRuleItemTotal) and one union per family (PromotionRule), so rswag emits them. The specs stay generated; nothing indocs/api-reference/*.yamlis edited by hand. - Typelizer. Serializers type
preferencesper family with the union name. The generated TypeScript and Zod schemas follow through the existing pipeline. - The
/…/typesendpoints. These returnschemafor every registered subtype. - Write validation. In the shared Admin and Seller resource controller, for every controller that permits
preferences.
Conformance spec
One spec walks every registered subtype in every family:
- The schema compiles.
- A record built from its factory serializes
preferencesthat validate against the schema. - Defaults validate.
- Each declared ID list rejects a foreign prefix.
- Each secret round-trips masked, unchanged on mask, and cleared on
null. - A key not in the schema returns 422.
This is the black-box check a second implementation must also pass.
Dashboard
The generic preference form (rule, action, calculator and integration editors) renders from schema instead of preference_schema. Widgets are chosen by format and x-spree-widget: currency select, country combobox, prefixed-ID resource picker, textarea, and masked secret input. Hand-written per-subtype forms keep working, and gain types from the unions.
Migration Path
PR A: declarations and generator (no wire change)
- Add
of:,keys:/values:,money:,format:,model:andscope:toPreferabledeclarations. Complete every:arrayand:hashdeclaration in core and providers. Resolve the:anydeclarations. - Replace the ID-decoding
parse_on_setlambdas withof: :id, model:, scope:. - Add
PreferenceSchema::JsonSchemaand a spec that fails for any registered subtype whose schema does not compile.
PR B: contract (breaking)
- Add OpenAPI components and family unions in
swagger_helper; serializers typepreferenceswith them; run the type generation pipeline. /…/typesendpoints returnschema; removepreference_schemafrom resource serializers.- Add
exposes_preferences; rename everypreferred_*wire field (exceptpreferred_stock_location_id) on read and write. - Move delivery methods to the nested calculator shape.
- Update the dashboard's generic preference form and every reference to renamed fields; e2e coverage for one subtype per family.
- Docs:
docs/developer/customization/model-preferences.mdx(new declaration options), the Admin API pages for each family,docs/developer/upgrades/5.6-to-6.0.mdx(rename table, removedpreference_schema, calculator shape),docs/changelog.mdx, and an SDK changeset.
PR C: enforcement
- Validate
preferenceswrites withjson_schemer; 422invalid_preferenceswith JSON pointers. - Drop the
normalize_paramsexception for preferences inAdmin::PaymentMethodsController, since IDs are now decoded by schema. - Add the conformance spec.
Verification per PR: pnpm test:changed, then pnpm test:rspec core and pnpm test:rspec api one at a time; pnpm typecheck and pnpm test for packages/sdk, packages/admin-sdk, packages/seller-sdk and packages/dashboard; dashboard e2e for the preference editors.
Constraints on Current Work
- A new preference declares its full type:
of:on arrays,keys:/values:on hashes, the:moneytype for money,choices:on fixed vocabularies,format:for currencies, countries and dates. Never:any. - An ID list is
of: :id, model:, scope:, never aparse_on_setdecoding lambda. - Never add a
preferred_*attribute to a serializer or a permitted-params list. Expose the setting under its plain name through the model. - Never add
preference_schemato a new serializer. Subtype schemas belong to the family's/…/typesendpoint. - A new configurable family publishes a
/…/typesendpoint and a typed union, with the fallback member, from day one. - A new calculator-bearing resource uses
calculator: { type, preferences }.
Open Questions
None. The three questions raised during design were settled on 2026-10-09 (see Key Decisions): the only name collision is storefront_url; exposes_preferences leaves seller permissions alone; incomplete plugin declarations warn in 6.0.
References
docs/plans/6.0-json-preferences.md: storage, decimals as strings, tiers as a list, encrypted secretsdocs/plans/6.0-money-correctness.md: money and rate string formats used byformat: moneyand:decimal- spree/spree#14837: Ruby class names replaced with short names; the precedent for this change
spree/core/app/models/concerns/spree/preference_schema.rb,spree/core/lib/spree/core/preferences/masking.rb- CLAUDE.md, "Typed values" and "Read and write attribute names must match"