@doeixd/machine 0.0.17 → 0.0.19

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.
@@ -20,7 +20,6 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/index.ts
21
21
  var src_exports = {};
22
22
  __export(src_exports, {
23
- ADVANCED_CONFIG_EXAMPLES: () => ADVANCED_CONFIG_EXAMPLES,
24
23
  BoundMachine: () => BoundMachine,
25
24
  CANCEL: () => CANCEL,
26
25
  META_KEY: () => META_KEY,
@@ -32,11 +31,13 @@ __export(src_exports, {
32
31
  branch: () => branch,
33
32
  call: () => call,
34
33
  chain: () => chain,
34
+ classCase: () => classCase,
35
35
  combine: () => combine,
36
36
  combineFactories: () => combineFactories,
37
37
  compose: () => compose,
38
38
  composeTyped: () => composeTyped,
39
39
  createAsyncMachine: () => createAsyncMachine,
40
+ createContext: () => createContext,
40
41
  createCustomMiddleware: () => createCustomMiddleware,
41
42
  createEnsemble: () => createEnsemble,
42
43
  createEnsembleFactory: () => createEnsembleFactory,
@@ -47,6 +48,7 @@ __export(src_exports, {
47
48
  createMachine: () => createMachine,
48
49
  createMachineBuilder: () => createMachineBuilder,
49
50
  createMachineFactory: () => createMachineFactory,
51
+ createMatcher: () => createMatcher,
50
52
  createMiddleware: () => createMiddleware,
51
53
  createMiddlewareFactory: () => createMiddlewareFactory,
52
54
  createMiddlewareRegistry: () => createMiddlewareRegistry,
@@ -58,12 +60,12 @@ __export(src_exports, {
58
60
  createTransition: () => createTransition,
59
61
  createTransitionExtender: () => createTransitionExtender,
60
62
  createTransitionFactory: () => createTransitionFactory,
63
+ customCase: () => customCase,
61
64
  delegateToChild: () => delegateToChild,
62
65
  describe: () => describe,
66
+ discriminantCase: () => discriminantCase,
63
67
  extendTransitions: () => extendTransitions,
64
- extractMachine: () => extractMachine,
65
- extractMachines: () => extractMachines,
66
- generateChart: () => generateChart,
68
+ forContext: () => forContext,
67
69
  guard: () => guard,
68
70
  guardAsync: () => guardAsync,
69
71
  guarded: () => guarded,
@@ -706,441 +708,6 @@ function createParallelMachine(m1, m2) {
706
708
  };
707
709
  }
708
710
 
709
- // src/extract.ts
710
- var import_ts_morph = require("ts-morph");
711
- function resolveClassName(node) {
712
- if (import_ts_morph.Node.isIdentifier(node)) {
713
- return node.getText();
714
- }
715
- if (import_ts_morph.Node.isTypeOfExpression(node)) {
716
- return node.getExpression().getText();
717
- }
718
- return "unknown";
719
- }
720
- function parseObjectLiteral(obj) {
721
- if (!import_ts_morph.Node.isObjectLiteralExpression(obj)) {
722
- return {};
723
- }
724
- const result = {};
725
- for (const prop of obj.getProperties()) {
726
- if (import_ts_morph.Node.isPropertyAssignment(prop)) {
727
- const name = prop.getName();
728
- const init = prop.getInitializer();
729
- if (init) {
730
- if (import_ts_morph.Node.isStringLiteral(init)) {
731
- result[name] = init.getLiteralValue();
732
- } else if (import_ts_morph.Node.isNumericLiteral(init)) {
733
- result[name] = init.getLiteralValue();
734
- } else if (init.getText() === "true" || init.getText() === "false") {
735
- result[name] = init.getText() === "true";
736
- } else if (import_ts_morph.Node.isIdentifier(init)) {
737
- result[name] = init.getText();
738
- } else if (import_ts_morph.Node.isObjectLiteralExpression(init)) {
739
- result[name] = parseObjectLiteral(init);
740
- } else if (import_ts_morph.Node.isArrayLiteralExpression(init)) {
741
- result[name] = init.getElements().map((el) => {
742
- if (import_ts_morph.Node.isObjectLiteralExpression(el)) {
743
- return parseObjectLiteral(el);
744
- }
745
- return el.getText();
746
- });
747
- }
748
- }
749
- }
750
- }
751
- return result;
752
- }
753
- function parseInvokeService(obj) {
754
- if (!import_ts_morph.Node.isObjectLiteralExpression(obj)) {
755
- return {};
756
- }
757
- const service = {};
758
- for (const prop of obj.getProperties()) {
759
- if (import_ts_morph.Node.isPropertyAssignment(prop)) {
760
- const name = prop.getName();
761
- const init = prop.getInitializer();
762
- if (!init) continue;
763
- if (name === "onDone" || name === "onError") {
764
- service[name] = resolveClassName(init);
765
- } else if (import_ts_morph.Node.isStringLiteral(init)) {
766
- service[name] = init.getLiteralValue();
767
- } else if (import_ts_morph.Node.isIdentifier(init)) {
768
- service[name] = init.getText();
769
- }
770
- }
771
- }
772
- return service;
773
- }
774
- function extractFromCallExpression(call2, verbose = false) {
775
- if (!import_ts_morph.Node.isCallExpression(call2)) {
776
- return null;
777
- }
778
- const expression = call2.getExpression();
779
- const fnName = import_ts_morph.Node.isIdentifier(expression) ? expression.getText() : null;
780
- if (!fnName) {
781
- return null;
782
- }
783
- const metadata2 = {};
784
- const args = call2.getArguments();
785
- switch (fnName) {
786
- case "transitionTo":
787
- if (args[0]) {
788
- metadata2.target = resolveClassName(args[0]);
789
- }
790
- break;
791
- case "describe":
792
- if (args[0] && import_ts_morph.Node.isStringLiteral(args[0])) {
793
- metadata2.description = args[0].getLiteralValue();
794
- }
795
- if (args[1] && import_ts_morph.Node.isCallExpression(args[1])) {
796
- const nested = extractFromCallExpression(args[1], verbose);
797
- if (nested) {
798
- Object.assign(metadata2, nested);
799
- }
800
- }
801
- break;
802
- case "guarded":
803
- if (args[0]) {
804
- const guard2 = parseObjectLiteral(args[0]);
805
- if (Object.keys(guard2).length > 0) {
806
- metadata2.guards = [guard2];
807
- }
808
- }
809
- if (args[1] && import_ts_morph.Node.isCallExpression(args[1])) {
810
- const nested = extractFromCallExpression(args[1], verbose);
811
- if (nested) {
812
- Object.assign(metadata2, nested);
813
- }
814
- }
815
- break;
816
- case "invoke":
817
- if (args[0]) {
818
- const service = parseInvokeService(args[0]);
819
- if (Object.keys(service).length > 0) {
820
- metadata2.invoke = service;
821
- }
822
- }
823
- break;
824
- case "action":
825
- if (args[0]) {
826
- const actionMeta = parseObjectLiteral(args[0]);
827
- if (Object.keys(actionMeta).length > 0) {
828
- metadata2.actions = [actionMeta];
829
- }
830
- }
831
- if (args[1] && import_ts_morph.Node.isCallExpression(args[1])) {
832
- const nested = extractFromCallExpression(args[1], verbose);
833
- if (nested) {
834
- Object.assign(metadata2, nested);
835
- }
836
- }
837
- break;
838
- case "guard":
839
- if (args[2]) {
840
- const options = parseObjectLiteral(args[2]);
841
- if (options.description) {
842
- metadata2.description = options.description;
843
- }
844
- }
845
- metadata2.guards = [{ name: "runtime_guard", description: metadata2.description || "Synchronous condition check" }];
846
- if (args[1] && import_ts_morph.Node.isCallExpression(args[1])) {
847
- const nested = extractFromCallExpression(args[1], verbose);
848
- if (nested) {
849
- Object.assign(metadata2, nested);
850
- }
851
- }
852
- break;
853
- case "guardAsync":
854
- if (args[2]) {
855
- const options = parseObjectLiteral(args[2]);
856
- if (options.description) {
857
- metadata2.description = options.description;
858
- }
859
- }
860
- metadata2.guards = [{ name: "runtime_guard_async", description: metadata2.description || "Asynchronous condition check" }];
861
- if (args[1] && import_ts_morph.Node.isCallExpression(args[1])) {
862
- const nested = extractFromCallExpression(args[1], verbose);
863
- if (nested) {
864
- Object.assign(metadata2, nested);
865
- }
866
- }
867
- break;
868
- default:
869
- return null;
870
- }
871
- return Object.keys(metadata2).length > 0 ? metadata2 : null;
872
- }
873
- function extractMetaFromMember(member, verbose = false) {
874
- if (!import_ts_morph.Node.isPropertyDeclaration(member)) {
875
- if (verbose) console.error(` ⚠️ Not a property declaration`);
876
- return null;
877
- }
878
- const initializer = member.getInitializer();
879
- if (!initializer) {
880
- if (verbose) console.error(` ⚠️ No initializer`);
881
- return null;
882
- }
883
- if (!import_ts_morph.Node.isCallExpression(initializer)) {
884
- if (verbose) console.error(` ⚠️ Initializer is not a call expression`);
885
- return null;
886
- }
887
- const metadata2 = extractFromCallExpression(initializer, verbose);
888
- if (metadata2 && verbose) {
889
- console.error(` ✅ Extracted metadata:`, JSON.stringify(metadata2, null, 2));
890
- }
891
- return metadata2;
892
- }
893
- function analyzeStateNode(classSymbol, verbose = false) {
894
- const chartNode = { on: {} };
895
- const classDeclaration = classSymbol.getDeclarations()[0];
896
- if (!classDeclaration || !import_ts_morph.Node.isClassDeclaration(classDeclaration)) {
897
- if (verbose) {
898
- console.error(`⚠️ Warning: Could not get class declaration for ${classSymbol.getName()}`);
899
- }
900
- return chartNode;
901
- }
902
- const className = classSymbol.getName();
903
- if (verbose) {
904
- console.error(` Analyzing state: ${className}`);
905
- }
906
- for (const member of classDeclaration.getInstanceMembers()) {
907
- const memberName = member.getName();
908
- if (verbose) {
909
- console.error(` Checking member: ${memberName}`);
910
- }
911
- const meta = extractMetaFromMember(member, verbose);
912
- if (!meta) continue;
913
- if (verbose) {
914
- console.error(` Found transition: ${memberName}`);
915
- }
916
- const { invoke: invoke2, actions, guards, ...onEntry } = meta;
917
- if (invoke2) {
918
- if (!chartNode.invoke) chartNode.invoke = [];
919
- chartNode.invoke.push({
920
- src: invoke2.src,
921
- onDone: { target: invoke2.onDone },
922
- onError: { target: invoke2.onError },
923
- description: invoke2.description
924
- });
925
- if (verbose) {
926
- console.error(` → Invoke: ${invoke2.src}`);
927
- }
928
- }
929
- if (onEntry.target) {
930
- const transition = { target: onEntry.target };
931
- if (onEntry.description) {
932
- transition.description = onEntry.description;
933
- }
934
- if (guards) {
935
- transition.cond = guards.map((g) => g.name).join(" && ");
936
- if (verbose) {
937
- console.error(` → Guard: ${transition.cond}`);
938
- }
939
- }
940
- if (actions && actions.length > 0) {
941
- transition.actions = actions.map((a) => a.name);
942
- if (verbose) {
943
- console.error(` → Actions: ${transition.actions.join(", ")}`);
944
- }
945
- }
946
- chartNode.on[memberName] = transition;
947
- if (verbose) {
948
- console.error(` → Target: ${onEntry.target}`);
949
- }
950
- }
951
- }
952
- return chartNode;
953
- }
954
- function analyzeStateNodeWithNesting(className, classSymbol, sourceFile, childConfig, verbose = false) {
955
- const stateNode = analyzeStateNode(classSymbol, verbose);
956
- if (childConfig) {
957
- if (verbose) {
958
- console.error(` 👪 Analyzing children for state: ${className}`);
959
- }
960
- stateNode.initial = childConfig.initialState;
961
- stateNode.states = {};
962
- for (const childClassName of childConfig.classes) {
963
- const childClassDeclaration = sourceFile.getClass(childClassName);
964
- if (childClassDeclaration) {
965
- const childSymbol = childClassDeclaration.getSymbolOrThrow();
966
- stateNode.states[childClassName] = analyzeStateNode(childSymbol, verbose);
967
- } else {
968
- console.warn(`⚠️ Warning: Child class '${childClassName}' not found.`);
969
- }
970
- }
971
- }
972
- return stateNode;
973
- }
974
- function extractMachine(config, project, verbose = false) {
975
- if (verbose) {
976
- console.error(`
977
- 🔍 Analyzing machine: ${config.id}`);
978
- console.error(` Source: ${config.input}`);
979
- }
980
- const sourceFile = project.getSourceFile(config.input);
981
- if (!sourceFile) {
982
- throw new Error(`Source file not found: ${config.input}`);
983
- }
984
- if (config.parallel) {
985
- if (verbose) {
986
- console.error(` ⏹️ Parallel machine detected. Analyzing regions.`);
987
- }
988
- const parallelChart = {
989
- id: config.id,
990
- type: "parallel",
991
- states: {}
992
- };
993
- if (config.description) {
994
- parallelChart.description = config.description;
995
- }
996
- for (const region of config.parallel.regions) {
997
- if (verbose) {
998
- console.error(` 📍 Analyzing region: ${region.name}`);
999
- }
1000
- const regionStates = {};
1001
- for (const className of region.classes) {
1002
- const classDeclaration = sourceFile.getClass(className);
1003
- if (classDeclaration) {
1004
- const classSymbol = classDeclaration.getSymbolOrThrow();
1005
- regionStates[className] = analyzeStateNode(classSymbol, verbose);
1006
- } else {
1007
- console.warn(`⚠️ Warning: Class '${className}' not found for region '${region.name}'.`);
1008
- }
1009
- }
1010
- parallelChart.states[region.name] = {
1011
- initial: region.initialState,
1012
- states: regionStates
1013
- };
1014
- }
1015
- if (verbose) {
1016
- console.error(` ✅ Extracted ${config.parallel.regions.length} parallel regions`);
1017
- }
1018
- return parallelChart;
1019
- }
1020
- if (!config.initialState || !config.classes) {
1021
- throw new Error(`Machine config for '${config.id}' must have either 'parallel' or 'initialState'/'classes'.`);
1022
- }
1023
- const fullChart = {
1024
- id: config.id,
1025
- initial: config.initialState,
1026
- states: {}
1027
- };
1028
- if (config.description) {
1029
- fullChart.description = config.description;
1030
- }
1031
- for (const className of config.classes) {
1032
- const classDeclaration = sourceFile.getClass(className);
1033
- if (!classDeclaration) {
1034
- console.warn(`⚠️ Warning: Class '${className}' not found in '${config.input}'. Skipping.`);
1035
- continue;
1036
- }
1037
- const classSymbol = classDeclaration.getSymbolOrThrow();
1038
- const hasChildren = className === config.initialState && config.children;
1039
- const stateNode = analyzeStateNodeWithNesting(
1040
- className,
1041
- classSymbol,
1042
- sourceFile,
1043
- hasChildren ? config.children : void 0,
1044
- verbose
1045
- );
1046
- fullChart.states[className] = stateNode;
1047
- }
1048
- if (verbose) {
1049
- console.error(` ✅ Extracted ${config.classes.length} states`);
1050
- }
1051
- return fullChart;
1052
- }
1053
- function extractMachines(config) {
1054
- var _a;
1055
- const verbose = (_a = config.verbose) != null ? _a : false;
1056
- if (verbose) {
1057
- console.error(`
1058
- 📊 Starting statechart extraction`);
1059
- console.error(` Machines to extract: ${config.machines.length}`);
1060
- }
1061
- const project = new import_ts_morph.Project();
1062
- project.addSourceFilesAtPaths("src/**/*.ts");
1063
- project.addSourceFilesAtPaths("examples/**/*.ts");
1064
- const results = [];
1065
- for (const machineConfig of config.machines) {
1066
- try {
1067
- const chart = extractMachine(machineConfig, project, verbose);
1068
- results.push(chart);
1069
- } catch (error) {
1070
- console.error(`❌ Error extracting machine '${machineConfig.id}':`, error);
1071
- if (!verbose) {
1072
- console.error(` Run with --verbose for more details`);
1073
- }
1074
- }
1075
- }
1076
- if (verbose) {
1077
- console.error(`
1078
- ✅ Extraction complete: ${results.length}/${config.machines.length} machines extracted`);
1079
- }
1080
- return results;
1081
- }
1082
- function generateChart() {
1083
- const config = {
1084
- input: "examples/authMachine.ts",
1085
- classes: [
1086
- "LoggedOutMachine",
1087
- "LoggingInMachine",
1088
- "LoggedInMachine",
1089
- "SessionExpiredMachine",
1090
- "ErrorMachine"
1091
- ],
1092
- id: "auth",
1093
- initialState: "LoggedOutMachine",
1094
- description: "Authentication state machine"
1095
- };
1096
- console.error("🔍 Using legacy generateChart function");
1097
- console.error("⚠️ Consider using extractMachines() with a config file instead\n");
1098
- const project = new import_ts_morph.Project();
1099
- project.addSourceFilesAtPaths("src/**/*.ts");
1100
- project.addSourceFilesAtPaths("examples/**/*.ts");
1101
- try {
1102
- const chart = extractMachine(config, project, true);
1103
- console.log(JSON.stringify(chart, null, 2));
1104
- } catch (error) {
1105
- console.error(`❌ Error:`, error);
1106
- process.exit(1);
1107
- }
1108
- }
1109
- var ADVANCED_CONFIG_EXAMPLES = {
1110
- hierarchical: {
1111
- input: "examples/dashboardMachine.ts",
1112
- id: "dashboard",
1113
- classes: ["DashboardMachine", "LoggedOutMachine"],
1114
- initialState: "DashboardMachine",
1115
- children: {
1116
- contextProperty: "child",
1117
- initialState: "ViewingChildMachine",
1118
- classes: ["ViewingChildMachine", "EditingChildMachine"]
1119
- }
1120
- },
1121
- parallel: {
1122
- input: "examples/editorMachine.ts",
1123
- id: "editor",
1124
- parallel: {
1125
- regions: [
1126
- {
1127
- name: "fontWeight",
1128
- initialState: "NormalWeight",
1129
- classes: ["NormalWeight", "BoldWeight"]
1130
- },
1131
- {
1132
- name: "textDecoration",
1133
- initialState: "NoDecoration",
1134
- classes: ["NoDecoration", "UnderlineState"]
1135
- }
1136
- ]
1137
- }
1138
- }
1139
- };
1140
- if (require.main === module) {
1141
- generateChart();
1142
- }
1143
-
1144
711
  // src/middleware/core.ts
1145
712
  var CANCEL = Symbol("CANCEL");
1146
713
  function createMiddleware(machine, hooks, options = {}) {
@@ -2114,6 +1681,132 @@ function state(context, transitions) {
2114
1681
  return createFunctionalMachine(context);
2115
1682
  }
2116
1683
 
1684
+ // src/matcher.ts
1685
+ function createMatcher(...cases) {
1686
+ const nameToCase = /* @__PURE__ */ new Map();
1687
+ for (const [name, _, predicate] of cases) {
1688
+ if (nameToCase.has(name)) {
1689
+ throw new Error(`Duplicate matcher case name: "${name}"`);
1690
+ }
1691
+ nameToCase.set(name, { predicate });
1692
+ }
1693
+ const isProxy = new Proxy({}, {
1694
+ get(_target, prop) {
1695
+ return function isGuard(machine) {
1696
+ const caseConfig = nameToCase.get(prop);
1697
+ if (!caseConfig) {
1698
+ const available = Array.from(nameToCase.keys()).join(", ");
1699
+ throw new Error(
1700
+ `Unknown matcher case: "${prop}". Available cases: ${available}`
1701
+ );
1702
+ }
1703
+ return caseConfig.predicate(machine);
1704
+ };
1705
+ }
1706
+ });
1707
+ const caseProxy = new Proxy({}, {
1708
+ get(_target, prop) {
1709
+ return function createCaseHandler(handler) {
1710
+ if (!nameToCase.has(prop)) {
1711
+ const available = Array.from(nameToCase.keys()).join(", ");
1712
+ throw new Error(
1713
+ `Unknown matcher case: "${prop}". Available cases: ${available}`
1714
+ );
1715
+ }
1716
+ return {
1717
+ __brand: "CaseHandler",
1718
+ __name: prop,
1719
+ __machine: void 0,
1720
+ __return: void 0,
1721
+ handler
1722
+ };
1723
+ };
1724
+ }
1725
+ });
1726
+ const exhaustive = { __exhaustive: true };
1727
+ function when2(machine) {
1728
+ return {
1729
+ is(...handlers) {
1730
+ if (handlers.length === 0) {
1731
+ throw new Error("Pattern match requires at least one handler and exhaustiveness marker");
1732
+ }
1733
+ const lastHandler = handlers[handlers.length - 1];
1734
+ if (!lastHandler || typeof lastHandler !== "object" || !("__exhaustive" in lastHandler)) {
1735
+ throw new Error(
1736
+ "Pattern match must end with match.exhaustive for compile-time exhaustiveness checking"
1737
+ );
1738
+ }
1739
+ const actualHandlers = handlers.slice(0, -1);
1740
+ for (const caseHandler of actualHandlers) {
1741
+ const caseName = caseHandler.__name;
1742
+ const caseConfig = nameToCase.get(caseName);
1743
+ if (!caseConfig) {
1744
+ throw new Error(`Internal error: Unknown matcher case in handler: ${caseName}`);
1745
+ }
1746
+ if (caseConfig.predicate(machine)) {
1747
+ return caseHandler.handler(machine);
1748
+ }
1749
+ }
1750
+ const handledCases = actualHandlers.map((h) => h.__name).join(", ");
1751
+ const allCases = Array.from(nameToCase.keys()).join(", ");
1752
+ throw new Error(
1753
+ `Non-exhaustive pattern match at runtime: no handler matched the machine.
1754
+ Handled cases: [${handledCases}]
1755
+ All cases: [${allCases}]
1756
+ This may occur if predicates don't cover all runtime possibilities.`
1757
+ );
1758
+ }
1759
+ };
1760
+ }
1761
+ function simpleMatcher(machine) {
1762
+ for (const [name, _, predicate] of cases) {
1763
+ if (predicate(machine)) {
1764
+ return name;
1765
+ }
1766
+ }
1767
+ return null;
1768
+ }
1769
+ return Object.assign(simpleMatcher, {
1770
+ is: isProxy,
1771
+ when: when2,
1772
+ case: caseProxy,
1773
+ exhaustive
1774
+ });
1775
+ }
1776
+ function classCase(name, machineClass) {
1777
+ return [
1778
+ name,
1779
+ void 0,
1780
+ // Type-only, not used at runtime
1781
+ (m) => m instanceof machineClass
1782
+ ];
1783
+ }
1784
+ function discriminantCase(name, key, value) {
1785
+ return [
1786
+ name,
1787
+ void 0,
1788
+ // Type-only, not used at runtime
1789
+ (m) => hasState(m, key, value)
1790
+ ];
1791
+ }
1792
+ function customCase(name, predicate) {
1793
+ return [name, void 0, predicate];
1794
+ }
1795
+ function forContext() {
1796
+ return {
1797
+ /**
1798
+ * Creates a discriminated union case with full type inference.
1799
+ */
1800
+ case(name, key, value) {
1801
+ return [
1802
+ name,
1803
+ void 0,
1804
+ (m) => hasState(m, key, value)
1805
+ ];
1806
+ }
1807
+ };
1808
+ }
1809
+
2117
1810
  // src/index.ts
2118
1811
  function createMachine(context, fnsOrFactory) {
2119
1812
  if (typeof fnsOrFactory === "function") {
@@ -2192,6 +1885,9 @@ function setContext(machine, newContextOrFn) {
2192
1885
  const newContext = typeof newContextOrFn === "function" ? newContextOrFn(context) : newContextOrFn;
2193
1886
  return createMachine(newContext, transitions);
2194
1887
  }
1888
+ function createContext(context) {
1889
+ return { context };
1890
+ }
2195
1891
  function overrideTransitions(machine, overrides) {
2196
1892
  const { context, ...originalTransitions } = machine;
2197
1893
  const newTransitions = { ...originalTransitions, ...overrides };