FeatureFlagConfig.fromJson constructor
Parse from the raw .zfa.json map. Accepts two features: shapes:
a list of { name, enabled, gates? } objects (canonical) or a map
{ name: { enabled, gates? } } (name implied by key).
Implementation
factory FeatureFlagConfig.fromJson(Map<String, dynamic> json) {
final rawFeatures = json['features'];
final flags = <String, FeatureFlag>{};
if (rawFeatures is List) {
for (final entry in rawFeatures) {
if (entry is! Map) {
throw FeatureConfigException(
'invalid features entry "$entry" — expected an object with '
'"name" and "enabled"',
);
}
final map = entry.cast<String, dynamic>();
final flag = _parseFlagObject(map);
if (flags.containsKey(flag.name)) {
throw FeatureConfigException(
'duplicate feature name "${flag.name}" in features section',
);
}
flags[flag.name] = flag;
}
} else if (rawFeatures is Map) {
for (final entry in rawFeatures.entries) {
final name = entry.key.toString();
final value = entry.value;
if (!isValidFeatureName(name)) {
throw FeatureConfigException(
'invalid feature name "$name" — use alphanumeric characters and '
'hyphens (e.g. "pro-analytics")',
);
}
if (value is bool) {
flags[name] = FeatureFlag(name: name, enabled: value);
continue;
}
if (value is! Map) {
throw FeatureConfigException(
'invalid features entry for "$name" — expected an object or '
'boolean',
);
}
final map = value.cast<String, dynamic>();
final embeddedName = map['name'];
if (embeddedName != null && embeddedName.toString() != name) {
throw FeatureConfigException(
'feature "$name" has mismatched embedded name '
'"${embeddedName.toString()}"',
);
}
final flag = _parseFlagObject(map, impliedName: name);
if (flags.containsKey(name)) {
throw FeatureConfigException(
'duplicate feature name "$name" in features section',
);
}
flags[name] = flag;
}
} else if (rawFeatures != null) {
throw FeatureConfigException(
'invalid "features" section — expected a list or a map',
);
}
final rawFlavors = json['flavors'];
final flavors = <String, Map<String, bool>>{};
if (rawFlavors is Map) {
for (final entry in rawFlavors.entries) {
final flavorName = entry.key.toString();
if (entry.value is! Map) {
throw FeatureConfigException(
'invalid flavor "$flavorName" — expected a map of '
'"<featureName>": <bool>',
);
}
final overrides = <String, bool>{};
for (final ov in (entry.value as Map).entries) {
final featureName = ov.key.toString();
if (!flags.containsKey(featureName)) {
throw FeatureConfigException(
'flavor "$flavorName" overrides unknown feature '
'"$featureName" — declare it in the features section first',
);
}
if (ov.value is! bool) {
throw FeatureConfigException(
'flavor "$flavorName" override for "$featureName" must be a '
'boolean',
);
}
overrides[featureName] = ov.value as bool;
}
flavors[flavorName] = overrides;
}
} else if (rawFlavors != null) {
throw FeatureConfigException(
'invalid "flavors" section — expected a map',
);
}
return FeatureFlagConfig(flags: flags, flavors: flavors);
}