@triflare/fx 2.3.0-alpha.1 → 2.3.0-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@triflare/fx",
3
- "version": "2.3.0-alpha.1",
3
+ "version": "2.3.0-alpha.2",
4
4
  "description": "Code PenguinMod projects with text.",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
package/product.yml CHANGED
@@ -1,7 +1,7 @@
1
1
  # Identity
2
2
  name: "Triflare Fx"
3
3
  command: "fx"
4
- version: "2.3.0-alpha.1"
4
+ version: "2.3.0-alpha.2"
5
5
  tagline: "Code PenguinMod projects with text."
6
6
  author: "Triflare"
7
7
  homepage: "https://github.com/triflare/fx"
@@ -1,9 +1,12 @@
1
1
  import path from "node:path";
2
+ import { findConfigPath } from "../../config.js";
2
3
  import {
3
4
  disableFeature,
4
5
  enableFeature,
5
6
  featureEnabled,
7
+ featureNames,
6
8
  getFeature,
9
+ migrateFeatureConfig,
7
10
  updateFeature,
8
11
  } from "../../features.js";
9
12
  import { loadVendorConfig, requireConfigPath } from "./vendor/helpers.js";
@@ -11,46 +14,115 @@ import { UsageError } from "../errors.js";
11
14
 
12
15
  const ACTIONS = ["enable", "disable", "update"];
13
16
 
