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

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.
@@ -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
+ }