Modul:Entity/StructuredData/Smw
Aus Star Citizen Wiki
Weitere Optionen
Die Dokumentation für dieses Modul kann unter Modul:Entity/StructuredData/Smw/doc erstellt werden
require('strict')
--- @module Entity/StructuredData/Smw
--- The SMW backend of Module:Entity/StructuredData: writes the shaped, routed
--- rows from the Entity manifest as page-level properties via `mw.smw.set`,
--- mirroring the German wiki's own Entity writers, which store every value on
--- the page's own subject; the one exception is `%rows` tables, whose rows
--- keep their per-row correlation as named subobjects (`mw.smw.subobject`,
--- see storeRow). Required only inside the 'smw' branch of
--- StructuredData.store, so the Bucket path never loads this file and this
--- file never touches `mw.ext.bucket`.
---
--- FIELD_SPECS below is the approved German crosswalk for the Vehicle, Item,
--- Commodity, Location and Mission routing buckets (plus the wearable_set
--- table of Module:WearableSet's own manifest, added with its domain slice),
--- built from the live-created/updated
--- declarations recorded in wiki-ports/entity-port (stage1-property-created.json,
--- existing-property-declarations-created.json, existing-property-updated.json),
--- the rev-pinned reuse targets of german-property-change-plan.md and, for the
--- Location rows, the legacy-writer census of research/location-legacy-smw.md.
--- Values
--- are German machine tokens, verbatim, and every emitted magnitude keeps its
--- Bucket scale: no field is rescaled or semantically converted here. Two
--- targets deliberately correct a live typo in the property name (see the
--- original_pledge_price and thermal_damage_modifier entries): the corrected
--- names are written fresh and the typo properties go dark at the switch.
---
--- Serialization follows the live sandbox results (smw-number-sandbox-results.md,
--- quantity-sandbox-results.md): the German wiki's SMW parses numbers in de
--- locale only, so every Lua number is serialized as a comma-decimal string by
--- germanNumber. Zahl targets carry no unit; quantity targets (Maß/Menge
--- declarations) append their unit token, because a bare fractional write is
--- only proven WITH a unit and a bare integer silently lands in the property's
--- primary unit. quantum_speed (Mm/s) and quantum_range (Gm) are written as the
--- m/s and m their properties expect; volumes stay µSCU and let the SCU
--- declaration's factors convert. Armor resistances keep the emitted whole
--- percent on distinct Zahl properties (Rüstungsresistenz (...)): the legacy
--- Modifikator erlittener ... family stores damage-taken multipliers, and
--- 1 - pct/100 would rescale the Bucket value, so it is not written there.
---
--- `pitch`/`yaw` carry formatted seat text ranges and numeric flight-controller
--- rates from two emitters through one Bucket column (remaining-property-
--- blockers.md §2). Their numbers_only specs map the numeric rates to the
--- existing Neigen/Gieren °/s targets - the properties the vehicle hull rates
--- and turret traverse speeds already write - and skip the seat text:
--- covering the ranges needs the upstream emitter/manifest split
--- (Neigebereich/Gierbereich), which changes the shared Bucket schema and is
--- deliberately not done here. UNRESOLVED_FIELDS holds the mission fields
--- without a German target, the remaining gate; a row carrying one fails
--- the store rather than writing a partial row - an unmapped write, whether
--- an English display-name fallback or a silent drop, would plant
--- half-translated data on the German wiki - so every gap stays a named,
--- test-pinned refusal instead. Routing buckets outside WRITABLE_BUCKETS
--- fail the store outright: their crosswalk is not built, and
--- half-translated rows would mix English and German. A plain-key spec
--- answers only for a bucket the registered manifests route the field to:
--- a misplaced field that merely reuses a global spec (a fabricated
--- wearable_set.uuid on the entity uuid mapping) fails as unmapped.
---
--- Two distinct fields mapping to one property (Schadenspunkte, Schildpunkte,
--- Maximalreichweite, Effektive Reichweite, Neigen, Gieren, Rollen, Dauer,
--- Aufladezeit, Abkühlzeit - all cross-kind or cross-subtype, never one page)
--- collapse when the values are equal and fail storage when they differ, so a
--- same-page co-emission becomes a loud error instead of a nondeterministic
--- loss.
--- beam_range deliberately has its own target (Strahlreichweite): tractor-beam
--- gadgets co-emit it with max_range from different API fields, so a shared
--- target would fail those pages outright.
---
--- Property pages still to be created on the German wiki before rollout (see
--- the specs' comments): seven resistances - Rüstungsresistenz (Physisch),
--- (Energie), (Thermisch), (Biochemisch), (Verzerrung), (Betäubung),
--- (Einschlag), Zahl, emitted percent unchanged; Strahlreichweite, Quantity
--- 1 m, tractor-beam and salvage-head range; and Zeit bis Maximalgeschwindigkeit,
--- Dauer (1 Sekunde, s). The flight-controller base rates use the existing
--- Neigen/Gieren/Rollen declarations. The Mission always-fields add four
--- creations: Verfügbar (Boolean), Verifizierung (Text), Ruf Mindeststufe
--- and Ruf Maximalstufe (Text); its numeric payouts add two Zahl creations,
--- Belohnung (aUEC) and Scrip. The WearableSet batch adds one creation,
--- Rüstungsklassifizierung (Text); its numerics reuse the live armor
--- declarations. Rüstungstyp requires a Text declaration before writes.
--- The Location batch (checklist:
--- research/location-smw-prerequisites.md) adds twelve creations - Services,
--- Klassifizierung, Entdeckt von, Entdeckt in, Sprungpunktgröße, Zuständigkeit,
--- Lagrange-Punkt, Betreiber, Übergeordnetes Objekt, Anzahl Stationen, Zone and
--- the Seite-typed Sternensystem - and two retypes: Attribut:Radius and
--- Attribut:Sternensystem Größe must be Maß (km / AE) before this backend
--- writes them. Separately, the seven reused Modifikator
--- declarations (revs 70356-70363) must be retyped from Maß with
--- Corresponds to::100 % to Zahl, and their legacy fraction-vintage values
--- reprocessed or isolated, before this backend writes them - wiki edits
--- deliberately not made here. Unit conversions and target spellings are
--- pinned to the cited revisions; re-verify live before the German
--- deployment selects this backend.
---
--- Vocab-marked specs store German VALUES as well as German property names:
--- serialize maps their English machine tokens to German through
--- Module:Entity/Vocab (pass-through for unmapped values).
--- Vocab is pure data with no mw dependency; Entity/Message (msg()) is
--- display-only and must never be required on the storage path.
local Vocab = require('Module:Entity/Vocab')
local structuredData = require('Module:Entity/StructuredData')
local locationStarmap = require('Module:Entity/Location/Starmap')
local PROPERTIES_PAGE = 'Module:Entity/properties.json'
--- Emitter field name (the manifest's Bucket column, lowercase snake_case) ->
--- German SMW property on star-citizen.wiki. A string value is a plain target
--- (Text/Seite/Zahl/Boolean): text and pages verbatim, numbers comma-decimal.
--- A table value adds serialization facts: `unit` (quantity token to append),
--- `factor` (multiply the emitted magnitude before serializing: the documented
--- Mm/s->m/s and Gm->m scale fixes, nothing semantic), `prefix` (prepend to
--- string values), `numbers_only` (non-number values write nothing: the seat
--- half of the pitch/yaw shape conflict), `parse_number` (string values parse
--- as German-format numbers, parseGermanNumber below, and an unparseable
--- string fails the store: the editor override of a Zahl field, which the
--- de-locale Zahl parser would otherwise rescale or drop), `integer` (a
--- manifest-INTEGER field: a fractional or nonfinite value, number or editor
--- string, fails the store instead of writing a comma decimal or 'inf'),
--- `vocab` (Vocab field name whose English values are translated to German
--- before the write), `strict_vocab`
--- (vocab plus a store refusal for values the vocabulary lacks: the field's
--- German property holds curated German values, and an unmapped token must
--- fail loudly instead of passing through as English).
--- A key may be bucket-qualified ('bucket.field'): the one way two routing
--- buckets share a field name with different targets, since the plain key
--- names the field in every bucket it is routed to (type: mission Auftragsklasse
--- vs wearable_set Rüstungstyp; classification: location Klassifizierung vs
--- wearable_set Rüstungsklassifizierung). Resolution tries the qualified key
--- first, the plain key second; one field name never has both.
--- @type table<string, string|table>
local FIELD_SPECS = {
-------------------------------------------------------------------
-- entity bucket: identity and classification (Base, Entity, Item,
-- Consumable, Inventory, FlightController, QuantumDrive, Vehicle)
-------------------------------------------------------------------
base_variant = 'Ist Basisversion',
class = { property = 'Klasse', vocab = 'class' },
class_name = 'Klassenname',
effects = { property = 'Effekt', vocab = 'effects' },
grade = 'Grad',
hei = 'Hydratationswirksamkeitsindex',
image = { property = 'Kopfbild', prefix = 'Datei:' },
item_type = { property = 'Typ', vocab = 'item_type' },
-- The coarse Entity kind (Vehicle, Item, ...), distinct from subject_type's
-- fine-grained Strukturtyp: Module:Entity/Data reads it back so a sibling
-- renderer on a uuid-less page resolves the infobox's kind.
kind = 'Art',
manual_api_field = 'Manuelles API-Feld',
manufacturer = 'Hersteller',
max_speed = { property = 'Maximalgeschwindigkeit', unit = 'm/s' },
name = 'Name',
ndr = 'Nährstoffdichteindex',
quantum_speed = { property = 'Quantengeschwindigkeit', unit = 'm/s', factor = 1000000 },
quantum_spool_time = { property = 'Quantenspulzeit', unit = 's' },
rarity = { property = 'Seltenheit', vocab = 'rarity' },
scm_speed = { property = 'Kampfgeschwindigkeit', unit = 'm/s' },
size = 'Größe',
storage_capacity = { property = 'Inventar', unit = 'µSCU' },
subject_type = { property = 'Strukturtyp', vocab = 'subject_type' },
systems = 'Sternensystem',
uuid = 'UUID',
volume = { property = 'Volumen', unit = 'µSCU' },
-------------------------------------------------------------------
-- cargo_grid bucket (one subobject row per grid; see storeRow)
-------------------------------------------------------------------
cargo_grid_capacity = { property = 'Cargo Grid Kapazität', unit = 'SCU' },
cargo_grid_external = 'Cargo Grid extern',
cargo_grid_height = { property = 'Cargo Grid Höhe', unit = 'm' },
cargo_grid_length = { property = 'Cargo Grid Länge', unit = 'm' },
cargo_grid_minimum_item_shortest_side = {
property = 'Minimale Objektgröße (Cargo Grid, kürzeste Seite)',
unit = 'm',
},
cargo_grid_minimum_item_middle_side = {
property = 'Minimale Objektgröße (Cargo Grid, mittlere Seite)',
unit = 'm',
},
cargo_grid_minimum_item_longest_side = {
property = 'Minimale Objektgröße (Cargo Grid, längste Seite)',
unit = 'm',
},
cargo_grid_maximum_item_shortest_side = {
property = 'Maximale Objektgröße (Cargo Grid, kürzeste Seite)',
unit = 'm',
},
cargo_grid_maximum_item_middle_side = {
property = 'Maximale Objektgröße (Cargo Grid, mittlere Seite)',
unit = 'm',
},
cargo_grid_maximum_item_longest_side = {
property = 'Maximale Objektgröße (Cargo Grid, längste Seite)',
unit = 'm',
},
cargo_grid_maximum_container_size = { property = 'Maximale Containergröße (Cargo Grid)', unit = 'SCU' },
cargo_grid_width = { property = 'Cargo Grid Breite', unit = 'm' },
-------------------------------------------------------------------
-- company bucket
-------------------------------------------------------------------
industry = 'Branche',
products = 'Produkte',
manufacturer_code = 'Hersteller Code',
race = { property = 'Volk', vocab = 'race' },
headquarters = 'Hauptsitz',
area_served = 'Gebiet',
founder = 'Gründer',
founded = 'Gründung',
parent_company = 'Muttergesellschaft',
subsidiaries = 'Tochtergesellschaften',
predecessor = 'Vorgänger',
successor = 'Nachfolger',
-------------------------------------------------------------------
-- vehicle bucket
-------------------------------------------------------------------
added_in_version = 'Eingeführt in Version',
average_purchase_price = { property = 'Durchschnittlicher Kaufpreis', unit = 'aUEC' },
average_rental_price = { property = 'Durchschnittlicher Mietpreis', unit = 'aUEC' },
beds = 'Betten',
career = { property = 'Karriere', vocab = 'career' },
cargo_capacity = { property = 'Frachtkapazität', unit = 'SCU' },
-- Editorial free text: Typ Text stores prose verbatim, where Typ Datum
-- silently drops a value that fails its parse.
concept_announcement_date = 'Ankündigungsdatum',
concept_sale_date = 'Concept-Sale-Datum',
crew_stations = 'Besatzungsstationen',
entity_height = { property = 'Höhe', unit = 'm' },
entity_length = { property = 'Länge', unit = 'm' },
entity_width = { property = 'Breite', unit = 'm' },
generation = 'Generation',
-- Unitless integers: the USD/minute/aUEC unit tokens of these legacy
-- declarations are not evidenced, and a bare integer is proven to land in
-- the property's primary unit (which is the emitted scale). Fractional
-- values (manifest DOUBLE) rely on the German parser accepting unitless
-- comma decimals like it does on Zahl - a documented live-verify item.
insurance_claim_time = 'Reklamationszeit',
insurance_expedite_cost = 'Beschleunigungskosten',
insurance_expedite_time = 'Beschleunigungszeit',
loaner_vehicle = 'Leihfahrzeug',
lore_release_date = 'Lore-Einführungsdatum',
lore_retirement_date = 'Lore-Ausmusterungsdatum',
mass = { property = 'Gewicht', unit = 'kg' },
maximum_cargo_container_size = { property = 'Maximale Frachtcontainergröße', unit = 'SCU' },
maximum_crew = 'Maximalbesatzung',
medical_bed_tier = 'Medizinbettstufe',
minimum_crew = 'Minimalbesatzung',
-- The variant-category opt-out: the German category design keeps series
-- grouping to '<Baureihe> (Baureihe)', so nothing reads the flag here, but
-- the manifest stores it and the write stays parity with .tools.
novariant = 'Keine Varianten',
ore_capacity = { property = 'Erzkapazität', unit = 'SCU' },
-- Corrected spelling: the live property is the typo 'Ursprünglicher
-- Pledege-Preis'. Writing the corrected name leaves the typo property to
-- go dark once every page re-parses onto this writer.
original_pledge_price = 'Ursprünglicher Pledge-Preis',
original_warbond_pledge_price = 'Ursprünglicher Warbond-Preis',
pledge_availability = 'Pledge Verfügbarkeit',
pledge_price = 'Schiffspreis',
production_state = { property = 'Produktionsstatus', vocab = 'production_state' },
retracted_height = { property = 'Eingezogene Höhe', unit = 'm' },
retracted_length = { property = 'Eingezogene Länge', unit = 'm' },
retracted_width = { property = 'Eingezogene Breite', unit = 'm' },
role = { property = 'Fokus', vocab = 'role' },
series = 'Baureihe',
-- Opt-in to series matching across manufacturers (an Esperia replica and
-- its Vanduul original); Module:Entity/Related needs both pages to set it.
shared_series = 'Gemeinsame Baureihe',
ship_matrix_size = { property = 'Ship Matrix Größe', vocab = 'ship_matrix_size' },
warbond_pledge_price = 'Warbond Pledgepreis',
weapon_rack_capacity = 'Waffenhalterungen',
-------------------------------------------------------------------
-- vehicle_stats bucket
-------------------------------------------------------------------
armor_deflection = 'Ablenkschwelle (Mittel)',
armor_resistance = 'Rüstungsresistenz',
biochemical_damage_modifier = 'Modifikator Biochemieschaden',
cs_signature_modifier = 'Modifikator Querschnittssignatur',
cross_section = 'Radarquerschnitt',
cross_section_height = 'Radarquerschnitt (Höhe)',
cross_section_length = 'Radarquerschnitt (Länge)',
cross_section_width = 'Radarquerschnitt (Breite)',
distortion_damage_modifier = 'Modifikator Verzerrungsschaden',
em_emission = 'Elektromagnetische Strahlung',
em_signature_modifier = 'Modifikator EM-Signatur',
energy_damage_modifier = 'Modifikator Energieschaden',
energy_deflection = 'Ablenkschwelle (Energie)',
health_point = 'Schadenspunkte',
-- Tank sizes keep the emitted SCU scale: Vehicle passes the API values
-- (fuel.capacity, quantum.quantum_fuel_capacity) with no x1000, so the
-- writer emits the API number as-is under unit SCU.
-- The local declarations are SCU-only; on the observed live wiki baseline (revs 88968/88969) the properties declare L/m³ equivalents, and on the one live page checked (315p) the fuel printouts answer m³ and stay rejected by the reader.
-- SCU read-back is verified only against the sandbox probe; that m³ disappears on production is not a promised outcome - it requires the declarations shipped, every page re-parsed and a live cohort check confirming the printout shape.
hydrogen_fuel_capacity = { property = 'Kraftstoffkapazität', unit = 'SCU' },
hydrogen_fuel_intake_rate = 'Wasserstoffkraftstoff-Aufnahmerate',
ir_emission = 'Infrarotstrahlung',
ir_signature_modifier = 'Modifikator Infrarotsignatur',
missile_damage = 'Raketenschaden',
physical_damage_modifier = 'Modifikator physischer Schaden',
physical_deflection = 'Ablenkschwelle (Physisch)',
pilot_dps = 'Piloten-DPS',
pilot_sustained_dps = 'Piloten-DPS (dauerhaft)',
quantum_fuel_capacity = { property = 'Quantenkraftstoffkapazität', unit = 'SCU' },
pitch_rate = { property = 'Neigen', unit = '°/s' },
quantum_range = { property = 'Quantenreichweite', unit = 'm', factor = 1000000000 },
roll_rate = { property = 'Rollen', unit = '°/s' },
shield_health_point = 'Schildpunkte',
stun_damage_modifier = 'Modifikator Betäubungsschaden',
-- Corrected spelling: the live property is the typo 'Modifikator
-- Thermieschaden'. Thermal has no noun compound in German, so the target
-- follows the adjective form of 'Modifikator physischer Schaden'; the
-- typo property goes dark once every page re-parses onto this writer.
thermal_damage_modifier = 'Modifikator thermischer Schaden',
turret_dps = 'Turm-DPS',
turret_sustained_dps = 'Turm-DPS (dauerhaft)',
yaw_rate = { property = 'Gieren', unit = '°/s' },
-- Renamed from the live Beschleunigung Maximum (rev 89459, declaration
-- mirrored verbatim under the new name): the old name reads as a
-- magnitude, not a time. The old-name page goes dark once pages re-parse
-- onto this writer.
zero_to_maximum_speed_time = { property = 'Zeit bis Maximalgeschwindigkeit', unit = 's' },
-------------------------------------------------------------------
-- item_weapon bucket
-------------------------------------------------------------------
alpha_damage = 'Alphaschaden',
ammo = 'Munition',
arm_time = { property = 'Aktivierungszeit', unit = 's' },
blast_radius = { property = 'Schadensradius', unit = 'm' },
capacity_count = 'Anzahl Anschlüsse',
capacity_size = 'Anschlussgröße',
-- The upstream union field holds the weapon chain's per-shot alpha total and
-- the grenade and magazine facets' damage; the store renames the weapon half
-- to alpha_damage (weaponAlphaDamage), so `damage` itself writes only facet
-- damage here and Bucket keeps the one union column. Readers of weapon alpha
-- resolve the Alpha damage name (Alphaschaden), never this property.
damage = 'Schaden',
damage_class = { property = 'Schadensart', vocab = 'damage_class' },
damage_type = { property = 'Schadenstyp', vocab = 'damage_type' },
dps = 'Schaden pro Sekunde',
drop_angle = { property = 'Abwurfwinkel', unit = '°' },
explosion_radius = { property = 'Maximaler Explosionsradius', unit = 'm' },
fire_rate = { property = 'Schussrate', unit = 'rpm' },
firing_type = { property = 'Waffentyp', vocab = 'firing_type' },
full_damage_range = { property = 'Volle Schadensreichweite', unit = 'm' },
laser_range = { property = 'Effektive Reichweite', unit = 'm' },
lock_angle = { property = 'Erfassungswinkel', unit = '°' },
lock_range = { property = 'Erfassungsreichweite', unit = 'm' },
lock_time = { property = 'Erfassungszeit', unit = 's' },
magnification = { property = 'Vergrößerungsfaktor', unit = 'x' },
max_range = { property = 'Maximalreichweite', unit = 'm' },
min_damage = 'Minimaler Schaden',
missile_range = { property = 'Maximalreichweite', unit = 'm' },
missile_speed = { property = 'Raketengeschwindigkeit', unit = 'm/s' },
muzzle_velocity = { property = 'Mündungsgeschwindigkeit', unit = 'm/s' },
pitch_speed = { property = 'Neigen', unit = '°/s' },
range_increment = { property = 'Nullstellung Schrittweite', unit = 'm' },
signal_type = { property = 'Signaltyp', vocab = 'signal_type' },
slash_damage = 'Schnittschaden',
stab_damage = 'Stichschaden',
warhead_damage = 'Sprengkopfschaden',
weapon_class = { property = 'Waffenklasse', vocab = 'weapon_class' },
yaw_speed = { property = 'Gieren', unit = '°/s' },
-------------------------------------------------------------------
-- item_tool bucket
-------------------------------------------------------------------
beam_force = { property = 'Maximale Kraft', unit = 'N' },
beam_max_angle = { property = 'Maximaler Winkel', unit = '°' },
-- Schwerlastkraft's declaration carries the live Attribut:Kraft dot-factor
-- defect (kN registers factor 1, MN dead); N-only writes are proven exact.
beam_mode_force = { property = 'Schwerlastkraft', unit = 'N' },
-- Own target, to be created (Quantity 1 m): tractor-beam gadgets co-emit
-- beam_range and max_range from different API fields, so sharing
-- Maximalreichweite would fail those pages' entire store.
beam_range = { property = 'Strahlreichweite', unit = 'm' },
beam_tether_break = { property = 'Seilbruchzeit', unit = 's' },
-- Seven distinct Zahl properties, to be created: the emitted whole percent
-- stored unchanged (Bucket parity); the legacy Modifikator erlittener ...
-- family stores damage-taken multipliers and is deliberately not written.
biochemical_resistance = 'Rüstungsresistenz (Biochemisch)',
blood_drug_level = 'Blutdrogenspiegel',
charges = 'Anwendungen',
damage_repair_rate = 'Schadensreparaturrate',
distortion_resistance = 'Rüstungsresistenz (Verzerrung)',
duration = { property = 'Dauer', unit = 's' },
energy_resistance = 'Rüstungsresistenz (Energie)',
error_chance = 'Fehlerchance',
extraction_efficiency = 'Modifikator Extraktionseffizienz',
extraction_throughput = 'Extraktionsdurchsatz',
health_repair_rate = 'Gesundheitsreparaturrate',
impact_resistance = 'Rüstungsresistenz (Einschlag)',
material_efficiency = 'Materialeffizienz',
maximum_range = { property = 'Maximalreichweite', unit = 'm' },
mining_power_max = 'Maximale Bergbau-Laserleistung',
mining_power_min = 'Minimale Bergbau-Laserleistung',
mining_type = { property = 'Bergbaumodultyp', vocab = 'mining_type' },
-- The Modifikator family writes as Zahl: the mining emitters pass signed
-- percent points through unchanged (Facet/Mining toNumber plus the
-- all_charge_rates negation; WeaponMining shares it), so no x100 and no
-- % suffix - comma-decimal only. The seven reused targets below (revs
-- 70356-70363) are live Maß with Corresponds to::100 %: retype each to
-- Zahl before rollout - a bare number in a percent-correspondence quantity
-- is read in its main unit and silently rescales - and reprocess or
-- isolate the stored fraction-vintage values (0.85 beside -85). Wiki
-- edits, deliberately not made here.
modifier_cluster_factor = 'Modifikator Clusterfaktor',
modifier_extraction_laser_power = 'Modifikator Extraktion-Laserleistung',
modifier_inert_materials = 'Modifikator Inerte Materialien',
modifier_laser_instability = 'Modifikator Laser-Instabilität',
modifier_mining_laser_power = 'Modifikator Bergbau-Laserleistung',
modifier_optimal_charge_rate = 'Modifikator Optimale Laderate',
modifier_optimal_charge_window_size = 'Modifikator Optimale Ladefenstergröße',
modifier_overcharge_rate = 'Modifikator Überladerate',
modifier_resistance = 'Modifikator Resistenz',
modifier_shatter_damage = 'Modifikator Splitterschaden',
module_slots = 'Modulplätze',
optimal_range = { property = 'Effektive Reichweite', unit = 'm' },
physical_resistance = 'Rüstungsresistenz (Physisch)',
radius_multiplier = 'Modifikator Radius',
ramp_down_time = { property = 'Auslaufzeit', unit = 's' },
ramp_up_time = { property = 'Anlaufzeit', unit = 's' },
salvage_speed_multiplier = 'Modifikator Bergungsgeschwindigkeit',
stun_resistance = 'Rüstungsresistenz (Betäubung)',
thermal_resistance = 'Rüstungsresistenz (Thermisch)',
weight_class = { property = 'Rüstungsklasse', vocab = 'weight_class' },
-------------------------------------------------------------------
-- item_component bucket
-------------------------------------------------------------------
vehicle = 'Fahrzeug',
boost_speed = { property = 'Boostgeschwindigkeit', unit = 'm/s' },
coolant_generation = 'Kühlmittelerzeugung',
cooling_rate = 'Kühlrate',
distortion = 'Verzerrung Gesundheit',
em_signature = 'Maximale elektromagnetische Signatur',
emp_charge_time = { property = 'Aufladezeit', unit = 's' },
emp_cooldown = { property = 'Abkühlzeit', unit = 's' },
emp_distortion_damage = 'EMP Verzerrungsschaden',
emp_duration = { property = 'Dauer', unit = 's' },
emp_radius = { property = 'EMP Radius', unit = 'm' },
g_force_resistance = 'G-Kraft-Resistenz',
health = 'Schadenspunkte',
ir_signature = 'Infrarotsignatur',
jump_alignment_rate = 'Sprungausrichtungsrate',
jump_fuel_usage_multiplier = 'Sprungkraftstoffverbrauch-Multiplikator',
jump_tuning_rate = 'Sprungabstimmungsrate',
maximum_temperature = { property = 'Maximaler Temperaturwiderstand', unit = '°C' },
minimum_temperature = { property = 'Minimaler Temperaturwiderstand', unit = '°C' },
-- Neigen/Gieren also hold the vehicle hull rates and turret traverse speeds, so the Seat text ranges are omitted (numbers_only); pitch_min/pitch_max and yaw_min/yaw_max retain the separate bounds.
pitch = { property = 'Neigen', unit = '°/s', numbers_only = true },
pitch_boosted = { property = 'Neigen (Boost)', unit = '°/s' },
pitch_max = { property = 'Maximaler Nickwinkel', unit = '°' },
pitch_min = { property = 'Minimaler Nickwinkel', unit = '°' },
power_generation = 'Leistung pro Segment',
power_output = 'Ausgangsleistung',
qig_charge_time = { property = 'Aufladezeit', unit = 's' },
qig_cooldown = { property = 'Abkühlzeit', unit = 's' },
qig_dampener_range = { property = 'Störreichweite', unit = 'm' },
qig_duration = { property = 'Dauer', unit = 's' },
qig_mode = 'Quantenstörmodus',
qig_snare_range = { property = 'Abriegelungsreichweite', unit = 'm' },
quantum_cooldown = { property = 'Quantenabkühlzeit', unit = 's' },
quantum_fuel_requirement = 'Quantenkraftstoffbedarf',
radar_aim_assist_range = { property = 'Zielhilfereichweite', unit = 'm' },
radar_cooldown = { property = 'Abkühlzeit', unit = 's' },
radar_resource_sensitivity = 'Radar Ressourcenempfindlichkeit',
radar_sensitivity = 'Radar Infrarotempfindlichkeit',
radiation_capacity = 'Strahlungskapazität',
radiation_dissipation = 'Strahlungsableitung',
roll = { property = 'Rollen', unit = '°/s' },
roll_boosted = { property = 'Rollen (Boost)', unit = '°/s' },
shield_health = 'Schildpunkte',
shield_regen_delay = { property = 'Schild Schadensverzögerung', unit = 's' },
shield_regeneration = 'Schildpunktregeneration',
-- Seat text vs numeric rates, as pitch above.
yaw = { property = 'Gieren', unit = '°/s', numbers_only = true },
yaw_boosted = { property = 'Gieren (Boost)', unit = '°/s' },
yaw_max = { property = 'Maximaler Gierwinkel', unit = '°' },
yaw_min = { property = 'Minimaler Gierwinkel', unit = '°' },
-------------------------------------------------------------------
-- commodity bucket
-------------------------------------------------------------------
-- Group/type values arrive already German from the kind's Germanized
-- LABELS map (one map feeds display and storage); tier and
-- acquisition_kind translate through their vocabularies. Density stays a
-- bare Zahl in g/cm3 and signature a Zahl; the legacy shop-writer price
-- subobjects (Haendler/Ort/Preis) are a separate domain this crosswalk
-- never touches. `systems` rides the shared entity-bucket spec
-- (Sternensystem).
acquisition_kind = { property = 'Erwerbart', vocab = 'acquisition_kind' },
commodity_group = 'Warengruppe',
commodity_type = 'Warenart',
density = 'Dichte',
mineable = 'Abbaubar',
signature = 'Signatur',
tier = { property = 'Seltenheit', vocab = 'rarity' },
-------------------------------------------------------------------
-- location bucket
-------------------------------------------------------------------
-- Property names verbatim from the owner-approved crosswalk
-- (research/location-legacy-smw.md), which adopts the legacy
-- Sternensystem/CelestialObject/SystemEntity writers' German properties
-- where semantics match, so community #ask queries survive the switch
-- from their per-body subobjects to these page-level writes. Legacy
-- properties without a manifest field (Status, Sternensystem Alter,
-- Frostlinie, Alter, Habitabel, the per-amenity counts, the zone/ATC
-- booleans - the crosswalk's dark list) simply stop being written once
-- pages re-parse. Text values keep the leaves' English machine tokens
-- (affiliation compact forms, Small/Medium/Large); system_type and the
-- body classifications translate through their vocabularies. PAGE fields write the bare
-- page names the shaping delivers, on the Hersteller/Leihfahrzeug
-- precedent: the Attribut's Seite declaration makes SMW link them.
-- Creation and retype prerequisites:
-- research/location-smw-prerequisites.md.
-- Affiliation names store compact ('UEE', 'Unclaimed') or as the delinked
-- free text of lore-only affiliations, both into the legacy Text property.
affiliation = 'Kontrolle',
-- Owner decision 2026-11-04: property and display section both read
-- Services; the values are the game's raw map-legend names, repeated and
-- not page titles, so the Attribut stays Text.
amenities = 'Services',
-- Owner decision 2026-11-05: the stored classification is German (the
-- BODY_TYPES browse noun via the body_type vocabulary), overruling the
-- crosswalk's original English-token passthrough; free text outside the
-- vocabulary stays verbatim, visible prose.
classification = { property = 'Klassifizierung', vocab = 'body_type' },
danger_rating = 'Gefahrenlage',
designation = 'Bezeichnung',
-- Declared Seite since rev 2122 and already [[subproperty of::Attribut:Sternensystem]]:
-- nothing to create, and the jump-point target keeps browsing under the
-- system property.
destination_gate = 'Sprungpunkt Zieltor',
destination_system = 'Sprungpunkt Ziel',
discovered_by = 'Entdeckt von',
discovered_in = 'Entdeckt in',
economy_rating = 'Wirtschaft',
jump_point_count = 'Anzahl Sprungpunkte',
jump_point_direction = 'Richtung',
starmap_code = 'Starmap Code',
-- Own target: legacy jump-point sizes went into the generic cross-kind
-- Größe, whose mixed-kind values cannot carry them cleanly.
jump_point_size = 'Sprungpunktgröße',
-- Legacy Rechtsraum is a boolean marker, not a name; reusing it would
-- shift the meaning, so jurisdiction gets its own Text property.
jurisdiction = 'Zuständigkeit',
lagrange_point = 'Lagrange-Punkt',
moon_count = 'Anzahl Monde',
operator = 'Betreiber',
parent = 'Übergeordnetes Objekt',
planet_count = 'Anzahl Planeten',
population_rating = 'Bevölkerungsgröße',
-- Legacy Radius holds formatted text ('1 234 km'); the quantity write
-- needs the Attribut retyped to Maß km first (deployment prerequisite).
radius = { property = 'Radius', unit = 'km' },
star_count = 'Anzahl Sterne',
station_count = 'Anzahl Stationen',
-- Shared with the entity bucket's systems (Sternensystem): Commodity and
-- Mission pages emit systems, Location pages system - never one page.
system = 'Sternensystem',
-- Legacy AE magnitudes are formatted text on the live Attribut; same
-- retype prerequisite, to Maß AE.
system_size = { property = 'Sternensystem Größe', unit = 'AE' },
-- Typ is shared with item_type (entity bucket): Item and Location pages
-- never co-emit it. The German nouns are the SYSTEM_TYPES browse
-- categories (Einsternsystem, Doppelsternsystem, Dreifachsternsystem);
-- the English side is the display label the StarSystem leaf stores, and
-- an unmapped ARK code passes through untranslated, a visible code.
-- Legacy Typ rows carry @en tokens, so existing rows keep reading English
-- until every page re-parses onto this writer - the same refresh
-- semantics as the vehicle value changeover.
system_type = { property = 'Typ', vocab = 'system_type' },
zone = 'Zone',
-------------------------------------------------------------------
-- mission bucket
-------------------------------------------------------------------
-- The legacy Modul:Contract writer's live properties (Kategorie:Auftrag):
-- Auftraggeber (Seite) for the issuing giver, Auftragsklasse (Text) for
-- the work type. Auftraggeber keeps the emitter's verbatim
-- token - giver names are page names on both wikis, so their language
-- follows the fetch locale. Auftragsklasse's live values are German, so
-- type translates through the 'type' vocabulary and an unmapped label
-- fails the store (strict_vocab) instead of storing English.
--
-- The four always-emitted fields write new properties: the nearest legacy
-- names shift meaning (Verfügbarkeit is the repeat cooldown, Text, not a
-- boolean; no legacy property holds standings).
orders = 'Aufträge',
rewards = 'Belohnungen',
available = 'Verfügbar',
faction = 'Auftraggeber',
-- Closed two-token set from the emitter (Mission stores
-- apiData.illegal and 'unverified' or 'verified'), so strict_vocab never
-- refuses a real row; the German values are the display words.
legality = { property = 'Verifizierung', vocab = 'legality', strict_vocab = true },
-- Verbatim English standing names incl. 'None' and API placeholder junk
-- (Bucket parity); a grounded German standing vocabulary can be added
-- later, additively - Text stays Text.
reputation_max = { property = 'Ruf Maximalstufe', vocab = 'standing' },
reputation_min = { property = 'Ruf Mindeststufe', vocab = 'standing' },
-- The Scrip property name stays verbatim: the game's own German strings
-- keep 'MG Scrip' (global_de.ini), and the emitter already sums MG and
-- Council scrip into one number - upstream's two-currency collapse, kept
-- for parity. Manifest INTEGER like uec: only finite integers store, from
-- a number or a German-format editor string.
scrip = { property = 'Scrip', parse_number = true, integer = true },
type = { property = 'Auftragsklasse', vocab = 'type' },
--- The aUEC payout keeps its emitted magnitude, with no unit token: the
-- Zahl target needs no QUANTITY_DIVISORS readback entry. The legacy
-- Bezahlung property stores formatted text ('45.000 aUEC'); reusing it
-- would retype its rows and still store no number, so the payout writes
-- its own Zahl property. Editor input arrives as a string
-- (|payout| overrides the API number), so parse_number reads
-- the German format and fails the store on anything else - a silent drop
-- would lose a valid override and the de parser's thousands-dot reading
-- would rescale a German '45.000' to 45. The manifest field is INTEGER, so
-- a fractional value fails the store whatever shape it arrives in.
uec = { property = 'Belohnung (aUEC)', parse_number = true, integer = true },
-------------------------------------------------------------------
-- wearable_set bucket (Module:WearableSet, its own manifest)
-------------------------------------------------------------------
-- The five numerics land on the live armor/clothing declarations the
-- item_component twins use (revs 70655/70659, 88774, 88784/88785): identity
-- scale, °C on the two temperatures, bare Zahl otherwise. Set pages and
-- item pages are different pages, so the shared targets are cross-kind
-- pairs the collapse check guards, never a co-emission.
g_resistance = 'G-Kraft-Resistenz',
max_temperature = { property = 'Maximaler Temperaturwiderstand', unit = '°C' },
min_temperature = { property = 'Minimaler Temperaturwiderstand', unit = '°C' },
radiation = 'Strahlungskapazität',
radiation_scrub_rate = 'Strahlungsableitung',
-- type and classification carry wearable semantics, not mission or
-- location ones: bucket-qualified keys give them targets without touching
-- the plain specs. Rüstungsklassifizierung is new (Text): values are the
-- game's own German armor terms (Vocab wearable_classification), keeping
-- Klassifizierung (Location body types) and Rüstungsklasse (item weight
-- classes) unmixed.
['wearable_set.type'] = { property = 'Rüstungstyp', vocab = 'wearable_type' },
['wearable_set.classification'] = {
property = 'Rüstungsklassifizierung',
vocab = 'wearable_classification',
},
}
--- In-scope fields with no entry in FIELD_SPECS, by blocker.
--- Everything else must be mapped: a manifest field reaching this list is a
--- crosswalk gap, and a mapped field absent from the manifest is dead weight.
--- Both directions are pinned by test. A row carrying one of these fields
--- fails the store before any write: the remaining optional mission fields
--- are display lines built for the English infobox (Orders/Lines,
--- Rewards/Lines), whose German line shape is not decided, so each needs a
--- target before it writes.
--- @type table<string, string>
local UNRESOLVED_FIELDS = {}
local p = {}
--- The spec `bucket`'s `field` writes through: the bucket-qualified key first,
--- the plain field name second. nil when neither is classified.
--- @param bucket string|nil
--- @param field string
--- @return string|table|nil
local function specFor(bucket, field)
if bucket ~= nil then
local qualified = FIELD_SPECS[bucket .. '.' .. field]
if qualified ~= nil then
return qualified
end
end
return FIELD_SPECS[field]
end
--- Expands a '%.14g' exponent form ('1.5e+14', '-5e-06') to plain
--- dot-decimal digits via string arithmetic: printf would reintroduce locale
--- and precision questions, while shifting the mantissa digits by the
--- exponent is exact.
--- @param s string dot-decimal number in exponent form
--- @return string plain dot-decimal number
local function expandExponent(s)
local sign, int, frac, esign, edigits = s:match('^(-?)(%d+)%.?(%d*)[eE]([+-]?)(%d+)$')
if not int then
return s
end
local digits = (int .. frac):gsub('^0+', '')
if digits == '' then
return '0'
end
local exp = (esign == '-' and -1 or 1) * tonumber(edigits) - #frac
local out
if exp >= 0 then
out = digits .. string.rep('0', exp)
elseif #digits + exp > 0 then
out = digits:sub(1, #digits + exp) .. '.' .. digits:sub(#digits + exp + 1)
else
out = '0.' .. string.rep('0', -(#digits + exp)) .. digits
end
return (sign == '-' and '-' or '') .. out
end
--- Serializes a number the German wiki's `Zahl` parser accepts: comma
--- decimal, no thousands dots, no exponent. That parser reads de format, and
--- SemanticScribunto stringifies raw Lua numbers with tostring first, so a
--- fractional number passed raw arrives as a dot-decimal string and is then
--- silently dropped or rescaled ('1.337' -> 1337) - mw.smw.set still reports
--- OK (sandbox report: wiki-ports/entity-port/smw-number-sandbox-results.md).
--- Integers are stringified too, so neither tostring's exponent form
--- ('1e+14') nor any PHP-side float stringification can intervene.
--- Precision follows Lua 5.1 tostring (%.14g, 14 significant digits); the one
--- exception is integral magnitudes >= 1e14, where %.0f keeps every digit up
--- to 2^53 that %.14g would round away. C-locale decimal commas are
--- normalized early because tostring and %f take theirs from LC_NUMERIC.
--- @param v number
--- @return string
local function germanNumber(v)
local s
if v % 1 == 0 and math.abs(v) >= 1e14 then
s = (string.format('%.0f', v):gsub(',', '.'))
else
s = (tostring(v):gsub(',', '.'))
end
if s:find('[eE]') then
s = expandExponent(s)
end
if s == '-0' then
s = '0'
end
return (s:gsub('%.', ','))
end
--- Parses one German-formatted number (de locale): optional minus, integer
--- digits with optional dot grouping in exact 3-digit groups, optional comma
--- fraction. nil for anything else - a dot decimal ('1.5'), English grouping
--- ('1,000.5'), exponents and unit tokens are all rejected rather than read
--- at the wrong magnitude, because this wiki's Zahl parser reads de format
--- and would rescale or drop them. The one definition shared by the write
--- path (parse_number specs) and the DataGrid filter grammar, so a stored
--- value and the literal that queries it can never drift apart.
--- @param s string
--- @return number|nil
function p.parseGermanNumber(s)
local neg = s:sub(1, 1) == '-'
if neg then
s = s:sub(2)
if s == '' then
return nil
end
end
local comma = s:find(',', 1, true)
local int, frac = s, nil
if comma then
int, frac = s:sub(1, comma - 1), s:sub(comma + 1)
-- Fraction is digits only: '1,5e2' would tonumber as 150.
if frac == '' or frac:find('%D') then
return nil
end
end
local digits = int
local dot = int:find('.', 1, true)
if dot then
local head = int:sub(1, dot - 1)
if head == '' or #head > 3 or head:find('%D') then
return nil
end
digits, int = head, int:sub(dot + 1)
-- A dot must open a group: '1.' is not a German number.
if int == '' then
return nil
end
while int ~= '' do
local at = int:find('.', 1, true)
local group = at and int:sub(1, at - 1) or int
if #group ~= 3 or group:find('%D') then
return nil
end
digits = digits .. group
if not at then
break
end
int = int:sub(at + 1)
-- A dot must open a group: '1.000.' would tonumber as 1000.
if int == '' then
return nil
end
end
elseif int == '' or int:find('%D') then
return nil
end
local n = tonumber(digits .. (frac and '.' .. frac or ''))
if n == nil or n ~= n or math.abs(n) == math.huge then
return nil
end
return neg and -n or n
end
--- The fallback property name for an unmapped field: the manifest display
--- name (ucfirst, underscores to spaces), the same derivation properties.json
--- keys use, so an unmapped field writes under the name the manifest already
--- gives it.
--- @param field string
--- @return string
local function autoName(field)
local spaced = field:gsub('_', ' ')
return (spaced:gsub('^%l', string.upper))
end
--- The German property a field writes to: its FIELD_SPECS target, else the
--- display-name fallback. The fallback is READ-ONLY support: the writer
--- itself never reaches it (unmapped writable fields fail the store), but
--- the SMW readers (Entity/Store/Smw, DataGrid/Smw) resolve every manifest
--- field and must still get a queryable name rather than nil. UNRESOLVED
--- fields they reject instead, on p.unresolved, before reaching here.
--- `bucket` picks the bucket-qualified spec for a field name two routing
--- buckets share (type, classification); nil reads the plain key.
--- @param field string
--- @param bucket string|nil
--- @return string
function p.property(field, bucket)
local spec = specFor(bucket, field)
if spec == nil then
return autoName(field)
end
if type(spec) == 'table' then
return spec.property
end
return spec
end
--- The blocker keeping `field` out of the German crosswalk, nil when the
--- field writes a target. The SMW readers reject unresolved fields on this:
--- the display-name fallback gives them a queryable name no page stores, so
--- a query would answer empty and look valid.
--- @param field string
--- @return string|nil
function p.unresolved(field)
return UNRESOLVED_FIELDS[field]
end
-- Reverse of p.property over FIELD_SPECS: property label -> its fields in
-- sorted order, built on first use. A label can name more than one field
-- (Typ: item_type and system_type translate through different
-- vocabularies), so the reverse map is a list, never a single pairs()-picked
-- entry: picking by iteration order silently queries the wrong vocabulary.
-- Entries carry the field name and, for a bucket-qualified spec key, the
-- bucket that owns it: the field name alone cannot express that identity
-- (type is a mission field in the Entity manifest and a wearable_set field
-- in Module:WearableSet's), so the reverse lookup must hand both back.
local propertyFields = nil
local function getPropertyFields()
if propertyFields == nil then
propertyFields = {}
for key, spec in pairs(FIELD_SPECS) do
local name = type(spec) == 'table' and spec.property or spec
local records = propertyFields[name]
if records == nil then
records = {}
propertyFields[name] = records
end
local bucket, field = key:match('^([^.]+)%.([^%.]+)$')
records[#records + 1] = { field = field or key, bucket = bucket }
end
for _, records in pairs(propertyFields) do
table.sort(records, function(a, b)
if a.field ~= b.field then
return a.field < b.field
end
return (a.bucket or '') < (b.bucket or '')
end)
end
end
return propertyFields
end
-- Registered manifests whose rows route through this store: the Entity
-- kind split plus every domain manifest (Module:WearableSet's). Test hook
-- aside, this is the closed set store() validates bucket/field membership
-- against.
local registeredManifests = nil
local function getRegisteredManifests()
if registeredManifests == nil then
registeredManifests = {
mw.loadJsonData(PROPERTIES_PAGE),
mw.loadJsonData('Module:WearableSet/properties.json'),
mw.loadJsonData('Module:Company/properties.json'),
}
end
return registeredManifests
end
-- bucket -> set of the fields the registered manifests route there, counting
-- a migrateTo target as a routing bucket (the writer fills both during a
-- migration), built on first use.
local bucketFields = nil
local function getBucketFields()
if bucketFields == nil then
bucketFields = {}
for _, manifest in ipairs(getRegisteredManifests()) do
for _, entry in pairs(manifest) do
if type(entry) == 'table' and type(entry.field) == 'string' and type(entry.bucket) == 'string' then
local function admit(bucket)
bucketFields[bucket] = bucketFields[bucket] or {}
bucketFields[bucket][entry.field] = true
end
admit(entry.bucket)
if type(entry.migrateTo) == 'string' then
admit(entry.migrateTo)
end
end
end
end
end
return bucketFields
end
-- Kind scope, built on first use from the Entity manifest: kind -> set of
-- the fields that kind both routes (its %kinds buckets) and emits (a modules
-- entry naming the kind module, bare or as the first path segment: 'Item',
-- 'Location/StarSystem'). Routing alone over-admits: the entity bucket is
-- routed by every kind, so item_type would scope to Location and Vehicle
-- too, kinds whose pages never carry the field.
local kindFields = nil
local function getKindFields()
if kindFields == nil then
kindFields = {}
local manifests = getRegisteredManifests()
local kinds, entries = {}, {}
for _, manifest in ipairs(manifests) do
for kind, list in pairs(manifest['%kinds'] or {}) do
kinds[kind] = list
end
for _, entry in pairs(manifest) do
if type(entry) == 'table' and type(entry.field) == 'string' and type(entry.bucket) == 'string' then
entries[#entries + 1] = entry
end
end
end
for kind, list in pairs(kinds) do
local allowed = {}
if type(list) == 'table' then
for _, bucket in ipairs(list) do
allowed[bucket] = true
end
end
-- Scope keys carry both forms: a plain reverse-lookup record matches
-- its bare field name, a bucket-qualified record only a kind that
-- routes its bucket.
local fields = {}
for _, entry in ipairs(entries) do
local companyIdentity = kind == 'Company'
and entry.bucket == 'entity'
and (entry.field == 'name' or entry.field == 'image' or entry.field == 'subject_type')
if allowed[entry.bucket] then
if kind == 'Company' and (entry.bucket == 'company' or companyIdentity) then
fields[entry.field] = true
fields[entry.bucket .. '.' .. entry.field] = true
else
for _, module in ipairs(type(entry.modules) == 'table' and entry.modules or {}) do
if module == kind or module:match('^[^/]+') == kind then
fields[entry.field] = true
fields[entry.bucket .. '.' .. entry.field] = true
break
end
end
end
end
end
kindFields[kind] = fields
end
end
return kindFields
end
--- The one record of a shared label `kind` resolves to: the label's records
--- whose bucket the kind both routes and emits (getKindFields). nil when the
--- kind names none, or still more than one.
--- @param records table[] candidate records { field, bucket }, sorted
--- @param kind string
--- @return table|nil
local function recordForKind(records, kind)
local scoped = getKindFields()[kind]
if scoped == nil then
return nil
end
local found, n = nil, 0
for _, record in ipairs(records) do
local key = record.bucket and (record.bucket .. '.' .. record.field) or record.field
if scoped[key] ~= nil then
found = record
n = n + 1
end
end
if n == 1 then
return found
end
return nil
end
--- The Vocab key the writer translates `field`'s values through, nil when the
--- field stores verbatim. The key can differ from the field name (tier and
--- rarity both write Seltenheit through 'rarity', classification writes
--- Klassifizierung through 'body_type'), so readers must translate with this
--- key, never with the field name: a field-keyed lookup passes the value
--- through untranslated and queries for a value no row carries. `bucket`
--- picks the bucket-qualified spec for a field name two routing buckets share.
--- @param field string
--- @param bucket string|nil
--- @return string|nil
function p.vocab(field, bucket)
local spec = specFor(bucket, field)
if type(spec) == 'table' then
return spec.vocab
end
return nil
end
--- Every field record a German property label names, as a fresh list of
--- { field, bucket } in the reverse map's sorted order, or nil when no spec
--- targets the label. A label can name more than one field (Typ: item_type
--- and system_type), and fieldForProperty kindlessly picks the sorted first
--- when the records are interchangeable; a caller that must NOT tolerate a
--- pick (a kindless datatable, where the chosen manifest row decides what the
--- column reads) refuses a multi-record list here instead.
--- @param label string
--- @return table[]|nil records { field, bucket }, bucket nil for a plain spec key
function p.fieldsForProperty(label)
local records = getPropertyFields()[label]
if records == nil then
return nil
end
local out = {}
for i, record in ipairs(records) do
out[i] = { field = record.field, bucket = record.bucket }
end
return out
end
--- The field a German property label belongs to, so SMW-side readers can
--- accept the stored property name as their editor surface. A label two
--- fields share resolves against `kind` first: the fields the kind routes
--- and emits pick the record (recordForKind), so kind=Item reads the item
--- vocabulary and kind=Location the system one. A shared label the kind
--- does not resolve is a loud error when its fields translate through
--- different vocabularies - a silent pick would query a vocabulary no row of
--- that kind carries - while fields sharing label and vocabulary are
--- interchangeable (same property, same translation) and resolve to the
--- sorted first. The second return is the bucket that owns a
--- bucket-qualified spec key (Rüstungstyp: 'type' of wearable_set), nil for
--- a plain key; callers resolving a manifest entry must match it, since the
--- bare field name can also name a field of another manifest (type is a
--- mission field in the Entity manifest). The display-name fallback
--- (autoName) stays unmatchable by design: its labels are generated, not
--- curated.
--- @param label string
--- @param kind string|nil Entity kind name (Item, Location, ...)
--- @return string|nil field
--- @return string|nil bucket nil when the label's spec is a plain key
function p.fieldForProperty(label, kind)
local records = getPropertyFields()[label]
if records == nil then
return nil
end
if #records == 1 then
return records[1].field, records[1].bucket
end
if kind ~= nil then
local record = recordForKind(records, kind)
if record ~= nil then
return record.field, record.bucket
end
end
local vocab = p.vocab(records[1].field, records[1].bucket)
for i = 2, #records do
if p.vocab(records[i].field, records[i].bucket) ~= vocab then
local names = {}
for i, record in ipairs(records) do
names[i] = record.bucket and (record.field .. ' (' .. record.bucket .. ')') or record.field
end
local msg = "SMW crosswalk: property label '" .. label .. "' is shared by " .. table.concat(names, ', ')
if kind == nil then
error(msg .. '; name a kind to resolve it', 0)
end
error(msg .. '; kind ' .. kind .. ' does not resolve it', 0)
end
end
return records[1].field, records[1].bucket
end
--- The stored serialization of one Bucket-scale number for its resolved
--- spec: factor applied, comma-decimal, unit token appended - exactly what
--- serialize writes, shared with p.storedNumber so the public by-field entry
--- and the writer can never drift. NaN and infinities have no Zahl
--- serialization - an input that is one, or overflows into one through the
--- factor, raises before any return, plain string mappings included, so no
--- caller can build an 'inf' or 'nan' literal.
--- @param spec string|table|nil
--- @param v number
--- @return string
local function storedNumberSpec(spec, v)
if v ~= v or math.abs(v) == math.huge then
error('SMW: invalid numeric value', 0)
end
if type(spec) ~= 'table' then
return germanNumber(v)
end
if spec.factor then
v = v * spec.factor
if v ~= v or math.abs(v) == math.huge then
error('SMW: invalid numeric value', 0)
end
end
local s = germanNumber(v)
if spec.unit then
return s .. ' ' .. spec.unit
end
return s
end
-- SMW trims whitespace before it detects a comparator, so padding cannot escape it.
--- @param value any
--- @return boolean
function p.comparatorShaped(value)
if type(value) ~= 'string' then
return false
end
local text = value:gsub('^[ \t\n\r\v]+', '')
-- The tokenizer strips Unicode whitespace only before a delimiter; PHP trim handles the leading side.
local presence = text
local previous
repeat
previous = presence
presence = presence:gsub('%s+$', ''):gsub('\194[\133\160]$', '')
presence = presence:gsub('\225\154\128$', ''):gsub('\225\160\142$', '')
presence = presence:gsub('\226\128[\128-\138\168\169\175]$', '')
presence = presence:gsub('\226\129\159$', ''):gsub('\227\128\128$', '')
until presence == previous
if presence == '+' or text:find('^[!~=]') or text:find('^\226\137\164') or text:find('^\226\137\165') then
return true
end
for _, prefix in ipairs({ 'like:', 'nlike:', 'in:', 'not:', 'phrase:' }) do
if text:sub(1, #prefix) == prefix then
return true
end
end
return false
end
--- The stored serialization of one Bucket-scale number for `field`: the
--- spec's factor applied, comma-decimal, unit token appended - exactly what
--- serialize writes, exposed so SMW-side condition builders
--- (Module:Entity/Store/Smw) compare in the stored scale rather than the
--- Bucket scale callers speak. NaN and infinities have no Zahl serialization
--- (see storedNumberSpec). `bucket` picks the bucket-qualified spec for a
--- field name two routing buckets share.
--- @param field string
--- @param v number
--- @param bucket string|nil
--- @return string
function p.storedNumber(field, v, bucket)
return storedNumberSpec(specFor(bucket, field), v)
end
--- The equality literal a Boolean-typed field queries with: a Lua boolean
--- as true/false, or one of the spellings SMW's Boolean datatype answers
--- identically per side in any case (true side true/ja/j/w/wahr/1, false
--- side false/nein/n/f/falsch/0 - live probes on Abbaubar, Modul:Sandbox
--- rev 93932 plus an independent action=ask audit, each side's spellings one
--- query hash). Anything else fails the build here: SMW rejects an unknown
--- Boolean literal by failing the whole query, which surfaces as a query-
--- layer failure rather than a named mistake. The printout letter t is not
--- a query spelling (SMW rejects it while accepting f); read-backs answer
--- real booleans, so they never round-trip into a filter unvalidated. The
--- writer's '1'/'0' serialization is inside the verified input set.
--- @param v any
--- @return string
function p.storedBoolean(v)
local s
if type(v) == 'boolean' then
if v then
s = 'true'
else
s = 'false'
end
elseif type(v) == 'number' then
s = tostring(v)
elseif type(v) == 'string' then
s = v:lower()
end
if
s == 'true'
or s == 'ja'
or s == 'j'
or s == 'w'
or s == 'wahr'
or s == '1'
or s == 'false'
or s == 'nein'
or s == 'n'
or s == 'f'
or s == 'falsch'
or s == '0'
then
return s
end
error('SMW: invalid Boolean value ' .. tostring(v), 0)
end
--- Serializes one shaped value for one field per its spec: booleans as '1'/
--- '0' (SemanticScribunto casts scalar booleans in PHP and false would become
--- empty; a live Boolean property parses this and the true/ja/false/nein
--- spellings, and answers printouts 't'/'f', which the reader normalizes -
--- see storedBoolean and Module:Entity/Store/Smw), numbers comma-decimal with the spec's factor and unit, strings
--- verbatim except for the spec's prefix and vocab translation (English
--- machine token -> German stored value; unmapped values verbatim, so a
--- legacy or not-yet-translated token is never dropped or coined). The
--- magnitude is never rescaled semantically: Bucket parity outranks
--- target-property convenience. Numeric-looking strings are NOT coerced:
--- emitters emit Lua numbers for numeric fields, and text that happens to
--- look numeric keeps its bytes - a parse_number spec is the one exception,
--- an editor override naming a stored number.
--- @param spec string|table|nil the resolved spec (specFor), named `field`
--- in error text only
--- @param field string
--- @param v any
--- @return any
local function serialize(spec, field, v)
if type(v) == 'boolean' then
return v and '1' or '0'
end
-- parse_number turns an editor string into the number it names before any
-- other string handling: what does not parse (or parses fractional, for
-- an integer field) raises, so the store refuses instead of writing a
-- silently rescaled or dropped value.
if type(spec) == 'table' and spec.parse_number and type(v) == 'string' then
local n = p.parseGermanNumber(v)
if n == nil then
error('SMW: field ' .. field .. ' value "' .. v .. '" is not a number', 0)
end
if spec.integer and n % 1 ~= 0 then
error('SMW: field ' .. field .. ' value "' .. v .. '" is not an integer', 0)
end
return storedNumberSpec(spec, n)
end
if type(v) == 'number' then
-- % 1 is NaN for NaN and the infinities, so one check holds a numeric
-- input to the same integer contract as an editor string; fields without
-- the flag keep storedNumber's finite-only guard.
if type(spec) == 'table' and spec.integer and v % 1 ~= 0 then
error('SMW: field ' .. field .. ' value ' .. tostring(v) .. ' is not an integer', 0)
end
return storedNumberSpec(spec, v)
end
if type(v) == 'string' and type(spec) == 'table' then
if spec.prefix then
return spec.prefix .. v
end
if spec.vocab then
return Vocab.toGerman(spec.vocab, v)
end
end
-- Multi-valued fields (e.g. food effects) translate element-wise; an
-- array spec without vocab passes through verbatim.
if type(v) == 'table' and type(spec) == 'table' and spec.vocab then
local out = {}
for i, e in ipairs(v) do
out[i] = Vocab.toGerman(spec.vocab, e)
end
return out
end
return v
end
--- The first value a strict_vocab field cannot store: a string the
--- vocabulary does not translate (Vocab's pass-through returns it
--- unchanged), or any non-string. nil when every value translates.
--- @param vocab string Vocab field name
--- @param v any
--- @return any
local function untranslatedValue(vocab, v)
if type(v) == 'table' then
for _, e in ipairs(v) do
local bad = untranslatedValue(vocab, e)
if bad ~= nil then
return bad
end
end
return nil
end
if type(v) == 'string' and Vocab.toGerman(vocab, v) ~= v then
return nil
end
return v
end
--- Structural equality of two serialized values: scalars by equality,
--- arrays element-wise. A migrateTo duplicate arrives as two separately
--- shaped arrays with equal contents, and reference equality would wrongly
--- fail it as a collision.
--- @param a any
--- @param b any
--- @return boolean
local function sameValue(a, b)
if a == b then
return true
end
if type(a) ~= 'table' or type(b) ~= 'table' or #a ~= #b then
return false
end
for i = 1, #a do
if a[i] ~= b[i] then
return false
end
end
return true
end
--- The routing buckets this crosswalk covers: every Entity kind's table,
--- plus the wearable_set table of Module:WearableSet, a domain manifest
--- outside the Entity %kinds split whose rows arrive through the same store.
--- Rows routed anywhere else (a future kind, or a foreign caller) have no
--- German crosswalk; writing them would plant English display-name
--- properties on the German wiki, so the store refuses them outright.
--- @type table<string, boolean>
local WRITABLE_BUCKETS = {
cargo_grid = true,
company = true,
commodity = true,
entity = true,
item_component = true,
item_tool = true,
item_weapon = true,
location = true,
mission = true,
vehicle = true,
vehicle_stats = true,
wearable_set = true,
}
-- Registered kinds whose every routing bucket WRITABLE_BUCKETS covers, built
-- on first use from every registered manifest's %kinds. Readers route their
-- SMW paths on this set, never on a hardcoded kind list: a copy of the list
-- goes stale the moment the crosswalk grows to another kind, and a table of
-- that kind then queries a backend it cannot answer.
local supportedKinds = nil
local function getSupportedKinds()
if supportedKinds == nil then
supportedKinds = {}
for _, manifest in ipairs(getRegisteredManifests()) do
for kind, buckets in pairs(manifest['%kinds'] or {}) do
local covered = type(buckets) == 'table'
if covered then
for _, bucket in ipairs(buckets) do
if not WRITABLE_BUCKETS[bucket] then
covered = false
break
end
end
end
if covered then
supportedKinds[kind] = true
end
end
end
end
return supportedKinds
end
--- Whether `kind` is a registered kind whose every routing bucket this
--- crosswalk writes: the kind an SMW-side reader (DataGrid's datatable path)
--- can query by German property name, because every field its pages emit is
--- either crosswalked or an UNRESOLVED_FIELDS refusal that names the gap.
--- Kinds come from every registered manifest's `%kinds`, so a domain
--- manifest's kind (Company, Wearable set) answers for its own buckets.
--- Anything else answers false, never an error, so a caller can route on it.
--- @param kind string|nil
--- @return boolean
function p.supportsKind(kind)
return type(kind) == 'string' and getSupportedKinds()[kind] == true
end
--- The sorted kind names supportsKind answers true for, for editor-facing
--- error text that cannot drift from the crosswalk's actual coverage.
--- @return string[]
function p.supportedKinds()
local names = {}
for kind in pairs(getSupportedKinds()) do
names[#names + 1] = kind
end
table.sort(names)
return names
end
--- The star-system fields: Location's system and destination_system and the
--- entity bucket's systems, which share the Seite-typed Sternensystem property
--- (destination_system its subproperty). They canonicalize at THIS seam, the
--- last point every writer passes through, on the value as the emitter
--- produced it - the PAGE shaping deliberately leaves these fields' redirects
--- unfollowed (see Module:Entity/StructuredData) - so every spelling (a short
--- name, a record alias, a decorated designation, free text) reduces to the
--- one canonical title the SMW filters derive their literals from - a second
--- stored spelling for one system could only appear by bypassing this seam.
--- The Bucket backend never runs here and keeps its verbatim columns. The set
--- is Starmap's, shared with the shaping and filter seams.
local SYSTEM_FIELDS = locationStarmap.systemFields
--- One system value (or a list of them) reduced to canonical titles; an
--- element that reduces to nothing (empty string) writes nothing, and a
--- canonicalized list deduplicates, first occurrence first. Every string
--- takes structuredData.shapedPageTitle first, the exact non-redirect PAGE
--- pass both SMW filter paths apply to their literals: the PAGE-typed fields
--- arrive already shaped (bucketValue), but the repeated TEXT systems field
--- arrives as the emitter wrote it, and its underscored or linked spellings
--- ('Stanton_System', '[[Stanton|Stanton system]]') canonicalize to the one
--- title only after that pass folds them - without it, writer and filters
--- derive different titles for one system.
--- @param value any
--- @return any
local function canonicalSystemValue(value)
if type(value) == 'table' then
local out, seen = {}, {}
for _, item in ipairs(value) do
if type(item) == 'string' then
item = locationStarmap.systemPageTitle(structuredData.shapedPageTitle(item))
end
if item ~= nil and not seen[item] then
seen[item] = true
out[#out + 1] = item
end
end
if #out == 0 then
return nil
end
return out
end
if type(value) == 'string' then
return locationStarmap.systemPageTitle(structuredData.shapedPageTitle(value))
end
return value
end
--- Translates routed puts to German properties, the serialization shared by
--- the page-level write (store) and the per-row subobject write (storeRow).
--- `puts` is the shaped bucket -> field -> value split from
--- Module:Entity/StructuredData; buckets are an Entity routing artifact only,
--- never an SMW property name, so the rows flatten to one property per
--- distinct field. A `migrateTo`
--- field arrives in two buckets with identical values and collapses to one
--- property here. A store() carrying a bucket outside WRITABLE_BUCKETS, a
--- field in UNRESOLVED_FIELDS, or a strict_vocab value the vocabulary lacks
--- fails before any write, refusing partial rows for unported kinds and
--- half-built crosswalks, and a field with no classification at all also
--- fails: the English display-name fallback would silently create
--- English properties on the German wiki. A plain-key spec answers only for
--- a bucket a registered manifest routes the field to (a fabricated
--- wearable_set.uuid fails as unmapped). numbers_only non-number values
--- write nothing (see the specs' comments); a parse_number string that does
--- not parse, or parses fractional, fails the store instead, so an invalid
--- editor override never disappears silently. Distinct fields that reach one
--- property with equal values collapse; with different values the store
--- fails loudly - the shared targets are cross-kind/cross-subtype
--- (never one page), so a difference means an untested co-emission that must
--- surface, not silently lose a value to pairs() order. A value that cannot
--- serialize (a number overflowing its scale factor) fails the store the
--- same way, before any write. Called only for main-namespace pages; the
--- caller guards the namespace.
--- @param puts table<string, table<string, any>> bucket -> field -> shaped value
--- @param missionApi table|nil|boolean The Mission page's apiData, false when an editorial override
--- replaces the payouts
--- @param weaponAlphaDamage boolean|nil True when the item_weapon `damage` row, if any, is the
--- weapon chain's per-shot alpha total: it stores under the alpha_damage spec (Alphaschaden),
--- so `damage` itself stores only the grenade and magazine facets' damage (Schaden). Bucket
--- never reaches this seam and keeps the union column.
--- @return table props German property -> serialized value
--- @return string|nil error
local function serializePuts(puts, missionApi, weaponAlphaDamage)
if weaponAlphaDamage and type(puts.item_weapon) == 'table' and puts.item_weapon.damage ~= nil then
puts.item_weapon.alpha_damage = puts.item_weapon.damage
puts.item_weapon.damage = nil
end
local props, sources = {}, {}
-- The loop is pcalled so a raise out of serialize (an overflowing number)
-- returns as an error string like the loop's own returns, keeping store()
-- a no-raise contract.
local serialized, failure = pcall(function()
local mission = puts.mission
local missionOrders, missionRewards
if mission and (missionApi ~= nil or mission.orders ~= nil or mission.rewards ~= nil) then
missionOrders, missionRewards = require('Module:Entity/StructuredData/Mission').lines(missionApi, mission)
end
-- Refuse uncovered routing buckets up front, before anything is
-- serialized: a caller routing a bucket this crosswalk does not cover
-- must not store a partial row that looks complete. The error surfaces
-- through StructuredData.store like any storage failure; the Bucket
-- backend is unaffected.
for bucket in pairs(puts) do
if not WRITABLE_BUCKETS[bucket] then
return 'SMW storage failed: routing bucket '
.. bucket
.. ' has no SMW crosswalk; refusing a partial write'
end
end
for bucket, fields in pairs(puts) do
for field, value in pairs(fields) do
local spec = specFor(bucket, field)
if UNRESOLVED_FIELDS[field] then
-- A field whose German target is not decided yet: dropping it
-- silently would store a partial row that looks complete, so the
-- whole store fails and the error names the gap.
return 'SMW storage failed: unresolved field '
.. field
.. ' (bucket '
.. bucket
.. '); refusing a partial write'
elseif spec == nil then
-- A manifest field with no classification is a crosswalk gap: an
-- English display-name write would silently create unmigrated
-- English properties on the German wiki, so fail the store before
-- mw.smw.set and let the coverage test pin the gap instead.
return 'SMW storage failed: unmapped field ' .. field .. ' (bucket ' .. bucket .. ')'
elseif
FIELD_SPECS[bucket .. '.' .. field] == nil and (getBucketFields()[bucket] or {})[field] == nil
then
-- The spec resolved through the plain key, but no registered
-- manifest routes the field to this bucket: a fabricated row
-- (wearable_set.uuid reusing the entity uuid mapping) must fail as
-- unmapped, not write another bucket's property under this one.
return 'SMW storage failed: unmapped field ' .. field .. ' (bucket ' .. bucket .. ')'
elseif type(spec) == 'table' and spec.numbers_only and type(value) ~= 'number' then
-- Seat's formatted ranges inside the pitch/yaw column: no German
-- property covers that shape, so it writes nothing (see the
-- specs' comments).
else
if type(spec) == 'table' and spec.strict_vocab then
local bad = untranslatedValue(spec.vocab, value)
if bad ~= nil then
-- The property's live values are curated German; an
-- unmapped token must fail the store, not pass through
-- as English (Vocab's own contract is pass-through).
return 'SMW storage failed: field '
.. field
.. ' value "'
.. tostring(bad)
.. '" has no German vocabulary entry (bucket '
.. bucket
.. ')'
end
end
if bucket == 'mission' and field == 'type' then
Vocab.missionTypeToGerman(value)
end
local name = p.property(field, bucket)
if bucket == 'mission' and field == 'orders' then
value = missionOrders
end
if bucket == 'mission' and field == 'rewards' then
value = missionRewards
end
if bucket == 'mission' and (field == 'reputation_min' or field == 'reputation_max') then
if value == 'Keine' then
error('reserved mission standing Keine')
end
end
if SYSTEM_FIELDS[field] then
value = canonicalSystemValue(value)
end
value = serialize(spec, field, value)
if type(value) == 'table' then
local vals = {}
for i, el in ipairs(value) do
vals[i] = serialize(spec, field, el)
end
value = vals
end
if sources[name] == nil then
sources[name] = field
props[name] = value
elseif sources[name] ~= field then
if not sameValue(props[name], value) then
return 'SMW storage failed: property '
.. name
.. ' written by '
.. sources[name]
.. ' and '
.. field
end
else
props[name] = value
end
end
end
end
return nil
end)
if not serialized then
return {}, 'SMW storage failed: ' .. tostring(failure)
end
if failure then
return {}, failure
end
return props, nil
end
--- Writes a page's one-row puts as the page's own properties. Called only
--- for main-namespace pages; the caller guards the namespace.
--- @param puts table<string, table<string, any>> bucket -> field -> shaped value
--- @param missionApi table|nil|boolean
--- @param weaponAlphaDamage boolean|nil
--- @return string|nil error
function p.store(puts, missionApi, weaponAlphaDamage)
local props, failure = serializePuts(puts, missionApi, weaponAlphaDamage)
if failure then
return failure
end
if next(props) == nil then
return nil
end
-- SemanticScribunto returns an error table rather than raising for parse errors.
local ok, res, err = pcall(function()
return mw.smw.set(props)
end)
if not ok then
return 'SMW storage failed: ' .. tostring(res)
end
if type(res) == 'table' and res[1] == false then
return 'SMW storage failed: ' .. tostring(res.error)
end
if not res then
return 'SMW storage failed: ' .. tostring(err)
end
return nil
end
--- Writes one row of a %rows table as a named subobject of the current page
--- (`mw.smw.subobject`, the Lua face of #subobject): the same translation as
--- the page-level write, but a subject of its own, so the fields of one row
--- stay correlated (a cargo grid's length, width and height belong to one
--- grid, not to the flattened set of all the page's grids) and a query can
--- test them together. Rows re-declared on reparse replace same-id subobjects;
--- ids the new parse no longer writes go dark with the page's other semantic
--- data. Bucket never reaches this seam: its own multi-row storage is
--- page_name_sub, not subobjects.
--- @param puts table<string, table<string, any>> bucket -> field -> shaped value, one row
--- @param sub string the row's id among the page's rows
--- @param subjectType string|nil the page's subject_type, copied into the row as its
--- Strukturtyp: an ask query cannot join a page-level property onto subobject
--- rows, so the row's own copy is the one way a query can filter by it
--- (the dimensions Fit gadget's group filter)
--- @return string|nil error
function p.storeRow(puts, sub, subjectType)
if subjectType ~= nil then
local copy = {}
for bucket, fields in pairs(puts) do
copy[bucket] = fields
end
copy.entity = {}
for field, value in pairs(puts.entity or {}) do
copy.entity[field] = value
end
copy.entity.subject_type = subjectType
puts = copy
end
local props, failure = serializePuts(puts, nil, nil)
if failure then
return failure
end
if next(props) == nil then
return nil
end
local ok, res, err = pcall(function()
return mw.smw.subobject(props, tostring(sub))
end)
if not ok then
return 'SMW storage failed: ' .. tostring(res)
end
if type(res) == 'table' and res[1] == false then
return 'SMW storage failed: ' .. tostring(res.error)
end
if not res then
return 'SMW storage failed: ' .. tostring(err)
end
return nil
end
-- Test-only exports.
p._internal = {
FIELD_SPECS = FIELD_SPECS,
UNRESOLVED_FIELDS = UNRESOLVED_FIELDS,
autoName = autoName,
specFor = specFor,
-- Installs decoded manifests in place of the registered pages and clears
-- every manifest-derived cache; for suites simulating a manifest state
-- the real pages do not carry yet (a migrateTo entry). nil restores the
-- real pages.
setRegisteredManifests = function(manifests)
registeredManifests = manifests
bucketFields, kindFields, supportedKinds = nil, nil, nil
end,
}
return p