17
+ function featureSetting(feature) {
18
+ return `fx.features.${feature.name}`;
19
+ }
20
+
21
+ function describeStatus(feature, enabled) {
22
+ if (enabled)
23
+ return feature.command
24
+ ? `Run "fx ${feature.command}" to use this feature.`
25
+ : `This feature is active in builds.`;
26
+ return `Run "fx feature ${feature.name} enable" to enable it.`;
27
+ }
28
+
14
29
  export const featureCommand = {
15
30
  name: "feature",
16
31
  group: "Core Commands:",
17
- summary: "Install, update or remove a built-in language feature",
18
- description: `Features are extension-backed language additions. "enable" copies the\nfeature's file into the project and records it under "features:" in fx.yml;\n"update" replaces that copy with the one bundled in this Fx version; and\n"disable" removes both. The file is committed, so Fx upgrades never change it.`,
19
- arguments: ["<name>", "[action]"],
32
+ summary: "List, install, update or remove an optional feature",
33
+ description: `Every optional feature is registered once and switched under
34
+ the "fx.features" key in fx.yml. "enable" turns a feature on (copying its
35
+ extension into the project when it has one); "update" replaces that copy
36
+ with the one bundled in this Fx version; and "disable" turns it off.
37
+ "fx feature migrate" moves older fx.tests, fx.run, fx.partialSprites, and
38
+ top-level features: settings under fx.features.`,
39
+ arguments: ["[name]", "[action]"],
20
40
  options: [
21
41
  {
22
42
  flags: "--force",
23
43
  description: "Replace an installed copy that was edited (enable)",
24
44
  },
25
- { flags: "--dry-run", description: "Preview update without writing files" },
45
+ { flags: "--dry-run", description: "Preview update or migration" },
26
46
  ],
27
47
  examples: [
28
- "fx feature temporaryvariables enable",
48
+ "fx feature list",
49
+ "fx feature tests enable",
50
+ "fx feature partialSprites enable",
29
51
  "fx feature temporaryvariables update --dry-run",
30
- "fx feature temporaryvariables disable",
52
+ "fx feature migrate",
31
53
  ],
32
54
  async run({ args, options, cwd, reporter, prompts, yes, product }) {
33
55
  const [name, action] = args;
56
+
57
+ if (name == null || name === "list") {
58
+ const configPath = findConfigPath(cwd);
59
+ const rows = featureNames().map((featureName) => {
60
+ const feature = getFeature(featureName);
61
+ const enabled = featureEnabled({ configPath, name: featureName });
62
+ reporter.item(featureName, enabled ? "enabled" : "disabled", {
63
+ width: 20,
64
+ suffix: feature.title,
65
+ });
66
+ return {
67
+ name: featureName,
68
+ title: feature.title,
69
+ enabled,
70
+ setting: featureSetting(feature),
71
+ };
72
+ });
73
+ return { features: rows };
74
+ }
75
+
76
+ if (name === "migrate") {
77
+ if (action != null)
78
+ throw new UsageError(`"fx feature migrate" does not take an action.`, {
79
+ hint: `use "fx feature <name> <action>" for a single feature`,
80
+ });
81
+ const configPath = requireConfigPath(cwd, product);
82
+ const result = migrateFeatureConfig({
83
+ configPath,
84
+ dryRun: Boolean(options.dryRun),
85
+ });
86
+ for (const name of result.conflicts)
87
+ reporter.warn(
88
+ `Left top-level features.${name} in place: ${name} is a core feature, so it cannot move under fx.features.`,
89
+ );
90
+ if (!result.changed) {
91
+ reporter.info("No legacy feature settings to migrate");
92
+ return {
93
+ action: "migrate",
94
+ migrated: [],
95
+ conflicts: result.conflicts,
96
+ changed: false,
97
+ };
98
+ }
99
+ reporter.text(result.diff);
100
+ if (options.dryRun) reporter.info("Dry run: fx.yml would be migrated");
101
+ else
102
+ reporter.success(
103
+ `Migrated ${result.migrated.length} feature setting(s); backup: ${path.basename(
104
+ result.backup,
105
+ )}`,
106
+ );
107
+ return {
108
+ action: "migrate",
109
+ migrated: result.migrated,
110
+ conflicts: result.conflicts,
111
+ changed: true,
112
+ dryRun: Boolean(options.dryRun),
113
+ };
114
+ }
115
+
34
116
  const configPath = requireConfigPath(cwd, product);
35
117
  const configDir = path.dirname(configPath);
36
118
  const feature = getFeature(name);
37
119
 
38
120
  if (action == null) {
39
- if (!feature.core)
40
- throw new UsageError(`Missing an action for ${JSON.stringify(name)}.`, {
41
- hint: `use one of: ${ACTIONS.join(", ")}`,
42
- });
43
121
  const enabled = featureEnabled({ configPath, name: feature.name });
44
122
  reporter.detail("Feature", feature.title);
45
123
  reporter.detail("Status", enabled ? "enabled" : "disabled");
46
- reporter.detail("Setting", `fx.${feature.name}`);
47
- reporter.info(
48
- enabled
49
- ? feature.command === "run"
50
- ? `Run "fx run" to run the project's entry point.`
51
- : `Run "fx ${feature.command ?? "test"}" to use this feature.`
52
- : `Run "fx feature ${feature.name} enable" to enable it.`,
53
- );
124
+ reporter.detail("Setting", featureSetting(feature));
125
+ reporter.info(describeStatus(feature, enabled));
54
126
  return {
55
127
  feature: feature.name,
56
128
  action: "status",
@@ -103,7 +175,6 @@ export const featureCommand = {
103
175
  };
104
176
  }
105
177
  reporter.success(`Disabled ${result.feature.title}`);
106
- if (result.warning) reporter.warn(result.warning);
107
178
  return {
108
179
  feature: result.name,
109
180
  action,
@@ -25,7 +25,8 @@ function configText({ name, width, height, target }) {
25
25
  " turbo: false",
26
26
  " interpolation: true",
27
27
  "fx:",
28
- " partialSprites: false",
28
+ " features:",
29
+ " partialSprites: false",
29
30
  ];
30
31
  if (target !== "none") {
31
32
  lines.push("package:", ` target: ${target}`);
@@ -55,8 +55,12 @@ function childKey(lines, start, end, key) {
55
55
 
56
56
  function childIndent(lines, start, end) {
57
57
  const limit = Math.min(end, lines.length);
58
+ // Comments can be indented differently from the entries they document, so
59
+ // only real content decides where direct children start.
58
60
  for (let index = start + 1; index < limit; index++) {
59
- const match = /^([ \t]+)\S/.exec(content(lines[index]));
61
+ const text = content(lines[index]);
62
+ if (text.trim() === "" || /^[ \t]*#/.test(text)) continue;
63
+ const match = /^([ \t]+)\S/.exec(text);
60
64
  if (match) return match[1];
61
65
  }
62
66
  return " ";
@@ -751,6 +755,342 @@ export function setFxScalar(configPath, key, value) {
751
755
  return { changed: true };
752
756
  }
753
757
 
758
+ /** True for a non-array object. */
759
+ function isPlainObject(value) {
760
+ return value != null && typeof value === "object" && !Array.isArray(value);
761
+ }
762
+
763
+ /** Read the raw `fx.features` mapping without normalising anything else. */
764
+ export function readFeatureSettings(configPath) {
765
+ const raw = yaml.load(fs.readFileSync(configPath, "utf8")) ?? {};
766
+ if (!isPlainObject(raw) || !isPlainObject(raw.fx)) return {};
767
+ return isPlainObject(raw.fx.features) ? raw.fx.features : {};
768
+ }
769
+
770
+ /** Read one raw `fx.features.<name>` value. */
771
+ export function readFeatureSetting(configPath, name) {
772
+ return readFeatureSettings(configPath)[String(name)];
773
+ }
774
+
775
+ /** Read entries from the legacy top-level `features:` mapping. */
776
+ export function readTopLevelFeatureEntries(configPath) {
777
+ const raw = yaml.load(fs.readFileSync(configPath, "utf8")) ?? {};
778
+ if (!isPlainObject(raw) || !isPlainObject(raw.features)) return [];
779
+ return Object.entries(raw.features)
780
+ .map(([name, value]) => ({
781
+ name,
782
+ file:
783
+ typeof value === "string"
784
+ ? value
785
+ : isPlainObject(value) && typeof value.file === "string"
786
+ ? value.file
787
+ : null,
788
+ }))
789
+ .filter((entry) => entry.file);
790
+ }
791
+
792
+ /** Serialize one feature value as YAML lines at `indent`. */
793
+ function featureValueLines(name, value, indent, eol) {
794
+ const head = `${indent}${quoteKey(name)}:`;
795
+ if (value == null || typeof value !== "object" || Array.isArray(value)) {
796
+ const scalar = typeof value === "string" ? quote(value) : String(value);
797
+ return [`${head} ${scalar}${eol}`];
798
+ }
799
+ const dumped = yaml
800
+ .dump(value, { lineWidth: -1, noRefs: true })
801
+ .trimEnd()
802
+ .split("\n");
803
+ return [`${head}${eol}`, ...dumped.map((line) => `${indent} ${line}${eol}`)];
804
+ }
805
+
806
+ /** Replace an inline flow mapping on `prefix` with a block mapping. */
807
+ function expandFlowMapping(
808
+ lines,
809
+ index,
810
+ indent,
811
+ prefix,
812
+ mapping,
813
+ comment,
814
+ eol,
815
+ ) {
816
+ const dumped = yaml
817
+ .dump({ [prefix]: mapping }, { lineWidth: -1, noRefs: true })
818
+ .split("\n")
819
+ .filter((line, i, all) => !(i === all.length - 1 && line === ""));
820
+ if (comment) dumped[0] = `${prefix}: ${comment}`;
821
+ replaceRange(
822
+ lines,
823
+ index,
824
+ index + 1,
825
+ dumped.map((line) => `${indent}${line}${eol}`),
826
+ );
827
+ }
828
+
829
+ /**
830
+ * Set `fx.features.<name>` without reformatting the rest of fx.yml.
831
+ *
832
+ * @param {string} configPath
833
+ * @param {string} name
834
+ * @param {unknown} value
835
+ * @returns {{changed: boolean}}
836
+ */
837
+ export function setFeatureSetting(configPath, name, value) {
838
+ const text = fs.readFileSync(configPath, "utf8");
839
+ const lines = splitLines(text);
840
+ const eol = eolOf(text);
841
+ const key = String(name);
842
+ const fx = topLevel(lines, "fx");
843
+
844
+ if (!fx) {
845
+ if (lines.length > 0 && !lines[lines.length - 1].endsWith("\n"))
846
+ lines[lines.length - 1] += eol;
847
+ lines.push(
848
+ `fx:${eol}`,
849
+ ` features:${eol}`,
850
+ ...featureValueLines(key, value, " ", eol),
851
+ );
852
+ writeDocument(configPath, lines.join(""));
853
+ return { changed: true };
854
+ }
855
+
856
+ const { value: fxRest, comment: fxComment } = splitComment(fx.rest);
857
+ if (fxRest !== "") {
858
+ if (!fxRest.startsWith("{") || !fxRest.endsWith("}"))
859
+ throw new Error("fx must be a block mapping to edit it");
860
+ const mapping = parseValue(fxRest);
861
+ if (!isPlainObject(mapping))
862
+ throw new Error("fx must be a mapping to edit it");
863
+ const features = isPlainObject(mapping.features) ? mapping.features : {};
864
+ features[key] = value;
865
+ mapping.features = features;
866
+ expandFlowMapping(lines, fx.index, "", "fx", mapping, fxComment, eol);
867
+ writeDocument(configPath, lines.join(""));
868
+ return { changed: true };
869
+ }
870
+
871
+ const fxEnd = sectionEnd(lines, fx.index);
872
+ const featuresSpan = mappingEntrySpans(lines, fx.index, fxEnd).find(
873
+ (span) => span.key === "features",
874
+ );
875
+
876
+ if (!featuresSpan) {
877
+ const indent = childIndent(lines, fx.index, fxEnd);
878
+ insertAt(
879
+ lines,
880
+ fxEnd,
881
+ [
882
+ `${indent}features:${eol}`,
883
+ ...featureValueLines(key, value, `${indent} `, eol),
884
+ ],
885
+ eol,
886
+ );
887
+ writeDocument(configPath, lines.join(""));
888
+ return { changed: true };
889
+ }
890
+
891
+ const { value: rest, comment } = splitComment(featuresSpan.rest);
892
+ if (rest !== "") {
893
+ if (!rest.startsWith("{") || !rest.endsWith("}"))
894
+ throw new Error("fx.features must be a block mapping to edit it");
895
+ const mapping = parseValue(rest);
896
+ if (!isPlainObject(mapping))
897
+ throw new Error("fx.features must be a mapping to edit it");
898
+ mapping[key] = value;
899
+ expandFlowMapping(
900
+ lines,
901
+ featuresSpan.index,
902
+ featuresSpan.indent,
903
+ "features",
904
+ mapping,
905
+ comment,
906
+ eol,
907
+ );
908
+ writeDocument(configPath, lines.join(""));
909
+ return { changed: true };
910
+ }
911
+
912
+ const childSpans = mappingEntrySpans(
913
+ lines,
914
+ featuresSpan.index,
915
+ featuresSpan.end,
916
+ );
917
+ const existing = childSpans.find((span) => span.key === key);
918
+ if (existing) {
919
+ let end = existing.end;
920
+ while (
921
+ end > existing.index + 1 &&
922
+ /^(?:[ \t]*#.*|[ \t]*)$/.test(content(lines[end - 1]))
923
+ )
924
+ end--;
925
+ replaceRange(
926
+ lines,
927
+ existing.index,
928
+ end,
929
+ featureValueLines(key, value, existing.indent, eol),
930
+ );
931
+ } else {
932
+ const indent = childIndent(lines, featuresSpan.index, featuresSpan.end);
933
+ insertAt(
934
+ lines,
935
+ featuresSpan.end,
936
+ featureValueLines(key, value, indent, eol),
937
+ eol,
938
+ );
939
+ }
940
+ writeDocument(configPath, lines.join(""));
941
+ return { changed: true };
942
+ }
943
+
944
+ /**
945
+ * Remove `fx.features.<name>` while keeping the rest of the file intact.
946
+ * @returns {{removed: unknown}}
947
+ */
948
+ export function removeFeatureSetting(configPath, name) {
949
+ const text = fs.readFileSync(configPath, "utf8");
950
+ const lines = splitLines(text);
951
+ const eol = eolOf(text);
952
+ const key = String(name);
953
+ const removedValue = readFeatureSetting(configPath, key);
954
+ const fx = topLevel(lines, "fx");
955
+ if (!fx) return { removed: undefined };
956
+
957
+ const { value: fxRest } = splitComment(fx.rest);
958
+ if (fxRest !== "") {
959
+ if (!fxRest.startsWith("{") || !fxRest.endsWith("}"))
960
+ throw new Error("fx must be a block mapping to edit it");
961
+ const mapping = parseValue(fxRest);
962
+ if (!isPlainObject(mapping) || !isPlainObject(mapping.features))
963
+ return { removed: undefined };
964
+ if (!Object.hasOwn(mapping.features, key)) return { removed: undefined };
965
+ delete mapping.features[key];
966
+ const dumped = yaml
967
+ .dump({ fx: mapping }, { lineWidth: -1, noRefs: true })
968
+ .split("\n")
969
+ .filter((line, i, all) => !(i === all.length - 1 && line === ""));
970
+ replaceRange(
971
+ lines,
972
+ fx.index,
973
+ fx.index + 1,
974
+ dumped.map((line) => `${line}${eol}`),
975
+ );
976
+ writeDocument(configPath, lines.join(""));
977
+ return { removed: removedValue };
978
+ }
979
+
980
+ const fxEnd = sectionEnd(lines, fx.index);
981
+ const featuresSpan = mappingEntrySpans(lines, fx.index, fxEnd).find(
982
+ (span) => span.key === "features",
983
+ );
984
+ if (!featuresSpan) return { removed: undefined };
985
+
986
+ const { value: rest, comment } = splitComment(featuresSpan.rest);
987
+ if (rest !== "") {
988
+ if (!rest.startsWith("{") || !rest.endsWith("}"))
989
+ return { removed: undefined };
990
+ const mapping = parseValue(rest);
991
+ if (!isPlainObject(mapping) || !Object.hasOwn(mapping, key))
992
+ return { removed: undefined };
993
+ delete mapping[key];
994
+ if (Object.keys(mapping).length === 0)
995
+ replaceRange(lines, featuresSpan.index, featuresSpan.index + 1, [
996
+ `${featuresSpan.indent}features: {}${comment ? ` ${comment}` : ""}${eol}`,
997
+ ]);
998
+ else
999
+ expandFlowMapping(
1000
+ lines,
1001
+ featuresSpan.index,
1002
+ featuresSpan.indent,
1003
+ "features",
1004
+ mapping,
1005
+ comment,
1006
+ eol,
1007
+ );
1008
+ writeDocument(configPath, lines.join(""));
1009
+ return { removed: removedValue };
1010
+ }
1011
+
1012
+ const childSpans = mappingEntrySpans(
1013
+ lines,
1014
+ featuresSpan.index,
1015
+ featuresSpan.end,
1016
+ );
1017
+ const existing = childSpans.find((span) => span.key === key);
1018
+ if (!existing) return { removed: undefined };
1019
+ let removeEnd = existing.end;
1020
+ while (
1021
+ removeEnd > existing.index + 1 &&
1022
+ /^(?:[ \t]*#.*|[ \t]*)$/.test(content(lines[removeEnd - 1]))
1023
+ )
1024
+ removeEnd--;
1025
+ const blockEnd = featuresSpan.end - (removeEnd - existing.index);
1026
+ replaceRange(lines, existing.index, removeEnd, []);
1027
+ const stays = mappingEntrySpans(lines, featuresSpan.index, blockEnd);
1028
+ if (stays.length === 0) {
1029
+ const line = lines[featuresSpan.index];
1030
+ lines[featuresSpan.index] =
1031
+ `${featuresSpan.indent}features: {}` +
1032
+ `${comment ? ` ${comment}` : ""}${ending(line) || eol}`;
1033
+ }
1034
+ writeDocument(configPath, lines.join(""));
1035
+ return { removed: removedValue };
1036
+ }
1037
+
1038
+ /**
1039
+ * Remove a top-level key and everything indented under it (used by migration).
1040
+ * @returns {boolean} whether something was removed
1041
+ */
1042
+ export function removeTopLevelKey(configPath, key) {
1043
+ const text = fs.readFileSync(configPath, "utf8");
1044
+ const lines = splitLines(text);
1045
+ const bounds = topLevelBounds(lines, String(key));
1046
+ if (!bounds) return false;
1047
+ replaceRange(lines, bounds.index, bounds.end, []);
1048
+ writeDocument(configPath, lines.join(""));
1049
+ return true;
1050
+ }
1051
+
1052
+ /**
1053
+ * Remove one `fx.<key>` entry (used by migration).
1054
+ * @returns {boolean} whether something was removed
1055
+ */
1056
+ export function removeFxKey(configPath, key) {
1057
+ const text = fs.readFileSync(configPath, "utf8");
1058
+ const lines = splitLines(text);
1059
+ const eol = eolOf(text);
1060
+ const fx = topLevel(lines, "fx");
1061
+ if (!fx) return false;
1062
+
1063
+ const { value: rest } = splitComment(fx.rest);
1064
+ if (rest !== "") {
1065
+ if (!rest.startsWith("{") || !rest.endsWith("}")) return false;
1066
+ const mapping = parseValue(rest);
1067
+ if (!isPlainObject(mapping) || !Object.hasOwn(mapping, String(key)))
1068
+ return false;
1069
+ delete mapping[String(key)];
1070
+ const dumped = yaml
1071
+ .dump({ fx: mapping }, { lineWidth: -1, noRefs: true })
1072
+ .split("\n")
1073
+ .filter((line, i, all) => !(i === all.length - 1 && line === ""));
1074
+ replaceRange(
1075
+ lines,
1076
+ fx.index,
1077
+ fx.index + 1,
1078
+ dumped.map((line) => `${line}${eol}`),
1079
+ );
1080
+ writeDocument(configPath, lines.join(""));
1081
+ return true;
1082
+ }
1083
+
1084
+ const fxEnd = sectionEnd(lines, fx.index);
1085
+ const existing = mappingEntrySpans(lines, fx.index, fxEnd).find(
1086
+ (span) => span.key === String(key),
1087
+ );
1088
+ if (!existing) return false;
1089
+ replaceRange(lines, existing.index, existing.end, []);
1090
+ writeDocument(configPath, lines.join(""));
1091
+ return true;
1092
+ }
1093
+
754
1094
  /**
755
1095
  * Remove a `features:` entry.
756
1096
  * @param {string} configPath
package/src/config.js CHANGED
@@ -12,6 +12,7 @@ import path from "node:path";
12
12
  import * as yaml from "js-yaml";
13
13
  import { configFilename, configFilenames, productName } from "./brand.js";
14
14
  import { DEFAULT_LINT, normalizeLintConfig } from "./lint/config.js";
15
+ import { FEATURES } from "./feature-registry.js";
15
16
 
16
17
  export const DEFAULT_PROJECT = {
17
18
  name: `${productName()} Project`,
@@ -57,6 +58,7 @@ export const DEFAULT_RUN = {
57
58
  * Kept in a separate top-level `fx:` block in fx.yml.
58
59
  */
59
60
  export const DEFAULT_FX = {
61
+ features: {},
60
62
  partialSprites: false,
61
63
  vendorDir: "extensions",
62
64
  tests: false,
@@ -83,7 +85,7 @@ export function normalizeTestConfig(value) {
83
85
  );
84
86
 
85
87
  const unknown = Object.keys(value).filter(
86
- (key) => !Object.hasOwn(DEFAULT_TESTS, key),
88
+ (key) => key !== "enabled" && !Object.hasOwn(DEFAULT_TESTS, key),
87
89
  );
88
90
  if (unknown.length)
89
91
  throw new Error(
@@ -92,6 +94,10 @@ export function normalizeTestConfig(value) {
92
94
  .join(", ")}`,
93
95
  );
94
96
 
97
+ // A mapping may stay in the file while the feature is off, so switching it
98
+ // back on does not lose the configured pattern, timeout, and so on.
99
+ if (value.enabled === false) return false;
100
+
95
101
  const tests = { enabled: true, ...DEFAULT_TESTS };
96
102
  if (value.pattern != null) {
97
103
  if (typeof value.pattern !== "string" || value.pattern.trim() === "")
@@ -145,7 +151,7 @@ export function normalizeRunConfig(value) {
145
151
  );
146
152
 
147
153
  const unknown = Object.keys(value).filter(
148
- (key) => !Object.hasOwn(DEFAULT_RUN, key),
154
+ (key) => key !== "enabled" && !Object.hasOwn(DEFAULT_RUN, key),
149
155
  );
150
156
  if (unknown.length)
151
157
  throw new Error(
@@ -154,6 +160,9 @@ export function normalizeRunConfig(value) {
154
160
  .join(", ")}`,
155
161
  );
156
162
 
163
+ // See normalizeTestConfig: a disabled mapping keeps its settings.
164
+ if (value.enabled === false) return false;
165
+
157
166
  const run = { enabled: true, ...DEFAULT_RUN };
158
167
  if (value.pattern != null) {
159
168
  if (typeof value.pattern !== "string" || value.pattern.trim() === "")
@@ -555,6 +564,108 @@ export function normalizeProject(raw = {}) {
555
564
  return project;
556
565
  }
557
566
 
567
+ /**
568
+ * Normalize the central `fx.features` mapping. The mapping keeps each
569
+ * feature's own value so settings survive a disable/enable cycle.
570
+ *
571
+ * @param {unknown} raw
572
+ * @returns {Record<string, unknown>}
573
+ */
574
+ export function normalizeFeatureSettings(raw = {}) {
575
+ if (raw == null) return {};
576
+ if (!isPlainObject(raw))
577
+ throw new Error(`${configFilename()}: fx.features must be a mapping`);
578
+ return { ...raw };
579
+ }
580
+
581
+ /** Whether a feature setting turns the feature on. */
582
+ function isFeatureOn(value) {
583
+ if (value == null || value === false) return false;
584
+ if (isPlainObject(value)) return value.enabled !== false;
585
+ return Boolean(value);
586
+ }
587
+
588
+ /**
589
+ * Normalize the `partialSprites` setting. It accepts a boolean or a mapping
590
+ * with `enabled`, matching the other feature switches.
591
+ */
592
+ export function normalizePartialSprites(value) {
593
+ return isFeatureOn(value);
594
+ }
595
+
596
+ /**
597
+ * Resolve an extension-backed feature's project file from its setting.
598
+ *
599
+ * `true` uses the bundled filename under the project's vendor directory; a
600
+ * string or `{ file }` pins an explicit path.
601
+ */
602
+ export function featureEntryFile(name, value, vendorDir = DEFAULT_VENDOR_DIR) {
603
+ const feature = FEATURES[name];
604
+ if (typeof value === "string" && value.trim()) return value.trim();
605
+ if (isPlainObject(value) && typeof value.file === "string" && value.file)
606
+ return value.file.trim();
607
+ if (value === true && feature?.filename)
608
+ return `./${String(vendorDir || DEFAULT_VENDOR_DIR)}/${feature.filename}`;
609
+ if (feature)
610
+ throw new Error(
611
+ `${configFilename()}: fx.features.${name} must be true, false, a file path, or { file: "<path>" }`,
612
+ );
613
+ throw new Error(
614
+ `${configFilename()}: fx.features.${name} is not a known feature and needs a file path`,
615
+ );
616
+ }
617
+
618
+ /**
619
+ * Extension entries declared under `fx.features` (core features never appear
620
+ * here). Entries for unknown names are accepted when they name a file, so
621
+ * project-local extensions keep working under the new key.
622
+ *
623
+ * @param {Record<string, unknown>} [settings]
624
+ * @param {string} [vendorDir]
625
+ * @returns {Array<{name: string, file: string}>}
626
+ */
627
+ export function featureEntriesFromSettings(
628
+ settings = {},
629
+ vendorDir = DEFAULT_VENDOR_DIR,
630
+ ) {
631
+ const entries = [];
632
+ for (const [name, value] of Object.entries(settings || {})) {
633
+ if (FEATURES[name]?.core || !isFeatureOn(value)) continue;
634
+ entries.push({ name, file: featureEntryFile(name, value, vendorDir) });
635
+ }
636
+ return entries;
637
+ }
638
+
639
+ /**
640
+ * Names that `fx.features` explicitly switches off. A matching legacy entry is
641
+ * dropped, so the effective feature list never contains a disabled feature.
642
+ */
643
+ export function disabledFeatureNames(settings = {}) {
644
+ return Object.entries(settings || {})
645
+ .filter(([, value]) => !isFeatureOn(value))
646
+ .map(([name]) => name);
647
+ }
648
+
649
+ /**
650
+ * Merge extension entries, with `override` (the new key) winning over `base`
651
+ * (the legacy top-level `features:` list). Names in `disabled` are removed
652
+ * from `base` entirely, so an explicit `false` still wins.
653
+ */
654
+ export function mergeFeatureEntries(base = [], override = [], disabled = []) {
655
+ const off = new Set(disabled.map(String));
656
+ const merged = base
657
+ .filter((entry) => !off.has(entry.name))
658
+ .map((entry) => ({ ...entry }));
659
+ for (const entry of override) {
660
+ const index = merged.findIndex(
661
+ (candidate) => candidate.name === entry.name,
662
+ );
663
+ if (index === -1) merged.push({ ...entry });
664
+ else merged[index] = { ...entry };
665
+ }
666
+ return merged;
667
+ }
668
+
558
669
  /**
559
670
  * @param {object} raw parsed YAML `fx` mapping
560
671
  * @returns {typeof DEFAULT_FX}
@@ -562,15 +673,32 @@ export function normalizeProject(raw = {}) {
562
673
  export function normalizeFx(raw = {}) {
563
674
  const fx = { ...DEFAULT_FX, lint: { ...DEFAULT_LINT, rules: {} } };
564
675
  if (raw && typeof raw === "object" && !Array.isArray(raw)) {
565
- if (raw.partialSprites != null)
566
- fx.partialSprites = Boolean(raw.partialSprites);
676
+ if (raw.features !== undefined)
677
+ fx.features = normalizeFeatureSettings(raw.features);
678
+ const features = fx.features || {};
679
+
567
680
  if (raw.vendorDir != null) {
568
681
  if (typeof raw.vendorDir !== "string" || raw.vendorDir.trim() === "")
569
682
  throw new Error(`${configFilename()}: fx.vendorDir must be a path`);
570
683
  fx.vendorDir = raw.vendorDir.trim();
571
684
  }
572
- if (raw.tests !== undefined) fx.tests = normalizeTestConfig(raw.tests);
573
- if (raw.run !== undefined) fx.run = normalizeRunConfig(raw.run);
685
+
686
+ // `fx.features` is the canonical switch. When it names a feature, it wins
687
+ // over the older `fx.<name>` setting; otherwise the old setting still
688
+ // applies, so existing projects keep working unchanged.
689
+ if (Object.hasOwn(features, "tests"))
690
+ fx.tests = normalizeTestConfig(features.tests);
691
+ else if (raw.tests !== undefined) fx.tests = normalizeTestConfig(raw.tests);
692
+
693
+ if (Object.hasOwn(features, "run"))
694
+ fx.run = normalizeRunConfig(features.run);
695
+ else if (raw.run !== undefined) fx.run = normalizeRunConfig(raw.run);
696
+
697
+ if (Object.hasOwn(features, "partialSprites"))
698
+ fx.partialSprites = normalizePartialSprites(features.partialSprites);
699
+ else if (raw.partialSprites != null)
700
+ fx.partialSprites = Boolean(raw.partialSprites);
701
+
574
702
  fx.lint = normalizeLintConfig(
575
703
  raw.lint,
576
704
  (message) => new Error(`${configFilename()}: ${message}`),
@@ -605,7 +733,11 @@ export function parseConfig(text) {
605
733
  fx,
606
734
  package: normalizePackage(raw.package || {}),
607
735
  vendor: normalizeVendor(raw.vendor || {}),
608
- features: normalizeFeatures(raw.features || {}),
736
+ features: mergeFeatureEntries(
737
+ normalizeFeatures(raw.features || {}),
738
+ featureEntriesFromSettings(fx.features, fx.vendorDir),
739
+ disabledFeatureNames(fx.features),
740
+ ),
609
741
  vendorDir: fx.vendorDir,
610
742
  raw,
611
743
  };
@@ -0,0 +1,85 @@
1
+ /**
2
+ * The single registry of Fx's optional features.
3
+ *
4
+ * Every optional feature is described here, and only here. The `fx feature`
5
+ * command, the `fx.features` config key, linting, and the build/test/run
6
+ * pipelines all read this registry, so adding a feature does not mean teaching
7
+ * each subsystem about it separately.
8
+ *
9
+ * A feature is either:
10
+ *
11
+ * - `core`: built into Fx and switched on by `fx.features.<name>`.
12
+ * - `extension`: backed by a JavaScript extension that `fx feature enable`
13
+ * copies into the project, so the project owns (and pins) the source.
14
+ */
15
+ import { fileURLToPath } from "node:url";
16
+
17
+ export class FeatureError extends Error {
18
+ constructor(message, options) {
19
+ super(message, options);
20
+ this.name = "FeatureError";
21
+ }
22
+ }
23
+
24
+ export const FEATURES = {
25
+ partialSprites: {
26
+ name: "partialSprites",
27
+ title: "Partial Sprites",
28
+ summary: "Add to a sprite from more than one source file.",
29
+ kind: "core",
30
+ core: true,
31
+ },
32
+ run: {
33
+ name: "run",
34
+ title: "Running",
35
+ summary: "Run headless entry points with `fx run`.",
36
+ kind: "core",
37
+ core: true,
38
+ command: "run",
39
+ },
40
+ temporaryvariables: {
41
+ name: "temporaryvariables",
42
+ title: "Temporary Variables",
43
+ summary: "Disposable per-thread and per-run variables.",
44
+ kind: "extension",
45
+ extensionId: "fxTempVars",
46
+ filename: "fx-tempvars.js",
47
+ source: fileURLToPath(
48
+ new URL("../vendor/tempvars/fx-tempvars.js", import.meta.url),
49
+ ),
50
+ },
51
+ tests: {
52
+ name: "tests",
53
+ title: "Testing",
54
+ summary: "Write project tests and run them with `fx test`.",
55
+ kind: "core",
56
+ core: true,
57
+ command: "test",
58
+ },
59
+ };
60
+
61
+ /** Core features, kept as a derived view for older callers. */
62
+ export const CORE_FEATURES = Object.fromEntries(
63
+ Object.entries(FEATURES).filter(([, feature]) => feature.core),
64
+ );
65
+
66
+ /** List feature names for help and error messages. */
67
+ export function featureNames() {
68
+ return Object.keys(FEATURES).sort();
69
+ }
70
+
71
+ /** Resolve one feature by name. */
72
+ export function getFeature(name) {
73
+ const key = String(name ?? "");
74
+ const feature = FEATURES[key];
75
+ if (!feature)
76
+ throw new FeatureError(
77
+ `Unknown feature ${JSON.stringify(key)}. Available features: ${featureNames().join(", ")}.`,
78
+ );
79
+ return feature;
80
+ }
81
+
82
+ /** Core feature names. */
83
+ export function coreFeatureNames() {
84
+ return featureNames().filter((name) => FEATURES[name].core);
85
+ }
package/src/features.js CHANGED
@@ -1,89 +1,46 @@
1
1
  /**
2
- * Built-in, project-local features.
2
+ * Optional feature management.
3
3
  *
4
- * `fx feature <name> enable` copies a feature's extension source into the
5
- * project and records that file under `features:` in `fx.yml`. Builds load the
6
- * committed file, so an Fx upgrade never changes a project's feature code, and
7
- * the project keeps working offline (and in Fx versions that predate the
8
- * feature system) because the extension is an ordinary JavaScript file.
4
+ * Every feature is described by `./feature-registry.js` and switched under the
5
+ * single `fx.features` key. Enabling an extension-backed feature copies its
6
+ * source into the project and records that file under `fx.features`, so an Fx
7
+ * upgrade never changes a project's feature code and the project keeps working
8
+ * offline. Core features (tests, run, partial sprites) are built into Fx and
9
+ * only record their switch.
9
10
  */
10
11
  import crypto from "node:crypto";
11
12
  import fs from "node:fs";
12
13
  import path from "node:path";
13
- import { fileURLToPath } from "node:url";
14
14
  import { parseConfig } from "./config.js";
15
15
  import {
16
- addFeatureEntry,
17
- readFxValue,
16
+ readFeatureSetting,
17
+ readTopLevelFeatureEntries,
18
18
  removeFeatureEntry,
19
- setFxScalar,
19
+ removeFeatureSetting,
20
+ removeFxKey,
21
+ removeTopLevelKey,
22
+ setFeatureSetting,
20
23
  } from "./config-edit.js";
24
+ import {
25
+ CORE_FEATURES,
26
+ FEATURES,
27
+ FeatureError,
28
+ coreFeatureNames,
29
+ featureNames,
30
+ getFeature,
31
+ } from "./feature-registry.js";
21
32
  import { loadExtensions } from "./extensions.js";
22
33
  import { formatDiff } from "./vendor.js";
23
34
 
24
- export class FeatureError extends Error {
25
- constructor(message, options) {
26
- super(message, options);
27
- this.name = "FeatureError";
28
- }
29
- }
30
-
31
- /**
32
- * Feature registry. `source` points at the fork that ships with Fx; `enable`
33
- * copies it into the project so the project owns (and pins) the bytes.
34
- */
35
- export const FEATURES = {
36
- temporaryvariables: {
37
- name: "temporaryvariables",
38
- title: "Temporary Variables",
39
- summary: "Disposable per-thread and per-run variables.",
40
- extensionId: "fxTempVars",
41
- filename: "fx-tempvars.js",
42
- source: fileURLToPath(
43
- new URL("../vendor/tempvars/fx-tempvars.js", import.meta.url),
44
- ),
45
- },
46
- };
47
-
48
- /**
49
- * Built-in language features. They live behind a single `fx.<name>` setting,
50
- * so they are enabled and disabled without touching `features:`. A core
51
- * feature may still ship an extension; Fx loads that bundled source itself
52
- * instead of copying it into the project.
53
- */
54
- export const CORE_FEATURES = {
55
- tests: {
56
- name: "tests",
57
- title: "Testing",
58
- summary: "Write project tests and run them with `fx test`.",
59
- core: true,
60
- command: "test",
61
- },
62
- run: {
63
- name: "run",
64
- title: "Running",
65
- summary: "Run headless entry points with `fx run`.",
66
- core: true,
67
- command: "run",
68
- },
35
+ export {
36
+ CORE_FEATURES,
37
+ FEATURES,
38
+ FeatureError,
39
+ coreFeatureNames,
40
+ featureNames,
41
+ getFeature,
69
42
  };
70
43
 
71
- /** List feature names for help and error messages. */
72
- export function featureNames() {
73
- return [...Object.keys(FEATURES), ...Object.keys(CORE_FEATURES)].sort();
74
- }
75
-
76
- /** Resolve one feature by name. */
77
- export function getFeature(name) {
78
- const key = String(name ?? "");
79
- const feature = FEATURES[key] ?? CORE_FEATURES[key];
80
- if (!feature)
81
- throw new FeatureError(
82
- `Unknown feature ${JSON.stringify(key)}. Available features: ${featureNames().join(", ")}.`,
83
- );
84
- return feature;
85
- }
86
-
87
44
  /** Absolute path of the extension source Fx ships for a feature. */
88
45
  export function featureSourcePath(name) {
89
46
  return getFeature(name).source;
@@ -169,9 +126,45 @@ function writeFileAtomic(file, data) {
169
126
  }
170
127
  }
171
128
 
172
- /** Read the `features:` list from a config file. */
173
- function readFeatureEntries(configPath) {
174
- return parseConfig(fs.readFileSync(configPath, "utf8")).features;
129
+ function isPlainObject(value) {
130
+ return value != null && typeof value === "object" && !Array.isArray(value);
131
+ }
132
+
133
+ /** Read a config file, or null when the project has none yet. */
134
+ function readConfig(configPath) {
135
+ if (!configPath || !fs.existsSync(configPath)) return null;
136
+ return parseConfig(fs.readFileSync(configPath, "utf8"));
137
+ }
138
+
139
+ /** The effective extension entry for a feature, if it is enabled. */
140
+ function featureEntry(configPath, feature) {
141
+ if (feature.core) return null;
142
+ const loaded = readConfig(configPath);
143
+ return loaded?.features.find((entry) => entry.name === feature.name) ?? null;
144
+ }
145
+
146
+ /**
147
+ * The value to write when re-enabling a core feature. A value from either the
148
+ * new key or the legacy `fx.<name>` setting keeps its options, so disabling and
149
+ * enabling again does not reset a pattern, timeout, or seed.
150
+ */
151
+ function retainedCoreValue(configPath, feature) {
152
+ const own = readFeatureSetting(configPath, feature.name);
153
+ if (isPlainObject(own)) return { ...own, enabled: true };
154
+ const loaded = readConfig(configPath);
155
+ const legacy = loaded?.raw?.fx?.[feature.name];
156
+ if (isPlainObject(legacy)) return { ...legacy, enabled: true };
157
+ return true;
158
+ }
159
+
160
+ /** The value to write when disabling a core feature, keeping its options. */
161
+ function disabledCoreValue(configPath, feature) {
162
+ const own = readFeatureSetting(configPath, feature.name);
163
+ if (isPlainObject(own)) return { ...own, enabled: false };
164
+ const loaded = readConfig(configPath);
165
+ const legacy = loaded?.raw?.fx?.[feature.name];
166
+ if (isPlainObject(legacy)) return { ...legacy, enabled: false };
167
+ return false;
175
168
  }
176
169
 
177
170
  /**
@@ -186,30 +179,27 @@ function readFeatureEntries(configPath) {
186
179
  * @param {boolean} [options.force] replace a modified copy
187
180
  * @returns {{feature: object, name: string, file: string, path: string, changed: boolean, configChanged: boolean}}
188
181
  */
189
- /** True when a feature's setting is enabled in the project config. */
190
- function coreFeatureEnabled(configPath, feature) {
191
- if (!configPath || !fs.existsSync(configPath)) return false;
192
- return Boolean(readFxValue(configPath, feature.name));
193
- }
194
-
195
182
  /**
196
183
  * Whether a feature is currently enabled in a project.
197
- * @param {{configPath?: string, name: string}} options
184
+ *
185
+ * `fx.features` is the canonical switch; the older `fx.<name>` setting and
186
+ * top-level `features:` entries stay readable, with the new key winning.
187
+ *
188
+ * @param {{configPath?: string, config?: object, name: string}} options
198
189
  */
199
- export function featureEnabled({ configPath, name } = {}) {
190
+ export function featureEnabled({ configPath, config, name } = {}) {
200
191
  const feature = getFeature(name);
201
- if (feature.core) return coreFeatureEnabled(configPath, feature);
202
- if (!configPath || !fs.existsSync(configPath)) return false;
203
- return Boolean(
204
- readFeatureEntries(configPath).find((entry) => entry.name === feature.name),
205
- );
192
+ const loaded = config ?? readConfig(configPath);
193
+ if (!loaded) return false;
194
+ if (feature.core) return Boolean(loaded.fx?.[feature.name]);
195
+ return Boolean(loaded.features?.find((entry) => entry.name === feature.name));
206
196
  }
207
197
 
208
198
  /**
209
199
  * Enable a feature in a project.
210
200
  *
211
201
  * Extension features copy their source into the project; core features only
212
- * record `fx.<name>: true` in `fx.yml`.
202
+ * record `fx.features.<name>: true` in `fx.yml`.
213
203
  *
214
204
  * @param {object} options
215
205
  * @param {string} options.configPath
@@ -228,15 +218,27 @@ export function enableFeature({
228
218
  } = {}) {
229
219
  const feature = getFeature(name);
230
220
  if (feature.core) {
231
- const changed = !coreFeatureEnabled(configPath, feature);
232
- if (changed) setFxScalar(configPath, feature.name, true);
221
+ if (featureEnabled({ configPath, name: feature.name }))
222
+ return {
223
+ feature,
224
+ name: feature.name,
225
+ file: null,
226
+ path: null,
227
+ changed: false,
228
+ configChanged: false,
229
+ };
230
+ setFeatureSetting(
231
+ configPath,
232
+ feature.name,
233
+ retainedCoreValue(configPath, feature),
234
+ );
233
235
  return {
234
236
  feature,
235
237
  name: feature.name,
236
238
  file: null,
237
239
  path: null,
238
- changed,
239
- configChanged: changed,
240
+ changed: true,
241
+ configChanged: true,
240
242
  };
241
243
  }
242
244
  const dir = assertInside(
@@ -261,18 +263,29 @@ export function enableFeature({
261
263
  writeFileAtomic(target, source);
262
264
  }
263
265
  const file = relativeProjectPath(configDir, target);
264
- const configured = readFeatureEntries(configPath).find(
265
- (entry) => entry.name === feature.name,
266
- );
267
- const needsEntry = !configured || configured.file !== file;
268
- if (needsEntry) addFeatureEntry(configPath, feature.name, file);
266
+ const own = readFeatureSetting(configPath, feature.name);
267
+ let configChanged = false;
268
+ if (own !== file) {
269
+ setFeatureSetting(configPath, feature.name, file);
270
+ configChanged = true;
271
+ }
272
+ // Enabling an older project moves its entry under `fx.features`, so a
273
+ // project ends up with the canonical key once it is written to.
274
+ if (
275
+ readTopLevelFeatureEntries(configPath).some(
276
+ (entry) => entry.name === feature.name,
277
+ )
278
+ ) {
279
+ removeFeatureEntry(configPath, feature.name);
280
+ configChanged = true;
281
+ }
269
282
  return {
270
283
  feature,
271
284
  name: feature.name,
272
285
  file,
273
286
  path: target,
274
287
  changed,
275
- configChanged: needsEntry,
288
+ configChanged,
276
289
  };
277
290
  }
278
291
 
@@ -281,12 +294,12 @@ export function enableFeature({
281
294
  *
282
295
  * A file is deleted only when its name and bytes match the packaged feature
283
296
  * source that `enable`/`update` write. A hand-pointed or edited project file is
284
- * user-owned and survives, even though its `features:` entry is removed.
297
+ * user-owned and survives, even though its config entry is removed.
285
298
  */
286
299
  export function disableFeature({ configPath, configDir, name } = {}) {
287
300
  const feature = getFeature(name);
288
301
  if (feature.core) {
289
- if (!coreFeatureEnabled(configPath, feature))
302
+ if (!featureEnabled({ configPath, name: feature.name }))
290
303
  return {
291
304
  feature,
292
305
  name: feature.name,
@@ -294,21 +307,20 @@ export function disableFeature({ configPath, configDir, name } = {}) {
294
307
  changed: false,
295
308
  warning: null,
296
309
  };
297
- setFxScalar(configPath, feature.name, false);
310
+ setFeatureSetting(
311
+ configPath,
312
+ feature.name,
313
+ disabledCoreValue(configPath, feature),
314
+ );
298
315
  return {
299
316
  feature,
300
317
  name: feature.name,
301
318
  file: null,
302
319
  changed: true,
303
- warning:
304
- feature.name === "tests"
305
- ? `${feature.title} will become a core feature in a future version.`
306
- : null,
320
+ warning: null,
307
321
  };
308
322
  }
309
- const entry = readFeatureEntries(configPath).find(
310
- (candidate) => candidate.name === feature.name,
311
- );
323
+ const entry = featureEntry(configPath, feature);
312
324
  if (!entry)
313
325
  throw new FeatureError(
314
326
  `${feature.title} is not enabled. Run "fx feature ${feature.name} enable" first.`,
@@ -331,6 +343,7 @@ export function disableFeature({ configPath, configDir, name } = {}) {
331
343
  installedByFx = false;
332
344
  }
333
345
  }
346
+ removeFeatureSetting(configPath, feature.name);
334
347
  removeFeatureEntry(configPath, feature.name);
335
348
  if (installedByFx) fs.rmSync(target, { force: true });
336
349
  return {
@@ -357,9 +370,7 @@ export function updateFeature({
357
370
  throw new FeatureError(
358
371
  `${feature.title} is built into Fx, so there is no vendored source or lock entry to update.`,
359
372
  );
360
- const entry = readFeatureEntries(configPath).find(
361
- (candidate) => candidate.name === feature.name,
362
- );
373
+ const entry = featureEntry(configPath, feature);
363
374
  if (!entry)
364
375
  throw new FeatureError(
365
376
  `${feature.title} is not enabled. Run "fx feature ${feature.name} enable" first.`,
@@ -467,3 +478,100 @@ export async function loadFeatureExtensions({ configDir, config } = {}) {
467
478
 
468
479
  return { catalog, extensionUrls, warnings, ids, unsandboxed };
469
480
  }
481
+
482
+ /**
483
+ * Move legacy feature settings under the single `fx.features` key.
484
+ *
485
+ * Legacy sources are `fx.tests`, `fx.run`, `fx.partialSprites`, and the
486
+ * top-level `features:` mapping. A value already present under `fx.features`
487
+ * wins; the legacy copy is removed either way. The config is backed up before
488
+ * it is changed.
489
+ *
490
+ * @param {{configPath: string, dryRun?: boolean}} options
491
+ * @returns {{migrated: string[], conflicts: string[], changed: boolean, backup: string|null, diff: string, configPath: string}}
492
+ */
493
+ export function migrateFeatureConfig({ configPath, dryRun = false } = {}) {
494
+ const original = fs.readFileSync(configPath, "utf8");
495
+ const loaded = parseConfig(original);
496
+ const rawFx = isPlainObject(loaded.raw?.fx) ? loaded.raw.fx : {};
497
+ const legacyEntries = readTopLevelFeatureEntries(configPath);
498
+ const coreNames = new Set(coreFeatureNames());
499
+
500
+ const migrated = new Set();
501
+ const moves = {};
502
+ // Top-level entries that can be removed after migration. A core-named entry
503
+ // stays where it is: writing its file path under `fx.features` would change
504
+ // the meaning of the key and make the result unloadable.
505
+ const removable = [];
506
+ const conflicts = [];
507
+ const legacyCoreKeys = coreFeatureNames().filter((name) =>
508
+ Object.hasOwn(rawFx, name),
509
+ );
510
+ for (const name of legacyCoreKeys) {
511
+ migrated.add(name);
512
+ if (readFeatureSetting(configPath, name) === undefined)
513
+ moves[name] = rawFx[name];
514
+ }
515
+ for (const entry of legacyEntries) {
516
+ if (coreNames.has(entry.name)) {
517
+ conflicts.push(entry.name);
518
+ continue;
519
+ }
520
+ migrated.add(entry.name);
521
+ removable.push(entry.name);
522
+ if (readFeatureSetting(configPath, entry.name) === undefined)
523
+ moves[entry.name] = entry.file;
524
+ }
525
+
526
+ if (
527
+ Object.keys(moves).length === 0 &&
528
+ removable.length === 0 &&
529
+ legacyCoreKeys.length === 0
530
+ )
531
+ return {
532
+ migrated: [],
533
+ conflicts,
534
+ changed: false,
535
+ backup: null,
536
+ diff: "",
537
+ configPath,
538
+ };
539
+
540
+ const dir = path.dirname(configPath);
541
+ const temp = path.join(
542
+ dir,
543
+ `.fx-migrate-${process.pid}-${crypto.randomBytes(4).toString("hex")}.yml`,
544
+ );
545
+ const target = dryRun ? temp : configPath;
546
+ if (dryRun) fs.writeFileSync(temp, original);
547
+
548
+ const backup = dryRun ? null : `${configPath}.bak`;
549
+ if (backup) fs.writeFileSync(backup, original);
550
+ try {
551
+ for (const [name, value] of Object.entries(moves))
552
+ setFeatureSetting(target, name, value);
553
+ for (const name of legacyCoreKeys) removeFxKey(target, name);
554
+ if (removable.length > 0) {
555
+ if (removable.length === legacyEntries.length)
556
+ removeTopLevelKey(target, "features");
557
+ else for (const name of removable) removeFeatureEntry(target, name);
558
+ }
559
+
560
+ const updated = fs.readFileSync(target, "utf8");
561
+ // Refuse to leave behind a config that the normal loader cannot read.
562
+ parseConfig(updated);
563
+ return {
564
+ migrated: [...migrated],
565
+ conflicts,
566
+ changed: true,
567
+ backup,
568
+ diff: formatDiff(original, updated, path.basename(configPath)),
569
+ configPath,
570
+ };
571
+ } catch (error) {
572
+ if (!dryRun) fs.writeFileSync(configPath, original);
573
+ throw error;
574
+ } finally {
575
+ if (dryRun) fs.rmSync(temp, { force: true });
576
+ }
577
+ }
@@ -3,8 +3,9 @@
3
3
  *
4
4
  * The full config loader (`src/config.js`) needs `node:fs` to search for the
5
5
  * file, so editors that only have the file's text use this instead. It reads
6
- * the settings lint diagnostics depend on — `fx.partialSprites`, `fx.lint` and
7
- * the declared extension names — and ignores everything else.
6
+ * the settings lint diagnostics depend on — `fx.features` (with the older
7
+ * `fx.<name>` keys as fallbacks), `fx.lint`, and the declared extension names —
8
+ * and ignores everything else.
8
9
  */
9
10
 
10
11
  import * as yaml from "js-yaml";
@@ -98,20 +99,40 @@ export function parseProjectConfigText(text) {
98
99
  }
99
100
  }
100
101
 
102
+ // `fx.features` is the canonical switch; older `fx.<name>` settings still
103
+ // apply when the new key does not name that feature.
104
+ const features =
105
+ fx.features &&
106
+ typeof fx.features === "object" &&
107
+ !Array.isArray(fx.features)
108
+ ? fx.features
109
+ : {};
110
+ const setting = (name) =>
111
+ Object.hasOwn(features, name) ? features[name] : fx[name];
112
+
101
113
  const patternOf = (value, fallback) => {
102
114
  if (value === true) return fallback;
103
115
  if (value && typeof value === "object" && !Array.isArray(value)) {
116
+ if (value.enabled === false) return null;
104
117
  if (value.pattern === undefined) return fallback;
105
118
  if (typeof value.pattern === "string" && value.pattern.trim())
106
119
  return value.pattern.trim();
107
120
  }
108
121
  return null;
109
122
  };
110
- const testPattern = patternOf(fx.tests, DEFAULT_TEST_PATTERN);
111
- const runPattern = patternOf(fx.run, DEFAULT_RUN_PATTERN);
123
+ const testPattern = patternOf(setting("tests"), DEFAULT_TEST_PATTERN);
124
+ const runPattern = patternOf(setting("run"), DEFAULT_RUN_PATTERN);
125
+ const partial = setting("partialSprites");
112
126
 
113
127
  return {
114
- config: { fx: { partialSprites: Boolean(fx.partialSprites) } },
128
+ config: {
129
+ fx: {
130
+ partialSprites:
131
+ partial != null && typeof partial === "object"
132
+ ? partial.enabled !== false
133
+ : Boolean(partial),
134
+ },
135
+ },
115
136
  lintConfig,
116
137
  declaredExtensions: [...declaredExtensions],
117
138
  testPattern,
@@ -2,5 +2,5 @@
2
2
  "name": "@penguinmod/packager",
3
3
  "version": "1.9.2",
4
4
  "commit": "53f868b85ec21d2edab9ce00fd2d709da93da6d6",
5
- "builtAt": "2026-11-26T05:48:41.391Z"
5
+ "builtAt": "2026-11-26T19:16:44.275Z"
6
6
  }
@@ -3,5 +3,5 @@
3
3
  "version": "0.2.0",
4
4
  "commit": "3822f284c8cda2c3a0a5c6dd928221dd9ff2cee1",
5
5
  "inputHash": "bb8f99fcce9f4ecdc563f11df5a0510dcc94c25d256c6931c7f1f113e0a1998b",
6
- "builtAt": "2026-11-26T05:49:36.222Z"
6
+ "builtAt": "2026-11-26T19:17:49.724Z"
7
7
  }