xstate 6.0.0-alpha.52 → 6.0.0-alpha.53
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.
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"xstate-scxml.umd.min.js","sources":["../../../node_modules/.pnpm/xmlchars@2.2.0/node_modules/xmlchars/xml/1.0/ed5.js","../../../node_modules/.pnpm/xmlchars@2.2.0/node_modules/xmlchars/xml/1.1/ed2.js","../../../node_modules/.pnpm/xmlchars@2.2.0/node_modules/xmlchars/xmlns/1.0/ed3.js","../../../node_modules/.pnpm/saxes@6.0.0/node_modules/saxes/saxes.js","../src/Mailbox.ts","../src/constants.ts","../src/eventUtils.ts","../src/reportUnhandledError.ts","../src/symbolObservable.ts","../src/actions.ts","../src/actorSource.ts","../src/actors/attached.ts","../src/actors/listener.ts","../src/actors/subscription.ts","../src/actorScope.ts","../src/transitionActions.ts","../src/delay.ts","../src/snapshotActorRef.ts","../src/getNextSnapshot.ts","../src/stateUtils.ts","../src/utils.ts","../src/remoteActorRef.ts","../src/State.ts","../src/runtimeHelpers.ts","../src/system.ts","../src/createActor.ts","../src/memo.ts","../src/StateNode.ts","../src/validation.ts","../src/StateMachine.ts","../src/spawn.ts","../src/scxml/runtime.ts","../src/createMachine.ts","../src/types.ts","../src/scxml/scxml.ts"],"sourcesContent":["\"use strict\";\n/**\n * Character classes and associated utilities for the 5th edition of XML 1.0.\n *\n * @author Louis-Dominique Dubeau\n * @license MIT\n * @copyright Louis-Dominique Dubeau\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//\n// Fragments.\n//\nexports.CHAR = \"\\t\\n\\r -\\uD7FF\\uE000-\\uFFFD\\uD800\\uDC00-\\uDBFF\\uDFFF\";\nexports.S = \" \\t\\r\\n\";\n// tslint:disable-next-line:max-line-length\nexports.NAME_START_CHAR = \":A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\uD800\\uDC00-\\uDB7F\\uDFFF\";\nexports.NAME_CHAR = \"-\" + exports.NAME_START_CHAR + \".0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040\";\n//\n// Regular expressions.\n//\nexports.CHAR_RE = new RegExp(\"^[\" + exports.CHAR + \"]$\", \"u\");\nexports.S_RE = new RegExp(\"^[\" + exports.S + \"]+$\", \"u\");\nexports.NAME_START_CHAR_RE = new RegExp(\"^[\" + exports.NAME_START_CHAR + \"]$\", \"u\");\nexports.NAME_CHAR_RE = new RegExp(\"^[\" + exports.NAME_CHAR + \"]$\", \"u\");\nexports.NAME_RE = new RegExp(\"^[\" + exports.NAME_START_CHAR + \"][\" + exports.NAME_CHAR + \"]*$\", \"u\");\nexports.NMTOKEN_RE = new RegExp(\"^[\" + exports.NAME_CHAR + \"]+$\", \"u\");\nvar TAB = 9;\nvar NL = 0xA;\nvar CR = 0xD;\nvar SPACE = 0x20;\n//\n// Lists.\n//\n/** All characters in the ``S`` production. */\nexports.S_LIST = [SPACE, NL, CR, TAB];\n/**\n * Determines whether a codepoint matches the ``CHAR`` production.\n *\n * @param c The code point.\n *\n * @returns ``true`` if the codepoint matches ``CHAR``.\n */\nfunction isChar(c) {\n return (c >= SPACE && c <= 0xD7FF) ||\n c === NL || c === CR || c === TAB ||\n (c >= 0xE000 && c <= 0xFFFD) ||\n (c >= 0x10000 && c <= 0x10FFFF);\n}\nexports.isChar = isChar;\n/**\n * Determines whether a codepoint matches the ``S`` (space) production.\n *\n * @param c The code point.\n *\n * @returns ``true`` if the codepoint matches ``S``.\n */\nfunction isS(c) {\n return c === SPACE || c === NL || c === CR || c === TAB;\n}\nexports.isS = isS;\n/**\n * Determines whether a codepoint matches the ``NAME_START_CHAR`` production.\n *\n * @param c The code point.\n *\n * @returns ``true`` if the codepoint matches ``NAME_START_CHAR``.\n */\nfunction isNameStartChar(c) {\n return ((c >= 0x41 && c <= 0x5A) ||\n (c >= 0x61 && c <= 0x7A) ||\n c === 0x3A ||\n c === 0x5F ||\n c === 0x200C ||\n c === 0x200D ||\n (c >= 0xC0 && c <= 0xD6) ||\n (c >= 0xD8 && c <= 0xF6) ||\n (c >= 0x00F8 && c <= 0x02FF) ||\n (c >= 0x0370 && c <= 0x037D) ||\n (c >= 0x037F && c <= 0x1FFF) ||\n (c >= 0x2070 && c <= 0x218F) ||\n (c >= 0x2C00 && c <= 0x2FEF) ||\n (c >= 0x3001 && c <= 0xD7FF) ||\n (c >= 0xF900 && c <= 0xFDCF) ||\n (c >= 0xFDF0 && c <= 0xFFFD) ||\n (c >= 0x10000 && c <= 0xEFFFF));\n}\nexports.isNameStartChar = isNameStartChar;\n/**\n * Determines whether a codepoint matches the ``NAME_CHAR`` production.\n *\n * @param c The code point.\n *\n * @returns ``true`` if the codepoint matches ``NAME_CHAR``.\n */\nfunction isNameChar(c) {\n return isNameStartChar(c) ||\n (c >= 0x30 && c <= 0x39) ||\n c === 0x2D ||\n c === 0x2E ||\n c === 0xB7 ||\n (c >= 0x0300 && c <= 0x036F) ||\n (c >= 0x203F && c <= 0x2040);\n}\nexports.isNameChar = isNameChar;\n//# sourceMappingURL=ed5.js.map","\"use strict\";\n/**\n * Character classes and associated utilities for the 2nd edition of XML 1.1.\n *\n * @author Louis-Dominique Dubeau\n * @license MIT\n * @copyright Louis-Dominique Dubeau\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//\n// Fragments.\n//\nexports.CHAR = \"\\u0001-\\uD7FF\\uE000-\\uFFFD\\uD800\\uDC00-\\uDBFF\\uDFFF\";\nexports.RESTRICTED_CHAR = \"\\u0001-\\u0008\\u000B\\u000C\\u000E-\\u001F\\u007F-\\u0084\\u0086-\\u009F\";\nexports.S = \" \\t\\r\\n\";\n// tslint:disable-next-line:max-line-length\nexports.NAME_START_CHAR = \":A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\uD800\\uDC00-\\uDB7F\\uDFFF\";\nexports.NAME_CHAR = \"-\" + exports.NAME_START_CHAR + \".0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040\";\n//\n// Regular expressions.\n//\nexports.CHAR_RE = new RegExp(\"^[\" + exports.CHAR + \"]$\", \"u\");\nexports.RESTRICTED_CHAR_RE = new RegExp(\"^[\" + exports.RESTRICTED_CHAR + \"]$\", \"u\");\nexports.S_RE = new RegExp(\"^[\" + exports.S + \"]+$\", \"u\");\nexports.NAME_START_CHAR_RE = new RegExp(\"^[\" + exports.NAME_START_CHAR + \"]$\", \"u\");\nexports.NAME_CHAR_RE = new RegExp(\"^[\" + exports.NAME_CHAR + \"]$\", \"u\");\nexports.NAME_RE = new RegExp(\"^[\" + exports.NAME_START_CHAR + \"][\" + exports.NAME_CHAR + \"]*$\", \"u\");\nexports.NMTOKEN_RE = new RegExp(\"^[\" + exports.NAME_CHAR + \"]+$\", \"u\");\nvar TAB = 9;\nvar NL = 0xA;\nvar CR = 0xD;\nvar SPACE = 0x20;\n//\n// Lists.\n//\n/** All characters in the ``S`` production. */\nexports.S_LIST = [SPACE, NL, CR, TAB];\n/**\n * Determines whether a codepoint matches the ``CHAR`` production.\n *\n * @param c The code point.\n *\n * @returns ``true`` if the codepoint matches ``CHAR``.\n */\nfunction isChar(c) {\n return (c >= 0x0001 && c <= 0xD7FF) ||\n (c >= 0xE000 && c <= 0xFFFD) ||\n (c >= 0x10000 && c <= 0x10FFFF);\n}\nexports.isChar = isChar;\n/**\n * Determines whether a codepoint matches the ``RESTRICTED_CHAR`` production.\n *\n * @param c The code point.\n *\n * @returns ``true`` if the codepoint matches ``RESTRICTED_CHAR``.\n */\nfunction isRestrictedChar(c) {\n return (c >= 0x1 && c <= 0x8) ||\n c === 0xB ||\n c === 0xC ||\n (c >= 0xE && c <= 0x1F) ||\n (c >= 0x7F && c <= 0x84) ||\n (c >= 0x86 && c <= 0x9F);\n}\nexports.isRestrictedChar = isRestrictedChar;\n/**\n * Determines whether a codepoint matches the ``CHAR`` production and does not\n * match the ``RESTRICTED_CHAR`` production. ``isCharAndNotRestricted(x)`` is\n * equivalent to ``isChar(x) && !isRestrictedChar(x)``. This function is faster\n * than running the two-call equivalent.\n *\n * @param c The code point.\n *\n * @returns ``true`` if the codepoint matches ``CHAR`` and does not match\n * ``RESTRICTED_CHAR``.\n */\nfunction isCharAndNotRestricted(c) {\n return (c === 0x9) ||\n (c === 0xA) ||\n (c === 0xD) ||\n (c > 0x1F && c < 0x7F) ||\n (c === 0x85) ||\n (c > 0x9F && c <= 0xD7FF) ||\n (c >= 0xE000 && c <= 0xFFFD) ||\n (c >= 0x10000 && c <= 0x10FFFF);\n}\nexports.isCharAndNotRestricted = isCharAndNotRestricted;\n/**\n * Determines whether a codepoint matches the ``S`` (space) production.\n *\n * @param c The code point.\n *\n * @returns ``true`` if the codepoint matches ``S``.\n */\nfunction isS(c) {\n return c === SPACE || c === NL || c === CR || c === TAB;\n}\nexports.isS = isS;\n/**\n * Determines whether a codepoint matches the ``NAME_START_CHAR`` production.\n *\n * @param c The code point.\n *\n * @returns ``true`` if the codepoint matches ``NAME_START_CHAR``.\n */\n// tslint:disable-next-line:cyclomatic-complexity\nfunction isNameStartChar(c) {\n return ((c >= 0x41 && c <= 0x5A) ||\n (c >= 0x61 && c <= 0x7A) ||\n c === 0x3A ||\n c === 0x5F ||\n c === 0x200C ||\n c === 0x200D ||\n (c >= 0xC0 && c <= 0xD6) ||\n (c >= 0xD8 && c <= 0xF6) ||\n (c >= 0x00F8 && c <= 0x02FF) ||\n (c >= 0x0370 && c <= 0x037D) ||\n (c >= 0x037F && c <= 0x1FFF) ||\n (c >= 0x2070 && c <= 0x218F) ||\n (c >= 0x2C00 && c <= 0x2FEF) ||\n (c >= 0x3001 && c <= 0xD7FF) ||\n (c >= 0xF900 && c <= 0xFDCF) ||\n (c >= 0xFDF0 && c <= 0xFFFD) ||\n (c >= 0x10000 && c <= 0xEFFFF));\n}\nexports.isNameStartChar = isNameStartChar;\n/**\n * Determines whether a codepoint matches the ``NAME_CHAR`` production.\n *\n * @param c The code point.\n *\n * @returns ``true`` if the codepoint matches ``NAME_CHAR``.\n */\nfunction isNameChar(c) {\n return isNameStartChar(c) ||\n (c >= 0x30 && c <= 0x39) ||\n c === 0x2D ||\n c === 0x2E ||\n c === 0xB7 ||\n (c >= 0x0300 && c <= 0x036F) ||\n (c >= 0x203F && c <= 0x2040);\n}\nexports.isNameChar = isNameChar;\n//# sourceMappingURL=ed2.js.map","\"use strict\";\n/**\n * Character class utilities for XML NS 1.0 edition 3.\n *\n * @author Louis-Dominique Dubeau\n * @license MIT\n * @copyright Louis-Dominique Dubeau\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//\n// Fragments.\n//\n// tslint:disable-next-line:max-line-length\nexports.NC_NAME_START_CHAR = \"A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\uD800\\uDC00-\\uDB7F\\uDFFF\";\nexports.NC_NAME_CHAR = \"-\" + exports.NC_NAME_START_CHAR + \".0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040\";\n//\n// Regular expressions.\n//\nexports.NC_NAME_START_CHAR_RE = new RegExp(\"^[\" + exports.NC_NAME_START_CHAR + \"]$\", \"u\");\nexports.NC_NAME_CHAR_RE = new RegExp(\"^[\" + exports.NC_NAME_CHAR + \"]$\", \"u\");\nexports.NC_NAME_RE = new RegExp(\"^[\" + exports.NC_NAME_START_CHAR + \"][\" + exports.NC_NAME_CHAR + \"]*$\", \"u\");\n/**\n * Determines whether a codepoint matches [[NC_NAME_START_CHAR]].\n *\n * @param c The code point.\n *\n * @returns ``true`` if the codepoint matches.\n */\n// tslint:disable-next-line:cyclomatic-complexity\nfunction isNCNameStartChar(c) {\n return ((c >= 0x41 && c <= 0x5A) ||\n c === 0x5F ||\n (c >= 0x61 && c <= 0x7A) ||\n (c >= 0xC0 && c <= 0xD6) ||\n (c >= 0xD8 && c <= 0xF6) ||\n (c >= 0x00F8 && c <= 0x02FF) ||\n (c >= 0x0370 && c <= 0x037D) ||\n (c >= 0x037F && c <= 0x1FFF) ||\n (c >= 0x200C && c <= 0x200D) ||\n (c >= 0x2070 && c <= 0x218F) ||\n (c >= 0x2C00 && c <= 0x2FEF) ||\n (c >= 0x3001 && c <= 0xD7FF) ||\n (c >= 0xF900 && c <= 0xFDCF) ||\n (c >= 0xFDF0 && c <= 0xFFFD) ||\n (c >= 0x10000 && c <= 0xEFFFF));\n}\nexports.isNCNameStartChar = isNCNameStartChar;\n/**\n * Determines whether a codepoint matches [[NC_NAME_CHAR]].\n *\n * @param c The code point.\n *\n * @returns ``true`` if the codepoint matches.\n */\nfunction isNCNameChar(c) {\n return isNCNameStartChar(c) ||\n (c === 0x2D ||\n c === 0x2E ||\n (c >= 0x30 && c <= 0x39) ||\n c === 0x00B7 ||\n (c >= 0x0300 && c <= 0x036F) ||\n (c >= 0x203F && c <= 0x2040));\n}\nexports.isNCNameChar = isNCNameChar;\n//# sourceMappingURL=ed3.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.SaxesParser = exports.EVENTS = void 0;\nconst ed5 = require(\"xmlchars/xml/1.0/ed5\");\nconst ed2 = require(\"xmlchars/xml/1.1/ed2\");\nconst NSed3 = require(\"xmlchars/xmlns/1.0/ed3\");\nvar isS = ed5.isS;\nvar isChar10 = ed5.isChar;\nvar isNameStartChar = ed5.isNameStartChar;\nvar isNameChar = ed5.isNameChar;\nvar S_LIST = ed5.S_LIST;\nvar NAME_RE = ed5.NAME_RE;\nvar isChar11 = ed2.isChar;\nvar isNCNameStartChar = NSed3.isNCNameStartChar;\nvar isNCNameChar = NSed3.isNCNameChar;\nvar NC_NAME_RE = NSed3.NC_NAME_RE;\nconst XML_NAMESPACE = \"http://www.w3.org/XML/1998/namespace\";\nconst XMLNS_NAMESPACE = \"http://www.w3.org/2000/xmlns/\";\nconst rootNS = {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment\n __proto__: null,\n xml: XML_NAMESPACE,\n xmlns: XMLNS_NAMESPACE,\n};\nconst XML_ENTITIES = {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment\n __proto__: null,\n amp: \"&\",\n gt: \">\",\n lt: \"<\",\n quot: \"\\\"\",\n apos: \"'\",\n};\n// EOC: end-of-chunk\nconst EOC = -1;\nconst NL_LIKE = -2;\nconst S_BEGIN = 0; // Initial state.\nconst S_BEGIN_WHITESPACE = 1; // leading whitespace\nconst S_DOCTYPE = 2; // <!DOCTYPE\nconst S_DOCTYPE_QUOTE = 3; // <!DOCTYPE \"//blah\nconst S_DTD = 4; // <!DOCTYPE \"//blah\" [ ...\nconst S_DTD_QUOTED = 5; // <!DOCTYPE \"//blah\" [ \"foo\nconst S_DTD_OPEN_WAKA = 6;\nconst S_DTD_OPEN_WAKA_BANG = 7;\nconst S_DTD_COMMENT = 8; // <!--\nconst S_DTD_COMMENT_ENDING = 9; // <!-- blah -\nconst S_DTD_COMMENT_ENDED = 10; // <!-- blah --\nconst S_DTD_PI = 11; // <?\nconst S_DTD_PI_ENDING = 12; // <?hi \"there\" ?\nconst S_TEXT = 13; // general stuff\nconst S_ENTITY = 14; // & and such\nconst S_OPEN_WAKA = 15; // <\nconst S_OPEN_WAKA_BANG = 16; // <!...\nconst S_COMMENT = 17; // <!--\nconst S_COMMENT_ENDING = 18; // <!-- blah -\nconst S_COMMENT_ENDED = 19; // <!-- blah --\nconst S_CDATA = 20; // <![CDATA[ something\nconst S_CDATA_ENDING = 21; // ]\nconst S_CDATA_ENDING_2 = 22; // ]]\nconst S_PI_FIRST_CHAR = 23; // <?hi, first char\nconst S_PI_REST = 24; // <?hi, rest of the name\nconst S_PI_BODY = 25; // <?hi there\nconst S_PI_ENDING = 26; // <?hi \"there\" ?\nconst S_XML_DECL_NAME_START = 27; // <?xml\nconst S_XML_DECL_NAME = 28; // <?xml foo\nconst S_XML_DECL_EQ = 29; // <?xml foo=\nconst S_XML_DECL_VALUE_START = 30; // <?xml foo=\nconst S_XML_DECL_VALUE = 31; // <?xml foo=\"bar\"\nconst S_XML_DECL_SEPARATOR = 32; // <?xml foo=\"bar\"\nconst S_XML_DECL_ENDING = 33; // <?xml ... ?\nconst S_OPEN_TAG = 34; // <strong\nconst S_OPEN_TAG_SLASH = 35; // <strong /\nconst S_ATTRIB = 36; // <a\nconst S_ATTRIB_NAME = 37; // <a foo\nconst S_ATTRIB_NAME_SAW_WHITE = 38; // <a foo _\nconst S_ATTRIB_VALUE = 39; // <a foo=\nconst S_ATTRIB_VALUE_QUOTED = 40; // <a foo=\"bar\nconst S_ATTRIB_VALUE_CLOSED = 41; // <a foo=\"bar\"\nconst S_ATTRIB_VALUE_UNQUOTED = 42; // <a foo=bar\nconst S_CLOSE_TAG = 43; // </a\nconst S_CLOSE_TAG_SAW_WHITE = 44; // </a >\nconst TAB = 9;\nconst NL = 0xA;\nconst CR = 0xD;\nconst SPACE = 0x20;\nconst BANG = 0x21;\nconst DQUOTE = 0x22;\nconst AMP = 0x26;\nconst SQUOTE = 0x27;\nconst MINUS = 0x2D;\nconst FORWARD_SLASH = 0x2F;\nconst SEMICOLON = 0x3B;\nconst LESS = 0x3C;\nconst EQUAL = 0x3D;\nconst GREATER = 0x3E;\nconst QUESTION = 0x3F;\nconst OPEN_BRACKET = 0x5B;\nconst CLOSE_BRACKET = 0x5D;\nconst NEL = 0x85;\nconst LS = 0x2028; // Line Separator\nconst isQuote = (c) => c === DQUOTE || c === SQUOTE;\nconst QUOTES = [DQUOTE, SQUOTE];\nconst DOCTYPE_TERMINATOR = [...QUOTES, OPEN_BRACKET, GREATER];\nconst DTD_TERMINATOR = [...QUOTES, LESS, CLOSE_BRACKET];\nconst XML_DECL_NAME_TERMINATOR = [EQUAL, QUESTION, ...S_LIST];\nconst ATTRIB_VALUE_UNQUOTED_TERMINATOR = [...S_LIST, GREATER, AMP, LESS];\nfunction nsPairCheck(parser, prefix, uri) {\n switch (prefix) {\n case \"xml\":\n if (uri !== XML_NAMESPACE) {\n parser.fail(`xml prefix must be bound to ${XML_NAMESPACE}.`);\n }\n break;\n case \"xmlns\":\n if (uri !== XMLNS_NAMESPACE) {\n parser.fail(`xmlns prefix must be bound to ${XMLNS_NAMESPACE}.`);\n }\n break;\n default:\n }\n switch (uri) {\n case XMLNS_NAMESPACE:\n parser.fail(prefix === \"\" ?\n `the default namespace may not be set to ${uri}.` :\n `may not assign a prefix (even \"xmlns\") to the URI \\\n${XMLNS_NAMESPACE}.`);\n break;\n case XML_NAMESPACE:\n switch (prefix) {\n case \"xml\":\n // Assinging the XML namespace to \"xml\" is fine.\n break;\n case \"\":\n parser.fail(`the default namespace may not be set to ${uri}.`);\n break;\n default:\n parser.fail(\"may not assign the xml namespace to another prefix.\");\n }\n break;\n default:\n }\n}\nfunction nsMappingCheck(parser, mapping) {\n for (const local of Object.keys(mapping)) {\n nsPairCheck(parser, local, mapping[local]);\n }\n}\nconst isNCName = (name) => NC_NAME_RE.test(name);\nconst isName = (name) => NAME_RE.test(name);\nconst FORBIDDEN_START = 0;\nconst FORBIDDEN_BRACKET = 1;\nconst FORBIDDEN_BRACKET_BRACKET = 2;\n/**\n * The list of supported events.\n */\nexports.EVENTS = [\n \"xmldecl\",\n \"text\",\n \"processinginstruction\",\n \"doctype\",\n \"comment\",\n \"opentagstart\",\n \"attribute\",\n \"opentag\",\n \"closetag\",\n \"cdata\",\n \"error\",\n \"end\",\n \"ready\",\n];\nconst EVENT_NAME_TO_HANDLER_NAME = {\n xmldecl: \"xmldeclHandler\",\n text: \"textHandler\",\n processinginstruction: \"piHandler\",\n doctype: \"doctypeHandler\",\n comment: \"commentHandler\",\n opentagstart: \"openTagStartHandler\",\n attribute: \"attributeHandler\",\n opentag: \"openTagHandler\",\n closetag: \"closeTagHandler\",\n cdata: \"cdataHandler\",\n error: \"errorHandler\",\n end: \"endHandler\",\n ready: \"readyHandler\",\n};\n// eslint-disable-next-line @typescript-eslint/ban-types\nclass SaxesParser {\n /**\n * @param opt The parser options.\n */\n constructor(opt) {\n this.opt = opt !== null && opt !== void 0 ? opt : {};\n this.fragmentOpt = !!this.opt.fragment;\n const xmlnsOpt = this.xmlnsOpt = !!this.opt.xmlns;\n this.trackPosition = this.opt.position !== false;\n this.fileName = this.opt.fileName;\n if (xmlnsOpt) {\n // This is the function we use to perform name checks on PIs and entities.\n // When namespaces are used, colons are not allowed in PI target names or\n // entity names. So the check depends on whether namespaces are used. See:\n //\n // https://www.w3.org/XML/xml-names-19990114-errata.html\n // NE08\n //\n this.nameStartCheck = isNCNameStartChar;\n this.nameCheck = isNCNameChar;\n this.isName = isNCName;\n // eslint-disable-next-line @typescript-eslint/unbound-method\n this.processAttribs = this.processAttribsNS;\n // eslint-disable-next-line @typescript-eslint/unbound-method\n this.pushAttrib = this.pushAttribNS;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment\n this.ns = Object.assign({ __proto__: null }, rootNS);\n const additional = this.opt.additionalNamespaces;\n if (additional != null) {\n nsMappingCheck(this, additional);\n Object.assign(this.ns, additional);\n }\n }\n else {\n this.nameStartCheck = isNameStartChar;\n this.nameCheck = isNameChar;\n this.isName = isName;\n // eslint-disable-next-line @typescript-eslint/unbound-method\n this.processAttribs = this.processAttribsPlain;\n // eslint-disable-next-line @typescript-eslint/unbound-method\n this.pushAttrib = this.pushAttribPlain;\n }\n //\n // The order of the members in this table needs to correspond to the state\n // numbers given to the states that correspond to the methods being recorded\n // here.\n //\n this.stateTable = [\n /* eslint-disable @typescript-eslint/unbound-method */\n this.sBegin,\n this.sBeginWhitespace,\n this.sDoctype,\n this.sDoctypeQuote,\n this.sDTD,\n this.sDTDQuoted,\n this.sDTDOpenWaka,\n this.sDTDOpenWakaBang,\n this.sDTDComment,\n this.sDTDCommentEnding,\n this.sDTDCommentEnded,\n this.sDTDPI,\n this.sDTDPIEnding,\n this.sText,\n this.sEntity,\n this.sOpenWaka,\n this.sOpenWakaBang,\n this.sComment,\n this.sCommentEnding,\n this.sCommentEnded,\n this.sCData,\n this.sCDataEnding,\n this.sCDataEnding2,\n this.sPIFirstChar,\n this.sPIRest,\n this.sPIBody,\n this.sPIEnding,\n this.sXMLDeclNameStart,\n this.sXMLDeclName,\n this.sXMLDeclEq,\n this.sXMLDeclValueStart,\n this.sXMLDeclValue,\n this.sXMLDeclSeparator,\n this.sXMLDeclEnding,\n this.sOpenTag,\n this.sOpenTagSlash,\n this.sAttrib,\n this.sAttribName,\n this.sAttribNameSawWhite,\n this.sAttribValue,\n this.sAttribValueQuoted,\n this.sAttribValueClosed,\n this.sAttribValueUnquoted,\n this.sCloseTag,\n this.sCloseTagSawWhite,\n /* eslint-enable @typescript-eslint/unbound-method */\n ];\n this._init();\n }\n /**\n * Indicates whether or not the parser is closed. If ``true``, wait for\n * the ``ready`` event to write again.\n */\n get closed() {\n return this._closed;\n }\n _init() {\n var _a;\n this.openWakaBang = \"\";\n this.text = \"\";\n this.name = \"\";\n this.piTarget = \"\";\n this.entity = \"\";\n this.q = null;\n this.tags = [];\n this.tag = null;\n this.topNS = null;\n this.chunk = \"\";\n this.chunkPosition = 0;\n this.i = 0;\n this.prevI = 0;\n this.carriedFromPrevious = undefined;\n this.forbiddenState = FORBIDDEN_START;\n this.attribList = [];\n // The logic is organized so as to minimize the need to check\n // this.opt.fragment while parsing.\n const { fragmentOpt } = this;\n this.state = fragmentOpt ? S_TEXT : S_BEGIN;\n // We want these to be all true if we are dealing with a fragment.\n this.reportedTextBeforeRoot = this.reportedTextAfterRoot = this.closedRoot =\n this.sawRoot = fragmentOpt;\n // An XML declaration is intially possible only when parsing whole\n // documents.\n this.xmlDeclPossible = !fragmentOpt;\n this.xmlDeclExpects = [\"version\"];\n this.entityReturnState = undefined;\n let { defaultXMLVersion } = this.opt;\n if (defaultXMLVersion === undefined) {\n if (this.opt.forceXMLVersion === true) {\n throw new Error(\"forceXMLVersion set but defaultXMLVersion is not set\");\n }\n defaultXMLVersion = \"1.0\";\n }\n this.setXMLVersion(defaultXMLVersion);\n this.positionAtNewLine = 0;\n this.doctype = false;\n this._closed = false;\n this.xmlDecl = {\n version: undefined,\n encoding: undefined,\n standalone: undefined,\n };\n this.line = 1;\n this.column = 0;\n this.ENTITIES = Object.create(XML_ENTITIES);\n (_a = this.readyHandler) === null || _a === void 0 ? void 0 : _a.call(this);\n }\n /**\n * The stream position the parser is currently looking at. This field is\n * zero-based.\n *\n * This field is not based on counting Unicode characters but is to be\n * interpreted as a plain index into a JavaScript string.\n */\n get position() {\n return this.chunkPosition + this.i;\n }\n /**\n * The column number of the next character to be read by the parser. *\n * This field is zero-based. (The first column in a line is 0.)\n *\n * This field reports the index at which the next character would be in the\n * line if the line were represented as a JavaScript string. Note that this\n * *can* be different to a count based on the number of *Unicode characters*\n * due to how JavaScript handles astral plane characters.\n *\n * See [[column]] for a number that corresponds to a count of Unicode\n * characters.\n */\n get columnIndex() {\n return this.position - this.positionAtNewLine;\n }\n /**\n * Set an event listener on an event. The parser supports one handler per\n * event type. If you try to set an event handler over an existing handler,\n * the old handler is silently overwritten.\n *\n * @param name The event to listen to.\n *\n * @param handler The handler to set.\n */\n on(name, handler) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access\n this[EVENT_NAME_TO_HANDLER_NAME[name]] = handler;\n }\n /**\n * Unset an event handler.\n *\n * @parma name The event to stop listening to.\n */\n off(name) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access\n this[EVENT_NAME_TO_HANDLER_NAME[name]] = undefined;\n }\n /**\n * Make an error object. The error object will have a message that contains\n * the ``fileName`` option passed at the creation of the parser. If position\n * tracking was turned on, it will also have line and column number\n * information.\n *\n * @param message The message describing the error to report.\n *\n * @returns An error object with a properly formatted message.\n */\n makeError(message) {\n var _a;\n let msg = (_a = this.fileName) !== null && _a !== void 0 ? _a : \"\";\n if (this.trackPosition) {\n if (msg.length > 0) {\n msg += \":\";\n }\n msg += `${this.line}:${this.column}`;\n }\n if (msg.length > 0) {\n msg += \": \";\n }\n return new Error(msg + message);\n }\n /**\n * Report a parsing error. This method is made public so that client code may\n * check for issues that are outside the scope of this project and can report\n * errors.\n *\n * @param message The error to report.\n *\n * @returns this\n */\n fail(message) {\n const err = this.makeError(message);\n const handler = this.errorHandler;\n if (handler === undefined) {\n throw err;\n }\n else {\n handler(err);\n }\n return this;\n }\n /**\n * Write a XML data to the parser.\n *\n * @param chunk The XML data to write.\n *\n * @returns this\n */\n // We do need object for the type here. Yes, it often causes problems\n // but not in this case.\n write(chunk) {\n if (this.closed) {\n return this.fail(\"cannot write after close; assign an onready handler.\");\n }\n let end = false;\n if (chunk === null) {\n // We cannot return immediately because carriedFromPrevious may need\n // processing.\n end = true;\n chunk = \"\";\n }\n else if (typeof chunk === \"object\") {\n chunk = chunk.toString();\n }\n // We checked if performing a pre-decomposition of the string into an array\n // of single complete characters (``Array.from(chunk)``) would be faster\n // than the current repeated calls to ``charCodeAt``. As of August 2018, it\n // isn't. (There may be Node-specific code that would perform faster than\n // ``Array.from`` but don't want to be dependent on Node.)\n if (this.carriedFromPrevious !== undefined) {\n // The previous chunk had char we must carry over.\n chunk = `${this.carriedFromPrevious}${chunk}`;\n this.carriedFromPrevious = undefined;\n }\n let limit = chunk.length;\n const lastCode = chunk.charCodeAt(limit - 1);\n if (!end &&\n // A trailing CR or surrogate must be carried over to the next\n // chunk.\n (lastCode === CR || (lastCode >= 0xD800 && lastCode <= 0xDBFF))) {\n // The chunk ends with a character that must be carried over. We cannot\n // know how to handle it until we get the next chunk or the end of the\n // stream. So save it for later.\n this.carriedFromPrevious = chunk[limit - 1];\n limit--;\n chunk = chunk.slice(0, limit);\n }\n const { stateTable } = this;\n this.chunk = chunk;\n this.i = 0;\n while (this.i < limit) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument\n stateTable[this.state].call(this);\n }\n this.chunkPosition += limit;\n return end ? this.end() : this;\n }\n /**\n * Close the current stream. Perform final well-formedness checks and reset\n * the parser tstate.\n *\n * @returns this\n */\n close() {\n return this.write(null);\n }\n /**\n * Get a single code point out of the current chunk. This updates the current\n * position if we do position tracking.\n *\n * This is the algorithm to use for XML 1.0.\n *\n * @returns The character read.\n */\n getCode10() {\n const { chunk, i } = this;\n this.prevI = i;\n // Yes, we do this instead of doing this.i++. Doing it this way, we do not\n // read this.i again, which is a bit faster.\n this.i = i + 1;\n if (i >= chunk.length) {\n return EOC;\n }\n // Using charCodeAt and handling the surrogates ourselves is faster\n // than using codePointAt.\n const code = chunk.charCodeAt(i);\n this.column++;\n if (code < 0xD800) {\n if (code >= SPACE || code === TAB) {\n return code;\n }\n switch (code) {\n case NL:\n this.line++;\n this.column = 0;\n this.positionAtNewLine = this.position;\n return NL;\n case CR:\n // We may get NaN if we read past the end of the chunk, which is fine.\n if (chunk.charCodeAt(i + 1) === NL) {\n // A \\r\\n sequence is converted to \\n so we have to skip over the\n // next character. We already know it has a size of 1 so ++ is fine\n // here.\n this.i = i + 2;\n }\n // Otherwise, a \\r is just converted to \\n, so we don't have to skip\n // ahead.\n // In either case, \\r becomes \\n.\n this.line++;\n this.column = 0;\n this.positionAtNewLine = this.position;\n return NL_LIKE;\n default:\n // If we get here, then code < SPACE and it is not NL CR or TAB.\n this.fail(\"disallowed character.\");\n return code;\n }\n }\n if (code > 0xDBFF) {\n // This is a specialized version of isChar10 that takes into account\n // that in this context code > 0xDBFF and code <= 0xFFFF. So it does not\n // test cases that don't need testing.\n if (!(code >= 0xE000 && code <= 0xFFFD)) {\n this.fail(\"disallowed character.\");\n }\n return code;\n }\n const final = 0x10000 + ((code - 0xD800) * 0x400) +\n (chunk.charCodeAt(i + 1) - 0xDC00);\n this.i = i + 2;\n // This is a specialized version of isChar10 that takes into account that in\n // this context necessarily final >= 0x10000.\n if (final > 0x10FFFF) {\n this.fail(\"disallowed character.\");\n }\n return final;\n }\n /**\n * Get a single code point out of the current chunk. This updates the current\n * position if we do position tracking.\n *\n * This is the algorithm to use for XML 1.1.\n *\n * @returns {number} The character read.\n */\n getCode11() {\n const { chunk, i } = this;\n this.prevI = i;\n // Yes, we do this instead of doing this.i++. Doing it this way, we do not\n // read this.i again, which is a bit faster.\n this.i = i + 1;\n if (i >= chunk.length) {\n return EOC;\n }\n // Using charCodeAt and handling the surrogates ourselves is faster\n // than using codePointAt.\n const code = chunk.charCodeAt(i);\n this.column++;\n if (code < 0xD800) {\n if ((code > 0x1F && code < 0x7F) || (code > 0x9F && code !== LS) ||\n code === TAB) {\n return code;\n }\n switch (code) {\n case NL: // 0xA\n this.line++;\n this.column = 0;\n this.positionAtNewLine = this.position;\n return NL;\n case CR: { // 0xD\n // We may get NaN if we read past the end of the chunk, which is\n // fine.\n const next = chunk.charCodeAt(i + 1);\n if (next === NL || next === NEL) {\n // A CR NL or CR NEL sequence is converted to NL so we have to skip\n // over the next character. We already know it has a size of 1.\n this.i = i + 2;\n }\n // Otherwise, a CR is just converted to NL, no skip.\n }\n /* yes, fall through */\n case NEL: // 0x85\n case LS: // Ox2028\n this.line++;\n this.column = 0;\n this.positionAtNewLine = this.position;\n return NL_LIKE;\n default:\n this.fail(\"disallowed character.\");\n return code;\n }\n }\n if (code > 0xDBFF) {\n // This is a specialized version of isCharAndNotRestricted that takes into\n // account that in this context code > 0xDBFF and code <= 0xFFFF. So it\n // does not test cases that don't need testing.\n if (!(code >= 0xE000 && code <= 0xFFFD)) {\n this.fail(\"disallowed character.\");\n }\n return code;\n }\n const final = 0x10000 + ((code - 0xD800) * 0x400) +\n (chunk.charCodeAt(i + 1) - 0xDC00);\n this.i = i + 2;\n // This is a specialized version of isCharAndNotRestricted that takes into\n // account that in this context necessarily final >= 0x10000.\n if (final > 0x10FFFF) {\n this.fail(\"disallowed character.\");\n }\n return final;\n }\n /**\n * Like ``getCode`` but with the return value normalized so that ``NL`` is\n * returned for ``NL_LIKE``.\n */\n getCodeNorm() {\n const c = this.getCode();\n return c === NL_LIKE ? NL : c;\n }\n unget() {\n this.i = this.prevI;\n this.column--;\n }\n /**\n * Capture characters into a buffer until encountering one of a set of\n * characters.\n *\n * @param chars An array of codepoints. Encountering a character in the array\n * ends the capture. (``chars`` may safely contain ``NL``.)\n *\n * @return The character code that made the capture end, or ``EOC`` if we hit\n * the end of the chunk. The return value cannot be NL_LIKE: NL is returned\n * instead.\n */\n captureTo(chars) {\n let { i: start } = this;\n const { chunk } = this;\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const c = this.getCode();\n const isNLLike = c === NL_LIKE;\n const final = isNLLike ? NL : c;\n if (final === EOC || chars.includes(final)) {\n this.text += chunk.slice(start, this.prevI);\n return final;\n }\n if (isNLLike) {\n this.text += `${chunk.slice(start, this.prevI)}\\n`;\n start = this.i;\n }\n }\n }\n /**\n * Capture characters into a buffer until encountering a character.\n *\n * @param char The codepoint that ends the capture. **NOTE ``char`` MAY NOT\n * CONTAIN ``NL``.** Passing ``NL`` will result in buggy behavior.\n *\n * @return ``true`` if we ran into the character. Otherwise, we ran into the\n * end of the current chunk.\n */\n captureToChar(char) {\n let { i: start } = this;\n const { chunk } = this;\n // eslint-disable-next-line no-constant-condition\n while (true) {\n let c = this.getCode();\n switch (c) {\n case NL_LIKE:\n this.text += `${chunk.slice(start, this.prevI)}\\n`;\n start = this.i;\n c = NL;\n break;\n case EOC:\n this.text += chunk.slice(start);\n return false;\n default:\n }\n if (c === char) {\n this.text += chunk.slice(start, this.prevI);\n return true;\n }\n }\n }\n /**\n * Capture characters that satisfy ``isNameChar`` into the ``name`` field of\n * this parser.\n *\n * @return The character code that made the test fail, or ``EOC`` if we hit\n * the end of the chunk. The return value cannot be NL_LIKE: NL is returned\n * instead.\n */\n captureNameChars() {\n const { chunk, i: start } = this;\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const c = this.getCode();\n if (c === EOC) {\n this.name += chunk.slice(start);\n return EOC;\n }\n // NL is not a name char so we don't have to test specifically for it.\n if (!isNameChar(c)) {\n this.name += chunk.slice(start, this.prevI);\n return c === NL_LIKE ? NL : c;\n }\n }\n }\n /**\n * Skip white spaces.\n *\n * @return The character that ended the skip, or ``EOC`` if we hit\n * the end of the chunk. The return value cannot be NL_LIKE: NL is returned\n * instead.\n */\n skipSpaces() {\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const c = this.getCodeNorm();\n if (c === EOC || !isS(c)) {\n return c;\n }\n }\n }\n setXMLVersion(version) {\n this.currentXMLVersion = version;\n /* eslint-disable @typescript-eslint/unbound-method */\n if (version === \"1.0\") {\n this.isChar = isChar10;\n this.getCode = this.getCode10;\n }\n else {\n this.isChar = isChar11;\n this.getCode = this.getCode11;\n }\n /* eslint-enable @typescript-eslint/unbound-method */\n }\n // STATE ENGINE METHODS\n // This needs to be a state separate from S_BEGIN_WHITESPACE because we want\n // to be sure never to come back to this state later.\n sBegin() {\n // We are essentially peeking at the first character of the chunk. Since\n // S_BEGIN can be in effect only when we start working on the first chunk,\n // the index at which we must look is necessarily 0. Note also that the\n // following test does not depend on decoding surrogates.\n // If the initial character is 0xFEFF, ignore it.\n if (this.chunk.charCodeAt(0) === 0xFEFF) {\n this.i++;\n this.column++;\n }\n this.state = S_BEGIN_WHITESPACE;\n }\n sBeginWhitespace() {\n // We need to know whether we've encountered spaces or not because as soon\n // as we run into a space, an XML declaration is no longer possible. Rather\n // than slow down skipSpaces even in places where we don't care whether it\n // skipped anything or not, we check whether prevI is equal to the value of\n // i from before we skip spaces.\n const iBefore = this.i;\n const c = this.skipSpaces();\n if (this.prevI !== iBefore) {\n this.xmlDeclPossible = false;\n }\n switch (c) {\n case LESS:\n this.state = S_OPEN_WAKA;\n // We could naively call closeText but in this state, it is not normal\n // to have text be filled with any data.\n if (this.text.length !== 0) {\n throw new Error(\"no-empty text at start\");\n }\n break;\n case EOC:\n break;\n default:\n this.unget();\n this.state = S_TEXT;\n this.xmlDeclPossible = false;\n }\n }\n sDoctype() {\n var _a;\n const c = this.captureTo(DOCTYPE_TERMINATOR);\n switch (c) {\n case GREATER: {\n (_a = this.doctypeHandler) === null || _a === void 0 ? void 0 : _a.call(this, this.text);\n this.text = \"\";\n this.state = S_TEXT;\n this.doctype = true; // just remember that we saw it.\n break;\n }\n case EOC:\n break;\n default:\n this.text += String.fromCodePoint(c);\n if (c === OPEN_BRACKET) {\n this.state = S_DTD;\n }\n else if (isQuote(c)) {\n this.state = S_DOCTYPE_QUOTE;\n this.q = c;\n }\n }\n }\n sDoctypeQuote() {\n const q = this.q;\n if (this.captureToChar(q)) {\n this.text += String.fromCodePoint(q);\n this.q = null;\n this.state = S_DOCTYPE;\n }\n }\n sDTD() {\n const c = this.captureTo(DTD_TERMINATOR);\n if (c === EOC) {\n return;\n }\n this.text += String.fromCodePoint(c);\n if (c === CLOSE_BRACKET) {\n this.state = S_DOCTYPE;\n }\n else if (c === LESS) {\n this.state = S_DTD_OPEN_WAKA;\n }\n else if (isQuote(c)) {\n this.state = S_DTD_QUOTED;\n this.q = c;\n }\n }\n sDTDQuoted() {\n const q = this.q;\n if (this.captureToChar(q)) {\n this.text += String.fromCodePoint(q);\n this.state = S_DTD;\n this.q = null;\n }\n }\n sDTDOpenWaka() {\n const c = this.getCodeNorm();\n this.text += String.fromCodePoint(c);\n switch (c) {\n case BANG:\n this.state = S_DTD_OPEN_WAKA_BANG;\n this.openWakaBang = \"\";\n break;\n case QUESTION:\n this.state = S_DTD_PI;\n break;\n default:\n this.state = S_DTD;\n }\n }\n sDTDOpenWakaBang() {\n const char = String.fromCodePoint(this.getCodeNorm());\n const owb = this.openWakaBang += char;\n this.text += char;\n if (owb !== \"-\") {\n this.state = owb === \"--\" ? S_DTD_COMMENT : S_DTD;\n this.openWakaBang = \"\";\n }\n }\n sDTDComment() {\n if (this.captureToChar(MINUS)) {\n this.text += \"-\";\n this.state = S_DTD_COMMENT_ENDING;\n }\n }\n sDTDCommentEnding() {\n const c = this.getCodeNorm();\n this.text += String.fromCodePoint(c);\n this.state = c === MINUS ? S_DTD_COMMENT_ENDED : S_DTD_COMMENT;\n }\n sDTDCommentEnded() {\n const c = this.getCodeNorm();\n this.text += String.fromCodePoint(c);\n if (c === GREATER) {\n this.state = S_DTD;\n }\n else {\n this.fail(\"malformed comment.\");\n // <!-- blah -- bloo --> will be recorded as\n // a comment of \" blah -- bloo \"\n this.state = S_DTD_COMMENT;\n }\n }\n sDTDPI() {\n if (this.captureToChar(QUESTION)) {\n this.text += \"?\";\n this.state = S_DTD_PI_ENDING;\n }\n }\n sDTDPIEnding() {\n const c = this.getCodeNorm();\n this.text += String.fromCodePoint(c);\n if (c === GREATER) {\n this.state = S_DTD;\n }\n }\n sText() {\n //\n // We did try a version of saxes where the S_TEXT state was split in two\n // states: one for text inside the root element, and one for text\n // outside. This was avoiding having to test this.tags.length to decide\n // what implementation to actually use.\n //\n // Peformance testing on gigabyte-size files did not show any advantage to\n // using the two states solution instead of the current one. Conversely, it\n // made the code a bit more complicated elsewhere. For instance, a comment\n // can appear before the root element so when a comment ended it was\n // necessary to determine whether to return to the S_TEXT state or to the\n // new text-outside-root state.\n //\n if (this.tags.length !== 0) {\n this.handleTextInRoot();\n }\n else {\n this.handleTextOutsideRoot();\n }\n }\n sEntity() {\n // This is essentially a specialized version of captureToChar(SEMICOLON...)\n let { i: start } = this;\n const { chunk } = this;\n // eslint-disable-next-line no-labels, no-restricted-syntax\n loop: \n // eslint-disable-next-line no-constant-condition\n while (true) {\n switch (this.getCode()) {\n case NL_LIKE:\n this.entity += `${chunk.slice(start, this.prevI)}\\n`;\n start = this.i;\n break;\n case SEMICOLON: {\n const { entityReturnState } = this;\n const entity = this.entity + chunk.slice(start, this.prevI);\n this.state = entityReturnState;\n let parsed;\n if (entity === \"\") {\n this.fail(\"empty entity name.\");\n parsed = \"&;\";\n }\n else {\n parsed = this.parseEntity(entity);\n this.entity = \"\";\n }\n if (entityReturnState !== S_TEXT || this.textHandler !== undefined) {\n this.text += parsed;\n }\n // eslint-disable-next-line no-labels\n break loop;\n }\n case EOC:\n this.entity += chunk.slice(start);\n // eslint-disable-next-line no-labels\n break loop;\n default:\n }\n }\n }\n sOpenWaka() {\n // Reminder: a state handler is called with at least one character\n // available in the current chunk. So the first call to get code inside of\n // a state handler cannot return ``EOC``. That's why we don't test\n // for it.\n const c = this.getCode();\n // either a /, ?, !, or text is coming next.\n if (isNameStartChar(c)) {\n this.state = S_OPEN_TAG;\n this.unget();\n this.xmlDeclPossible = false;\n }\n else {\n switch (c) {\n case FORWARD_SLASH:\n this.state = S_CLOSE_TAG;\n this.xmlDeclPossible = false;\n break;\n case BANG:\n this.state = S_OPEN_WAKA_BANG;\n this.openWakaBang = \"\";\n this.xmlDeclPossible = false;\n break;\n case QUESTION:\n this.state = S_PI_FIRST_CHAR;\n break;\n default:\n this.fail(\"disallowed character in tag name\");\n this.state = S_TEXT;\n this.xmlDeclPossible = false;\n }\n }\n }\n sOpenWakaBang() {\n this.openWakaBang += String.fromCodePoint(this.getCodeNorm());\n switch (this.openWakaBang) {\n case \"[CDATA[\":\n if (!this.sawRoot && !this.reportedTextBeforeRoot) {\n this.fail(\"text data outside of root node.\");\n this.reportedTextBeforeRoot = true;\n }\n if (this.closedRoot && !this.reportedTextAfterRoot) {\n this.fail(\"text data outside of root node.\");\n this.reportedTextAfterRoot = true;\n }\n this.state = S_CDATA;\n this.openWakaBang = \"\";\n break;\n case \"--\":\n this.state = S_COMMENT;\n this.openWakaBang = \"\";\n break;\n case \"DOCTYPE\":\n this.state = S_DOCTYPE;\n if (this.doctype || this.sawRoot) {\n this.fail(\"inappropriately located doctype declaration.\");\n }\n this.openWakaBang = \"\";\n break;\n default:\n // 7 happens to be the maximum length of the string that can possibly\n // match one of the cases above.\n if (this.openWakaBang.length >= 7) {\n this.fail(\"incorrect syntax.\");\n }\n }\n }\n sComment() {\n if (this.captureToChar(MINUS)) {\n this.state = S_COMMENT_ENDING;\n }\n }\n sCommentEnding() {\n var _a;\n const c = this.getCodeNorm();\n if (c === MINUS) {\n this.state = S_COMMENT_ENDED;\n (_a = this.commentHandler) === null || _a === void 0 ? void 0 : _a.call(this, this.text);\n this.text = \"\";\n }\n else {\n this.text += `-${String.fromCodePoint(c)}`;\n this.state = S_COMMENT;\n }\n }\n sCommentEnded() {\n const c = this.getCodeNorm();\n if (c !== GREATER) {\n this.fail(\"malformed comment.\");\n // <!-- blah -- bloo --> will be recorded as\n // a comment of \" blah -- bloo \"\n this.text += `--${String.fromCodePoint(c)}`;\n this.state = S_COMMENT;\n }\n else {\n this.state = S_TEXT;\n }\n }\n sCData() {\n if (this.captureToChar(CLOSE_BRACKET)) {\n this.state = S_CDATA_ENDING;\n }\n }\n sCDataEnding() {\n const c = this.getCodeNorm();\n if (c === CLOSE_BRACKET) {\n this.state = S_CDATA_ENDING_2;\n }\n else {\n this.text += `]${String.fromCodePoint(c)}`;\n this.state = S_CDATA;\n }\n }\n sCDataEnding2() {\n var _a;\n const c = this.getCodeNorm();\n switch (c) {\n case GREATER: {\n (_a = this.cdataHandler) === null || _a === void 0 ? void 0 : _a.call(this, this.text);\n this.text = \"\";\n this.state = S_TEXT;\n break;\n }\n case CLOSE_BRACKET:\n this.text += \"]\";\n break;\n default:\n this.text += `]]${String.fromCodePoint(c)}`;\n this.state = S_CDATA;\n }\n }\n // We need this separate state to check the first character fo the pi target\n // with this.nameStartCheck which allows less characters than this.nameCheck.\n sPIFirstChar() {\n const c = this.getCodeNorm();\n // This is first because in the case where the file is well-formed this is\n // the branch taken. We optimize for well-formedness.\n if (this.nameStartCheck(c)) {\n this.piTarget += String.fromCodePoint(c);\n this.state = S_PI_REST;\n }\n else if (c === QUESTION || isS(c)) {\n this.fail(\"processing instruction without a target.\");\n this.state = c === QUESTION ? S_PI_ENDING : S_PI_BODY;\n }\n else {\n this.fail(\"disallowed character in processing instruction name.\");\n this.piTarget += String.fromCodePoint(c);\n this.state = S_PI_REST;\n }\n }\n sPIRest() {\n // Capture characters into a piTarget while ``this.nameCheck`` run on the\n // character read returns true.\n const { chunk, i: start } = this;\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const c = this.getCodeNorm();\n if (c === EOC) {\n this.piTarget += chunk.slice(start);\n return;\n }\n // NL cannot satisfy this.nameCheck so we don't have to test specifically\n // for it.\n if (!this.nameCheck(c)) {\n this.piTarget += chunk.slice(start, this.prevI);\n const isQuestion = c === QUESTION;\n if (isQuestion || isS(c)) {\n if (this.piTarget === \"xml\") {\n if (!this.xmlDeclPossible) {\n this.fail(\"an XML declaration must be at the start of the document.\");\n }\n this.state = isQuestion ? S_XML_DECL_ENDING : S_XML_DECL_NAME_START;\n }\n else {\n this.state = isQuestion ? S_PI_ENDING : S_PI_BODY;\n }\n }\n else {\n this.fail(\"disallowed character in processing instruction name.\");\n this.piTarget += String.fromCodePoint(c);\n }\n break;\n }\n }\n }\n sPIBody() {\n if (this.text.length === 0) {\n const c = this.getCodeNorm();\n if (c === QUESTION) {\n this.state = S_PI_ENDING;\n }\n else if (!isS(c)) {\n this.text = String.fromCodePoint(c);\n }\n }\n // The question mark character is not valid inside any of the XML\n // declaration name/value pairs.\n else if (this.captureToChar(QUESTION)) {\n this.state = S_PI_ENDING;\n }\n }\n sPIEnding() {\n var _a;\n const c = this.getCodeNorm();\n if (c === GREATER) {\n const { piTarget } = this;\n if (piTarget.toLowerCase() === \"xml\") {\n this.fail(\"the XML declaration must appear at the start of the document.\");\n }\n (_a = this.piHandler) === null || _a === void 0 ? void 0 : _a.call(this, {\n target: piTarget,\n body: this.text,\n });\n this.piTarget = this.text = \"\";\n this.state = S_TEXT;\n }\n else if (c === QUESTION) {\n // We ran into ?? as part of a processing instruction. We initially took\n // the first ? as a sign that the PI was ending, but it is not. So we have\n // to add it to the body but we take the new ? as a sign that the PI is\n // ending.\n this.text += \"?\";\n }\n else {\n this.text += `?${String.fromCodePoint(c)}`;\n this.state = S_PI_BODY;\n }\n this.xmlDeclPossible = false;\n }\n sXMLDeclNameStart() {\n const c = this.skipSpaces();\n // The question mark character is not valid inside any of the XML\n // declaration name/value pairs.\n if (c === QUESTION) {\n // It is valid to go to S_XML_DECL_ENDING from this state.\n this.state = S_XML_DECL_ENDING;\n return;\n }\n if (c !== EOC) {\n this.state = S_XML_DECL_NAME;\n this.name = String.fromCodePoint(c);\n }\n }\n sXMLDeclName() {\n const c = this.captureTo(XML_DECL_NAME_TERMINATOR);\n // The question mark character is not valid inside any of the XML\n // declaration name/value pairs.\n if (c === QUESTION) {\n this.state = S_XML_DECL_ENDING;\n this.name += this.text;\n this.text = \"\";\n this.fail(\"XML declaration is incomplete.\");\n return;\n }\n if (!(isS(c) || c === EQUAL)) {\n return;\n }\n this.name += this.text;\n this.text = \"\";\n if (!this.xmlDeclExpects.includes(this.name)) {\n switch (this.name.length) {\n case 0:\n this.fail(\"did not expect any more name/value pairs.\");\n break;\n case 1:\n this.fail(`expected the name ${this.xmlDeclExpects[0]}.`);\n break;\n default:\n this.fail(`expected one of ${this.xmlDeclExpects.join(\", \")}`);\n }\n }\n this.state = c === EQUAL ? S_XML_DECL_VALUE_START : S_XML_DECL_EQ;\n }\n sXMLDeclEq() {\n const c = this.getCodeNorm();\n // The question mark character is not valid inside any of the XML\n // declaration name/value pairs.\n if (c === QUESTION) {\n this.state = S_XML_DECL_ENDING;\n this.fail(\"XML declaration is incomplete.\");\n return;\n }\n if (isS(c)) {\n return;\n }\n if (c !== EQUAL) {\n this.fail(\"value required.\");\n }\n this.state = S_XML_DECL_VALUE_START;\n }\n sXMLDeclValueStart() {\n const c = this.getCodeNorm();\n // The question mark character is not valid inside any of the XML\n // declaration name/value pairs.\n if (c === QUESTION) {\n this.state = S_XML_DECL_ENDING;\n this.fail(\"XML declaration is incomplete.\");\n return;\n }\n if (isS(c)) {\n return;\n }\n if (!isQuote(c)) {\n this.fail(\"value must be quoted.\");\n this.q = SPACE;\n }\n else {\n this.q = c;\n }\n this.state = S_XML_DECL_VALUE;\n }\n sXMLDeclValue() {\n const c = this.captureTo([this.q, QUESTION]);\n // The question mark character is not valid inside any of the XML\n // declaration name/value pairs.\n if (c === QUESTION) {\n this.state = S_XML_DECL_ENDING;\n this.text = \"\";\n this.fail(\"XML declaration is incomplete.\");\n return;\n }\n if (c === EOC) {\n return;\n }\n const value = this.text;\n this.text = \"\";\n switch (this.name) {\n case \"version\": {\n this.xmlDeclExpects = [\"encoding\", \"standalone\"];\n const version = value;\n this.xmlDecl.version = version;\n // This is the test specified by XML 1.0 but it is fine for XML 1.1.\n if (!/^1\\.[0-9]+$/.test(version)) {\n this.fail(\"version number must match /^1\\\\.[0-9]+$/.\");\n }\n // When forceXMLVersion is set, the XML declaration is ignored.\n else if (!this.opt.forceXMLVersion) {\n this.setXMLVersion(version);\n }\n break;\n }\n case \"encoding\":\n if (!/^[A-Za-z][A-Za-z0-9._-]*$/.test(value)) {\n this.fail(\"encoding value must match \\\n/^[A-Za-z0-9][A-Za-z0-9._-]*$/.\");\n }\n this.xmlDeclExpects = [\"standalone\"];\n this.xmlDecl.encoding = value;\n break;\n case \"standalone\":\n if (value !== \"yes\" && value !== \"no\") {\n this.fail(\"standalone value must match \\\"yes\\\" or \\\"no\\\".\");\n }\n this.xmlDeclExpects = [];\n this.xmlDecl.standalone = value;\n break;\n default:\n // We don't need to raise an error here since we've already raised one\n // when checking what name was expected.\n }\n this.name = \"\";\n this.state = S_XML_DECL_SEPARATOR;\n }\n sXMLDeclSeparator() {\n const c = this.getCodeNorm();\n // The question mark character is not valid inside any of the XML\n // declaration name/value pairs.\n if (c === QUESTION) {\n // It is valid to go to S_XML_DECL_ENDING from this state.\n this.state = S_XML_DECL_ENDING;\n return;\n }\n if (!isS(c)) {\n this.fail(\"whitespace required.\");\n this.unget();\n }\n this.state = S_XML_DECL_NAME_START;\n }\n sXMLDeclEnding() {\n var _a;\n const c = this.getCodeNorm();\n if (c === GREATER) {\n if (this.piTarget !== \"xml\") {\n this.fail(\"processing instructions are not allowed before root.\");\n }\n else if (this.name !== \"version\" &&\n this.xmlDeclExpects.includes(\"version\")) {\n this.fail(\"XML declaration must contain a version.\");\n }\n (_a = this.xmldeclHandler) === null || _a === void 0 ? void 0 : _a.call(this, this.xmlDecl);\n this.name = \"\";\n this.piTarget = this.text = \"\";\n this.state = S_TEXT;\n }\n else {\n // We got here because the previous character was a ?, but the question\n // mark character is not valid inside any of the XML declaration\n // name/value pairs.\n this.fail(\"The character ? is disallowed anywhere in XML declarations.\");\n }\n this.xmlDeclPossible = false;\n }\n sOpenTag() {\n var _a;\n const c = this.captureNameChars();\n if (c === EOC) {\n return;\n }\n const tag = this.tag = {\n name: this.name,\n attributes: Object.create(null),\n };\n this.name = \"\";\n if (this.xmlnsOpt) {\n this.topNS = tag.ns = Object.create(null);\n }\n (_a = this.openTagStartHandler) === null || _a === void 0 ? void 0 : _a.call(this, tag);\n this.sawRoot = true;\n if (!this.fragmentOpt && this.closedRoot) {\n this.fail(\"documents may contain only one root.\");\n }\n switch (c) {\n case GREATER:\n this.openTag();\n break;\n case FORWARD_SLASH:\n this.state = S_OPEN_TAG_SLASH;\n break;\n default:\n if (!isS(c)) {\n this.fail(\"disallowed character in tag name.\");\n }\n this.state = S_ATTRIB;\n }\n }\n sOpenTagSlash() {\n if (this.getCode() === GREATER) {\n this.openSelfClosingTag();\n }\n else {\n this.fail(\"forward-slash in opening tag not followed by >.\");\n this.state = S_ATTRIB;\n }\n }\n sAttrib() {\n const c = this.skipSpaces();\n if (c === EOC) {\n return;\n }\n if (isNameStartChar(c)) {\n this.unget();\n this.state = S_ATTRIB_NAME;\n }\n else if (c === GREATER) {\n this.openTag();\n }\n else if (c === FORWARD_SLASH) {\n this.state = S_OPEN_TAG_SLASH;\n }\n else {\n this.fail(\"disallowed character in attribute name.\");\n }\n }\n sAttribName() {\n const c = this.captureNameChars();\n if (c === EQUAL) {\n this.state = S_ATTRIB_VALUE;\n }\n else if (isS(c)) {\n this.state = S_ATTRIB_NAME_SAW_WHITE;\n }\n else if (c === GREATER) {\n this.fail(\"attribute without value.\");\n this.pushAttrib(this.name, this.name);\n this.name = this.text = \"\";\n this.openTag();\n }\n else if (c !== EOC) {\n this.fail(\"disallowed character in attribute name.\");\n }\n }\n sAttribNameSawWhite() {\n const c = this.skipSpaces();\n switch (c) {\n case EOC:\n return;\n case EQUAL:\n this.state = S_ATTRIB_VALUE;\n break;\n default:\n this.fail(\"attribute without value.\");\n // Should we do this???\n // this.tag.attributes[this.name] = \"\";\n this.text = \"\";\n this.name = \"\";\n if (c === GREATER) {\n this.openTag();\n }\n else if (isNameStartChar(c)) {\n this.unget();\n this.state = S_ATTRIB_NAME;\n }\n else {\n this.fail(\"disallowed character in attribute name.\");\n this.state = S_ATTRIB;\n }\n }\n }\n sAttribValue() {\n const c = this.getCodeNorm();\n if (isQuote(c)) {\n this.q = c;\n this.state = S_ATTRIB_VALUE_QUOTED;\n }\n else if (!isS(c)) {\n this.fail(\"unquoted attribute value.\");\n this.state = S_ATTRIB_VALUE_UNQUOTED;\n this.unget();\n }\n }\n sAttribValueQuoted() {\n // We deliberately do not use captureTo here. The specialized code we use\n // here is faster than using captureTo.\n const { q, chunk } = this;\n let { i: start } = this;\n // eslint-disable-next-line no-constant-condition\n while (true) {\n switch (this.getCode()) {\n case q:\n this.pushAttrib(this.name, this.text + chunk.slice(start, this.prevI));\n this.name = this.text = \"\";\n this.q = null;\n this.state = S_ATTRIB_VALUE_CLOSED;\n return;\n case AMP:\n this.text += chunk.slice(start, this.prevI);\n this.state = S_ENTITY;\n this.entityReturnState = S_ATTRIB_VALUE_QUOTED;\n return;\n case NL:\n case NL_LIKE:\n case TAB:\n this.text += `${chunk.slice(start, this.prevI)} `;\n start = this.i;\n break;\n case LESS:\n this.text += chunk.slice(start, this.prevI);\n this.fail(\"disallowed character.\");\n return;\n case EOC:\n this.text += chunk.slice(start);\n return;\n default:\n }\n }\n }\n sAttribValueClosed() {\n const c = this.getCodeNorm();\n if (isS(c)) {\n this.state = S_ATTRIB;\n }\n else if (c === GREATER) {\n this.openTag();\n }\n else if (c === FORWARD_SLASH) {\n this.state = S_OPEN_TAG_SLASH;\n }\n else if (isNameStartChar(c)) {\n this.fail(\"no whitespace between attributes.\");\n this.unget();\n this.state = S_ATTRIB_NAME;\n }\n else {\n this.fail(\"disallowed character in attribute name.\");\n }\n }\n sAttribValueUnquoted() {\n // We don't do anything regarding EOL or space handling for unquoted\n // attributes. We already have failed by the time we get here, and the\n // contract that saxes upholds states that upon failure, it is not safe to\n // rely on the data passed to event handlers (other than\n // ``onerror``). Passing \"bad\" data is not a problem.\n const c = this.captureTo(ATTRIB_VALUE_UNQUOTED_TERMINATOR);\n switch (c) {\n case AMP:\n this.state = S_ENTITY;\n this.entityReturnState = S_ATTRIB_VALUE_UNQUOTED;\n break;\n case LESS:\n this.fail(\"disallowed character.\");\n break;\n case EOC:\n break;\n default:\n if (this.text.includes(\"]]>\")) {\n this.fail(\"the string \\\"]]>\\\" is disallowed in char data.\");\n }\n this.pushAttrib(this.name, this.text);\n this.name = this.text = \"\";\n if (c === GREATER) {\n this.openTag();\n }\n else {\n this.state = S_ATTRIB;\n }\n }\n }\n sCloseTag() {\n const c = this.captureNameChars();\n if (c === GREATER) {\n this.closeTag();\n }\n else if (isS(c)) {\n this.state = S_CLOSE_TAG_SAW_WHITE;\n }\n else if (c !== EOC) {\n this.fail(\"disallowed character in closing tag.\");\n }\n }\n sCloseTagSawWhite() {\n switch (this.skipSpaces()) {\n case GREATER:\n this.closeTag();\n break;\n case EOC:\n break;\n default:\n this.fail(\"disallowed character in closing tag.\");\n }\n }\n // END OF STATE ENGINE METHODS\n handleTextInRoot() {\n // This is essentially a specialized version of captureTo which is optimized\n // for performing the ]]> check. A previous version of this code, checked\n // ``this.text`` for the presence of ]]>. It simplified the code but was\n // very costly when character data contained a lot of entities to be parsed.\n //\n // Since we are using a specialized loop, we also keep track of the presence\n // of ]]> in text data. The sequence ]]> is forbidden to appear as-is.\n //\n let { i: start, forbiddenState } = this;\n const { chunk, textHandler: handler } = this;\n // eslint-disable-next-line no-labels, no-restricted-syntax\n scanLoop: \n // eslint-disable-next-line no-constant-condition\n while (true) {\n switch (this.getCode()) {\n case LESS: {\n this.state = S_OPEN_WAKA;\n if (handler !== undefined) {\n const { text } = this;\n const slice = chunk.slice(start, this.prevI);\n if (text.length !== 0) {\n handler(text + slice);\n this.text = \"\";\n }\n else if (slice.length !== 0) {\n handler(slice);\n }\n }\n forbiddenState = FORBIDDEN_START;\n // eslint-disable-next-line no-labels\n break scanLoop;\n }\n case AMP:\n this.state = S_ENTITY;\n this.entityReturnState = S_TEXT;\n if (handler !== undefined) {\n this.text += chunk.slice(start, this.prevI);\n }\n forbiddenState = FORBIDDEN_START;\n // eslint-disable-next-line no-labels\n break scanLoop;\n case CLOSE_BRACKET:\n switch (forbiddenState) {\n case FORBIDDEN_START:\n forbiddenState = FORBIDDEN_BRACKET;\n break;\n case FORBIDDEN_BRACKET:\n forbiddenState = FORBIDDEN_BRACKET_BRACKET;\n break;\n case FORBIDDEN_BRACKET_BRACKET:\n break;\n default:\n throw new Error(\"impossible state\");\n }\n break;\n case GREATER:\n if (forbiddenState === FORBIDDEN_BRACKET_BRACKET) {\n this.fail(\"the string \\\"]]>\\\" is disallowed in char data.\");\n }\n forbiddenState = FORBIDDEN_START;\n break;\n case NL_LIKE:\n if (handler !== undefined) {\n this.text += `${chunk.slice(start, this.prevI)}\\n`;\n }\n start = this.i;\n forbiddenState = FORBIDDEN_START;\n break;\n case EOC:\n if (handler !== undefined) {\n this.text += chunk.slice(start);\n }\n // eslint-disable-next-line no-labels\n break scanLoop;\n default:\n forbiddenState = FORBIDDEN_START;\n }\n }\n this.forbiddenState = forbiddenState;\n }\n handleTextOutsideRoot() {\n // This is essentially a specialized version of captureTo which is optimized\n // for a specialized task. We keep track of the presence of non-space\n // characters in the text since these are errors when appearing outside the\n // document root element.\n let { i: start } = this;\n const { chunk, textHandler: handler } = this;\n let nonSpace = false;\n // eslint-disable-next-line no-labels, no-restricted-syntax\n outRootLoop: \n // eslint-disable-next-line no-constant-condition\n while (true) {\n const code = this.getCode();\n switch (code) {\n case LESS: {\n this.state = S_OPEN_WAKA;\n if (handler !== undefined) {\n const { text } = this;\n const slice = chunk.slice(start, this.prevI);\n if (text.length !== 0) {\n handler(text + slice);\n this.text = \"\";\n }\n else if (slice.length !== 0) {\n handler(slice);\n }\n }\n // eslint-disable-next-line no-labels\n break outRootLoop;\n }\n case AMP:\n this.state = S_ENTITY;\n this.entityReturnState = S_TEXT;\n if (handler !== undefined) {\n this.text += chunk.slice(start, this.prevI);\n }\n nonSpace = true;\n // eslint-disable-next-line no-labels\n break outRootLoop;\n case NL_LIKE:\n if (handler !== undefined) {\n this.text += `${chunk.slice(start, this.prevI)}\\n`;\n }\n start = this.i;\n break;\n case EOC:\n if (handler !== undefined) {\n this.text += chunk.slice(start);\n }\n // eslint-disable-next-line no-labels\n break outRootLoop;\n default:\n if (!isS(code)) {\n nonSpace = true;\n }\n }\n }\n if (!nonSpace) {\n return;\n }\n // We use the reportedTextBeforeRoot and reportedTextAfterRoot flags\n // to avoid reporting errors for every single character that is out of\n // place.\n if (!this.sawRoot && !this.reportedTextBeforeRoot) {\n this.fail(\"text data outside of root node.\");\n this.reportedTextBeforeRoot = true;\n }\n if (this.closedRoot && !this.reportedTextAfterRoot) {\n this.fail(\"text data outside of root node.\");\n this.reportedTextAfterRoot = true;\n }\n }\n pushAttribNS(name, value) {\n var _a;\n const { prefix, local } = this.qname(name);\n const attr = { name, prefix, local, value };\n this.attribList.push(attr);\n (_a = this.attributeHandler) === null || _a === void 0 ? void 0 : _a.call(this, attr);\n if (prefix === \"xmlns\") {\n const trimmed = value.trim();\n if (this.currentXMLVersion === \"1.0\" && trimmed === \"\") {\n this.fail(\"invalid attempt to undefine prefix in XML 1.0\");\n }\n this.topNS[local] = trimmed;\n nsPairCheck(this, local, trimmed);\n }\n else if (name === \"xmlns\") {\n const trimmed = value.trim();\n this.topNS[\"\"] = trimmed;\n nsPairCheck(this, \"\", trimmed);\n }\n }\n pushAttribPlain(name, value) {\n var _a;\n const attr = { name, value };\n this.attribList.push(attr);\n (_a = this.attributeHandler) === null || _a === void 0 ? void 0 : _a.call(this, attr);\n }\n /**\n * End parsing. This performs final well-formedness checks and resets the\n * parser to a clean state.\n *\n * @returns this\n */\n end() {\n var _a, _b;\n if (!this.sawRoot) {\n this.fail(\"document must contain a root element.\");\n }\n const { tags } = this;\n while (tags.length > 0) {\n const tag = tags.pop();\n this.fail(`unclosed tag: ${tag.name}`);\n }\n if ((this.state !== S_BEGIN) && (this.state !== S_TEXT)) {\n this.fail(\"unexpected end.\");\n }\n const { text } = this;\n if (text.length !== 0) {\n (_a = this.textHandler) === null || _a === void 0 ? void 0 : _a.call(this, text);\n this.text = \"\";\n }\n this._closed = true;\n (_b = this.endHandler) === null || _b === void 0 ? void 0 : _b.call(this);\n this._init();\n return this;\n }\n /**\n * Resolve a namespace prefix.\n *\n * @param prefix The prefix to resolve.\n *\n * @returns The namespace URI or ``undefined`` if the prefix is not defined.\n */\n resolve(prefix) {\n var _a, _b;\n let uri = this.topNS[prefix];\n if (uri !== undefined) {\n return uri;\n }\n const { tags } = this;\n for (let index = tags.length - 1; index >= 0; index--) {\n uri = tags[index].ns[prefix];\n if (uri !== undefined) {\n return uri;\n }\n }\n uri = this.ns[prefix];\n if (uri !== undefined) {\n return uri;\n }\n return (_b = (_a = this.opt).resolvePrefix) === null || _b === void 0 ? void 0 : _b.call(_a, prefix);\n }\n /**\n * Parse a qname into its prefix and local name parts.\n *\n * @param name The name to parse\n *\n * @returns\n */\n qname(name) {\n // This is faster than using name.split(\":\").\n const colon = name.indexOf(\":\");\n if (colon === -1) {\n return { prefix: \"\", local: name };\n }\n const local = name.slice(colon + 1);\n const prefix = name.slice(0, colon);\n if (prefix === \"\" || local === \"\" || local.includes(\":\")) {\n this.fail(`malformed name: ${name}.`);\n }\n return { prefix, local };\n }\n processAttribsNS() {\n var _a;\n const { attribList } = this;\n const tag = this.tag;\n {\n // add namespace info to tag\n const { prefix, local } = this.qname(tag.name);\n tag.prefix = prefix;\n tag.local = local;\n const uri = tag.uri = (_a = this.resolve(prefix)) !== null && _a !== void 0 ? _a : \"\";\n if (prefix !== \"\") {\n if (prefix === \"xmlns\") {\n this.fail(\"tags may not have \\\"xmlns\\\" as prefix.\");\n }\n if (uri === \"\") {\n this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`);\n tag.uri = prefix;\n }\n }\n }\n if (attribList.length === 0) {\n return;\n }\n const { attributes } = tag;\n const seen = new Set();\n // Note: do not apply default ns to attributes:\n // http://www.w3.org/TR/REC-xml-names/#defaulting\n for (const attr of attribList) {\n const { name, prefix, local } = attr;\n let uri;\n let eqname;\n if (prefix === \"\") {\n uri = name === \"xmlns\" ? XMLNS_NAMESPACE : \"\";\n eqname = name;\n }\n else {\n uri = this.resolve(prefix);\n // if there's any attributes with an undefined namespace,\n // then fail on them now.\n if (uri === undefined) {\n this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`);\n uri = prefix;\n }\n eqname = `{${uri}}${local}`;\n }\n if (seen.has(eqname)) {\n this.fail(`duplicate attribute: ${eqname}.`);\n }\n seen.add(eqname);\n attr.uri = uri;\n attributes[name] = attr;\n }\n this.attribList = [];\n }\n processAttribsPlain() {\n const { attribList } = this;\n // eslint-disable-next-line prefer-destructuring\n const attributes = this.tag.attributes;\n for (const { name, value } of attribList) {\n if (attributes[name] !== undefined) {\n this.fail(`duplicate attribute: ${name}.`);\n }\n attributes[name] = value;\n }\n this.attribList = [];\n }\n /**\n * Handle a complete open tag. This parser code calls this once it has seen\n * the whole tag. This method checks for well-formeness and then emits\n * ``onopentag``.\n */\n openTag() {\n var _a;\n this.processAttribs();\n const { tags } = this;\n const tag = this.tag;\n tag.isSelfClosing = false;\n // There cannot be any pending text here due to the onopentagstart that was\n // necessarily emitted before we get here. So we do not check text.\n (_a = this.openTagHandler) === null || _a === void 0 ? void 0 : _a.call(this, tag);\n tags.push(tag);\n this.state = S_TEXT;\n this.name = \"\";\n }\n /**\n * Handle a complete self-closing tag. This parser code calls this once it has\n * seen the whole tag. This method checks for well-formeness and then emits\n * ``onopentag`` and ``onclosetag``.\n */\n openSelfClosingTag() {\n var _a, _b, _c;\n this.processAttribs();\n const { tags } = this;\n const tag = this.tag;\n tag.isSelfClosing = true;\n // There cannot be any pending text here due to the onopentagstart that was\n // necessarily emitted before we get here. So we do not check text.\n (_a = this.openTagHandler) === null || _a === void 0 ? void 0 : _a.call(this, tag);\n (_b = this.closeTagHandler) === null || _b === void 0 ? void 0 : _b.call(this, tag);\n const top = this.tag = (_c = tags[tags.length - 1]) !== null && _c !== void 0 ? _c : null;\n if (top === null) {\n this.closedRoot = true;\n }\n this.state = S_TEXT;\n this.name = \"\";\n }\n /**\n * Handle a complete close tag. This parser code calls this once it has seen\n * the whole tag. This method checks for well-formeness and then emits\n * ``onclosetag``.\n */\n closeTag() {\n const { tags, name } = this;\n // Our state after this will be S_TEXT, no matter what, and we can clear\n // tagName now.\n this.state = S_TEXT;\n this.name = \"\";\n if (name === \"\") {\n this.fail(\"weird empty close tag.\");\n this.text += \"</>\";\n return;\n }\n const handler = this.closeTagHandler;\n let l = tags.length;\n while (l-- > 0) {\n const tag = this.tag = tags.pop();\n this.topNS = tag.ns;\n handler === null || handler === void 0 ? void 0 : handler(tag);\n if (tag.name === name) {\n break;\n }\n this.fail(\"unexpected close tag.\");\n }\n if (l === 0) {\n this.closedRoot = true;\n }\n else if (l < 0) {\n this.fail(`unmatched closing tag: ${name}.`);\n this.text += `</${name}>`;\n }\n }\n /**\n * Resolves an entity. Makes any necessary well-formedness checks.\n *\n * @param entity The entity to resolve.\n *\n * @returns The parsed entity.\n */\n parseEntity(entity) {\n // startsWith would be significantly slower for this test.\n if (entity[0] !== \"#\") {\n const defined = this.ENTITIES[entity];\n if (defined !== undefined) {\n return defined;\n }\n this.fail(this.isName(entity) ? \"undefined entity.\" :\n \"disallowed character in entity name.\");\n return `&${entity};`;\n }\n let num = NaN;\n if (entity[1] === \"x\" && /^#x[0-9a-f]+$/i.test(entity)) {\n num = parseInt(entity.slice(2), 16);\n }\n else if (/^#[0-9]+$/.test(entity)) {\n num = parseInt(entity.slice(1), 10);\n }\n // The character reference is required to match the CHAR production.\n if (!this.isChar(num)) {\n this.fail(\"malformed character entity.\");\n return `&${entity};`;\n }\n return String.fromCodePoint(num);\n }\n}\nexports.SaxesParser = SaxesParser;\n//# sourceMappingURL=saxes.js.map","interface MailboxItem<T> {\n value: T;\n next: MailboxItem<T> | null;\n}\n\nexport class Mailbox<T> {\n private _active: boolean = false;\n private _current: MailboxItem<T> | null = null;\n private _last: MailboxItem<T> | null = null;\n\n constructor(private _process: (ev: T) => void) {}\n\n public start() {\n this._active = true;\n this.flush();\n }\n\n public clear(): void {\n // we can't set _current to null because we might be currently processing\n // and enqueue following clear shouldn't start processing the enqueued item immediately\n if (this._current) {\n this._current.next = null;\n this._last = this._current;\n }\n }\n\n public enqueue(event: T): void {\n const enqueued = {\n value: event,\n next: null\n };\n\n if (this._current) {\n this._last!.next = enqueued;\n this._last = enqueued;\n return;\n }\n\n this._current = enqueued;\n this._last = enqueued;\n\n if (this._active) {\n this.flush();\n }\n }\n\n private flush() {\n while (this._current) {\n // atm the given _process is responsible for implementing proper try/catch handling\n // we assume here that this won't throw in a way that can affect this mailbox\n const consumed = this._current;\n this._process(consumed.value);\n this._current = consumed.next;\n }\n this._last = null;\n }\n}\n","export const STATE_DELIMITER = '.';\nexport const TARGETLESS_KEY = '';\nexport const NULL_EVENT = '';\nexport const STATE_IDENTIFIER = '#';\nexport const WILDCARD = '*';\nexport const XSTATE_INIT = '@xstate.init';\nexport const XSTATE_START = '@xstate.start';\nexport const XSTATE_SPAWN = '@xstate.spawn';\nexport const XSTATE_STOP = '@xstate.stop';\nexport const XSTATE_TERMINATE = '@xstate.terminate';\nexport const XSTATE_TIMER = 'xstate.timer';\n\nexport const XSTATE_LOGIC_EFFECT_RESOLVE = 'xstate.logic.effect.resolve';\nexport const XSTATE_LOGIC_EFFECT_REJECT = 'xstate.logic.effect.reject';\nexport const XSTATE_LOGIC_EFFECT_START = 'xstate.logic.effect.start';\n","import { XSTATE_INIT } from './constants.ts';\nimport {\n ActorTimeoutEvent,\n AfterEvent,\n DoneActorEvent,\n DoneStateEvent,\n ErrorActorEvent,\n ErrorPlatformEvent,\n TimeoutEvent\n} from './types.ts';\n\n/**\n * Returns an event that represents an implicit event that is sent after the\n * specified `delay`.\n *\n * @param delayRef The delay in milliseconds\n * @param id The state node ID where this event is handled\n */\nexport function createAfterEvent(\n delayRef: number | string,\n id: string\n): AfterEvent {\n return { type: 'xstate.after', delay: delayRef, stateId: id };\n}\n\nexport function createAfterEventId(delayRef: number | string, id: string) {\n return `xstate.after.${delayRef}.${id}`;\n}\n\n/**\n * Returns an event that represents an implicit state-level timeout. Fired when\n * a state's `timeout` duration elapses without the state being exited.\n *\n * @param id The state node ID where this timeout is configured\n */\nexport function createTimeoutEvent(id: string): TimeoutEvent {\n return { type: 'xstate.timeout', stateId: id };\n}\n\nexport function createTimeoutEventId(id: string) {\n return `xstate.timeout.${id}`;\n}\n\n/**\n * Returns an event that represents an implicit invoke-level timeout. Fired when\n * an invoked actor has not completed within its `timeout` duration.\n *\n * @param invokeId The invoked actor's ID\n */\nexport function createInvokeTimeoutEvent(\n invokeId: string,\n sessionId?: string\n): ActorTimeoutEvent {\n return {\n type: 'xstate.timeout.actor',\n actorId: invokeId,\n sessionId\n };\n}\n\nexport function createInvokeTimeoutEventId(invokeId: string) {\n return `xstate.timeout.actor.${invokeId}`;\n}\n\n/**\n * Returns an event that represents that a final state node has been reached in\n * the parent state node.\n *\n * @param id The final state node's parent state node `id`\n * @param output The data to pass into the event\n */\nexport function createDoneStateEvent(\n id: string,\n output?: unknown\n): DoneStateEvent {\n return {\n type: 'xstate.done.state',\n stateId: id,\n output\n };\n}\n\n/**\n * Returns an event that represents that an invoked service has terminated.\n *\n * An invoked service is terminated when it has reached a top-level final state\n * node, but not when it is canceled.\n *\n * @param invokeId The invoked service ID\n * @param output The data to pass into the event\n * @param sessionId The unique session ID of the completed actor\n */\nexport function createDoneActorEvent(\n invokeId: string,\n output: unknown,\n sessionId: string\n): DoneActorEvent {\n return {\n type: 'xstate.done.actor',\n output,\n actorId: invokeId,\n sessionId\n };\n}\n\nexport function createErrorActorEvent(\n id: string,\n error: unknown,\n sessionId: string\n): ErrorActorEvent {\n return {\n type: 'xstate.error.actor',\n error,\n actorId: id,\n sessionId\n };\n}\n\nexport function createErrorPlatformEvent(\n kind: string,\n error?: unknown\n): ErrorPlatformEvent {\n return { type: `xstate.error.${kind}`, error };\n}\n\nexport function createInitEvent(input: unknown) {\n return { type: XSTATE_INIT, input } as const;\n}\n","/**\n * This function makes sure that unhandled errors are thrown in a separate\n * macrotask. It allows those errors to be detected by global error handlers and\n * reported to bug tracking services without interrupting our own stack of\n * execution.\n *\n * @param err Error to be thrown\n */\nexport function reportUnhandledError(err: unknown) {\n setTimeout(() => {\n throw err;\n });\n}\n","export const symbolObservable: typeof Symbol.observable = (() =>\n (typeof Symbol === 'function' && Symbol.observable) ||\n '@@observable')() as any;\n","import isDevelopment from '#is-development';\nimport {\n type ActorTermination,\n AnyActor,\n AnyActorScope,\n EventObject\n} from './types';\n\nexport function assertSendToEvent(event: EventObject): void {\n if (typeof event === 'string') {\n throw new Error(\n isDevelopment\n ? // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n `Only event objects may be used with sendTo; use sendTo({ type: \"${event}\" }) instead`\n : `Only event objects may be used with sendTo`\n );\n }\n}\n\nexport const builtInActions = {\n // Actor refs are created while resolving the next snapshot. Starting is a\n // separate deferred effect so the returned list remains execution-complete.\n ['@xstate.spawn']: (actor: AnyActor) => {\n return actor.system.spawnActor(actor._parent, actor);\n },\n ['@xstate.start']: (actor: AnyActor) => {\n return actor.system.startActor(actor);\n },\n ['@xstate.raise']: (\n actorScope: AnyActorScope,\n _event: EventObject,\n options: { id?: string; delay?: number }\n ) => {\n return actorScope.system.scheduleTimer(\n actorScope.self,\n options.id!,\n options?.delay ?? 0\n );\n },\n ['@xstate.sendTo']: (\n actorScope: AnyActorScope,\n actor: AnyActor,\n event: EventObject,\n options: { id?: string; delay?: number }\n ) => {\n assertSendToEvent(event);\n if (options?.delay !== undefined) {\n return actorScope.system.scheduleTimer(\n actorScope.self,\n options.id!,\n options?.delay ?? 0\n );\n } else {\n return actorScope.system._relay(actorScope.self, actor, event);\n }\n },\n ['@xstate.cancel']: (actorScope: AnyActorScope, sendId: string) => {\n return actorScope.system.cancelTimer(actorScope.self, sendId);\n },\n ['@xstate.stop']: (actorScope: AnyActorScope, actor: AnyActor) => {\n return actorScope.system.stopActor(actor);\n },\n ['@xstate.terminate']: (actor: AnyActor, termination: ActorTermination) => {\n return actor.system.terminateActor(actor, termination);\n }\n};\n","import type { AnyActorLogic } from './types.ts';\n\nconst sourceKeyCaches = new WeakMap<object, Map<AnyActorLogic, string>>();\n\n/** @internal */\nexport function resolveRegisteredActorSource(\n actors: Record<string, AnyActorLogic>,\n logic: AnyActorLogic\n): string | undefined {\n let cache = sourceKeyCaches.get(actors);\n if (!cache) {\n cache = new Map();\n for (const key of Object.keys(actors)) {\n const registeredLogic = actors[key];\n // Several source keys may intentionally share one implementation. The\n // first key is its canonical persistence identity when spawning by the\n // raw logic value, which cannot retain which alias was used to access it.\n if (!cache.has(registeredLogic)) {\n cache.set(registeredLogic, key);\n }\n }\n sourceKeyCaches.set(actors, cache);\n }\n\n return cache.get(logic);\n}\n","import { XSTATE_STOP } from '../constants.ts';\nimport type { AnyActorSystem } from '../system.ts';\nimport type {\n AnyActor,\n EventObject,\n Snapshot,\n Subscription\n} from '../types.ts';\n\nconst subscriptions = /* #__PURE__ */ new WeakMap<AnyActor, Subscription>();\n\n/**\n * Internal factory for actor logic that attaches to another actor on start\n * (`enq.listen()` / `enq.subscribeTo()`) and detaches when stopped.\n */\nexport function createAttachedLogic(\n attach: (\n input: any,\n scope: { self: AnyActor; system: AnyActorSystem }\n ) => Subscription | undefined,\n /**\n * Names the logic so its generated actor ids get their own prefix, out of\n * the id space that user sources allocate from.\n */\n id?: string\n): any {\n const initialTransition = (input: unknown, _: unknown) =>\n [\n {\n status: 'active',\n output: undefined,\n error: undefined,\n input\n },\n []\n ] as const;\n\n return {\n id,\n start: (state: any, { self, system }: any) => {\n // Don't attach if the target doesn't exist or is stopped.\n const target = state.input.actor;\n if (!target || target.getSnapshot().status === 'stopped') {\n return;\n }\n const subscription = attach(state.input, { self, system });\n if (!subscription) {\n return;\n }\n\n // Attached actors are not registered as children (their `input` holds\n // non-serializable function mappers), so a parent stop does not cascade\n // to them. Subscribe to the parent and tear down when it stops/errors,\n // so the subscription never relays to a stopped parent or leaks the\n // source subscription.\n let parentSubscription: Subscription | undefined;\n let torndown = false;\n const teardown = () => {\n if (torndown) {\n return;\n }\n torndown = true;\n subscription.unsubscribe();\n parentSubscription?.unsubscribe();\n };\n\n const parent: AnyActor | undefined = self._parent;\n if (parent) {\n parentSubscription = parent.subscribe({\n complete: teardown,\n error: teardown\n });\n }\n\n subscriptions.set(self, { unsubscribe: teardown });\n },\n transition: (state: any, event: EventObject, { self }: any) => {\n if (event.type === XSTATE_STOP) {\n subscriptions.get(self)?.unsubscribe();\n subscriptions.delete(self);\n return [\n {\n ...state,\n status: 'stopped',\n error: undefined\n },\n []\n ];\n }\n return [state, []];\n },\n initialTransition,\n getInitialSnapshot: (actorScope: unknown, input: unknown) =>\n initialTransition(input, actorScope)[0],\n getPersistedSnapshot: (snapshot: Snapshot<unknown>) => snapshot,\n restoreSnapshot: (snapshot: Snapshot<unknown>) => snapshot\n };\n}\n\n/**\n * Relays a mapped event to the attached actor's parent, unless the attached\n * actor has been stopped (the mapper is not called in that case).\n */\nexport function relayMappedToParent(\n self: AnyActor,\n system: AnyActorSystem,\n getEvent: () => EventObject\n): void {\n if (self.getSnapshot().status === 'stopped' || !self._parent) {\n return;\n }\n system._relay(self, self._parent, getEvent());\n}\n","import { AnyActorSystem } from '../system.ts';\nimport { matchesEventDescriptor } from '../utils.ts';\nimport {\n ActorLogic,\n ActorRefFromLogic,\n AnyActor,\n EventObject,\n Snapshot\n} from '../types';\nimport { createAttachedLogic, relayMappedToParent } from './attached.ts';\n\nexport type ListenerSnapshot = Snapshot<undefined> & {\n input: ListenerInput<any, any>;\n};\n\nexport interface ListenerInput<\n TEmitted extends EventObject,\n TMappedEvent extends EventObject\n> {\n actor: AnyActor;\n eventType: string;\n mapper: (event: TEmitted) => TMappedEvent;\n}\n\nexport type ListenerActorLogic<\n TEmitted extends EventObject = EventObject,\n TMappedEvent extends EventObject = EventObject\n> = ActorLogic<\n ListenerSnapshot,\n EventObject,\n ListenerInput<TEmitted, TMappedEvent>,\n AnyActorSystem,\n EventObject\n>;\n\nexport type ListenerActorRef<\n TEmitted extends EventObject = EventObject,\n TMappedEvent extends EventObject = EventObject\n> = ActorRefFromLogic<ListenerActorLogic<TEmitted, TMappedEvent>>;\n\n/**\n * Creates actor logic for listening to emitted events from another actor. Used\n * internally by `enq.listen()`.\n */\nexport function createListenerLogic<\n TEmitted extends EventObject = EventObject,\n TMappedEvent extends EventObject = EventObject\n>(): ListenerActorLogic<TEmitted, TMappedEvent> {\n return createAttachedLogic(\n (\n { actor, eventType, mapper }: ListenerInput<TEmitted, TMappedEvent>,\n { self, system }\n ) => {\n // Determine the subscription type:\n // - For exact matches or '*', subscribe directly\n // - For partial wildcards ('data.*'), subscribe to '*' and filter\n const isPartialWildcard = eventType !== '*' && eventType.endsWith('.*');\n\n return actor.on(isPartialWildcard ? '*' : eventType, (emittedEvent) => {\n if (\n isPartialWildcard &&\n !matchesEventDescriptor(emittedEvent.type, eventType)\n ) {\n return;\n }\n relayMappedToParent(self, system, () =>\n mapper(emittedEvent as TEmitted)\n );\n });\n },\n 'xstate.listener'\n );\n}\n\n// Singleton logic instance\nexport const listenerLogic = /* #__PURE__ */ createListenerLogic();\n","import { AnyActorSystem } from '../system.ts';\nimport {\n ActorLogic,\n ActorRefFromLogic,\n AnyActorRef,\n EventObject,\n Snapshot\n} from '../types';\nimport { createAttachedLogic, relayMappedToParent } from './attached.ts';\n\nexport type SubscriptionSnapshot = Snapshot<undefined> & {\n input: SubscriptionInput<any, any, any, any>;\n};\n\nexport interface SubscriptionMappers<\n TSnapshot extends Snapshot<unknown>,\n TOutput,\n TMappedEvent extends EventObject\n> {\n snapshot?: (snapshot: TSnapshot) => TMappedEvent;\n done?: (output: TOutput) => TMappedEvent;\n error?: (error: unknown) => TMappedEvent;\n}\n\nexport interface SubscriptionInput<\n TSnapshot extends Snapshot<unknown>,\n TOutput,\n TMappedEvent extends EventObject,\n TMappers extends SubscriptionMappers<TSnapshot, TOutput, TMappedEvent>\n> {\n actor: AnyActorRef;\n mappers: TMappers;\n}\n\nexport type SubscriptionActorLogic<\n TSnapshot extends Snapshot<unknown> = Snapshot<unknown>,\n TOutput = unknown,\n TMappedEvent extends EventObject = EventObject\n> = ActorLogic<\n SubscriptionSnapshot,\n EventObject,\n SubscriptionInput<\n TSnapshot,\n TOutput,\n TMappedEvent,\n SubscriptionMappers<TSnapshot, TOutput, TMappedEvent>\n >,\n AnyActorSystem,\n EventObject\n>;\n\nexport type SubscriptionActorRef<\n TSnapshot extends Snapshot<unknown> = Snapshot<unknown>,\n TOutput = unknown,\n TMappedEvent extends EventObject = EventObject\n> = ActorRefFromLogic<SubscriptionActorLogic<TSnapshot, TOutput, TMappedEvent>>;\n\n/**\n * Creates actor logic for subscribing to lifecycle events (done/error/snapshot)\n * from another actor. Used internally by `enq.subscribeTo()`.\n */\nexport function createSubscriptionLogic<\n TSnapshot extends Snapshot<unknown> = Snapshot<unknown>,\n TOutput = unknown,\n TMappedEvent extends EventObject = EventObject\n>(): SubscriptionActorLogic<TSnapshot, TOutput, TMappedEvent> {\n return createAttachedLogic(({ actor, mappers }, { self, system }) => {\n const { done, error, snapshot: onSnapshot } = mappers;\n\n return actor.subscribe({\n next: (snapshot: TSnapshot) => {\n if (snapshot.status === 'done' && done) {\n relayMappedToParent(self, system, () =>\n done(snapshot.output as TOutput)\n );\n } else if (snapshot.status === 'error' && error) {\n relayMappedToParent(self, system, () => error(snapshot.error));\n } else if (snapshot.status === 'active' && onSnapshot) {\n relayMappedToParent(self, system, () => onSnapshot(snapshot));\n }\n },\n error: (err: unknown) => {\n if (error) {\n relayMappedToParent(self, system, () => error(err));\n }\n },\n complete: () => {\n // Actor completed without output (stopped); no action needed\n }\n });\n }, 'xstate.subscription');\n}\n\n// Singleton logic instance\nexport const subscriptionLogic = /* #__PURE__ */ createSubscriptionLogic();\n","import type { AnyActor, AnyActorScope } from './types.ts';\n\n/** Marks the internal lazy scope without imposing structure on custom runtimes. @internal */\nexport const lazyActorScope = Symbol();\n\ntype InternalActorScope = AnyActorScope & {\n _parent?: AnyActor;\n [lazyActorScope]?: true;\n};\n\n/** Whether actor capabilities are represented by a lazy pure-transition scope. @internal */\nexport function isLazyActorScope(actorScope: AnyActorScope): boolean {\n return !!(actorScope as InternalActorScope)[lazyActorScope];\n}\n\n/** Reads parent metadata without otherwise touching actor capabilities. @internal */\nexport function getActorScopeParent(\n actorScope: AnyActorScope\n): AnyActor | undefined {\n return isLazyActorScope(actorScope)\n ? (actorScope as InternalActorScope)._parent\n : actorScope.self._parent;\n}\n\n/** Adds only `self`, preserving callback surfaces that expose no other capabilities. @internal */\nexport function withActorSelf<T extends object>(\n args: T,\n actorScope: AnyActorScope\n): T & Pick<AnyActorScope, 'self'> {\n if (!isLazyActorScope(actorScope)) {\n return Object.assign(args, { self: actorScope.self });\n }\n Object.defineProperty(args, 'self', {\n enumerable: true,\n get: () => actorScope.self\n });\n return args as T & Pick<AnyActorScope, 'self'>;\n}\n\n/** Adds the actor reference and parent without exposing the system. @internal */\nexport function withActorSelfAndParent<T extends object>(\n args: T,\n actorScope: AnyActorScope\n): T & Pick<AnyActorScope, 'self'> & { parent: AnyActor | undefined } {\n if (!isLazyActorScope(actorScope)) {\n const self = actorScope.self;\n return Object.assign(args, { self, parent: self._parent });\n }\n Object.defineProperties(args, {\n self: { enumerable: true, get: () => actorScope.self },\n parent: { enumerable: true, get: () => getActorScopeParent(actorScope) }\n });\n return args as T &\n Pick<AnyActorScope, 'self'> & { parent: AnyActor | undefined };\n}\n\n/** Adds actor capabilities without reading them until the callback does. @internal */\nexport function withActorScope<T extends object>(\n args: T,\n actorScope: AnyActorScope\n): T &\n Pick<AnyActorScope, 'self' | 'system'> & {\n parent: AnyActor | undefined;\n } {\n if (!isLazyActorScope(actorScope)) {\n const actorArgs = args as T &\n Pick<AnyActorScope, 'self' | 'system'> & {\n parent: AnyActor | undefined;\n };\n const self = actorScope.self;\n actorArgs.self = self;\n actorArgs.system = actorScope.system;\n actorArgs.parent = self._parent;\n return actorArgs;\n }\n Object.defineProperties(args, {\n self: { enumerable: true, get: () => actorScope.self },\n system: { enumerable: true, get: () => actorScope.system },\n parent: { enumerable: true, get: () => getActorScopeParent(actorScope) }\n });\n return args as T &\n Pick<AnyActorScope, 'self' | 'system'> & {\n parent: AnyActor | undefined;\n };\n}\n","import isDevelopment from '#is-development';\nimport { assertSendToEvent, builtInActions } from './actions.ts';\nimport { resolveRegisteredActorSource } from './actorSource.ts';\nimport { listenerLogic, type ListenerInput } from './actors/listener.ts';\nimport {\n subscriptionLogic,\n type SubscriptionInput,\n type SubscriptionMappers\n} from './actors/subscription.ts';\nimport { XSTATE_SPAWN, XSTATE_START, XSTATE_TERMINATE } from './constants.ts';\nimport { createErrorPlatformEvent } from './eventUtils.ts';\nimport {\n getActorIdPrefix,\n parseGeneratedActorId,\n type ActorSystemRuntime,\n type DeadLetterDetail,\n type EventRejectionReason\n} from './system.ts';\nimport { isLazyActorScope, withActorScope } from './actorScope.ts';\nimport { getEventOutput } from './utils.ts';\nimport type {\n Action,\n ActorTermination,\n AnyAction,\n AnyActor,\n AnyActorLogic,\n AnyActorScope,\n AnyEventObject,\n AnyMachineSnapshot,\n CancelExecutableActionObject,\n CustomExecutableActionObject,\n EmitExecutableActionObject,\n EnqueueObject,\n EventObject,\n ExecutableActionObject,\n MachineContext,\n RaiseExecutableActionObject,\n DeadLetterExecutableActionObject,\n SendToExecutableActionObject,\n Snapshot,\n SpecialExecutableAction,\n SpawnExecutableActionObject,\n StartExecutableActionObject,\n StopExecutableActionObject,\n TerminateExecutableActionObject\n} from './types.ts';\n\ntype TransitionActionRecord = {\n action: (...args: any[]) => any;\n args: any[];\n childUpdate?:\n | {\n type: 'add';\n actor: AnyActor;\n id: string;\n counters?: Record<string, number>;\n }\n | { type: 'remove'; actor: AnyActor };\n};\n\ntype EffectRuntime = Partial<ActorSystemRuntime>;\n\nfunction execCustomEffect(\n this: CustomExecutableActionObject\n): void | PromiseLike<void> | undefined {\n return this.action?.(...this.args);\n}\n\nfunction execEmitEffect(\n this: EmitExecutableActionObject,\n runtime: EffectRuntime = this.source.system\n): void | PromiseLike<void> {\n return runtime.emitEvent!(this.source, this.event);\n}\n\n/** @internal Creates an emitted-event effect. */\nexport function createEmitEffect(\n actorScope: AnyActorScope,\n event: EventObject\n): EmitExecutableActionObject {\n return {\n kind: 'emit',\n exec: execEmitEffect,\n type: event.type,\n source: actorScope.self,\n event,\n params: undefined,\n args: []\n };\n}\n\nfunction execDeadLetterEffect(\n this: DeadLetterExecutableActionObject,\n runtime: EffectRuntime = this.target.system\n): void | PromiseLike<void> {\n return runtime.deadLetter!(\n this.source,\n this.target,\n this.event,\n this.reason,\n this.detail\n );\n}\n\n/** @internal Creates a dead-letter effect for a boundary-rejected event. */\nexport function createDeadLetterEffect(\n actorScope: AnyActorScope,\n source: AnyActor | undefined,\n event: AnyEventObject,\n reason: EventRejectionReason,\n detail?: DeadLetterDetail\n): DeadLetterExecutableActionObject {\n return {\n kind: 'builtin',\n type: '@xstate.deadLetter',\n exec: execDeadLetterEffect,\n source,\n target: actorScope.self,\n event,\n reason,\n detail,\n params: undefined,\n args: []\n };\n}\n\n/** @internal Creates a directly executable user effect. */\nexport function createCustomEffect(\n type: string,\n action: (runtime?: EffectRuntime) => void | PromiseLike<void> | undefined,\n params?: unknown\n): CustomExecutableActionObject {\n return {\n kind: 'action',\n exec: action,\n type,\n action: action as () => void | PromiseLike<void>,\n params,\n args: []\n };\n}\n\nfunction execSpawnEffect(\n this: SpawnExecutableActionObject,\n runtime: EffectRuntime = this.actor.system\n): void | PromiseLike<void> {\n return runtime.spawnActor!(this.source, this.actor);\n}\n\nfunction execStartEffect(\n this: StartExecutableActionObject,\n runtime: EffectRuntime = this.actor.system\n): void | PromiseLike<void> {\n return runtime.startActor!(this.actor);\n}\n\nfunction execStopEffect(\n this: StopExecutableActionObject,\n runtime: EffectRuntime = this.source.system\n): void | PromiseLike<void> {\n return runtime.stopActor!(this.actor);\n}\n\nfunction execTerminateEffect(\n this: TerminateExecutableActionObject,\n runtime: EffectRuntime = this.actor.system\n): void | PromiseLike<void> {\n const termination: ActorTermination =\n this.status === 'done'\n ? { status: 'done', output: this.output, error: undefined }\n : { status: 'error', output: undefined, error: this.error };\n return runtime.terminateActor!(this.actor, termination);\n}\n\nfunction execRaiseEffect(\n this: RaiseExecutableActionObject,\n runtime: EffectRuntime = this.source.system\n): void | PromiseLike<void> {\n return runtime.scheduleTimer!(this.source, this.id!, this.delay ?? 0);\n}\n\nfunction execSendToEffect(\n this: SendToExecutableActionObject,\n runtime: EffectRuntime = this.source.system\n): void | PromiseLike<void> {\n assertSendToEvent(this.event);\n if (this.delay !== undefined) {\n return runtime.scheduleTimer!(this.source, this.id!, this.delay);\n }\n return runtime.sendEvent!(this.source, this.target, this.event);\n}\n\nfunction execCancelEffect(\n this: CancelExecutableActionObject,\n runtime: EffectRuntime = this.source.system\n): void | PromiseLike<void> {\n return runtime.cancelTimer!(this.source, this.id);\n}\n\nfunction updateLogicalTimers(\n snapshot: AnyMachineSnapshot,\n effect: ExecutableActionObject,\n actorScope: AnyActorScope\n): AnyMachineSnapshot {\n if (!isBuiltInExecutableAction(effect)) {\n return snapshot;\n }\n\n if (effect.type === '@xstate.cancel') {\n if (!snapshot.timers?.[effect.id]) {\n return snapshot;\n }\n const timers = { ...snapshot.timers };\n delete timers[effect.id];\n return { ...snapshot, timers };\n }\n\n if (\n (effect.type !== '@xstate.raise' && effect.type !== '@xstate.sendTo') ||\n effect.delay === undefined\n ) {\n return snapshot;\n }\n\n let nextTimerId = snapshot._nextTimerId ?? 0;\n const id = effect.id ?? `xstate.timer.auto.${nextTimerId++}`;\n effect.id = id;\n const target =\n effect.type === '@xstate.raise' || effect.target === actorScope.self\n ? 'self'\n : effect.target;\n\n return {\n ...snapshot,\n timers: {\n ...snapshot.timers,\n [id]: {\n id,\n delay: effect.delay,\n type: effect.type,\n event: effect.event,\n target\n }\n },\n _nextTimerId: nextTimerId\n };\n}\n\nexport function mergeContextPatch(\n context: MachineContext,\n patch: MachineContext\n): MachineContext {\n return { ...context, ...patch };\n}\n\nfunction pushBuiltInAction(actions: any[], action: any, ...args: any[]) {\n const actionRecord: TransitionActionRecord = { action, args };\n actions.push(actionRecord as AnyAction);\n return actionRecord;\n}\n\n/** @internal Max-merges generated-id counter records, copy-on-write. */\nexport function mergeActorIdCounters(\n current: Record<string, number> | undefined,\n update: Record<string, number>\n): Record<string, number> {\n const merged = { ...current };\n for (const key of Object.keys(update)) {\n merged[key] = Math.max(merged[key] ?? 0, update[key]);\n }\n return merged;\n}\n\nfunction applyChildUpdate(\n snapshot: AnyMachineSnapshot,\n update: NonNullable<TransitionActionRecord['childUpdate']>,\n actorScope: AnyActorScope\n): AnyMachineSnapshot {\n if (update.type === 'add') {\n return {\n ...snapshot,\n children: { ...snapshot.children, [update.id]: update.actor },\n ...(update.counters && {\n _nextActorIds: mergeActorIdCounters(\n snapshot._nextActorIds,\n update.counters\n )\n })\n };\n }\n\n const children = { ...snapshot.children };\n let owned = update.actor._parent === actorScope.self;\n for (const key of Object.keys(children)) {\n if (children[key] === update.actor) {\n owned = true;\n delete children[key];\n }\n }\n if (!owned) {\n throw new Error(\n isDevelopment\n ? `Cannot stop child actor ${update.actor.id} of ${actorScope.self.id} because it is not a child`\n : `Cannot stop non-child actor ${update.actor.id}`\n );\n }\n actorScope.system._unregister(update.actor);\n return { ...snapshot, children };\n}\n\nfunction getTransitionActionRecord(\n action: AnyAction\n): TransitionActionRecord | undefined {\n if (\n typeof action === 'object' &&\n action !== null &&\n 'action' in action &&\n typeof action.action === 'function'\n ) {\n return action as TransitionActionRecord;\n }\n return undefined;\n}\n\nfunction pushSpawnedChild(\n actions: any[],\n actor: AnyActor,\n id: string,\n counters?: Record<string, number>\n) {\n const action = pushBuiltInAction(\n actions,\n builtInActions['@xstate.spawn'],\n actor\n );\n action.childUpdate = { type: 'add', actor, id, counters };\n}\n\n/**\n * Spawn-allocation state shared by every enqueue object of one transition, so\n * generated ids stay unique and resolvable across action functions and\n * microsteps of the same event.\n */\ninterface SpawnAllocation {\n counters: Map<string, number>;\n /** Explicit child ids claimed by spawns/invokes of this transition. */\n explicitIds: Set<string>;\n /** Ids of children stopped by this transition, freeing them for reuse. */\n stoppedIds: Set<string>;\n}\n\nconst spawnAllocations = new WeakMap<object, SpawnAllocation>();\n\nconst createSpawnAllocation = (): SpawnAllocation => ({\n counters: new Map(),\n explicitIds: new Set(),\n stoppedIds: new Set()\n});\n\n/**\n * Starts a fresh spawn-allocation transaction for one logical transition.\n * Called at every transition boundary so pure replays from the same snapshot\n * allocate identical ids.\n *\n * @internal\n */\nexport function beginSpawnAllocation(actorScope: AnyActorScope): void {\n spawnAllocations.set(actorScope, createSpawnAllocation());\n}\n\n// Read the raw snapshot: getSnapshot() throws while the actor initializes,\n// and entry actions run before any snapshot exists.\nfunction getWorkingSnapshotOf(actorScope: AnyActorScope):\n | {\n _nextActorIds?: Record<string, number>;\n children?: Record<string, AnyActor | undefined>;\n }\n | undefined {\n return (\n actorScope.self as {\n _snapshot?: {\n _nextActorIds?: Record<string, number>;\n children?: Record<string, AnyActor | undefined>;\n };\n }\n )._snapshot;\n}\n\nfunction getRegisteredActors(\n actorScope: AnyActorScope\n): Record<string, AnyActorLogic> | undefined {\n return (\n actorScope.self as {\n logic?: { sources?: { actors?: Record<string, AnyActorLogic> } };\n }\n ).logic?.sources?.actors;\n}\n\nfunction resolveTransitionSpawnSource(\n actorScope: AnyActorScope,\n source: string | AnyActorLogic\n): { logic: AnyActorLogic; src: string | undefined } {\n const registeredActors = getRegisteredActors(actorScope);\n if (typeof source === 'string') {\n const logic = registeredActors?.[source];\n if (!logic) {\n throw new Error(`Actor source '${source}' is not provided`);\n }\n return { logic, src: source };\n }\n if (!registeredActors) {\n return { logic: source, src: undefined };\n }\n return {\n logic: source,\n src: resolveRegisteredActorSource(registeredActors, source)\n };\n}\n\n/**\n * Internal helper actors (listeners, subscriptions) number their ids from\n * system-level counters under `xstate.`-prefixed names; snapshot-owned\n * children number from per-snapshot counters. The two spaces only stay\n * collision-free because their prefixes are disjoint, so user sources must\n * not enter the reserved namespace.\n */\nfunction assertUnreservedPrefix(prefix: string): void {\n if (isDevelopment && prefix.startsWith('xstate.')) {\n throw new Error(\n `Child actor ids with the \"xstate.\" prefix are reserved for internal actors; rename the \"${prefix}\" source or logic id.`\n );\n }\n}\n\n/**\n * The next free index for a prefix. The parent snapshot's persisted counter\n * is always a floor, so a freed id is never handed out again — not even when\n * an explicit id reserved a lower one earlier in the transition.\n */\nfunction nextChildIndex(\n actorScope: AnyActorScope,\n allocation: SpawnAllocation,\n prefix: string\n): number {\n return Math.max(\n allocation.counters.get(prefix) ?? 0,\n getWorkingSnapshotOf(actorScope)?._nextActorIds?.[prefix] ?? 0\n );\n}\n\n/**\n * Allocates the next generated child id for the transition's allocation\n * transaction, seeded from the parent snapshot's own persisted counters. This\n * is the single allocator for snapshot-owned children (`enq.spawn` and\n * context-factory spawns); a correct allocation cannot collide.\n *\n * @internal\n */\nexport function allocateChildId(\n actorScope: AnyActorScope,\n src: string | AnyActorLogic,\n localAllocation?: SpawnAllocation\n): { id: string; counters: Record<string, number> } {\n if (isDevelopment && !spawnAllocations.get(actorScope)) {\n console.warn(\n 'A child id was generated outside a spawn-allocation transaction; ids may repeat across enqueue objects. Transition entry points must call beginSpawnAllocation().'\n );\n }\n const allocation =\n spawnAllocations.get(actorScope) ??\n localAllocation ??\n createSpawnAllocation();\n const prefix = getActorIdPrefix(src);\n assertUnreservedPrefix(prefix);\n const next = nextChildIndex(actorScope, allocation, prefix);\n allocation.counters.set(prefix, next + 1);\n return { id: `${prefix}:${next}`, counters: { [prefix]: next + 1 } };\n}\n\n/**\n * Requires an explicit child id to be unoccupied before a spawn or invoke\n * claims it: an address must name at most one live actor. An id is occupied\n * when a child of this parent already holds it and this transition has not\n * stopped that child, or when an earlier spawn of this transition claimed it.\n *\n * @internal\n */\nexport function assertChildIdFree(\n actorScope: AnyActorScope,\n id: string,\n localAllocation?: SpawnAllocation\n): void {\n const allocation =\n spawnAllocations.get(actorScope) ??\n localAllocation ??\n createSpawnAllocation();\n const existing = getWorkingSnapshotOf(actorScope)?.children?.[id] as\n | AnyActor\n | undefined;\n // A terminated child no longer occupies its id: it relayed its completion\n // and is removed from `children` right after the transition handling it,\n // so the supervisor pattern — respawn under the same name while handling\n // the child's done/error event — must not conflict with the outgoing\n // entry. Remote handles never expose a terminal status locally; the\n // completion event that removes one is the owning runtime's business.\n const occupied =\n existing !== undefined &&\n !allocation.stoppedIds.has(id) &&\n existing.getSnapshot().status === 'active';\n if (allocation.explicitIds.has(id) || occupied) {\n throw new Error(\n isDevelopment\n ? `Cannot spawn child actor with id '${id}': the id is already in use by another child of '${actorScope.self.id}'. Stop the existing child before reusing its id.`\n : `Child actor id '${id}' is already in use`\n );\n }\n allocation.explicitIds.add(id);\n}\n\n/**\n * Records that this transition stopped a child, freeing its id for a later\n * spawn or invoke of the same transition (the invoke restart pattern).\n *\n * @internal\n */\nfunction recordStoppedChild(actorScope: AnyActorScope, actor: AnyActor): void {\n const allocation = spawnAllocations.get(actorScope);\n if (allocation) {\n allocation.stoppedIds.add(actor.id);\n allocation.explicitIds.delete(actor.id);\n }\n}\n\n/**\n * Reserves an explicit generated-shaped id (`worker:5`) in the transaction\n * and the parent snapshot, so live runs and pure replays allocate the same\n * later ids even after this child is removed.\n *\n * @internal\n */\nexport function reserveChildId(\n actorScope: AnyActorScope,\n id: string,\n localAllocation?: SpawnAllocation\n): Record<string, number> | undefined {\n const generated = parseGeneratedActorId(id);\n if (!generated) {\n return undefined;\n }\n assertUnreservedPrefix(generated.prefix);\n const allocation =\n spawnAllocations.get(actorScope) ??\n localAllocation ??\n createSpawnAllocation();\n // The requested id is used as asked, but numbering continues from the\n // highest reservation: an explicit low id never rewinds the counter.\n const next = Math.max(\n nextChildIndex(actorScope, allocation, generated.prefix),\n generated.index + 1\n );\n allocation.counters.set(generated.prefix, next);\n return { [generated.prefix]: next };\n}\n\n/**\n * The counters allocated so far in the transition's transaction, for\n * committing into a snapshot built outside `applyChildUpdate` (the\n * pre-initial snapshot with context-factory spawns).\n *\n * @internal\n */\nexport function takeSpawnAllocationCounters(\n actorScope: AnyActorScope\n): Record<string, number> | undefined {\n const counters = spawnAllocations.get(actorScope)?.counters;\n if (!counters?.size) {\n return undefined;\n }\n return Object.fromEntries(counters);\n}\n\nexport function createTransitionEnqueue(\n actorScope: AnyActorScope,\n actions: any[],\n internalEvents: EventObject[],\n actorSubscriptions = false,\n createActors = true\n) {\n // Paths that never begin a transaction keep a per-enqueue scope.\n const localAllocation =\n spawnAllocations.get(actorScope) ?? createSpawnAllocation();\n const props: Partial<EnqueueObject<any, any>> = {\n cancel: (id: string) => {\n pushBuiltInAction(\n actions,\n builtInActions['@xstate.cancel'],\n actorScope,\n id\n );\n },\n emit: (emittedEvent) => {\n actions.push(emittedEvent);\n },\n log: (...args) => {\n pushBuiltInAction(actions, actorScope.logger, ...args);\n },\n raise: (raisedEvent, options) => {\n if (typeof raisedEvent === 'string') {\n throw new Error(\n isDevelopment\n ? `Only event objects may be used with raise; use raise({ type: \"${raisedEvent}\" }) instead`\n : `Only event objects may be used with raise`\n );\n }\n if (options?.delay !== undefined) {\n pushBuiltInAction(\n actions,\n builtInActions['@xstate.raise'],\n actorScope,\n raisedEvent,\n options\n );\n } else {\n internalEvents.push(raisedEvent);\n }\n },\n spawn: (source: string | AnyActorLogic, options: any) => {\n const { logic, src } = resolveTransitionSpawnSource(actorScope, source);\n if (!createActors) {\n // TODO: replace this speculative placeholder with a typed inert actor ref.\n return {\n id: options?.id ?? options?.registryKey ?? src ?? (logic as any).id\n } as AnyActor;\n }\n // Generated ids allocate from the parent snapshot's own counters\n // through the transition's allocation transaction; explicit\n // generated-shaped ids reserve their numbering the same way.\n let id = options?.id;\n let counters: Record<string, number> | undefined;\n if (id === undefined) {\n ({ id, counters } = allocateChildId(\n actorScope,\n src ?? logic,\n localAllocation\n ));\n } else {\n assertChildIdFree(actorScope, id, localAllocation);\n counters = reserveChildId(actorScope, id, localAllocation);\n }\n const actor = actorScope.system.createActorRef(logic, {\n ...options,\n ...(src !== undefined && { src }),\n id,\n parent: actorScope.self\n });\n pushSpawnedChild(actions, actor, id, counters);\n return actor;\n },\n sendTo: (actor, event, options) => {\n if (!actor) {\n internalEvents.push(\n createErrorPlatformEvent('communication', {\n message: 'Unable to send event to an undefined actor',\n event\n })\n );\n return;\n }\n pushBuiltInAction(\n actions,\n builtInActions['@xstate.sendTo'],\n actorScope,\n actor,\n event,\n options\n );\n },\n stop: (actor) => {\n if (actor) {\n // enq.stop accepts the consumer ActorRef contract; refs handed to\n // machine code are always full actor instances at runtime.\n const actorInstance = actor as AnyActor;\n const action = pushBuiltInAction(\n actions,\n builtInActions['@xstate.stop'],\n actorScope,\n actorInstance\n );\n action.childUpdate = { type: 'remove', actor: actorInstance };\n recordStoppedChild(actorScope, actorInstance);\n }\n }\n };\n\n if (actorSubscriptions) {\n Object.assign(props, {\n listen: (actor: any, eventType: string, mapper: any) => {\n if (!createActors) {\n return { id: undefined } as unknown as AnyActor;\n }\n const input: ListenerInput<any, any> = {\n actor,\n eventType,\n mapper\n };\n const listenerActor = actorScope.system.createActorRef(listenerLogic, {\n input,\n parent: actorScope.self\n });\n pushBuiltInAction(\n actions,\n builtInActions['@xstate.spawn'],\n listenerActor\n );\n return listenerActor;\n },\n subscribeTo: (actor: any, mappers: any) => {\n if (!createActors) {\n return { id: undefined } as unknown as AnyActor;\n }\n const normalizedMappers: SubscriptionMappers<any, any, any> =\n typeof mappers === 'function' ? { snapshot: mappers } : mappers;\n\n const input: SubscriptionInput<any, any, any, any> = {\n actor,\n mappers: normalizedMappers\n };\n const subscriptionActor = actorScope.system.createActorRef(\n subscriptionLogic,\n {\n input,\n parent: actorScope.self\n }\n );\n pushBuiltInAction(\n actions,\n builtInActions['@xstate.spawn'],\n subscriptionActor\n );\n return subscriptionActor;\n }\n });\n }\n\n return createEnqueueObject(props, (action, ...args) => {\n pushBuiltInAction(actions, action, ...args);\n });\n}\n\nfunction getBuiltInActionFields(\n action: (...args: any[]) => void,\n args: unknown[]\n): Partial<SpecialExecutableAction> | undefined {\n switch (action) {\n case builtInActions['@xstate.spawn']: {\n const [actor] = args as Parameters<\n (typeof builtInActions)['@xstate.spawn']\n >;\n return {\n type: '@xstate.spawn',\n kind: 'builtin',\n exec: execSpawnEffect,\n source: actor._parent,\n actor,\n id: actor.id,\n logic: (actor as any).logic,\n src: actor.src,\n input: (actor as any).options?.input\n };\n }\n case builtInActions['@xstate.raise']: {\n const [, event, options] = args as Parameters<\n (typeof builtInActions)['@xstate.raise']\n >;\n return {\n type: '@xstate.raise',\n kind: 'builtin',\n exec: execRaiseEffect,\n source: (\n args as Parameters<(typeof builtInActions)['@xstate.raise']>\n )[0].self,\n event,\n id: options?.id,\n delay: options?.delay\n };\n }\n case builtInActions['@xstate.sendTo']: {\n const [, target, event, options] = args as Parameters<\n (typeof builtInActions)['@xstate.sendTo']\n >;\n return {\n type: '@xstate.sendTo',\n kind: 'builtin',\n exec: execSendToEffect,\n source: (\n args as Parameters<(typeof builtInActions)['@xstate.sendTo']>\n )[0].self,\n target,\n event,\n id: options?.id,\n delay: options?.delay\n };\n }\n case builtInActions['@xstate.cancel']: {\n const [, id] = args as Parameters<\n (typeof builtInActions)['@xstate.cancel']\n >;\n return {\n type: '@xstate.cancel',\n kind: 'builtin',\n exec: execCancelEffect,\n source: (\n args as Parameters<(typeof builtInActions)['@xstate.cancel']>\n )[0].self,\n id\n };\n }\n case builtInActions['@xstate.stop']: {\n const [, actor] = args as Parameters<\n (typeof builtInActions)['@xstate.stop']\n >;\n return {\n type: '@xstate.stop',\n kind: 'builtin',\n exec: execStopEffect,\n source: (args as Parameters<(typeof builtInActions)['@xstate.stop']>)[0]\n .self,\n actor,\n id: actor.id\n };\n }\n default:\n return undefined;\n }\n}\n\nfunction createStartEffect(actor: AnyActor): StartExecutableActionObject {\n const args: Parameters<(typeof builtInActions)['@xstate.start']> = [actor];\n return {\n kind: 'builtin',\n exec: execStartEffect,\n type: XSTATE_START,\n source: actor._parent,\n params: undefined,\n args,\n actor,\n id: actor.id\n };\n}\n\nexport function createSpawnEffect(\n actor: AnyActor\n): SpawnExecutableActionObject {\n const args: Parameters<(typeof builtInActions)['@xstate.spawn']> = [actor];\n return {\n kind: 'builtin',\n exec: execSpawnEffect,\n type: XSTATE_SPAWN,\n source: actor._parent,\n params: undefined,\n args,\n actor,\n id: actor.id,\n logic: (actor as any).logic,\n src: actor.src,\n input: (actor as any).options?.input\n };\n}\n\n/** @internal Creates an immediate actor-to-actor delivery effect. */\nexport function createSendToEffect(\n actorScope: AnyActorScope,\n target: AnyActor,\n event: EventObject\n): SendToExecutableActionObject {\n const args: Parameters<(typeof builtInActions)['@xstate.sendTo']> = [\n actorScope,\n target,\n event,\n {}\n ];\n return {\n kind: 'builtin',\n exec: execSendToEffect,\n type: '@xstate.sendTo',\n source: actorScope.self,\n target,\n event,\n id: undefined,\n delay: undefined,\n params: undefined,\n args\n };\n}\n\n/** @internal Creates the terminal lifecycle effect for an actor. */\nexport function createTerminationEffect(\n actorScope: AnyActorScope,\n snapshot: Snapshot<unknown>\n): TerminateExecutableActionObject {\n if (snapshot.status !== 'done' && snapshot.status !== 'error') {\n throw new Error('Cannot terminate an active or stopped actor');\n }\n const termination: ActorTermination =\n snapshot.status === 'done'\n ? { status: 'done', output: snapshot.output, error: undefined }\n : { status: 'error', output: undefined, error: snapshot.error };\n const args: Parameters<(typeof builtInActions)['@xstate.terminate']> = [\n actorScope.self,\n termination\n ];\n return {\n kind: 'builtin',\n exec: execTerminateEffect,\n type: XSTATE_TERMINATE,\n source: actorScope.self,\n actor: actorScope.self,\n id: actorScope.self.id,\n ...termination,\n params: undefined,\n args\n };\n}\n\n/**\n * Ensures that a newly terminal snapshot has exactly one ordered actor\n * termination effect.\n *\n * @internal\n */\nexport function finalizeTransitionResult<\n TSnapshot extends Snapshot<unknown>,\n TEffect\n>(\n actorScope: AnyActorScope,\n previousSnapshot: TSnapshot | undefined,\n [nextSnapshot, effects]: [TSnapshot, TEffect[]]\n): [TSnapshot, Array<TEffect | TerminateExecutableActionObject>] {\n const becameTerminal =\n nextSnapshot.status === 'done' || nextSnapshot.status === 'error';\n const wasTerminal =\n previousSnapshot?.status === 'done' || previousSnapshot?.status === 'error';\n const hasTerminationEffect = effects.some(\n (effect) =>\n typeof effect === 'object' &&\n effect !== null &&\n 'type' in effect &&\n effect.type === XSTATE_TERMINATE\n );\n\n return becameTerminal && !wasTerminal && !hasTerminationEffect\n ? [\n nextSnapshot,\n [...effects, createTerminationEffect(actorScope, nextSnapshot)]\n ]\n : [nextSnapshot, effects];\n}\n\n/**\n * Attached (listener/subscription) starts are ordered before child starts so\n * that a listener/subscription captures events emitted synchronously as its\n * target actor starts.\n */\nexport function deriveDeferredStarts(\n effects: ReadonlyArray<ExecutableActionObject>\n): StartExecutableActionObject[] {\n const attachedStarts: StartExecutableActionObject[] = [];\n const childStarts: StartExecutableActionObject[] = [];\n\n for (const effect of effects) {\n if (!isBuiltInExecutableAction(effect) || effect.type !== XSTATE_SPAWN) {\n continue;\n }\n const { actor, logic } = effect;\n const start = createStartEffect(actor);\n if (logic === listenerLogic || logic === subscriptionLogic) {\n attachedStarts.push(start);\n } else {\n childStarts.push(start);\n }\n }\n\n return [...attachedStarts, ...childStarts];\n}\n\nexport function isBuiltInExecutableAction(\n action: ExecutableActionObject\n): action is SpecialExecutableAction {\n return action.kind === 'builtin';\n}\n\n/** Executes transition effects sequentially, awaiting each runtime operation. */\nexport async function executeEffects(\n effects: readonly ExecutableActionObject[],\n runtime?: Partial<ActorSystemRuntime>\n): Promise<void> {\n for (const effect of effects) {\n await effect.exec(runtime);\n }\n}\n\nexport function resolveActionsWithContext(\n currentSnapshot: AnyMachineSnapshot,\n event: AnyEventObject,\n actorScope: AnyActorScope,\n actions: AnyAction[]\n): [AnyMachineSnapshot, ExecutableActionObject[]] {\n let intermediateSnapshot = currentSnapshot;\n const executableActions: ExecutableActionObject[] = [];\n\n for (const action of actions) {\n const actionArgs = isLazyActorScope(actorScope)\n ? withActorScope(\n {\n context: intermediateSnapshot.context,\n event,\n output: getEventOutput(event),\n children: intermediateSnapshot.children,\n actions: currentSnapshot.machine.sources.actions,\n actors: currentSnapshot.machine.sources.actors\n },\n actorScope\n )\n : {\n context: intermediateSnapshot.context,\n event,\n output: getEventOutput(event),\n self: actorScope.self,\n system: actorScope.system,\n parent: actorScope.self._parent,\n children: intermediateSnapshot.children,\n actions: currentSnapshot.machine.sources.actions,\n actors: currentSnapshot.machine.sources.actors\n };\n\n const isInline = typeof action === 'function';\n const actionRecord = getTransitionActionRecord(action);\n\n const resolvedAction = isInline\n ? action\n : actionRecord\n ? actionRecord.action.bind(null, ...actionRecord.args)\n : false;\n\n let actionParams = undefined;\n\n if (typeof action === 'object' && action !== null) {\n const {\n type: _,\n childUpdate: _childUpdate,\n ...emittedEventParams\n } = action as any;\n actionParams = emittedEventParams;\n }\n\n if (actionRecord?.childUpdate) {\n intermediateSnapshot = applyChildUpdate(\n intermediateSnapshot,\n actionRecord.childUpdate,\n actorScope\n );\n }\n\n if (resolvedAction && '_special' in resolvedAction) {\n executableActions.push({\n kind: 'action',\n exec: execCustomEffect,\n type:\n typeof action === 'object'\n ? 'action' in action && typeof action.action === 'function'\n ? (action.action.name ?? '(anonymous)')\n : ((action as any).type ?? '(anonymous)')\n : action.name || '(anonymous)',\n params: actionParams,\n args: [],\n action: undefined\n });\n\n const specialAction = resolvedAction as unknown as Action<\n any,\n any,\n any,\n any,\n any,\n any,\n any\n >;\n\n const res = specialAction(actionArgs as any, emptyEnqueueObject);\n\n if (res && ('context' in res || 'children' in res)) {\n // Special-action patches never change `nodes`, so a shallow clone is\n // equivalent to `cloneMachineSnapshot` — and keeps this module (and\n // non-machine logic like `createFSM`) independent of State.ts.\n intermediateSnapshot = {\n ...intermediateSnapshot,\n ...(res.context !== undefined\n ? {\n context: mergeContextPatch(\n intermediateSnapshot.context,\n res.context\n )\n }\n : {}),\n ...('children' in res ? { children: res.children } : {})\n };\n }\n continue;\n }\n\n if (!resolvedAction || !('resolve' in resolvedAction)) {\n const builtInFields =\n typeof action === 'object' &&\n action !== null &&\n 'action' in action &&\n typeof action.action === 'function'\n ? getBuiltInActionFields(action.action, action.args)\n : undefined;\n const isEmittedEvent =\n typeof action === 'object' && action !== null && !actionRecord;\n\n const executableAction = {\n kind: builtInFields\n ? ('builtin' as const)\n : isEmittedEvent\n ? ('emit' as const)\n : ('action' as const),\n type:\n typeof action === 'object'\n ? 'action' in action && typeof action.action === 'function'\n ? (action.action.name ?? '(anonymous)')\n : (action as AnyEventObject).type\n : action.name || '(anonymous)',\n params: builtInFields ? undefined : actionParams,\n args:\n typeof action === 'object' && 'action' in action ? action.args : [],\n ...(builtInFields\n ? {}\n : isEmittedEvent\n ? { source: actorScope.self, event: action }\n : {\n action: actionRecord?.action ?? (isInline ? action : undefined)\n }),\n ...(!builtInFields\n ? { exec: isEmittedEvent ? execEmitEffect : execCustomEffect }\n : {}),\n ...builtInFields\n };\n\n const typedExecutableAction = executableAction as ExecutableActionObject;\n intermediateSnapshot = updateLogicalTimers(\n intermediateSnapshot,\n typedExecutableAction,\n actorScope\n );\n executableActions.push(typedExecutableAction);\n continue;\n }\n }\n\n return [intermediateSnapshot, executableActions];\n}\n\nexport function createEnqueueObject(\n props: Partial<EnqueueObject<any, any>>,\n action: <T extends (...args: any[]) => any>(\n fn: T,\n ...args: Parameters<T>\n ) => void\n): EnqueueObject<any, any> {\n const enqueueFn = (\n fn: (...args: any[]) => any,\n ...args: Parameters<typeof fn>\n ) => {\n action(fn, ...args);\n };\n\n Object.assign(enqueueFn, {\n cancel: noop,\n emit: noop,\n log: noop,\n raise: noop,\n spawn: emptyActor,\n sendTo: noop,\n stop: noop,\n listen: emptyActor,\n subscribeTo: emptyActor,\n ...props\n });\n\n return enqueueFn as any;\n}\n\nconst noop = () => {};\nconst emptyActor = () => ({}) as any;\n\nconst emptyEnqueueObject = createEnqueueObject({}, noop);\n","export function parseDurationToMilliseconds(\n duration: string\n): number | undefined {\n const normalizedDuration = duration.trim();\n\n const millisecondsMatch = normalizedDuration.match(/^(\\d+)ms$/i);\n if (millisecondsMatch) {\n return parseInt(millisecondsMatch[1], 10);\n }\n\n const secondsMatch = normalizedDuration.match(/^(\\d*)(\\.?)(\\d*)s$/i);\n if (secondsMatch) {\n const wholePart = secondsMatch[1] ? parseInt(secondsMatch[1], 10) : 0;\n const hasDecimal = !!secondsMatch[2];\n const fracPart = secondsMatch[3]\n ? parseInt(secondsMatch[3].padEnd(3, '0').slice(0, 3), 10)\n : 0;\n\n return wholePart * 1000 + (hasDecimal ? fracPart : 0);\n }\n\n const iso8601DurationMatch = normalizedDuration.match(\n /^P(?:(?<weeks>\\d+(?:[.,]\\d+)?)W)?(?:(?<days>\\d+(?:[.,]\\d+)?)D)?(?:T(?:(?<hours>\\d+(?:[.,]\\d+)?)H)?(?:(?<minutes>\\d+(?:[.,]\\d+)?)M)?(?:(?<seconds>\\d+(?:[.,]\\d+)?)S)?)?$/i\n );\n\n if (!iso8601DurationMatch?.groups) {\n return undefined;\n }\n\n const { weeks, days, hours, minutes, seconds } = iso8601DurationMatch.groups;\n if (!weeks && !days && !hours && !minutes && !seconds) {\n return undefined;\n }\n\n const toNumber = (value: string | undefined) =>\n value ? Number(value.replace(',', '.')) : 0;\n\n return (\n toNumber(weeks) * 7 * 24 * 60 * 60 * 1000 +\n toNumber(days) * 24 * 60 * 60 * 1000 +\n toNumber(hours) * 60 * 60 * 1000 +\n toNumber(minutes) * 60 * 1000 +\n toNumber(seconds) * 1000\n );\n}\n\nexport function parseDelayToMilliseconds(\n delay: string | number | undefined\n): number | undefined {\n if (delay === undefined) {\n return undefined;\n }\n\n if (typeof delay === 'number') {\n return delay;\n }\n\n return parseDurationToMilliseconds(delay);\n}\n","import { hasAmbientInspector } from './inspectionAmbient.ts';\nimport type { AnyActor, Snapshot } from './types.ts';\n\n/** Snapshot-scoped actor identity and system view. @internal */\nexport interface SnapshotActorRef {\n actor: AnyActor;\n systemState: SnapshotSystemState;\n}\n\ninterface SnapshotSystemState {\n root?: AnyActor;\n children?: Map<string, AnyActor>;\n keyedActors: Map<PropertyKey, AnyActor | undefined>;\n snapshot: AnyActor['system']['_snapshot'];\n sourceSystem: AnyActor['system'];\n sourceVersion: number;\n}\n\nconst snapshotActorRefs = new WeakMap<object, SnapshotActorRef>();\nconst lazySnapshotActorRefs = new WeakMap<object, () => SnapshotActorRef>();\nconst emptyKeyedActors = new Map<PropertyKey, AnyActor | undefined>();\n\nfunction copyRegisteredActors(\n system: AnyActor['system'],\n state?: SnapshotSystemState\n): Map<string, AnyActor> {\n if (state) {\n const children = new Map<string, AnyActor>(state.children);\n if (state.root?.sessionId) {\n children.set(state.root.sessionId, state.root);\n }\n return children;\n }\n return new Map(system.children);\n}\n\nfunction captureRegisteredActors(system: AnyActor['system']): {\n root?: AnyActor;\n children?: Map<string, AnyActor>;\n} {\n const root = system._getRootActor?.();\n const peekedChildren = system._peekChildren?.();\n if (!root && !peekedChildren) {\n if (system._getRootActor && system._peekChildren) {\n return {};\n }\n const children = new Map<string, AnyActor>(system.children);\n return children.size ? { children } : {};\n }\n if (!peekedChildren?.size) {\n return root ? { root } : {};\n }\n return { children: new Map<string, AnyActor>(system.children) };\n}\n\nfunction getKeyedActors(\n system: AnyActor['system']\n): Map<PropertyKey, AnyActor | undefined> {\n const peek = system._peekKeyedActors;\n if (peek) {\n return peek.call(system) ?? emptyKeyedActors;\n }\n return system.keyedActors;\n}\n\n/** Marks topology or persisted runtime state as changed. @internal */\nexport function markSystemSnapshotDirty(system: AnyActor['system']): void {\n system._snapshotVersion++;\n}\n\nfunction getSystemSnapshotVersion(system: AnyActor['system']): number {\n return system._snapshotVersion;\n}\n\nfunction getSnapshotChildren(\n snapshot: Snapshot<unknown>\n): Record<string, AnyActor | undefined> {\n return 'children' in snapshot && snapshot.children\n ? (snapshot.children as Record<string, AnyActor | undefined>)\n : {};\n}\n\n/**\n * Creates the isolated receptionist/id view used by a pure branch. Scheduling,\n * relaying and clocks remain delegated to the snapshot's execution system.\n *\n * @internal\n */\nexport function createSnapshotSystem(\n baseSystem: AnyActor['system'],\n children: Record<string, AnyActor | undefined>,\n baseState?: SnapshotSystemState\n): AnyActor['system'] {\n const forwardInspection = hasAmbientInspector();\n const registeredActors = copyRegisteredActors(baseSystem, baseState);\n const keyedActors = new Map<PropertyKey, AnyActor | undefined>(\n baseState?.keyedActors ?? getKeyedActors(baseSystem)\n );\n const reverseKeyedActors = new WeakMap<AnyActor, PropertyKey>();\n const system: AnyActor['system'] = Object.assign(Object.create(baseSystem), {\n children: registeredActors,\n keyedActors,\n reverseKeyedActors,\n _snapshot: { ...(baseState?.snapshot ?? baseSystem._snapshot) },\n _snapshotVersion: baseState?.sourceVersion ?? baseSystem._snapshotVersion,\n _register: (sessionId: string, actor: AnyActor) => {\n registeredActors.set(sessionId, actor);\n markSystemSnapshotDirty(system);\n return sessionId;\n },\n _unregister: (actor: AnyActor) => {\n if (actor.sessionId) {\n registeredActors.delete(actor.sessionId);\n }\n const registryKey = reverseKeyedActors.get(actor);\n if (registryKey !== undefined && keyedActors.get(registryKey) === actor) {\n keyedActors.delete(registryKey);\n }\n reverseKeyedActors.delete(actor);\n markSystemSnapshotDirty(system);\n },\n _set: (registryKey: PropertyKey, actor: AnyActor) => {\n const existing = keyedActors.get(registryKey);\n if (existing && existing !== actor) {\n throw new Error(\n `Actor with registry key '${String(registryKey)}' already exists.`\n );\n }\n keyedActors.set(registryKey, actor);\n reverseKeyedActors.set(actor, registryKey);\n markSystemSnapshotDirty(system);\n },\n get: (registryKey: PropertyKey) => keyedActors.get(registryKey),\n getAll: () => Object.fromEntries(keyedActors),\n // Pure transition resolution must not leak topology inspection events\n // into a live runtime system — planning branches stay silent. The one\n // exception is a durable execution's own transitions (marked by the\n // ambient inspector at creation time): there the pure path IS the\n // execution, so inspection forwards to the base system's observers.\n _hasInspectionObservers: forwardInspection\n ? () => baseSystem._hasInspectionObservers?.() ?? false\n : () => false,\n _sendInspectionEvent: forwardInspection\n ? (event: Parameters<AnyActor['system']['_sendInspectionEvent']>[0]) =>\n baseSystem._sendInspectionEvent(event)\n : () => {}\n });\n\n for (const [registryKey, actor] of keyedActors) {\n if (!actor) {\n continue;\n }\n reverseKeyedActors.set(actor, registryKey);\n }\n for (const actor of Object.values(children)) {\n if (!actor) {\n continue;\n }\n if (actor.sessionId) {\n registeredActors.set(actor.sessionId, actor);\n }\n const registryKey = actor.registryKey;\n if (registryKey) {\n keyedActors.set(registryKey, actor);\n reverseKeyedActors.set(actor, registryKey);\n }\n }\n\n return system;\n}\n\n/** Returns the actor identity associated with a transition snapshot. @internal */\nexport function getSnapshotActorRef(\n snapshot: Snapshot<unknown>\n): SnapshotActorRef | undefined {\n const existing = snapshotActorRefs.get(snapshot);\n if (existing) {\n return existing;\n }\n const create = lazySnapshotActorRefs.get(snapshot);\n if (!create) {\n return undefined;\n }\n const created = create();\n snapshotActorRefs.set(snapshot, created);\n lazySnapshotActorRefs.delete(snapshot);\n return created;\n}\n\n/** Reads an already materialized snapshot association without creating one. @internal */\nexport function peekSnapshotActorRef(\n snapshot: Snapshot<unknown>\n): SnapshotActorRef | undefined {\n return snapshotActorRefs.get(snapshot);\n}\n\n/** Returns the existing identity provider without resolving it. @internal */\nexport function getSnapshotActorRefProvider(\n snapshot: Snapshot<unknown>\n): (() => SnapshotActorRef) | undefined {\n const existing = snapshotActorRefs.get(snapshot);\n return existing ? () => existing : lazySnapshotActorRefs.get(snapshot);\n}\n\n/** Defers actor/system identity allocation until a snapshot capability is used. @internal */\nexport function setLazySnapshotActorRef(\n snapshot: Snapshot<unknown>,\n create: () => SnapshotActorRef\n): void {\n snapshotActorRefs.delete(snapshot);\n lazySnapshotActorRefs.set(snapshot, create);\n}\n\n/**\n * Copies an internal actor association without rebuilding its system view.\n *\n * @internal\n */\nexport function copySnapshotActorRef(\n source: Snapshot<unknown>,\n target: Snapshot<unknown>\n): boolean {\n const ref = snapshotActorRefs.get(source);\n if (ref) {\n snapshotActorRefs.set(target, ref);\n return true;\n }\n const create = lazySnapshotActorRefs.get(source);\n if (create) {\n lazySnapshotActorRefs.set(target, create);\n return true;\n }\n return false;\n}\n\n/** Refreshes the only topology change made by an otherwise idle root start. */\nexport function refreshSnapshotActorRefRoot(\n snapshot: Snapshot<unknown>,\n actor: AnyActor,\n system: AnyActor['system']\n): boolean {\n const ref = snapshotActorRefs.get(snapshot);\n const sourceVersion = getSystemSnapshotVersion(system);\n if (\n ref?.actor !== actor ||\n ref.systemState.sourceSystem !== system ||\n ref.systemState.sourceVersion + 1 !== sourceVersion ||\n system._getRootActor?.() !== actor ||\n system._peekChildren?.()\n ) {\n return false;\n }\n ref.systemState.root = actor;\n ref.systemState.sourceVersion = sourceVersion;\n return true;\n}\n\n/**\n * Associates a transition snapshot with an actor and an immutable system view.\n * The internal association is excluded from enumeration and persistence.\n *\n * @internal\n */\nexport function setSnapshotActorRef(\n snapshot: Snapshot<unknown>,\n actor: AnyActor,\n baseSystem: AnyActor['system'] = actor.system,\n previousSnapshot?: Snapshot<unknown>\n): void {\n lazySnapshotActorRefs.delete(snapshot);\n const sourceVersion = getSystemSnapshotVersion(baseSystem);\n const previousRef = previousSnapshot\n ? getSnapshotActorRef(previousSnapshot)\n : undefined;\n const reusableRef =\n previousRef?.actor === actor ? previousRef : getSnapshotActorRef(snapshot);\n\n if (\n reusableRef?.actor === actor &&\n reusableRef.systemState.sourceSystem === baseSystem &&\n reusableRef.systemState.sourceVersion === sourceVersion\n ) {\n snapshotActorRefs.set(snapshot, reusableRef);\n return;\n }\n\n const capturedActors = captureRegisteredActors(baseSystem);\n let children = capturedActors.children;\n const baseKeyedActors = getKeyedActors(baseSystem);\n let keyedActors = baseKeyedActors.size\n ? new Map(baseKeyedActors)\n : emptyKeyedActors;\n for (const child of Object.values(getSnapshotChildren(snapshot))) {\n if (!child) {\n continue;\n }\n if (child.sessionId) {\n (children ??= new Map()).set(child.sessionId, child);\n }\n const registryKey = child.registryKey;\n if (registryKey) {\n if (keyedActors === emptyKeyedActors) {\n keyedActors = new Map();\n }\n keyedActors.set(registryKey, child);\n }\n }\n snapshotActorRefs.set(snapshot, {\n actor,\n systemState: {\n ...capturedActors,\n children,\n keyedActors,\n snapshot: { ...baseSystem._snapshot },\n sourceSystem: baseSystem,\n sourceVersion\n }\n } satisfies SnapshotActorRef);\n}\n","import { createActor } from './createActor.ts';\nimport { isMachineSnapshot } from './State.ts';\nimport {\n createSnapshotSystem,\n getSnapshotActorRef,\n getSnapshotActorRefProvider,\n peekSnapshotActorRef,\n setLazySnapshotActorRef,\n setSnapshotActorRef,\n type SnapshotActorRef\n} from './snapshotActorRef.ts';\nimport {\n ActorScope,\n AnyActor,\n AnyActorLogic,\n AnyActorScope,\n EmittedFrom,\n EventFromLogic,\n InputFrom,\n Snapshot,\n SnapshotFrom\n} from './types.ts';\nimport { lazyActorScope } from './actorScope.ts';\n\n/** @internal */\nexport function setInertActorScopeSnapshot<T>(\n actorScope: AnyActorScope,\n snapshot: T,\n attachActorRef = true\n): T {\n const lazyState = getLazyInertActorState(actorScope);\n if (lazyState) {\n lazyState.snapshot = snapshot;\n if (lazyState.materialized) {\n (lazyState.materialized.self as any)._snapshot = snapshot;\n }\n } else {\n (actorScope.self as any)._snapshot = snapshot;\n }\n if (attachActorRef && snapshot && typeof snapshot === 'object') {\n setSnapshotActorRef(snapshot as any, actorScope.self);\n }\n return snapshot;\n}\n\n/** @internal */\nexport function isInertActorScope(actorScope: AnyActorScope): boolean {\n return (\n !!getLazyInertActorState(actorScope) ||\n !!(actorScope.self as any).options?._inert\n );\n}\n\n/** @internal */\nexport function attachSnapshotActorRef<TSnapshot>(\n actorScope: AnyActorScope,\n snapshot: TSnapshot\n): TSnapshot {\n setInertActorScopeSnapshot(actorScope, snapshot, false);\n const lazyState = getLazyInertActorState(actorScope);\n snapshotActorScopes.set(snapshot as object, actorScope);\n const create = () => {\n setSnapshotActorRef(\n snapshot as Snapshot<unknown>,\n actorScope.self,\n actorScope.system\n );\n return getSnapshotActorRef(snapshot as Snapshot<unknown>)!;\n };\n if (lazyState) {\n if (lazyState.materialized) {\n lazyState.identityProvider = create;\n } else {\n lazyState.identityProvider ??= create;\n }\n }\n setLazySnapshotActorRef(snapshot as Snapshot<unknown>, create);\n return snapshot;\n}\n\ntype LazyInertActorState = {\n snapshot: unknown;\n materialized?: AnyActorScope;\n sourceRef?: () => SnapshotActorRef;\n sourceChildren: Record<string, AnyActor | undefined>;\n identityProvider?: () => SnapshotActorRef;\n parent?: AnyActor;\n parentKnown: boolean;\n materialize: () => AnyActorScope;\n};\n\nconst lazyInertActorState = Symbol();\ntype LazyInertActorScope = AnyActorScope & {\n [lazyInertActorState]?: LazyInertActorState;\n};\nconst snapshotActorScopes = new WeakMap<object, AnyActorScope>();\nlet inertActorMaterializationObserver: (() => void) | undefined;\n\nfunction getLazyInertActorState(\n actorScope: AnyActorScope\n): LazyInertActorState | undefined {\n return (actorScope as LazyInertActorScope)[lazyInertActorState];\n}\n\nfunction materializeInertActorScope(actorScope: AnyActorScope): AnyActorScope {\n return getLazyInertActorState(actorScope)!.materialize();\n}\n\nconst lazyInertActorScopePrototype = {\n [lazyActorScope]: true,\n get _parent() {\n const actorScope = this as AnyActorScope;\n const state = getLazyInertActorState(actorScope)!;\n return state.parentKnown\n ? state.parent\n : materializeInertActorScope(actorScope).self._parent;\n },\n get self() {\n return materializeInertActorScope(this as AnyActorScope).self;\n },\n get defer() {\n return materializeInertActorScope(this as AnyActorScope).defer;\n },\n get id() {\n return materializeInertActorScope(this as AnyActorScope).id;\n },\n get logger() {\n return materializeInertActorScope(this as AnyActorScope).logger;\n },\n get sessionId() {\n return materializeInertActorScope(this as AnyActorScope).sessionId;\n },\n get stopChild() {\n return materializeInertActorScope(this as AnyActorScope).stopChild;\n },\n get system() {\n return materializeInertActorScope(this as AnyActorScope).system;\n },\n get emit() {\n return materializeInertActorScope(this as AnyActorScope).emit;\n },\n get actionExecutor() {\n return materializeInertActorScope(this as AnyActorScope).actionExecutor;\n }\n};\n\n/** Test-only allocation instrumentation. @internal */\nexport function setInertActorMaterializationObserver(\n observer: (() => void) | undefined\n): void {\n inertActorMaterializationObserver = observer;\n}\n\nfunction createMaterializedInertActorScope<T extends AnyActorLogic>(\n actorLogic: T,\n sourceRef: (() => SnapshotActorRef) | undefined,\n sourceChildren: Record<string, AnyActor | undefined>,\n currentSnapshot: SnapshotFrom<T> | undefined,\n sourceSelf?: AnyActor\n): AnyActorScope {\n inertActorMaterializationObserver?.();\n const snapshotRef = sourceRef?.();\n const previousSelf = sourceSelf ?? snapshotRef?.actor;\n const baseSystem = previousSelf?.system;\n const system =\n previousSelf && baseSystem\n ? createSnapshotSystem(\n baseSystem,\n sourceChildren,\n sourceSelf ? undefined : snapshotRef?.systemState\n )\n : undefined;\n const self = createActor(\n actorLogic as AnyActorLogic,\n {\n _inert: true,\n ...(previousSelf\n ? {\n id: previousSelf.id,\n _sessionId: previousSelf.sessionId\n }\n : {}),\n ...(system ? { _systemRef: { current: system } } : {})\n } as any\n );\n if (previousSelf?._parent) {\n self._parent = previousSelf._parent;\n // `address` memoizes on first read assuming `_parent` is final; nothing\n // reads it between construction and this assignment, but drop any memo so\n // a future construction-time read cannot pin a root-shaped address.\n (self as unknown as { _address?: string })._address = undefined;\n }\n if (currentSnapshot) {\n (self as any)._snapshot = currentSnapshot;\n }\n\n // Reuse the branch actor's scope while keeping planning transactional.\n return Object.create((self as any)._actorScope, {\n defer: { value: () => {} },\n stopChild: { value: (child: AnyActor) => (child as any)._stop() },\n actionExecutor: { value: () => {} }\n });\n}\n\n/** @internal */\nexport function createInertActorScope<T extends AnyActorLogic>(\n actorLogic: T,\n snapshot?: SnapshotFrom<T>,\n sourceSelf?: AnyActor,\n sourceActorScope?: AnyActorScope\n): AnyActorScope {\n const sourceScope =\n sourceActorScope ??\n (snapshot && typeof snapshot === 'object'\n ? snapshotActorScopes.get(snapshot as object)\n : undefined);\n const sourceState = sourceScope\n ? getLazyInertActorState(sourceScope)\n : undefined;\n const eagerSourceRef =\n snapshot && typeof snapshot === 'object'\n ? peekSnapshotActorRef(snapshot as Snapshot<unknown>)\n : undefined;\n const sourceRef =\n sourceState?.identityProvider ??\n (snapshot && typeof snapshot === 'object'\n ? getSnapshotActorRefProvider(snapshot as Snapshot<unknown>)\n : undefined);\n const state = {\n snapshot,\n sourceRef,\n sourceChildren: isMachineSnapshot(snapshot)\n ? (snapshot as any).children\n : {},\n identityProvider: sourceState?.identityProvider ?? sourceRef,\n parent:\n sourceSelf?._parent ??\n sourceState?.parent ??\n eagerSourceRef?.actor._parent,\n parentKnown:\n !!sourceSelf ||\n !!sourceState?.parentKnown ||\n !!eagerSourceRef ||\n !snapshot\n } as LazyInertActorState;\n state.materialize = () =>\n (state.materialized ??= createMaterializedInertActorScope(\n actorLogic,\n state.sourceRef,\n state.sourceChildren,\n state.snapshot as SnapshotFrom<T>,\n sourceSelf\n ));\n if (!state.identityProvider && !snapshot) {\n const identitySnapshot = {} as Snapshot<unknown>;\n const identitySourceRef = state.sourceRef;\n const identitySourceChildren = state.sourceChildren;\n let identityScope: AnyActorScope | undefined;\n let identityRef: SnapshotActorRef | undefined;\n const getIdentityScope = () =>\n (identityScope ??= createMaterializedInertActorScope(\n actorLogic,\n identitySourceRef,\n identitySourceChildren,\n undefined,\n sourceSelf\n ));\n state.materialize = () => {\n const scope = getIdentityScope();\n if (state.snapshot !== undefined) {\n (scope.self as any)._snapshot = state.snapshot;\n }\n return (state.materialized = scope);\n };\n state.identityProvider = () => {\n if (identityRef) {\n return identityRef;\n }\n const scope = getIdentityScope();\n setSnapshotActorRef(identitySnapshot, scope.self, scope.system);\n return (identityRef = getSnapshotActorRef(identitySnapshot)!);\n };\n }\n const actorScope = Object.create(lazyInertActorScopePrototype) as ActorScope<\n SnapshotFrom<T>,\n EventFromLogic<T>,\n any,\n EmittedFrom<T>\n >;\n (actorScope as LazyInertActorScope)[lazyInertActorState] = state;\n return actorScope;\n}\n\n/** @deprecated Use `initialTransition(…)` instead. */\nexport function getInitialSnapshot<T extends AnyActorLogic>(\n actorLogic: T,\n ...[input]: undefined extends InputFrom<T>\n ? [input?: InputFrom<T>]\n : [input: InputFrom<T>]\n): SnapshotFrom<T> {\n const actorScope = createInertActorScope(actorLogic);\n return actorLogic.initialTransition(input, actorScope)[0];\n}\n\n/**\n * Determines the next snapshot for the given `actorLogic` based on the given\n * `snapshot` and `event`.\n *\n * If the `snapshot` is `undefined`, the initial snapshot of the `actorLogic` is\n * used.\n *\n * @deprecated Use `transition(…)` instead.\n * @example\n *\n * ```ts\n * import { getNextSnapshot } from 'xstate';\n * import { trafficLightMachine } from './trafficLightMachine.ts';\n *\n * const nextSnapshot = getNextSnapshot(\n * trafficLightMachine, // actor logic\n * undefined, // snapshot (or initial state if undefined)\n * { type: 'TIMER' }\n * ); // event object\n *\n * console.log(nextSnapshot.value);\n * // => 'yellow'\n *\n * const nextSnapshot2 = getNextSnapshot(\n * trafficLightMachine, // actor logic\n * nextSnapshot, // snapshot\n * { type: 'TIMER' }\n * ); // event object\n *\n * console.log(nextSnapshot2.value);\n * // =>'red'\n * ```\n */\nexport function getNextSnapshot<T extends AnyActorLogic>(\n actorLogic: T,\n snapshot: SnapshotFrom<T>,\n event: EventFromLogic<T>\n): SnapshotFrom<T> {\n const actorScope = createInertActorScope(actorLogic, snapshot);\n const transitionResult = actorLogic.transition(snapshot, event, actorScope);\n const nextSnapshot = Array.isArray(transitionResult)\n ? transitionResult[0]\n : transitionResult;\n setInertActorScopeSnapshot(actorScope, nextSnapshot, false);\n return nextSnapshot === snapshot\n ? nextSnapshot\n : attachSnapshotActorRef(actorScope, nextSnapshot);\n}\n","import isDevelopment from '#is-development';\nimport { MachineSnapshot, cloneMachineSnapshot } from './State.ts';\nimport type { StateNode } from './StateNode.ts';\nimport {\n createAfterEvent,\n createAfterEventId,\n createDoneStateEvent,\n createInvokeTimeoutEvent,\n createInvokeTimeoutEventId,\n createTimeoutEvent,\n createTimeoutEventId\n} from './eventUtils.ts';\nimport {\n XSTATE_INIT,\n STATE_DELIMITER,\n STATE_IDENTIFIER,\n XSTATE_STOP,\n XSTATE_TIMER\n} from './constants.ts';\nimport {\n getEventOutput,\n isErrorEvent,\n matchesEvent,\n matchesEventDescriptor\n} from './utils.ts';\nimport {\n AnyEventObject,\n AnyMachineSnapshot,\n AnyStateMachine,\n AnyStateNode,\n AnyTransitionDefinition,\n DelayedTransitionDefinition,\n EventObject,\n ExecutableActionObject,\n HistoryValue,\n MachineContext,\n StateValue,\n TransitionDefinition,\n AnyAction,\n AnyTransitionConfig,\n AnyActor,\n AnyActorScope,\n DoneStateEvent\n} from './types.ts';\nimport {\n resolveOutput,\n normalizeTarget,\n toArray,\n toStatePath,\n resolveReferencedActor,\n toTransitionConfigArray\n} from './utils.ts';\nimport { builtInActions } from './actions.ts';\nimport {\n assertChildIdFree,\n createEnqueueObject,\n createTerminationEffect,\n createTransitionEnqueue,\n createSendToEffect,\n deriveDeferredStarts,\n mergeContextPatch,\n resolveActionsWithContext\n} from './transitionActions.ts';\nimport { parseDurationToMilliseconds } from './delay.ts';\nimport { transitionEffectSignal, transitionEffectTargets } from './system.ts';\nimport { isInertActorScope } from './getNextSnapshot.ts';\nimport {\n getActorScopeParent,\n isLazyActorScope,\n withActorSelfAndParent,\n withActorScope\n} from './actorScope.ts';\n\ntype AnyStateNodeIterable = Iterable<AnyStateNode>;\n\nfunction getConfiguredDelayValue(\n delay: number | string,\n delaySource: Record<string, any>\n) {\n if (typeof delay !== 'string') {\n return delay;\n }\n\n const referencedDelay = delaySource[delay];\n if (referencedDelay !== undefined) {\n return referencedDelay;\n }\n\n return parseDurationToMilliseconds(delay) ?? delay;\n}\n\nfunction resolveDelay(\n delay: number | string | ((args: any) => number),\n delaySource: Record<string, any>,\n args: {\n context: MachineContext;\n event: EventObject;\n stateNode: AnyStateNode;\n input?: Record<string, unknown>;\n }\n) {\n if (typeof delay === 'function') {\n return delay(args);\n }\n\n const configuredDelay = getConfiguredDelayValue(delay, delaySource);\n if (typeof configuredDelay === 'function') {\n return configuredDelay(args);\n }\n\n return configuredDelay;\n}\n\nfunction getStateInput(snapshot: AnyMachineSnapshot, stateNodeId: string) {\n return snapshot._stateInputs?.[stateNodeId];\n}\n\nexport function isAtomicStateNode(stateNode: AnyStateNode) {\n return (\n stateNode.type === 'atomic' ||\n stateNode.type === 'final' ||\n stateNode.type === 'choice'\n );\n}\n\nfunction getChildren(stateNode: AnyStateNode): Array<AnyStateNode> {\n return Object.values(stateNode.states).filter((sn) => sn.type !== 'history');\n}\n\nexport function getProperAncestors(\n stateNode: AnyStateNode,\n toStateNode: AnyStateNode | undefined\n): Array<typeof stateNode> {\n const ancestors: Array<typeof stateNode> = [];\n\n if (toStateNode === stateNode) {\n return ancestors;\n }\n\n // add all ancestors\n let m = stateNode.parent;\n while (m && m !== toStateNode) {\n ancestors.push(m);\n m = m.parent;\n }\n\n return ancestors;\n}\n\nexport function getAllStateNodes(\n stateNodes: Iterable<AnyStateNode>\n): Set<AnyStateNode> {\n const nodeSet = new Set(stateNodes);\n const activeParentSet = new Set<AnyStateNode>();\n for (const stateNode of nodeSet) {\n if (stateNode.parent) {\n activeParentSet.add(stateNode.parent);\n }\n }\n\n // add descendants\n for (const s of nodeSet) {\n // if previously active, add existing child nodes\n if (s.type === 'compound' && !activeParentSet.has(s)) {\n for (const sn of getInitialStateNodes(s)) {\n nodeSet.add(sn);\n }\n continue;\n }\n\n if (s.type === 'parallel') {\n for (const child of getChildren(s)) {\n if (!nodeSet.has(child)) {\n const initialStates = getInitialStateNodes(child);\n for (const initialStateNode of initialStates) {\n nodeSet.add(initialStateNode);\n }\n }\n }\n }\n }\n\n // add all ancestors\n // Stop walking up as soon as we hit a node already in the set: its own\n // ancestor chain is guaranteed to be added when it is visited by this loop\n // (Set iteration visits elements added during iteration), so shared ancestor\n // chains are never re-walked once per descendant.\n for (const s of nodeSet) {\n let m = s.parent;\n\n while (m && !nodeSet.has(m)) {\n nodeSet.add(m);\n m = m.parent;\n }\n }\n\n return nodeSet;\n}\n\nexport function getStateValue(\n rootNode: AnyStateNode,\n stateNodes: AnyStateNodeIterable\n): StateValue {\n const config = getAllStateNodes(stateNodes);\n const adjList = new Map<AnyStateNode, Array<AnyStateNode>>();\n\n for (const s of config) {\n if (!adjList.has(s)) {\n adjList.set(s, []);\n }\n\n if (!s.parent) {\n continue;\n }\n\n if (!adjList.has(s.parent)) {\n adjList.set(s.parent, []);\n }\n\n adjList.get(s.parent)!.push(s);\n }\n\n const getValueFromAdj = (baseNode: AnyStateNode): StateValue => {\n const childStateNodes = adjList.get(baseNode);\n\n if (!childStateNodes) {\n return {}; // todo: fix?\n }\n\n if (baseNode.type === 'compound') {\n const childStateNode = childStateNodes[0];\n if (!childStateNode) {\n return {};\n }\n if (isAtomicStateNode(childStateNode)) {\n return childStateNode.key;\n }\n }\n\n const stateValue: StateValue = {};\n for (const childStateNode of childStateNodes) {\n stateValue[childStateNode.key] = getValueFromAdj(childStateNode);\n }\n\n return stateValue;\n };\n\n return getValueFromAdj(rootNode);\n}\n\nexport function isInFinalState(\n stateNodeSet: Set<AnyStateNode>,\n stateNode: AnyStateNode\n): boolean {\n if (stateNode.type === 'compound') {\n return getChildren(stateNode).some(\n (s) => s.type === 'final' && stateNodeSet.has(s)\n );\n }\n if (stateNode.type === 'parallel') {\n return getChildren(stateNode).every((sn) =>\n isInFinalState(stateNodeSet, sn)\n );\n }\n\n return stateNode.type === 'final';\n}\n\nexport const isStateId = (str: string) => str[0] === STATE_IDENTIFIER;\n\nfunction getLegacyEventType(event: EventObject): string | undefined {\n switch (event.type) {\n case 'xstate.done.actor':\n case 'xstate.error.actor':\n return `${event.type}.${(event as any).actorId}`;\n case 'xstate.snapshot.actor':\n return `xstate.snapshot.${(event as any).actorId}`;\n case 'xstate.done.state':\n return `xstate.done.state.${(event as any).stateId}`;\n case 'xstate.after':\n return `xstate.after.${(event as any).delay}.${(event as any).stateId}`;\n case 'xstate.timeout':\n return `xstate.timeout.${(event as any).stateId}`;\n case 'xstate.timeout.actor':\n return `xstate.timeout.actor.${(event as any).actorId}`;\n default:\n return undefined;\n }\n}\n\nfunction getEventTypeAliases(event: EventObject): string[] {\n const legacyType = getLegacyEventType(event);\n return legacyType ? [event.type, legacyType] : [event.type];\n}\n\nexport function getEventDescriptorKey(event: EventObject): string {\n const legacyType = getLegacyEventType(event);\n return legacyType ? `${event.type}|${legacyType}` : event.type;\n}\n\nexport function matchesActorSession(\n event: EventObject,\n snapshot: AnyMachineSnapshot,\n actorId: string\n): boolean {\n const child = snapshot.children[actorId];\n if (!child || !('sessionId' in event)) {\n return true;\n }\n // One rule: a ref that knows its incarnation compares it; a remote handle\n // without a host-supplied token (sessionId undefined) defers to the\n // runtime that owns the child.\n return (\n child.sessionId === undefined ||\n child.sessionId === (event as { sessionId?: string }).sessionId\n );\n}\n\nfunction normalizeLegacyInternalEvent(\n event: EventObject,\n machine: AnyStateMachine\n): EventObject {\n if (\n event.type === 'xstate.done.actor' ||\n event.type === 'xstate.error.actor' ||\n event.type === 'xstate.snapshot.actor' ||\n event.type === 'xstate.done.state' ||\n event.type === 'xstate.after' ||\n event.type === 'xstate.timeout' ||\n event.type === 'xstate.timeout.actor'\n ) {\n return event;\n }\n\n const normalizeWithId = (\n prefix: string,\n type: string,\n idKey: 'actorId' | 'stateId'\n ) =>\n event.type.startsWith(prefix)\n ? {\n ...event,\n type,\n [idKey]: (event as any)[idKey] ?? event.type.slice(prefix.length)\n }\n : undefined;\n\n const normalized =\n normalizeWithId('xstate.done.actor.', 'xstate.done.actor', 'actorId') ??\n normalizeWithId('xstate.error.actor.', 'xstate.error.actor', 'actorId') ??\n normalizeWithId('xstate.snapshot.', 'xstate.snapshot.actor', 'actorId') ??\n normalizeWithId('xstate.done.state.', 'xstate.done.state', 'stateId') ??\n normalizeWithId(\n 'xstate.timeout.actor.',\n 'xstate.timeout.actor',\n 'actorId'\n ) ??\n normalizeWithId('xstate.timeout.', 'xstate.timeout', 'stateId');\n\n if (normalized) {\n return normalized;\n }\n\n const afterPrefix = 'xstate.after.';\n if (!event.type.startsWith(afterPrefix)) {\n return event;\n }\n\n const stateId = [...machine.idMap.keys()]\n .sort((a, b) => b.length - a.length)\n .find((id) => event.type.endsWith(`.${id}`));\n if (!stateId) {\n return event;\n }\n const delayText = event.type.slice(afterPrefix.length, -stateId.length - 1);\n return {\n ...event,\n type: 'xstate.after',\n delay: Number.isNaN(+delayText) ? delayText : +delayText,\n stateId\n } as AnyEventObject;\n}\n\nexport function getCandidates<TEvent extends EventObject>(\n stateNode: StateNode<any, TEvent>,\n event: TEvent\n): Array<TransitionDefinition<any, TEvent>> {\n const eventTypes = getEventTypeAliases(event);\n const exactMatches = eventTypes.flatMap(\n (eventType) => stateNode.transitions.get(eventType) ?? []\n );\n const wildcardCandidates = [...stateNode.transitions.keys()]\n .filter(\n (eventDescriptor) =>\n !eventTypes.includes(eventDescriptor) &&\n eventTypes.some((eventType) =>\n matchesEventDescriptor(eventType, eventDescriptor)\n )\n )\n .sort((a, b) => b.length - a.length)\n .flatMap((key) => stateNode.transitions.get(key)!);\n\n return exactMatches.length\n ? [...exactMatches, ...wildcardCandidates]\n : wildcardCandidates;\n}\n\nfunction scheduleDelayedEvent(\n stateNode: AnyStateNode,\n timerId: string,\n resolveEvent: (args: any) => AnyEventObject,\n resolveScheduledDelay: (x: {\n context: MachineContext;\n event: EventObject;\n delays: Record<string, any>;\n input?: Record<string, unknown>;\n }) => any\n) {\n const oldEntry = stateNode.entry;\n stateNode.entry = (x: any, enq: any) => {\n enq.raise(resolveEvent(x) as any, {\n id: timerId,\n delay: resolveScheduledDelay(x)\n });\n return typeof oldEntry === 'function' ? oldEntry(x, enq) : undefined;\n };\n const oldExit = stateNode.exit;\n stateNode.exit = (_: any, enq: any) => {\n enq.cancel(timerId);\n return typeof oldExit === 'function' ? oldExit(_, enq) : undefined;\n };\n}\n\n/** All delayed transitions from the config. */\nexport function getDelayedTransitions(\n stateNode: AnyStateNode\n): Array<DelayedTransitionDefinition<MachineContext, EventObject>> {\n const afterConfig = stateNode.config.after;\n const timeoutConfig = (stateNode.config as any).timeout;\n const onTimeoutConfig = (stateNode.config as any).onTimeout;\n const invokeDefs = stateNode.invoke.filter(\n (invokeDef) => invokeDef.timeout !== undefined\n );\n\n if (!afterConfig && timeoutConfig === undefined && invokeDefs.length === 0) {\n return [];\n }\n\n if (isDevelopment && timeoutConfig !== undefined && !onTimeoutConfig) {\n throw new Error(\n `State \"${stateNode.id}\" has \\`timeout\\` but no \\`onTimeout\\` transition.`\n );\n }\n\n if (isDevelopment) {\n for (const invokeDef of invokeDefs) {\n if (!invokeDef.onTimeout) {\n throw new Error(\n `Invoke on state \"${stateNode.id}\" has \\`timeout\\` but no \\`onTimeout\\` transition.`\n );\n }\n }\n }\n\n // Every delayed transition — `after`, state-level `timeout`/`onTimeout`, and\n // invoke-level `timeout`/`onTimeout` — has the same shape: an event raised on\n // entry (and cancelled on exit) plus a transition that catches it. They\n // differ only in the event raised, the transition(s) caught, and whether the\n // delay resolves against the machine's `delays` map (invoke timeouts do not).\n //\n // `xstate.timeout` is a dedicated event category so a state-level `timeout`\n // cannot collide with an explicit `after` entry on the same state. Invoke\n // timeouts are scheduled on the enclosing state; completion transitions\n // cancel the timer separately, so it clears even when the parent stays active.\n const sources: Array<{\n event: AnyEventObject;\n timerId: string;\n resolveEvent?: (args: any) => AnyEventObject;\n eventMatcher?: (\n event: EventObject,\n snapshot: AnyMachineSnapshot\n ) => boolean;\n delay: any;\n transitions: unknown;\n fromDelaysMap: boolean;\n }> = [];\n\n if (afterConfig) {\n for (const key of Object.keys(afterConfig)) {\n const delay = Number.isNaN(+key) ? key : +key;\n sources.push({\n event: createAfterEvent(delay, stateNode.id),\n timerId: createAfterEventId(delay, stateNode.id),\n delay,\n transitions: afterConfig[key],\n fromDelaysMap: true\n });\n }\n }\n\n if (timeoutConfig !== undefined && onTimeoutConfig) {\n sources.push({\n event: createTimeoutEvent(stateNode.id),\n timerId: createTimeoutEventId(stateNode.id),\n delay: timeoutConfig,\n transitions: onTimeoutConfig,\n fromDelaysMap: true\n });\n }\n\n for (const invokeDef of invokeDefs) {\n sources.push({\n event: createInvokeTimeoutEvent(invokeDef.id),\n timerId: createInvokeTimeoutEventId(invokeDef.id),\n resolveEvent: ({ children }: any) =>\n createInvokeTimeoutEvent(\n invokeDef.id,\n children[invokeDef.id]?.sessionId\n ),\n eventMatcher: (event, snapshot) =>\n matchesActorSession(event, snapshot, invokeDef.id),\n delay: invokeDef.timeout!,\n transitions: invokeDef.onTimeout,\n fromDelaysMap: false\n });\n }\n\n // `delay` here is the raw config value, retained only as metadata on the\n // transition definition — the live delay is resolved at runtime in the\n // scheduled entry action, so no eager resolution is needed.\n const delayedTransitions: Array<\n AnyTransitionConfig & {\n event: string;\n delay: any;\n _eventMatcher?: (\n event: EventObject,\n snapshot: AnyMachineSnapshot\n ) => boolean;\n }\n > = [];\n\n for (const {\n event,\n timerId,\n resolveEvent,\n eventMatcher,\n delay,\n transitions,\n fromDelaysMap\n } of sources) {\n scheduleDelayedEvent(\n stateNode,\n timerId,\n resolveEvent ?? (() => event),\n (x) =>\n resolveDelay(delay, fromDelaysMap ? x.delays : {}, {\n context: x.context,\n event: x.event,\n stateNode,\n input: x.input\n })\n );\n const { type: eventType, ...eventPattern } = event;\n for (const transition of toTransitionConfigArray(transitions as any)) {\n delayedTransitions.push({\n ...transition,\n matches: {\n ...transition.matches,\n ...Object.fromEntries(\n Object.entries(eventPattern).filter(\n ([, value]) => value !== undefined\n )\n )\n },\n event: eventType,\n delay,\n _eventMatcher: eventMatcher\n });\n }\n }\n\n return delayedTransitions.map((delayedTransition) => ({\n ...formatTransition(\n stateNode,\n delayedTransition.event,\n delayedTransition as AnyTransitionConfig\n ),\n delay: delayedTransition.delay\n }));\n}\n\nexport function formatTransition(\n stateNode: AnyStateNode,\n descriptor: string,\n transitionConfig: AnyTransitionConfig\n): AnyTransitionDefinition {\n const normalizedTarget = normalizeTarget(transitionConfig.target);\n const reenter = transitionConfig.reenter ?? false;\n const target = resolveTarget(stateNode, normalizedTarget);\n assertLegalTargetSet(stateNode, target);\n\n const transition = {\n ...transitionConfig,\n target,\n source: stateNode,\n reenter,\n eventType: descriptor,\n toJSON: () => ({\n ...transition,\n source: `#${stateNode.id}`,\n target: target ? target.map((t) => `#${t.id}`) : undefined\n })\n };\n\n return transition;\n}\n\nfunction isStateNodeDescendantOf(\n stateNode: AnyStateNode,\n ancestor: AnyStateNode\n): boolean {\n for (let current = stateNode.parent; current; current = current.parent) {\n if (current === ancestor) {\n return true;\n }\n }\n return false;\n}\n\nfunction getLeastCommonStateNodeAncestor(\n left: AnyStateNode,\n right: AnyStateNode\n): AnyStateNode | undefined {\n const leftAncestors = new Set<AnyStateNode>();\n for (\n let current: AnyStateNode | undefined = left;\n current;\n current = current.parent\n ) {\n leftAncestors.add(current);\n }\n for (\n let current: AnyStateNode | undefined = right;\n current;\n current = current.parent\n ) {\n if (leftAncestors.has(current)) {\n return current;\n }\n }\n return undefined;\n}\n\nfunction assertLegalTargetSet(\n source: AnyStateNode,\n targets: readonly AnyStateNode[] | undefined\n): void {\n if (!targets || targets.length < 2) {\n return;\n }\n for (let leftIndex = 0; leftIndex < targets.length; leftIndex++) {\n for (\n let rightIndex = leftIndex + 1;\n rightIndex < targets.length;\n rightIndex++\n ) {\n const left = targets[leftIndex];\n const right = targets[rightIndex];\n const commonAncestor = getLeastCommonStateNodeAncestor(left, right);\n if (\n left === right ||\n isStateNodeDescendantOf(left, right) ||\n isStateNodeDescendantOf(right, left) ||\n commonAncestor?.type !== 'parallel'\n ) {\n throw new Error(\n isDevelopment\n ? `Invalid transition definition for state node '${source.id}': target set is not a legal SCXML configuration.`\n : `Invalid target set for '${source.id}'`\n );\n }\n }\n }\n}\n\n/**\n * Collects route transitions from all descendants with explicit IDs. Called\n * once on the root node to avoid O(N²) repeated traversals.\n */\nexport function formatRouteTransitions(rootStateNode: AnyStateNode): void {\n const routeTransitions: AnyTransitionDefinition[] = [];\n const collectRoutes = (states: Record<string, AnyStateNode>) => {\n Object.values(states).forEach((sn) => {\n if (sn.config.route && sn.config.id) {\n const routeId = sn.config.id;\n const routeConfig = sn.config.route;\n const routeMatches = ({ event }: { event: any }) =>\n event.to === `#${routeId}`;\n\n if (typeof routeConfig === 'function') {\n // Transition-style route: the function is the guard and resolver.\n // Returning undefined/false blocks the route; returning true or a\n // config object allows it.\n routeTransitions.push(\n formatTransition(rootStateNode, 'xstate.route', {\n guard: routeMatches,\n to: (args: any) => {\n const result = routeConfig(args);\n if (!result) {\n return undefined;\n }\n return {\n ...(result === true ? {} : result),\n target: `#${routeId}`\n };\n }\n } as AnyTransitionConfig)\n );\n if (sn.states) {\n collectRoutes(sn.states);\n }\n return;\n }\n\n const { guard: _guard, ...routeOptions } = routeConfig as any;\n const transition: AnyTransitionConfig = {\n ...routeOptions,\n guard: routeMatches,\n target: `#${routeId}`\n };\n\n routeTransitions.push(\n formatTransition(rootStateNode, 'xstate.route', transition)\n );\n }\n if (sn.states) {\n collectRoutes(sn.states);\n }\n });\n };\n collectRoutes(rootStateNode.states);\n if (routeTransitions.length > 0) {\n rootStateNode.transitions.set('xstate.route', routeTransitions as any);\n }\n}\n\nfunction resolveTarget(\n stateNode: AnyStateNode,\n targets: ReadonlyArray<string | AnyStateNode> | undefined\n): ReadonlyArray<AnyStateNode> | undefined {\n if (targets === undefined) {\n // an undefined target signals that the state node should not transition from that state when receiving that event\n return undefined;\n }\n return targets.map((target) => {\n if (typeof target !== 'string') {\n return target;\n }\n if (isStateId(target)) {\n return stateNode.machine.getStateNodeById(target);\n }\n\n const isInternalTarget = target[0] === STATE_DELIMITER;\n // If internal target is defined on machine,\n // do not include machine key on target\n if (isInternalTarget && !stateNode.parent) {\n return getStateNodeByPath(stateNode, target.slice(1));\n }\n const resolvedTarget = isInternalTarget ? stateNode.key + target : target;\n if (stateNode.parent) {\n try {\n const targetStateNode = getStateNodeByPath(\n stateNode.parent,\n resolvedTarget\n );\n return targetStateNode;\n } catch (err: any) {\n throw new Error(\n isDevelopment\n ? `Invalid transition definition for state node '${stateNode.id}':\\n${err.message}`\n : `Invalid transition for '${stateNode.id}': ${err.message}`\n );\n }\n } else {\n throw new Error(\n isDevelopment\n ? `Invalid target: \"${target}\" is not a valid target from the root node. Did you mean \".${target}\"?`\n : `Invalid target: \"${target}\"`\n );\n }\n });\n}\n\nfunction resolveHistoryDefaultTransition(\n stateNode: AnyStateNode & { type: 'history' }\n): AnyTransitionDefinition {\n const normalizedTarget = normalizeTarget(stateNode.config.target);\n if (!normalizedTarget) {\n if (stateNode.parent!.type === 'parallel') {\n return {\n target: [stateNode.parent!],\n source: stateNode,\n reenter: false,\n eventType: '' as any\n };\n }\n return stateNode.parent!.initial as AnyTransitionDefinition;\n }\n const target = normalizedTarget.map((t) =>\n typeof t === 'string' ? getStateNodeByPath(stateNode.parent!, t) : t\n );\n assertLegalTargetSet(stateNode, target);\n return {\n target,\n source: stateNode,\n reenter: false,\n eventType: '' as any,\n to: (stateNode.config as any)._historyDefaultTransition\n };\n}\n\nfunction isHistoryNode(\n stateNode: AnyStateNode\n): stateNode is AnyStateNode & { type: 'history' } {\n return stateNode.type === 'history';\n}\n\nfunction getInitialStateNodes(stateNode: AnyStateNode) {\n const set = new Set<AnyStateNode>();\n\n function iter(descStateNode: AnyStateNode): void {\n if (set.has(descStateNode)) {\n return;\n }\n set.add(descStateNode);\n if (descStateNode.type === 'compound') {\n for (const target of descStateNode.initial.target ?? []) {\n iter(target);\n }\n } else if (descStateNode.type === 'parallel') {\n for (const child of getChildren(descStateNode)) {\n iter(child);\n }\n }\n }\n\n iter(stateNode);\n for (const initialState of set) {\n for (const ancestor of getProperAncestors(initialState, stateNode)) {\n set.add(ancestor);\n }\n }\n\n return set;\n}\n\n/** Returns the child state node from its relative `stateKey`, or throws. */\nfunction getStateNode(stateNode: AnyStateNode, stateKey: string): AnyStateNode {\n if (isStateId(stateKey)) {\n return stateNode.machine.getStateNodeById(stateKey);\n }\n const result = stateNode.states?.[stateKey];\n if (!result) {\n throw new Error(\n isDevelopment && !stateNode.states\n ? `Unable to retrieve child state '${stateKey}' from '${stateNode.id}'; no child states exist.`\n : `Child state '${stateKey}' does not exist on '${stateNode.id}'`\n );\n }\n return result;\n}\n\n/**\n * Returns the relative state node from the given `statePath`, or throws.\n *\n * @param statePath The string or string array relative path to the state node.\n */\nexport function getStateNodeByPath(\n stateNode: AnyStateNode,\n statePath: string | string[]\n): AnyStateNode {\n if (typeof statePath === 'string' && isStateId(statePath)) {\n try {\n return stateNode.machine.getStateNodeById(statePath);\n } catch {\n // try individual paths\n // throw e;\n }\n }\n const arrayStatePath = toStatePath(statePath).slice();\n let currentStateNode: AnyStateNode = stateNode;\n while (arrayStatePath.length) {\n const key = arrayStatePath.shift()!;\n if (!key.length) {\n break;\n }\n currentStateNode = getStateNode(currentStateNode, key);\n }\n return currentStateNode;\n}\n\n/**\n * Returns the state nodes represented by the current state value.\n *\n * @param stateValue The state value or State instance\n */\nexport function getStateNodes(\n stateNode: AnyStateNode,\n stateValue: StateValue\n): Array<AnyStateNode> {\n if (typeof stateValue === 'string') {\n const childStateNode = stateNode.states[stateValue];\n if (!childStateNode) {\n throw new Error(\n `State '${stateValue}' does not exist on '${stateNode.id}'`\n );\n }\n return [stateNode, childStateNode];\n }\n\n const childStateKeys = Object.keys(stateValue);\n const childStateNodes = new Array<AnyStateNode>(childStateKeys.length);\n const allStateNodes: Array<AnyStateNode> = [\n stateNode.machine.root,\n stateNode\n ];\n\n for (let i = 0; i < childStateKeys.length; i++) {\n const subStateNode = getStateNode(stateNode, childStateKeys[i]);\n childStateNodes[i] = subStateNode;\n allStateNodes.push(subStateNode);\n }\n\n for (let i = 0; i < childStateKeys.length; i++) {\n allStateNodes.push(\n ...getStateNodes(childStateNodes[i], stateValue[childStateKeys[i]]!)\n );\n }\n\n return allStateNodes;\n}\n\nexport type TransitionSelectionResult = {\n enabled: boolean;\n result: unknown;\n reusable: boolean;\n};\n\nexport type TransitionSelectionResults = Map<\n AnyTransitionDefinition,\n TransitionSelectionResult\n>;\n\nexport function transitionNode<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(\n stateNode: AnyStateNode,\n stateValue: StateValue,\n snapshot: MachineSnapshot<\n TContext,\n TEvent,\n any,\n any,\n any,\n any,\n any,\n any // TStateSchema\n >,\n event: TEvent,\n actorScope: AnyActorScope,\n selectionResults?: TransitionSelectionResults\n): Array<TransitionDefinition<TContext, TEvent>> | undefined {\n // leaf node\n if (typeof stateValue === 'string') {\n const childStateNode = getStateNode(stateNode, stateValue);\n const next = childStateNode.next(\n snapshot,\n event,\n actorScope,\n selectionResults\n );\n\n if (!next || !next.length) {\n return stateNode.next(snapshot, event, actorScope, selectionResults);\n }\n\n return next;\n }\n\n const subStateKeys = Object.keys(stateValue);\n const subStateKey = subStateKeys[0];\n\n if (subStateKeys.length === 1) {\n const childStateNode = getStateNode(stateNode, subStateKey);\n const next = transitionNode(\n childStateNode,\n stateValue[subStateKey]!,\n snapshot,\n event,\n actorScope,\n selectionResults\n );\n\n if (!next || !next.length) {\n return stateNode.next(snapshot, event, actorScope, selectionResults);\n }\n\n return next;\n }\n\n const allInnerTransitions: Array<TransitionDefinition<TContext, TEvent>> = [];\n\n for (const subStateKey of subStateKeys) {\n const subStateValue = stateValue[subStateKey];\n\n if (!subStateValue) {\n continue;\n }\n\n const subStateNode = getStateNode(stateNode, subStateKey);\n const innerTransitions = transitionNode(\n subStateNode,\n subStateValue,\n snapshot,\n event,\n actorScope,\n selectionResults\n );\n if (innerTransitions) {\n allInnerTransitions.push(...innerTransitions);\n }\n }\n\n if (!allInnerTransitions.length) {\n return stateNode.next(snapshot, event, actorScope, selectionResults);\n }\n\n return allInnerTransitions;\n}\n\nfunction isDescendant(\n childStateNode: AnyStateNode,\n parentStateNode: AnyStateNode\n): boolean {\n let marker = childStateNode;\n while (marker.parent && marker.parent !== parentStateNode) {\n marker = marker.parent;\n }\n\n return marker.parent === parentStateNode;\n}\n\nfunction hasDescendantState(\n stateNodes: Set<AnyStateNode>,\n parentStateNode: AnyStateNode\n): boolean {\n for (const stateNode of stateNodes) {\n if (isDescendant(stateNode, parentStateNode)) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction hasIntersection<T>(s1: Iterable<T>, s2: Iterable<T>): boolean {\n const s1Size =\n s1 instanceof Set ? s1.size : Array.isArray(s1) ? s1.length : undefined;\n const s2Size =\n s2 instanceof Set ? s2.size : Array.isArray(s2) ? s2.length : undefined;\n\n if (s1Size !== undefined && s2Size !== undefined && s2Size < s1Size) {\n [s1, s2] = [s2, s1];\n }\n\n const set1 = s1 instanceof Set ? s1 : new Set(s1);\n for (const item of s2) {\n if (set1.has(item)) {\n return true;\n }\n }\n return false;\n}\n\nfunction removeConflictingTransitions(\n enabledTransitions: Array<AnyTransitionDefinition>,\n stateNodeSet: Set<AnyStateNode>,\n snapshot: AnyMachineSnapshot,\n resolveTransition: TransitionResultResolver\n): Array<AnyTransitionDefinition> {\n const filteredTransitions = new Set<AnyTransitionDefinition>();\n const exitSets = new Map<AnyTransitionDefinition, Array<AnyStateNode>>();\n\n const getExitSet = (transition: AnyTransitionDefinition) => {\n let exitSet = exitSets.get(transition);\n if (!exitSet) {\n exitSet = computeExitSet(\n [transition],\n stateNodeSet,\n snapshot,\n resolveTransition\n );\n exitSets.set(transition, exitSet);\n }\n\n return exitSet;\n };\n\n for (const t1 of enabledTransitions) {\n let t1Preempted = false;\n const transitionsToRemove = new Set<AnyTransitionDefinition>();\n for (const t2 of filteredTransitions) {\n if (hasIntersection(getExitSet(t1), getExitSet(t2))) {\n if (isDescendant(t1.source, t2.source)) {\n transitionsToRemove.add(t2);\n } else if (t2.source.type === 'final' && t1.source.type !== 'final') {\n // A transition sourced in a final state yields to a conflicting\n // transition from a live state, so a done region doesn't keep\n // consuming events its siblings can still handle.\n transitionsToRemove.add(t2);\n } else {\n t1Preempted = true;\n break;\n }\n }\n }\n if (!t1Preempted) {\n for (const t3 of transitionsToRemove) {\n filteredTransitions.delete(t3);\n }\n filteredTransitions.add(t1);\n }\n }\n\n return Array.from(filteredTransitions);\n}\n\ntype ResolvableTransition = Parameters<typeof getTransitionResult>[0];\ntype TransitionResultResolver = (\n transition: ResolvableTransition\n) => ReturnType<typeof getTransitionResult>;\n\nfunction createTransitionResultResolver(\n snapshot: AnyMachineSnapshot,\n event: AnyEventObject,\n actorScope: AnyActorScope,\n resolveActions: boolean,\n selectionResults?: TransitionSelectionResults\n): TransitionResultResolver {\n let cache:\n | Map<ResolvableTransition, ReturnType<typeof getTransitionResult>>\n | undefined;\n return (transition) => {\n if (!transition.to) {\n return getTransitionResult(transition, snapshot, event, actorScope, {\n resolveActions,\n selectionResult: selectionResults?.get(\n transition as AnyTransitionDefinition\n )\n });\n }\n let result = cache?.get(transition);\n if (!result) {\n result = getTransitionResult(transition, snapshot, event, actorScope, {\n resolveActions,\n selectionResult: selectionResults?.get(\n transition as AnyTransitionDefinition\n )\n });\n (cache ??= new Map()).set(transition, result);\n }\n return result;\n };\n}\n\nfunction getEffectiveTargetStates(\n transition: Pick<AnyTransitionDefinition, 'target' | 'source'>,\n snapshot: AnyMachineSnapshot,\n resolveTransition: TransitionResultResolver\n): Array<AnyStateNode> {\n const historyValue = snapshot.historyValue;\n const { targets } = resolveTransition(transition);\n if (!targets) {\n return [];\n }\n\n const targetSet = new Set<AnyStateNode>();\n\n for (const targetNode of targets) {\n if (isHistoryNode(targetNode)) {\n if (historyValue[targetNode.id]) {\n for (const node of historyValue[targetNode.id]) {\n targetSet.add(node);\n }\n } else {\n for (const node of getEffectiveTargetStates(\n resolveHistoryDefaultTransition(targetNode),\n snapshot,\n resolveTransition\n )) {\n targetSet.add(node);\n }\n }\n } else {\n targetSet.add(targetNode);\n }\n }\n\n return [...targetSet];\n}\n\n/**\n * Narrows a parallel domain to the single child region that contains every\n * effective target, so that a transition confined to one region does not exit\n * (and reset) its sibling regions.\n */\nfunction narrowParallelDomain(\n domain: AnyStateNode,\n targetStates: Array<AnyStateNode>\n): AnyStateNode {\n let narrowed = domain;\n while (narrowed.type === 'parallel') {\n const region = getChildren(narrowed).find((child) =>\n targetStates.every(\n (target) => target === child || isDescendant(target, child)\n )\n );\n if (!region) {\n break;\n }\n narrowed = region;\n }\n return narrowed;\n}\n\nfunction getTransitionDomain(\n transition: AnyTransitionDefinition,\n snapshot: AnyMachineSnapshot,\n resolveTransition: TransitionResultResolver\n): AnyStateNode | undefined {\n const targetStates = getEffectiveTargetStates(\n transition,\n snapshot,\n resolveTransition\n );\n\n const { targets, reenter } = resolveTransition(transition);\n\n if (transition._transitionDomain) {\n if (\n transition._transitionDomain === 'internal' &&\n transition.source.type === 'compound' &&\n targetStates.every((target) => isDescendant(target, transition.source))\n ) {\n return transition.source;\n }\n\n const [head, ...tail] = targetStates.concat(transition.source);\n for (const ancestor of getProperAncestors(head, undefined)) {\n if (\n ancestor.type === 'compound' &&\n tail.every((stateNode) => isDescendant(stateNode, ancestor))\n ) {\n return ancestor;\n }\n }\n\n return;\n }\n\n // A history target that restores the source itself must exit and reenter\n // the source (SCXML domain = the source's ancestor), unlike a plain\n // non-reentering self-target: the enter set restores the stored\n // configuration from outside the source, so the exit set must match or the\n // source's invoked actors are re-created without being stopped.\n const restoresSourceViaHistory =\n targets?.some(isHistoryNode) &&\n targetStates.some((target) => target === transition.source);\n\n if (\n !restoresSourceViaHistory &&\n targetStates.every(\n (target) =>\n target === transition.source || isDescendant(target, transition.source)\n )\n ) {\n // Targets are contained within the source. A reentering transition\n // exits and reenters the source itself; otherwise the domain narrows\n // past parallel nodes so sibling regions are left untouched.\n return reenter\n ? transition.source\n : narrowParallelDomain(transition.source, targetStates);\n }\n\n const [head, ...tail] = targetStates.concat(transition.source);\n // Find the least common ancestor (LCA) of the source and effective targets.\n for (const ancestor of getProperAncestors(head, undefined)) {\n if (tail.every((sn) => isDescendant(sn, ancestor))) {\n // A cross-region transition (source in one parallel region, targets in\n // another) only exits the region containing its targets; the source\n // region and other sibling regions stay put unless it reenters.\n return reenter ? ancestor : narrowParallelDomain(ancestor, targetStates);\n }\n }\n\n // at this point we know that it's a root transition since LCA couldn't be found\n if (reenter) {\n return;\n }\n\n return narrowParallelDomain(transition.source.machine.root, targetStates);\n}\n\nfunction computeExitSet(\n transitions: Array<AnyTransitionDefinition>,\n stateNodeSet: Set<AnyStateNode>,\n snapshot: AnyMachineSnapshot,\n resolveTransition: TransitionResultResolver\n): Array<AnyStateNode> {\n const statesToExit = new Set<AnyStateNode>();\n for (const transition of transitions) {\n const { targets, reenter } = resolveTransition(transition);\n\n if (targets?.length) {\n const domain = getTransitionDomain(\n transition,\n snapshot,\n resolveTransition\n );\n\n if (reenter && transition.source === domain) {\n statesToExit.add(domain);\n }\n\n for (const stateNode of stateNodeSet) {\n if (isDescendant(stateNode, domain!)) {\n statesToExit.add(stateNode);\n }\n }\n }\n }\n\n return [...statesToExit];\n}\n\ntype Microstep = readonly [AnyMachineSnapshot, ExecutableActionObject[]];\n\nexport function initialMicrostep(\n root: AnyStateNode,\n preInitialState: AnyMachineSnapshot,\n actorScope: AnyActorScope,\n initEvent: AnyEventObject,\n internalQueue: AnyEventObject[]\n): Microstep {\n const initialStateNodes = [...getInitialStateNodes(root)];\n const statesForDefaultEntry = new Set<AnyStateNode>();\n const collectDefaultEntryStates = (stateNode: AnyStateNode): void => {\n if (stateNode.type === 'compound') {\n statesForDefaultEntry.add(stateNode);\n for (const target of stateNode.initial.target ?? []) {\n collectDefaultEntryStates(target);\n }\n } else if (stateNode.type === 'parallel') {\n for (const child of getChildren(stateNode)) {\n collectDefaultEntryStates(child);\n }\n }\n };\n collectDefaultEntryStates(root);\n return microstep(\n [\n {\n target: initialStateNodes.filter(\n (stateNode) =>\n !initialStateNodes.some(\n (other) => other !== stateNode && isDescendant(other, stateNode)\n )\n ),\n source: root,\n reenter: true,\n eventType: null as any,\n toJSON: null as any,\n _statesForDefaultEntry: [...statesForDefaultEntry]\n } as AnyTransitionDefinition\n ],\n preInitialState,\n actorScope,\n initEvent,\n true,\n internalQueue\n );\n}\n\n/** https://www.w3.org/TR/scxml/#microstepProcedure */\nfunction microstep(\n transitions: Array<AnyTransitionDefinition>,\n currentSnapshot: AnyMachineSnapshot,\n actorScope: AnyActorScope,\n event: AnyEventObject,\n isInitial: boolean,\n internalQueue: Array<AnyEventObject>,\n selectionResults?: TransitionSelectionResults\n): Microstep {\n const executableActions: ExecutableActionObject[] = [];\n\n if (!transitions.length) {\n return [currentSnapshot, executableActions];\n }\n\n {\n const mutStateNodeSet = new Set(currentSnapshot.nodes as StateNode[]);\n let historyValue = currentSnapshot.historyValue;\n const originalContext = currentSnapshot.context;\n\n const filteredTransitions =\n transitions.length === 1\n ? transitions\n : removeConflictingTransitions(\n transitions,\n mutStateNodeSet,\n currentSnapshot,\n createTransitionResultResolver(\n currentSnapshot,\n event,\n actorScope,\n false,\n selectionResults\n )\n );\n const getCurrentTransitionResult = createTransitionResultResolver(\n currentSnapshot,\n event,\n actorScope,\n true,\n selectionResults\n );\n const changesState = filteredTransitions.some((transition) => {\n const { targets, reenter } = getCurrentTransitionResult(transition);\n return !!targets?.length || !!reenter;\n });\n const getStateActionsAndContext = (\n transitionFn: any,\n context: MachineContext,\n children: AnyMachineSnapshot['children'],\n input: Record<string, unknown> | undefined\n ): [\n actions: any[],\n context: MachineContext | undefined,\n internalEvents: EventObject[] | undefined\n ] => {\n if (transitionFn.length === 2) {\n // enqueue action; retrieve\n const actions: any[] = [];\n const internalEvents: EventObject[] = [];\n let updatedContext: MachineContext | undefined;\n\n const enqueue = createTransitionEnqueue(\n actorScope,\n actions,\n internalEvents,\n true\n );\n\n const args = isLazyActorScope(actorScope)\n ? withActorScope(\n {\n context,\n event,\n children,\n actions: currentSnapshot.machine.sources.actions,\n actors: currentSnapshot.machine.sources.actors,\n guards: currentSnapshot.machine.sources.guards,\n delays: currentSnapshot.machine.sources.delays,\n input\n },\n actorScope\n )\n : {\n context,\n event,\n parent: actorScope.self._parent,\n self: actorScope.self,\n children,\n system: actorScope.system,\n actions: currentSnapshot.machine.sources.actions,\n actors: currentSnapshot.machine.sources.actors,\n guards: currentSnapshot.machine.sources.guards,\n delays: currentSnapshot.machine.sources.delays,\n input\n };\n const res = transitionFn(args, enqueue);\n\n if (res?.context !== undefined) {\n updatedContext = mergeContextPatch(context, res.context);\n }\n\n return [actions, updatedContext, internalEvents];\n }\n\n // For 1-argument actions, wrap them to include input\n // Preserve _special flag if present (for entry/exit actions)\n const wrappedAction = Object.assign(\n (args: any, enqueue: any) =>\n transitionFn(\n isLazyActorScope(actorScope)\n ? withActorScope(\n {\n context: args.context,\n event: args.event,\n output: args.output,\n children: args.children,\n actions: args.actions,\n actors: args.actors,\n input\n },\n actorScope\n )\n : { ...args, input },\n enqueue\n ),\n '_special' in transitionFn ? { _special: true } : {}\n );\n return [[wrappedAction], undefined, undefined];\n };\n\n let nextState = currentSnapshot;\n const getInvokeStopActions = (\n stateNode: AnyStateNode,\n children: AnyMachineSnapshot['children']\n ): AnyAction[] => {\n const actions: AnyAction[] = [];\n const enqueue = createTransitionEnqueue(actorScope, actions, []);\n for (const invokeDef of stateNode.invoke) {\n const child = children[invokeDef.id];\n if (child) {\n enqueue.stop(child);\n }\n }\n return actions;\n };\n const exitStates = () => {\n const statesToExit = computeExitSet(\n filteredTransitions,\n mutStateNodeSet,\n currentSnapshot,\n getCurrentTransitionResult\n );\n\n statesToExit.sort((a, b) => b.order - a.order);\n\n let changedHistory: HistoryValue | undefined;\n const currentStateNodes = [...mutStateNodeSet];\n\n // From SCXML algorithm: https://www.w3.org/TR/scxml/#exitStates\n for (const exitStateNode of statesToExit) {\n for (const historyNode of Object.values(exitStateNode.states)) {\n if (historyNode.type !== 'history') {\n continue;\n }\n\n const predicate =\n historyNode.history === 'deep'\n ? (sn: AnyStateNode) =>\n isAtomicStateNode(sn) && isDescendant(sn, exitStateNode)\n : (sn: AnyStateNode) => sn.parent === exitStateNode;\n\n changedHistory ??= { ...historyValue };\n changedHistory[historyNode.id] = currentStateNodes.filter(predicate);\n }\n }\n\n for (const exitStateNode of statesToExit) {\n const stateInput = getStateInput(currentSnapshot, exitStateNode.id);\n\n const [exitActions, nextContext, internalEvents] = exitStateNode.exit\n ? getStateActionsAndContext(\n exitStateNode.exit,\n nextState.context,\n currentSnapshot.children,\n stateInput\n )\n : [[], undefined, undefined];\n if (internalEvents?.length) {\n internalQueue.push(...internalEvents);\n }\n if (nextContext) {\n nextState = cloneMachineSnapshot(nextState, {\n context: nextContext\n });\n }\n const [resolvedState, resolvedActions] = resolveActionsWithContext(\n nextState,\n event,\n actorScope,\n exitActions\n );\n nextState = resolvedState;\n executableActions.push(...resolvedActions);\n\n const invokeStopActions = getInvokeStopActions(\n exitStateNode,\n nextState.children\n );\n if (invokeStopActions.length) {\n const [stoppedState, stopEffects] = resolveActionsWithContext(\n nextState,\n event,\n actorScope,\n invokeStopActions\n );\n nextState = stoppedState;\n executableActions.push(...stopEffects);\n }\n\n mutStateNodeSet.delete(exitStateNode);\n }\n\n historyValue = changedHistory || historyValue;\n };\n\n // Exit states\n if (!isInitial && changesState) {\n exitStates();\n }\n\n let context = nextState.context;\n const transitionActions: AnyAction[] = [];\n const internalEvents: EventObject[] = [];\n\n for (const t of filteredTransitions) {\n if (t.actions) {\n transitionActions.push(...toArray(t.actions));\n }\n const res = getCurrentTransitionResult(t);\n if (res.context !== undefined) {\n context = mergeContextPatch(context, res.context);\n }\n if (res.actions) {\n transitionActions.push(...res.actions);\n }\n if (res.internalEvents) {\n internalEvents.push(...res.internalEvents);\n }\n }\n\n if (internalEvents.length) {\n internalQueue.push(...internalEvents);\n }\n\n const enterStates = () => {\n const getMachineOutput = (rootCompletionNode: AnyStateNode) => {\n const rootNode = nextState.machine.root;\n\n let completionOutput: unknown;\n if (\n rootCompletionNode.output !== undefined &&\n rootCompletionNode.parent\n ) {\n const rootDoneEvent = internalQueue.find(\n (e) =>\n e.type === 'xstate.done.state' &&\n (e as DoneStateEvent).stateId === rootNode.id\n ) as DoneStateEvent | undefined;\n completionOutput =\n rootDoneEvent && rootCompletionNode.parent === rootNode\n ? rootDoneEvent.output\n : resolveOutput(\n rootCompletionNode.output,\n nextState.context,\n event,\n actorScope.self,\n stateInputMap[rootCompletionNode.id]\n );\n } else if (rootCompletionNode.type === 'parallel') {\n const parallelDoneEvent = internalQueue.find(\n (e) =>\n e.type === 'xstate.done.state' &&\n (e as DoneStateEvent).stateId === rootCompletionNode.id\n ) as DoneStateEvent | undefined;\n completionOutput = parallelDoneEvent?.output;\n }\n\n if (rootNode.output === undefined) {\n return rootCompletionNode.parent === rootNode\n ? completionOutput\n : undefined;\n }\n\n return resolveOutput(\n rootNode.output,\n nextState.context,\n createDoneStateEvent(rootCompletionNode.id, completionOutput),\n actorScope.self\n );\n };\n\n const statesToEnter = new Set<AnyStateNode>();\n // those are states that were directly targeted or indirectly targeted by the explicit target\n // in other words, those are states for which initial actions should be executed\n // when we target `#deep_child` initial actions of its ancestors shouldn't be executed\n const statesForDefaultEntry = new Set<AnyStateNode>();\n const historyDefaultsByParent = new Map<\n AnyStateNode,\n AnyTransitionDefinition[]\n >();\n const addAncestorStatesToEnter = (\n ancestors: AnyStateNode[],\n reentrancyDomain: AnyStateNode | undefined\n ) => {\n for (const anc of ancestors) {\n if (!reentrancyDomain || isDescendant(anc, reentrancyDomain)) {\n statesToEnter.add(anc);\n }\n if (anc.type === 'parallel') {\n for (const child of getChildren(anc)) {\n if (!hasDescendantState(statesToEnter, child)) {\n statesToEnter.add(child);\n addDescendantStatesToEnter(child);\n }\n }\n }\n }\n };\n\n const addDescendantStatesToEnter = (stateNode: AnyStateNode) => {\n if (isHistoryNode(stateNode)) {\n if (historyValue[stateNode.id]) {\n const historyStateNodes = historyValue[stateNode.id];\n for (const s of historyStateNodes) {\n statesToEnter.add(s);\n addDescendantStatesToEnter(s);\n }\n for (const s of historyStateNodes) {\n addAncestorStatesToEnter(\n getProperAncestors(s, stateNode.parent),\n undefined\n );\n }\n } else {\n const historyDefaultTransition =\n resolveHistoryDefaultTransition(stateNode);\n const historyParent = stateNode.parent!;\n statesForDefaultEntry.add(historyParent);\n const defaults = historyDefaultsByParent.get(historyParent) ?? [];\n defaults.push(historyDefaultTransition);\n historyDefaultsByParent.set(historyParent, defaults);\n const { targets } = getCurrentTransitionResult(\n historyDefaultTransition\n );\n for (const s of targets ?? []) {\n statesToEnter.add(s);\n\n if (historyDefaultTransition === stateNode.parent?.initial) {\n statesForDefaultEntry.add(stateNode.parent);\n }\n\n addDescendantStatesToEnter(s);\n }\n\n for (const s of targets ?? []) {\n addAncestorStatesToEnter(\n getProperAncestors(s, stateNode.parent),\n undefined\n );\n }\n }\n return;\n }\n\n if (stateNode.type === 'compound') {\n const initialStates =\n getCurrentTransitionResult(stateNode.initial).targets ?? [];\n\n for (const initialState of initialStates) {\n if (!isHistoryNode(initialState)) {\n statesToEnter.add(initialState);\n }\n }\n statesForDefaultEntry.add(stateNode);\n for (const initialState of initialStates) {\n addDescendantStatesToEnter(initialState);\n }\n for (const initialState of initialStates) {\n addAncestorStatesToEnter(\n getProperAncestors(initialState, stateNode),\n undefined\n );\n }\n return;\n }\n\n if (stateNode.type === 'parallel') {\n for (const child of getChildren(stateNode)) {\n if (!hasDescendantState(statesToEnter, child)) {\n statesToEnter.add(child);\n statesForDefaultEntry.add(child);\n addDescendantStatesToEnter(child);\n }\n }\n }\n };\n\n for (const transition of filteredTransitions) {\n const domain = getTransitionDomain(\n transition,\n currentSnapshot,\n getCurrentTransitionResult\n );\n\n const { targets, reenter } = getCurrentTransitionResult(transition);\n\n for (const targetNode of targets ?? []) {\n if (\n !isHistoryNode(targetNode) &&\n (transition.source !== targetNode ||\n transition.source !== domain ||\n reenter)\n ) {\n statesToEnter.add(targetNode);\n statesForDefaultEntry.add(targetNode);\n }\n addDescendantStatesToEnter(targetNode);\n }\n const targetStates = getEffectiveTargetStates(\n transition,\n currentSnapshot,\n getCurrentTransitionResult\n );\n for (const s of targetStates) {\n const ancestors = getProperAncestors(s, domain);\n if (domain?.type === 'parallel') {\n ancestors.push(domain);\n }\n addAncestorStatesToEnter(\n ancestors,\n !transition.source.parent && reenter ? undefined : domain\n );\n }\n if (reenter && domain === transition.source) {\n // A reentering transition whose domain is its own source exits and\n // reenters the source, so the source must be entered explicitly —\n // it has no ancestor inside the domain to add it.\n statesToEnter.add(transition.source);\n }\n }\n\n if (isInitial) {\n for (const stateNode of (filteredTransitions[0] as any)\n ._statesForDefaultEntry ?? [currentSnapshot.machine.root]) {\n statesForDefaultEntry.add(stateNode);\n }\n }\n\n const stateInputMap: Record<string, Record<string, unknown>> = {\n ...currentSnapshot._stateInputs\n };\n let stateInputsChanged = false;\n for (const transition of filteredTransitions) {\n const { targets, input } = getCurrentTransitionResult(transition);\n if (input && targets) {\n for (const targetNode of targets) {\n stateInputMap[targetNode.id] = input;\n stateInputsChanged = true;\n }\n }\n }\n\n const completedNodes = new Set<AnyStateNode>();\n const children = { ...nextState.children };\n for (const stateNodeToEnter of [...statesToEnter].sort(\n (a, b) => a.order - b.order\n )) {\n mutStateNodeSet.add(stateNodeToEnter);\n const actions: AnyAction[] = [];\n\n let invoked = false;\n for (const invokeDef of stateNodeToEnter.invoke) {\n invoked = true;\n\n let src = invokeDef.logic;\n if (typeof src === 'function') {\n src = src({\n actors: currentSnapshot.machine.sources.actors,\n context: nextState.context,\n event,\n self: actorScope.self\n });\n }\n\n const logic =\n typeof src === 'string'\n ? resolveReferencedActor(currentSnapshot.machine, src)\n : src;\n\n if (!logic) {\n throw new Error(\n isDevelopment\n ? `Actor logic '${typeof src === 'string' ? src : 'inline'}' not implemented in machine '${currentSnapshot.machine.id}'`\n : `Actor logic '${typeof src === 'string' ? src : 'inline'}' not implemented`\n );\n }\n\n const input =\n typeof invokeDef.input === 'function'\n ? invokeDef.input({\n self: actorScope.self,\n context: nextState.context,\n event,\n input: stateInputMap[stateNodeToEnter.id],\n output: getEventOutput(event)\n })\n : invokeDef.input;\n\n assertChildIdFree(actorScope, invokeDef.id);\n const actor = actorScope.system.createActorRef(logic, {\n ...invokeDef,\n input,\n parent: actorScope.self,\n syncSnapshot: !!invokeDef.onSnapshot\n });\n\n actions.push({\n action: builtInActions['@xstate.spawn'],\n args: [actor]\n });\n\n if (invokeDef.id) {\n children[invokeDef.id] = actor;\n }\n }\n\n if (invoked) {\n nextState = cloneMachineSnapshot(nextState, { children });\n }\n let context = nextState.context;\n let contextChangedByEntry = false;\n\n const stateInput = stateInputMap[stateNodeToEnter.id];\n\n if (stateNodeToEnter.entry) {\n const [resultActions, nextContext, nextInternalEvents] =\n getStateActionsAndContext(\n stateNodeToEnter.entry,\n context,\n children,\n stateInput\n );\n actions.push(...resultActions);\n if (nextInternalEvents?.length) {\n internalQueue.push(...nextInternalEvents);\n }\n if (nextContext) {\n context = nextContext;\n contextChangedByEntry = true;\n }\n }\n\n if (contextChangedByEntry) {\n nextState.context = context;\n }\n\n if (statesForDefaultEntry.has(stateNodeToEnter)) {\n const defaultTransitions = [\n stateNodeToEnter.initial,\n ...(historyDefaultsByParent.get(stateNodeToEnter) ?? [])\n ].filter(Boolean);\n for (const defaultTransition of defaultTransitions) {\n const {\n actions: initialActions,\n context: initialContext,\n input: initialInput,\n internalEvents: initialInternalEvents\n } = getTransitionResult(\n defaultTransition,\n nextState,\n event,\n actorScope\n );\n if (initialActions) {\n actions.push(...initialActions);\n }\n if (initialInternalEvents?.length) {\n internalQueue.push(...initialInternalEvents);\n }\n if (initialContext !== undefined) {\n nextState.context = mergeContextPatch(\n nextState.context,\n initialContext\n );\n }\n if (initialInput && defaultTransition.target) {\n for (const targetNode of defaultTransition.target) {\n stateInputMap[targetNode.id] = initialInput;\n stateInputsChanged = true;\n }\n }\n }\n }\n\n const [resolvedState, resolvedActions] = resolveActionsWithContext(\n nextState,\n event,\n actorScope,\n actions\n );\n nextState = resolvedState;\n actions.length = 0;\n executableActions.push(...resolvedActions);\n\n if (stateNodeToEnter.type !== 'final') {\n continue;\n }\n\n const parent = stateNodeToEnter.parent;\n let ancestorMarker =\n parent?.type === 'parallel' ? parent : parent?.parent;\n let rootCompletionNode = ancestorMarker || stateNodeToEnter;\n\n if (parent?.type === 'compound') {\n internalQueue.push(\n createDoneStateEvent(\n parent.id,\n stateNodeToEnter.output !== undefined\n ? resolveOutput(\n stateNodeToEnter.output,\n nextState.context,\n event,\n actorScope.self,\n stateInput\n )\n : undefined\n )\n );\n }\n\n while (\n ancestorMarker?.type === 'parallel' &&\n !completedNodes.has(ancestorMarker) &&\n isInFinalState(mutStateNodeSet, ancestorMarker)\n ) {\n completedNodes.add(ancestorMarker);\n const regionOutput: Record<string, unknown> = {};\n for (const region of getChildren(ancestorMarker)) {\n if (region.type === 'final') {\n regionOutput[region.key] =\n region.output !== undefined\n ? resolveOutput(\n region.output,\n nextState.context,\n event,\n actorScope.self,\n stateInputMap[region.id]\n )\n : undefined;\n continue;\n }\n\n if (region.type === 'parallel') {\n const regionDoneEvent = internalQueue.find(\n (e) =>\n e.type === 'xstate.done.state' &&\n (e as DoneStateEvent).stateId === region.id\n ) as DoneStateEvent | undefined;\n regionOutput[region.key] = regionDoneEvent?.output;\n continue;\n }\n\n const finalChild = getChildren(region).find(\n (s) => s.type === 'final' && mutStateNodeSet.has(s)\n );\n regionOutput[region.key] =\n finalChild?.output !== undefined\n ? resolveOutput(\n finalChild.output,\n nextState.context,\n event,\n actorScope.self,\n stateInputMap[finalChild.id]\n )\n : undefined;\n }\n internalQueue.push(\n createDoneStateEvent(ancestorMarker.id, regionOutput)\n );\n rootCompletionNode = ancestorMarker;\n ancestorMarker = ancestorMarker.parent;\n }\n if (ancestorMarker) {\n continue;\n }\n\n nextState = cloneMachineSnapshot(nextState, {\n status: 'done',\n output: getMachineOutput(rootCompletionNode)\n });\n }\n\n if (stateInputsChanged) {\n nextState = cloneMachineSnapshot(nextState, {\n _stateInputs: stateInputMap\n });\n }\n };\n\n // Execute transition content\n const [resolvedTransitionState, transitionExecutableActions] =\n resolveActionsWithContext(\n nextState,\n event,\n actorScope,\n transitionActions\n );\n nextState = resolvedTransitionState;\n executableActions.push(...transitionExecutableActions);\n if (context && context !== currentSnapshot.context) {\n nextState = cloneMachineSnapshot(nextState, { context });\n }\n\n // Enter states\n if (isInitial || changesState) {\n enterStates();\n }\n\n const nextStateNodes = [...mutStateNodeSet];\n\n if (nextState.status === 'done') {\n const allExitActions: AnyAction[] = [];\n const nextStateNodesToExit = nextStateNodes.sort(\n (a, b) => b.order - a.order\n );\n\n nextStateNodesToExit.forEach((stateNode) => {\n if (stateNode.exit) {\n const stateInput = getStateInput(nextState, stateNode.id);\n const [exitActions, , nextInternalEvents] = getStateActionsAndContext(\n stateNode.exit,\n nextState.context,\n nextState.children,\n stateInput\n );\n allExitActions.push(...exitActions);\n if (nextInternalEvents?.length) {\n internalQueue.push(...nextInternalEvents);\n }\n }\n });\n\n const [resolvedState, resolvedActions] = resolveActionsWithContext(\n nextState,\n event,\n actorScope,\n allExitActions\n );\n nextState = resolvedState;\n executableActions.push(...resolvedActions);\n\n const [stoppedState, stopEffects] = stopChildren(\n nextState,\n event,\n actorScope\n );\n nextState = stoppedState;\n executableActions.push(...stopEffects);\n\n const [withoutTimers, cancelEffects] = cancelTimers(\n nextState,\n event,\n actorScope\n );\n nextState = withoutTimers;\n executableActions.push(...cancelEffects);\n }\n\n if (\n historyValue === currentSnapshot.historyValue &&\n currentSnapshot.nodes.length === mutStateNodeSet.size &&\n currentSnapshot.nodes.every((node) =>\n mutStateNodeSet.has(node as StateNode)\n )\n ) {\n // If context was changed (e.g. by entry actions during self-transition),\n // clone to ensure reference inequality for eventless transition re-evaluation\n if (nextState.context !== originalContext) {\n return [\n nextState === currentSnapshot\n ? cloneMachineSnapshot(nextState)\n : nextState,\n executableActions\n ];\n }\n return [nextState, executableActions];\n }\n\n return [\n cloneMachineSnapshot(nextState, {\n _nodes: nextStateNodes,\n historyValue\n }),\n executableActions\n ];\n }\n}\n\n/**\n * Gets the transition result for a given transition without executing the\n * transition.\n */\nexport function getTransitionResult(\n transition: Pick<AnyTransitionDefinition, 'target' | 'to' | 'source'> & {\n reenter?: AnyTransitionDefinition['reenter'];\n input?: AnyTransitionDefinition['input'];\n context?: AnyTransitionDefinition['context'];\n },\n snapshot: AnyMachineSnapshot,\n event: AnyEventObject,\n actorScope: AnyActorScope,\n options?: {\n resolveActions?: boolean;\n selectionResult?: TransitionSelectionResult;\n }\n): {\n targets: Readonly<AnyStateNode[]> | undefined;\n context: MachineContext | undefined;\n actions: AnyAction[] | undefined;\n reenter?: boolean;\n internalEvents: EventObject[] | undefined;\n input: Record<string, unknown> | undefined;\n} {\n let transitionArgs: any;\n const getTransitionArgs = () =>\n (transitionArgs ??= isLazyActorScope(actorScope)\n ? withActorScope(\n {\n context: snapshot.context,\n event,\n output: getEventOutput(event),\n value: snapshot.value,\n children: snapshot.children,\n actions: snapshot.machine.sources.actions,\n actors: snapshot.machine.sources.actors,\n guards: snapshot.machine.sources.guards,\n delays: snapshot.machine.sources.delays,\n input: getStateInput(snapshot, transition.source.id)\n },\n actorScope\n )\n : {\n context: snapshot.context,\n event,\n output: getEventOutput(event),\n value: snapshot.value,\n children: snapshot.children,\n system: actorScope.system,\n parent: actorScope.self._parent,\n self: actorScope.self,\n actions: snapshot.machine.sources.actions,\n actors: snapshot.machine.sources.actors,\n guards: snapshot.machine.sources.guards,\n delays: snapshot.machine.sources.delays,\n input: getStateInput(snapshot, transition.source.id)\n });\n\n if (transition.to) {\n const actions: AnyAction[] = [];\n const internalEvents: EventObject[] = [];\n const res = options?.selectionResult?.reusable\n ? options.selectionResult.result\n : transition.to(\n getTransitionArgs(),\n createTransitionEnqueue(\n actorScope,\n actions,\n internalEvents,\n true,\n options?.resolveActions ?? true\n )\n );\n\n const targets = res?.target\n ? resolveTarget(transition.source, toArray(res.target) as string[])\n : undefined;\n\n const resolvedInput =\n res?.input ??\n (typeof transition.input === 'function'\n ? transition.input({\n context: snapshot.context,\n event,\n output: getEventOutput(event)\n })\n : transition.input);\n\n return {\n targets: targets,\n context: res?.context,\n reenter: res?.reenter,\n actions,\n internalEvents,\n input: resolvedInput\n };\n }\n\n // Resolve input for regular transitions\n const resolvedInput =\n typeof transition.input === 'function'\n ? transition.input({\n context: snapshot.context,\n event,\n output: getEventOutput(event)\n })\n : transition.input;\n const resolvedContext =\n typeof transition.context === 'function'\n ? transition.context(getTransitionArgs())\n : transition.context;\n\n return {\n targets: transition.target as AnyStateNode[] | undefined,\n context: resolvedContext,\n reenter: transition.reenter,\n actions: undefined,\n internalEvents: undefined,\n input: resolvedInput\n };\n}\n\nexport function macrostep(\n snapshot: AnyMachineSnapshot,\n event: EventObject,\n actorScope: AnyActorScope,\n internalQueue: AnyEventObject[],\n initialMicrosteps: Microstep[] = []\n): {\n snapshot: typeof snapshot;\n microsteps: Microstep[];\n} {\n let nextSnapshot = snapshot;\n const microsteps: Microstep[] = initialMicrosteps.slice();\n\n function removeTerminatedChild(terminalEvent: EventObject) {\n if (\n terminalEvent.type !== 'xstate.done.actor' &&\n terminalEvent.type !== 'xstate.error.actor'\n ) {\n return;\n }\n\n const { actorId, sessionId } = terminalEvent as AnyEventObject & {\n actorId?: string;\n sessionId?: string;\n };\n if (!actorId) {\n return;\n }\n const child = nextSnapshot.children[actorId];\n if (!child) {\n return;\n }\n // The same staleness rule matchesActorSession applies to transition\n // selection: a completion from a different incarnation must not remove\n // the still-running child either.\n if (child.sessionId !== undefined && child.sessionId !== sessionId) {\n return;\n }\n\n const children = { ...nextSnapshot.children };\n delete children[actorId];\n actorScope.system._unregister(child);\n nextSnapshot = cloneMachineSnapshot(nextSnapshot, { children });\n\n if (microsteps.length) {\n const [, lastEffects] = microsteps.at(-1)!;\n microsteps[microsteps.length - 1] = [nextSnapshot, lastEffects];\n } else {\n microsteps.push([nextSnapshot, []]);\n }\n }\n\n function completeMacrostep() {\n const effects = microsteps.flatMap(([, actions]) => actions);\n const starts = deriveDeferredStarts(effects);\n const shouldTerminate =\n (snapshot.status === 'active' || initialMicrosteps.length > 0) &&\n (nextSnapshot.status === 'done' || nextSnapshot.status === 'error');\n\n if (starts.length || shouldTerminate) {\n const terminalEffects = shouldTerminate\n ? [...starts, createTerminationEffect(actorScope, nextSnapshot)]\n : starts;\n if (microsteps.length) {\n const [lastSnapshot, lastEffects] = microsteps.at(-1)!;\n microsteps[microsteps.length - 1] = [\n lastSnapshot,\n [...lastEffects, ...terminalEffects]\n ];\n } else {\n microsteps.push([nextSnapshot, terminalEffects]);\n }\n }\n\n return { snapshot: nextSnapshot, microsteps };\n }\n\n function addMicrostep(\n step: Microstep,\n transitions: AnyTransitionDefinition[]\n ) {\n // collect microsteps; surfaced on the enclosing '@xstate.transition' event\n // via its `microsteps[]` facet (there is no standalone microstep event)\n if (\n !isInertActorScope(actorScope) &&\n (event.type === XSTATE_INIT ||\n (actorScope.system._hasInspectionObservers?.() ?? true))\n ) {\n const collectedMicrosteps =\n ((actorScope.self as any)._collectedMicrosteps as any[]) || [];\n collectedMicrosteps.push(...transitions);\n (actorScope.self as any)._collectedMicrosteps = collectedMicrosteps;\n }\n microsteps.push(step);\n }\n\n // Handle stop event\n if (event.type === XSTATE_STOP) {\n const [stoppedChildrenSnapshot, stopEffects] = stopChildren(\n nextSnapshot,\n event,\n actorScope\n );\n const [withoutTimers, cancelEffects] = cancelTimers(\n stoppedChildrenSnapshot,\n event,\n actorScope\n );\n nextSnapshot = cloneMachineSnapshot(withoutTimers, {\n status: 'stopped'\n });\n addMicrostep([nextSnapshot, [...stopEffects, ...cancelEffects]], []);\n return completeMacrostep();\n }\n\n let nextEvent = normalizeLegacyInternalEvent(event, snapshot.machine);\n\n if (event.type === XSTATE_TIMER) {\n const timer = nextSnapshot.timers[(event as any).id];\n if (!timer) {\n return completeMacrostep();\n }\n\n const timers = { ...nextSnapshot.timers };\n delete timers[timer.id];\n nextSnapshot = cloneMachineSnapshot(nextSnapshot, { timers });\n if (timer.type === '@xstate.raise') {\n internalQueue.push(timer.event);\n addMicrostep([nextSnapshot, []], []);\n } else {\n const target = timer.target === 'self' ? actorScope.self : timer.target;\n addMicrostep(\n [nextSnapshot, [createSendToEffect(actorScope, target, timer.event)]],\n []\n );\n }\n }\n\n // Assume the state is at rest (no raised events)\n // Determine the next state based on the next microstep\n if (nextEvent.type !== XSTATE_INIT && nextEvent.type !== XSTATE_TIMER) {\n const currentEvent = nextEvent;\n const isErr = isErrorEvent(currentEvent);\n const selectionResults: TransitionSelectionResults = new Map();\n\n const transitions = nextSnapshot.machine.getTransitionData(\n nextSnapshot as any,\n currentEvent,\n actorScope,\n selectionResults\n );\n\n if (isErr && !transitions.length) {\n if (\n currentEvent.type === 'xstate.error.actor' &&\n !matchesActorSession(\n currentEvent,\n nextSnapshot,\n (currentEvent as AnyEventObject).actorId\n )\n ) {\n return completeMacrostep();\n }\n // TODO: we should likely only allow transitions selected by very explicit descriptors\n // `*` shouldn't be matched, likely `xstate.error.*` shouldn't be either\n // similarly `xstate.error.actor.*` and `xstate.error.actor.todo.*` have to be considered too\n nextSnapshot = cloneMachineSnapshot<typeof snapshot>(snapshot, {\n status: 'error',\n error: currentEvent.error\n });\n addMicrostep([nextSnapshot, []], []);\n removeTerminatedChild(currentEvent);\n return completeMacrostep();\n }\n const step = microstep(\n transitions,\n snapshot,\n actorScope,\n nextEvent,\n false, // isInitial\n internalQueue,\n selectionResults\n );\n nextSnapshot = step[0];\n addMicrostep(step, transitions);\n removeTerminatedChild(currentEvent);\n }\n\n if (\n !internalQueue.length &&\n snapshot.machine._hasEventlessTransitions === false\n ) {\n return completeMacrostep();\n }\n\n let shouldSelectEventlessTransitions = true;\n const maxIterations = snapshot.machine.options?.maxIterations ?? Infinity;\n let iterationCount = 0;\n\n let microstepCount = 0;\n while (nextSnapshot.status === 'active') {\n microstepCount++;\n if (microstepCount > 1000) {\n throw new Error('Microstep count exceeded 1000');\n }\n iterationCount++;\n if (iterationCount > maxIterations) {\n throw new Error(\n isDevelopment\n ? `Infinite loop detected: the machine has processed more than ${maxIterations} microsteps without reaching a stable state. This usually happens when there's a cycle of transitions (e.g., eventless transitions or raised events causing state A -> B -> C -> A).`\n : `Infinite loop detected (>${maxIterations} microsteps)`\n );\n }\n\n let selectionResults: TransitionSelectionResults | undefined;\n let enabledTransitions: AnyTransitionDefinition[] =\n shouldSelectEventlessTransitions\n ? selectEventlessTransitions(nextSnapshot, nextEvent, actorScope)\n : [];\n\n // eventless transitions should always be selected after selecting *regular* transitions\n // by assigning `undefined` to `previousState` we ensure that `shouldSelectEventlessTransitions` gets always computed to true in such a case\n const previousState = enabledTransitions.length ? nextSnapshot : undefined;\n\n if (!enabledTransitions.length) {\n if (!internalQueue.length) {\n break;\n }\n nextEvent = internalQueue.shift()!;\n selectionResults = new Map();\n enabledTransitions = nextSnapshot.machine.getTransitionData(\n nextSnapshot as any,\n nextEvent,\n actorScope,\n selectionResults\n );\n }\n\n const step = microstep(\n enabledTransitions,\n nextSnapshot,\n actorScope,\n nextEvent,\n false,\n internalQueue,\n selectionResults\n );\n nextSnapshot = step[0];\n shouldSelectEventlessTransitions = nextSnapshot !== previousState;\n addMicrostep(step, enabledTransitions);\n removeTerminatedChild(nextEvent);\n }\n\n return completeMacrostep();\n}\n\n/**\n * Resolves a partial state value with its full representation in the state\n * node's machine.\n *\n * @param stateValue The partial state value to resolve.\n */\nexport function resolveStateValue(\n rootNode: AnyStateNode,\n stateValue: StateValue\n): StateValue {\n const allStateNodes = getAllStateNodes(getStateNodes(rootNode, stateValue));\n return getStateValue(rootNode, allStateNodes);\n}\n\nexport function hasEffect(\n transition: AnyTransitionDefinition,\n context: MachineContext,\n event: EventObject,\n snapshot: AnyMachineSnapshot,\n actorScope: AnyActorScope\n): boolean {\n if (transition.to) {\n return evaluateTransitionFunction(\n transition.to,\n context,\n event,\n snapshot,\n actorScope,\n snapshot.machine.sources,\n transition.source.id\n ).enabled;\n }\n\n return false;\n}\n\nconst triggerTransitionEffect = () => {\n throw transitionEffectSignal;\n};\nlet transitionEffectEnqueue: ReturnType<typeof createEnqueueObject> | undefined;\nfunction getTransitionEffectEnqueue() {\n return (transitionEffectEnqueue ??= createEnqueueObject(\n {\n emit: triggerTransitionEffect,\n cancel: triggerTransitionEffect,\n log: triggerTransitionEffect,\n raise: triggerTransitionEffect,\n spawn: triggerTransitionEffect,\n sendTo: triggerTransitionEffect,\n stop: triggerTransitionEffect,\n listen: triggerTransitionEffect,\n subscribeTo: triggerTransitionEffect\n },\n triggerTransitionEffect\n ));\n}\n\nfunction evaluateTransitionFunction(\n transitionTo: NonNullable<AnyTransitionDefinition['to']>,\n context: MachineContext,\n event: EventObject,\n snapshot: AnyMachineSnapshot,\n actorScope: AnyActorScope,\n sources: AnyMachineSnapshot['machine']['sources'],\n sourceId: string\n): TransitionSelectionResult {\n let res;\n const parent = getActorScopeParent(actorScope);\n if (parent) {\n transitionEffectTargets.push(parent);\n }\n\n try {\n res = transitionTo(\n withActorScope(\n {\n context,\n event,\n output: getEventOutput(event),\n value: snapshot.value,\n children: snapshot.children,\n actions: sources.actions,\n actors: sources.actors,\n guards: sources.guards,\n delays: sources.delays,\n input: getStateInput(snapshot, sourceId)\n },\n actorScope\n ),\n getTransitionEffectEnqueue()\n );\n } catch (err) {\n if (err === transitionEffectSignal) {\n return { enabled: true, result: undefined, reusable: false };\n }\n throw err;\n } finally {\n if (parent) {\n transitionEffectTargets.pop();\n }\n }\n\n return { enabled: res !== undefined, result: res, reusable: true };\n}\n\nfunction stopChildren(\n snapshot: AnyMachineSnapshot,\n event: AnyEventObject,\n actorScope: AnyActorScope\n): [AnyMachineSnapshot, ExecutableActionObject[]] {\n let children: AnyActor[];\n if (\n !snapshot.children ||\n (children = Object.values(snapshot.children).filter(Boolean) as AnyActor[])\n .length === 0\n ) {\n return [snapshot, []];\n }\n const actions: AnyAction[] = [];\n const enqueue = createTransitionEnqueue(actorScope, actions, []);\n for (const child of children) {\n enqueue.stop(child);\n }\n return resolveActionsWithContext(snapshot, event, actorScope, actions);\n}\n\nfunction cancelTimers(\n snapshot: AnyMachineSnapshot,\n event: AnyEventObject,\n actorScope: AnyActorScope\n): [AnyMachineSnapshot, ExecutableActionObject[]] {\n const timerIds = Object.keys(snapshot.timers);\n if (!timerIds.length) {\n return [snapshot, []];\n }\n const actions: AnyAction[] = [];\n const enqueue = createTransitionEnqueue(actorScope, actions, []);\n for (const id of timerIds) {\n enqueue.cancel(id);\n }\n return resolveActionsWithContext(snapshot, event, actorScope, actions);\n}\n\nfunction selectEventlessTransitions(\n snapshot: AnyMachineSnapshot,\n event: AnyEventObject,\n actorScope: AnyActorScope\n) {\n const enabledTransitionSet: Set<AnyTransitionDefinition> = new Set();\n const atomicStates = snapshot.nodes.filter(isAtomicStateNode);\n\n for (const atomicStateNode of atomicStates) {\n loop: for (\n let stateNode: AnyStateNode | undefined = atomicStateNode;\n stateNode;\n stateNode = stateNode.parent\n ) {\n if (!stateNode.always) {\n continue;\n }\n for (const transition of stateNode.always) {\n if (\n evaluateCandidate(transition, event, snapshot, stateNode, actorScope)\n ) {\n enabledTransitionSet.add(transition);\n break loop;\n }\n }\n }\n }\n\n return removeConflictingTransitions(\n Array.from(enabledTransitionSet),\n new Set(snapshot.nodes),\n snapshot,\n createTransitionResultResolver(snapshot, event, actorScope, false)\n );\n}\n\nexport function evaluateCandidate(\n candidate: AnyTransitionDefinition,\n event: EventObject,\n snapshot: AnyMachineSnapshot,\n stateNode: AnyStateNode,\n actorScope: AnyActorScope,\n selectionResults?: TransitionSelectionResults\n): boolean {\n if (candidate.matches && !matchesEvent(event, candidate.matches)) {\n return false;\n }\n\n if (candidate._eventMatcher && !candidate._eventMatcher(event, snapshot)) {\n return false;\n }\n\n if (candidate.guard) {\n const guardArgs = withActorSelfAndParent(\n {\n context: snapshot.context,\n event,\n output: getEventOutput(event),\n children: snapshot.children,\n actions: stateNode.machine.sources.actions,\n actors: stateNode.machine.sources.actors,\n guards: stateNode.machine.sources.guards,\n delays: stateNode.machine.sources.delays,\n _snapshot: snapshot\n },\n actorScope\n );\n if (!(candidate.guard as (args: typeof guardArgs) => boolean)(guardArgs)) {\n return false;\n }\n }\n\n if (candidate.to) {\n const evaluation = evaluateTransitionFunction(\n candidate.to,\n snapshot.context,\n event,\n snapshot,\n actorScope,\n stateNode.machine.sources,\n candidate.source.id\n );\n selectionResults?.set(candidate, evaluation);\n return evaluation.enabled;\n }\n\n return true;\n}\n","import isDevelopment from '#is-development';\nimport { isMachineSnapshot } from './State.ts';\nimport type { StateNode } from './StateNode.ts';\nimport { TARGETLESS_KEY, WILDCARD } from './constants.ts';\nimport { isStateId } from './stateUtils.ts';\nimport type {\n AnyActor,\n AnyEventObject,\n AnyMachineSnapshot,\n AnyStateMachine,\n AnyTransitionConfig,\n AnyTransitionConfigFunction,\n ErrorEvent,\n EventObject,\n InvokeConfig,\n MachineContext,\n Mapper,\n NonReducibleUnknown,\n Observer,\n OutputArg,\n SingleOrArray,\n StateLike,\n StateValue,\n TransitionConfigTarget\n} from './types.ts';\n\nexport function matchesState(\n parentStateId: StateValue,\n childStateId: StateValue\n): boolean {\n const parentStateValue = toStateValue(parentStateId);\n const childStateValue = toStateValue(childStateId);\n\n if (typeof childStateValue === 'string') {\n if (typeof parentStateValue === 'string') {\n return childStateValue === parentStateValue;\n }\n\n // Parent more specific than child\n return false;\n }\n\n if (typeof parentStateValue === 'string') {\n return parentStateValue in childStateValue;\n }\n\n return Object.keys(parentStateValue).every((key) => {\n if (!(key in childStateValue)) {\n return false;\n }\n\n return matchesState(parentStateValue[key]!, childStateValue[key]!);\n });\n}\n\nexport function checkStateIn(\n snapshot: AnyMachineSnapshot,\n stateValue: StateValue\n) {\n if (typeof stateValue === 'string' && isStateId(stateValue)) {\n const target = snapshot.machine.getStateNodeById(stateValue);\n return snapshot.nodes.some((sn) => sn === target);\n }\n\n return snapshot.matches(stateValue);\n}\n\nexport function toStatePath(stateId: string | string[]): string[] {\n if (isArray(stateId)) {\n return stateId;\n }\n\n const result: string[] = [];\n let segment = '';\n\n for (let i = 0; i < stateId.length; i++) {\n const char = stateId.charCodeAt(i);\n switch (char) {\n // \\\n case 92:\n // consume the next character\n segment += stateId[i + 1];\n // and skip over it\n i++;\n continue;\n // .\n case 46:\n result.push(segment);\n segment = '';\n continue;\n }\n segment += stateId[i];\n }\n\n result.push(segment);\n\n return result;\n}\n\nfunction toStateValue(stateValue: StateLike<any> | StateValue): StateValue {\n if (isMachineSnapshot(stateValue)) {\n return stateValue.value;\n }\n\n if (typeof stateValue !== 'string') {\n return stateValue as StateValue;\n }\n\n const statePath = toStatePath(stateValue);\n\n return pathToStateValue(statePath);\n}\n\nexport function pathToStateValue(statePath: string[]): StateValue {\n if (statePath.length === 1) {\n return statePath[0];\n }\n\n const value: StateValue = {};\n let marker = value;\n\n for (let i = 0; i < statePath.length - 1; i++) {\n if (i === statePath.length - 2) {\n marker[statePath[i]] = statePath[i + 1];\n } else {\n const previous = marker;\n marker = {};\n previous[statePath[i]] = marker;\n }\n }\n\n return value;\n}\n\nexport function mapValues<P, O extends Record<string, unknown>>(\n collection: O,\n iteratee: (item: O[keyof O], key: keyof O, collection: O, i: number) => P\n): { [key in keyof O]: P };\nexport function mapValues(\n collection: Record<string, unknown>,\n iteratee: (\n item: unknown,\n key: string,\n collection: Record<string, unknown>,\n i: number\n ) => unknown\n) {\n const result: Record<string, unknown> = {};\n\n const collectionKeys = Object.keys(collection);\n for (let i = 0; i < collectionKeys.length; i++) {\n const key = collectionKeys[i];\n result[key] = iteratee(collection[key], key, collection, i);\n }\n\n return result;\n}\n\nfunction toArrayStrict<T>(value: readonly T[] | T): readonly T[] {\n if (isArray(value)) {\n return value;\n }\n return [value];\n}\n\nexport function toArray<T>(value: readonly T[] | T | undefined): readonly T[] {\n if (value === undefined) {\n return [];\n }\n return toArrayStrict(value);\n}\n\nexport function resolveOutput<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject\n>(\n mapper:\n | Mapper<TContext, TExpressionEvent, unknown, EventObject>\n | NonReducibleUnknown,\n context: TContext,\n event: TExpressionEvent,\n self: AnyActor,\n input?: Record<string, unknown>\n): unknown {\n if (typeof mapper === 'function') {\n const outputMapper = mapper as Mapper<\n TContext,\n TExpressionEvent,\n unknown,\n EventObject\n >;\n const args = {\n context,\n event,\n output: getEventOutput(event),\n self,\n input\n } as unknown as Parameters<typeof outputMapper>[0];\n\n return outputMapper(args);\n }\n\n if (\n isDevelopment &&\n !!mapper &&\n typeof mapper === 'object' &&\n Object.values(mapper).some((val) => typeof val === 'function')\n ) {\n console.warn(\n `Dynamically mapping values to individual properties is deprecated. Use a single function that returns the mapped object instead.\\nFound object containing properties whose values are possibly mapping functions: ${Object.entries(\n mapper\n )\n .filter(([, value]) => typeof value === 'function')\n .map(\n ([key, value]) =>\n `\\n - ${key}: ${(value as () => any)\n .toString()\n .replace(/\\n\\s*/g, '')}`\n )\n .join('')}`\n );\n }\n\n return mapper;\n}\n\nexport function getEventOutput<TEvent extends EventObject>(\n event: TEvent\n): OutputArg<TEvent>['output'] {\n if (isDoneEvent(event)) {\n const doneEvent = event as unknown as EventObject & { output: unknown };\n return doneEvent.output as OutputArg<TEvent>['output'];\n }\n\n return undefined as OutputArg<TEvent>['output'];\n}\n\nfunction isDoneEvent(event: EventObject): boolean {\n return (\n event.type === 'xstate.done.actor' || event.type === 'xstate.done.state'\n );\n}\n\nfunction isArray(value: any): value is readonly any[] {\n return Array.isArray(value);\n}\n\nexport function isErrorEvent(event: AnyEventObject): event is ErrorEvent {\n return event.type.startsWith('xstate.error.');\n}\n\nexport function toTransitionConfigArray(\n configLike: SingleOrArray<\n AnyTransitionConfig | TransitionConfigTarget | AnyTransitionConfigFunction\n >\n): Array<AnyTransitionConfig> {\n return toArrayStrict(configLike).map((transitionLike) => {\n if (\n typeof transitionLike === 'undefined' ||\n typeof transitionLike === 'string'\n ) {\n return { target: transitionLike };\n }\n\n if (typeof transitionLike === 'function') {\n return { to: transitionLike };\n }\n\n return transitionLike;\n });\n}\n\nexport function normalizeTarget<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(\n target: SingleOrArray<string | StateNode<TContext, TEvent>> | undefined\n): ReadonlyArray<string | StateNode<TContext, TEvent>> | undefined {\n if (target === undefined || target === TARGETLESS_KEY) {\n return undefined;\n }\n return toArray(target);\n}\n\nexport function toObserver<T>(\n nextHandler?: Observer<T> | ((value: T) => void),\n errorHandler?: (error: any) => void,\n completionHandler?: () => void\n): Observer<T> {\n const isObserver = typeof nextHandler === 'object';\n const self = isObserver ? nextHandler : undefined;\n\n return {\n next: (isObserver ? nextHandler.next : nextHandler)?.bind(self),\n error: (isObserver ? nextHandler.error : errorHandler)?.bind(self),\n complete: (isObserver ? nextHandler.complete : completionHandler)?.bind(\n self\n )\n };\n}\n\nexport function createInvokeId(stateNodeId: string, index: number): string {\n return `${index}.${stateNodeId}`;\n}\n\nexport function resolveReferencedActor(machine: AnyStateMachine, src: string) {\n const match = src.match(/^xstate\\.invoke\\.(\\d+)\\.(.*)/)!;\n if (!match) {\n return machine.sources.actors[src];\n }\n const [, indexStr, nodeId] = match;\n const node = machine.getStateNodeById(nodeId);\n const invokeConfig = node.config.invoke!;\n const configSrc = (\n Array.isArray(invokeConfig)\n ? invokeConfig[indexStr as any]\n : (invokeConfig as InvokeConfig<\n any,\n any,\n any,\n any,\n any,\n any,\n any, // TEmitted\n any // TMeta\n >)\n ).src;\n // A referenced actor may itself be registered by name.\n return typeof configSrc === 'string'\n ? machine.sources.actors[configSrc]\n : configSrc;\n}\n\nexport function getAllOwnEventDescriptors(snapshot: AnyMachineSnapshot) {\n return [...new Set([...snapshot.nodes.flatMap((sn) => sn.ownEvents)])];\n}\n\n/** @internal Events synthesized from active transition descriptors. */\nexport function getAllOwnEvents(snapshot: AnyMachineSnapshot) {\n const events = snapshot.nodes.flatMap((stateNode) =>\n [...stateNode.transitions.values()].flatMap((transitions) =>\n transitions.map((transition) => {\n const event: AnyEventObject = {\n type: transition.eventType,\n ...transition.matches\n };\n if (\n 'actorId' in event &&\n (event.type === 'xstate.done.actor' ||\n event.type === 'xstate.error.actor' ||\n event.type === 'xstate.snapshot.actor' ||\n event.type === 'xstate.timeout.actor')\n ) {\n event.sessionId = snapshot.children[event.actorId]?.sessionId;\n }\n return event;\n })\n )\n );\n return events.filter(\n (event, index) =>\n events.findIndex((candidate) => {\n const keys = Object.keys(event);\n return (\n keys.length === Object.keys(candidate).length &&\n keys.every((key) => Object.is(event[key], candidate[key]))\n );\n }) === index\n );\n}\n\nexport function matchesEvent(\n event: EventObject,\n pattern: Record<string, unknown>\n): boolean {\n return Object.entries(pattern).every(([key, value]) =>\n Object.is((event as AnyEventObject)[key], value)\n );\n}\n\n/**\n * Checks if an event type matches an event descriptor, supporting wildcards.\n * Event descriptors can be:\n *\n * - Exact matches: \"event.type\"\n * - Wildcard: \"*\"\n * - Partial matches: \"event.*\"\n *\n * @param eventType - The actual event type string\n * @param descriptor - The event descriptor to match against\n * @returns True if the event type matches the descriptor\n */\nexport function matchesEventDescriptor(\n eventType: string,\n descriptor: string\n): boolean {\n if (descriptor === eventType) {\n return true;\n }\n\n if (descriptor === WILDCARD) {\n return true;\n }\n\n if (!descriptor.endsWith('.*')) {\n return false;\n }\n\n if (isDevelopment && /.*\\*.+/.test(descriptor)) {\n console.warn(\n `Wildcards can only be the last token of an event descriptor (e.g., \"event.*\") or the entire event descriptor (\"*\"). Check the \"${descriptor}\" event.`\n );\n }\n\n const partialEventTokens = descriptor.split('.');\n const eventTokens = eventType.split('.');\n\n for (\n let tokenIndex = 0;\n tokenIndex < partialEventTokens.length;\n tokenIndex++\n ) {\n const partialEventToken = partialEventTokens[tokenIndex];\n const eventToken = eventTokens[tokenIndex];\n\n if (partialEventToken === '*') {\n const isLastToken = tokenIndex === partialEventTokens.length - 1;\n\n if (isDevelopment && !isLastToken) {\n console.warn(\n `Infix wildcards in transition events are not allowed. Check the \"${descriptor}\" transition.`\n );\n }\n\n return isLastToken;\n }\n\n if (partialEventToken !== eventToken) {\n return false;\n }\n }\n\n return true;\n}\n","import { ACTOR_REF_TYPE } from './createActor.ts';\nimport type { AnyActorSystem } from './system.ts';\nimport type {\n AnyActor,\n AnyEventObject,\n Snapshot,\n Subscription\n} from './types.ts';\n\nconst emptySubscription: Subscription = { unsubscribe() {} };\n\nconst restoreHint =\n 'or restore this snapshot with embedded children on the runtime that owns them.';\n\n/** @internal */\nexport function isRemoteActorRef(actorRef: AnyActor): boolean {\n return (actorRef as { _remote?: boolean })._remote === true;\n}\n\n/**\n * The lifecycle-only snapshot a remote handle exposes. `active` is accurate\n * by construction: a completion removes the child from its parent's\n * `children`, so a handle only exists while the child is presumed active,\n * and the terminal result arrives as a completion event instead of a\n * snapshot. Full snapshots are a co-location capability.\n */\nconst remoteSnapshot: Snapshot<undefined> = Object.freeze({\n status: 'active' as const,\n output: undefined,\n error: undefined\n});\n\n/**\n * Creates a location-transparent handle to an actor whose state lives with\n * another runtime. The handle is constructed from identity alone — no lookup\n * — and every send routes through the system's runtime; its state is not\n * synchronously readable.\n *\n * The surface is deliberately minimal: it covers every member the runtime\n * reaches for a restored child (send/_send, lifecycle via start/_stop and\n * system.stopActor, persistence, subscribe/on as inert subscriptions).\n * Members that only make sense for a co-located actor (public stop(),\n * select(), trigger) throw a descriptive error rather than being absent, so\n * calling one reports what went wrong instead of a bare TypeError. Observable\n * interop and _processingStatus are omitted entirely.\n *\n * @internal\n */\nexport function createRemoteActorRef(\n system: AnyActorSystem,\n options: {\n id: string;\n address: string;\n src: string;\n parent: AnyActor | undefined;\n registryKey?: string;\n syncSnapshot?: boolean;\n incarnation?: string;\n }\n): AnyActor {\n const handle = {\n _remote: true as const,\n // Self-reference so context persistence recognizes the handle as an\n // actor reference instead of recursing into it.\n ref: undefined as unknown as AnyActor,\n id: options.id,\n address: options.address,\n src: options.src,\n registryKey: options.registryKey,\n // The host-supplied incarnation token, when present: the owner's\n // sessionId for this child, letting this side drop stale completions and\n // journaled sends name the intended incarnation. Without one the handle\n // does not know the child's incarnation and the owning runtime is the\n // authority on staleness.\n sessionId: options.incarnation as string,\n system,\n _parent: options.parent,\n // Round-trips through persistence verbatim (undefined stays undefined,\n // so re-persisting is byte-stable); a remote handle cannot act on it\n // locally.\n _syncSnapshot: options.syncSnapshot,\n send(event: AnyEventObject) {\n void system.sendEvent(undefined, ref, event);\n },\n _send(event: AnyEventObject) {\n throw new Error(\n `Remote actor '${options.address}' has no local mailbox to receive \"${event.type}\". Its state lives with another runtime; install a runtime that can reach it (via \\`createDurable\\`'s adapter runtime operations, or \\`system.runtime\\`) before sending, ${restoreHint}`\n );\n },\n getSnapshot(): Snapshot<undefined> {\n return remoteSnapshot;\n },\n getPersistedSnapshot(): never {\n throw new Error(\n `Cannot persist remote actor '${options.address}' from here: its state lives with the runtime that owns it. Persist it there, ${restoreHint}`\n );\n },\n start() {},\n _stop() {},\n stop() {\n throw new Error(\n `Cannot stop remote actor '${options.address}' directly: stopping is a co-located operation. Stop it through the system runtime that owns it (\\`system.stopActor(ref)\\`), ${restoreHint}`\n );\n },\n select() {\n throw new Error(\n `Cannot select from remote actor '${options.address}': its snapshot is not synchronously readable because its state lives with another runtime. Read it on the runtime that owns it, ${restoreHint}`\n );\n },\n get trigger(): never {\n throw new Error(\n `Remote actor '${options.address}' has no \\`trigger\\` shorthand: it requires a co-located actor. Use \\`send(...)\\`, which routes through the system runtime.`\n );\n },\n // Observation is a co-location capability: a remote handle never emits,\n // so subscriptions are inert rather than errors — generic observers may\n // attach to any ref.\n subscribe(): Subscription {\n return emptySubscription;\n },\n on(): Subscription {\n return emptySubscription;\n },\n _isRunning() {\n return false;\n },\n // The same shape Actor.toJSON produces, so serialized snapshots carry\n // one actor-reference marker whether a child is co-located or remote.\n toJSON() {\n return {\n xstate$type: ACTOR_REF_TYPE,\n id: options.id,\n address: options.address,\n src: options.src\n };\n }\n };\n const ref = handle as unknown as AnyActor;\n handle.ref = ref;\n return ref;\n}\n","import isDevelopment from '#is-development';\nimport { ACTOR_REF_TYPE } from './createActor.ts';\nimport { getStateValue } from './stateUtils.ts';\nimport type {\n AnyMachineSnapshot,\n AnyStateMachine,\n AnyActor,\n EventObject,\n HistoryValue,\n MachineContext,\n StateConfig,\n StateValue,\n StateValueMap,\n AnyActorRef,\n Snapshot,\n MetaObject,\n StateSchema,\n StateId,\n StateIdInputs,\n StateContextFromStateValue,\n SnapshotStatus,\n PersistedHistoryValue,\n AnyStateNode,\n LogicalTimer\n} from './types.ts';\nimport { matchesState } from './utils.ts';\nimport {\n copySnapshotActorRef,\n getSnapshotActorRef,\n setSnapshotActorRef\n} from './snapshotActorRef.ts';\nimport { isRemoteActorRef } from './remoteActorRef.ts';\n\nconst emptySnapshotRecord = Object.freeze({});\n\nfunction compactSnapshotRecord<T extends object>(value: T | undefined): T {\n if (value === emptySnapshotRecord) {\n return value;\n }\n return value && Object.keys(value).length\n ? value\n : (emptySnapshotRecord as T);\n}\n\nexport function isMachineSnapshot(value: unknown): value is AnyMachineSnapshot {\n return (\n !!value &&\n typeof value === 'object' &&\n 'machine' in value &&\n 'value' in value\n );\n}\n\ntype Values<T> = T[keyof T];\n\ntype MatchingObjectStateValue<\n TStateValue extends Record<string, unknown>,\n TTestStateValue extends Record<string, unknown>\n> =\n false extends Values<{\n [K in keyof TTestStateValue]: K extends keyof TStateValue\n ? NonNullable<TStateValue[K]> extends StateValue\n ? NonNullable<TTestStateValue[K]> extends StateValue\n ? [\n MatchingStateValue<\n NonNullable<TStateValue[K]>,\n NonNullable<TTestStateValue[K]>\n >\n ] extends [never]\n ? false\n : true\n : false\n : false\n : false;\n }>\n ? never\n : {\n [K in keyof TStateValue]: K extends keyof TTestStateValue\n ? MatchingStateValue<\n NonNullable<TStateValue[K]>,\n NonNullable<TTestStateValue[K]>\n >\n : TStateValue[K];\n };\n\ntype MatchingStateValue<\n TStateValue extends StateValue,\n TTestStateValue extends StateValue\n> = StateValue extends TTestStateValue\n ? TStateValue\n : string extends TTestStateValue\n ? TStateValue\n : TStateValue extends unknown\n ? TTestStateValue extends string\n ? TStateValue extends string\n ? TTestStateValue extends TStateValue\n ? TTestStateValue\n : Extract<TStateValue, TTestStateValue>\n : TStateValue extends Record<string, unknown>\n ? TStateValue & Record<TTestStateValue, StateValue | undefined>\n : never\n : TTestStateValue extends Record<string, unknown>\n ? TStateValue extends Record<string, unknown>\n ? MatchingObjectStateValue<TStateValue, TTestStateValue>\n : never\n : never\n : never;\n\ninterface MachineSnapshotBase<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TStateValue extends StateValue,\n TTag extends string,\n _TOutput,\n TMeta extends MetaObject,\n TStateSchema extends StateSchema = StateSchema\n> {\n /** The state machine that produced this state snapshot. */\n machine: AnyStateMachine;\n /** The tags of the active state nodes that represent the current state value. */\n tags: Set<string>;\n /**\n * The current state value.\n *\n * This represents the active state nodes in the state machine.\n *\n * - For atomic state nodes, it is a string.\n * - For compound parent state nodes, it is an object where:\n *\n * - The key is the parent state node's key\n * - The value is the current state value of the active child state node(s)\n *\n * @example\n *\n * ```ts\n * // single-level state node\n * snapshot.value; // => 'yellow'\n *\n * // nested state nodes\n * snapshot.value; // => { red: 'wait' }\n * ```\n */\n value: TStateValue;\n /** The current status of this snapshot. */\n status: SnapshotStatus;\n error: unknown;\n context: TContext;\n\n historyValue: Readonly<HistoryValue>;\n /** The enabled state nodes representative of the state value. */\n nodes: Array<AnyStateNode>;\n /** An object mapping actor names to spawned/invoked actors. */\n children: TChildren;\n /** Pending logical timers owned by this machine snapshot. */\n timers: Readonly<Record<string, LogicalTimer>>;\n /** @internal */\n _stateInputs: Record<string, Record<string, unknown>>;\n /** @internal */\n _nextTimerId: number;\n /** @internal */\n _nextActorIds?: Record<string, number>;\n /**\n * Whether the current state value is a subset of the given partial state\n * value.\n *\n * @param partialStateValue\n */\n matches<const TTestStateValue extends string>(\n partialStateValue: TTestStateValue,\n ...args: string extends TTestStateValue ? [never] : []\n ): this is MachineSnapshot<\n StateContextFromStateValue<TStateSchema, TContext, TTestStateValue>,\n TEvent,\n TChildren,\n MatchingStateValue<TStateValue, TTestStateValue>,\n TTag,\n _TOutput,\n TMeta,\n TStateSchema\n >;\n matches<const TTestStateValue extends StateValueMap>(\n partialStateValue: TTestStateValue,\n ...args: string extends keyof TTestStateValue ? [never] : []\n ): this is MachineSnapshot<\n StateContextFromStateValue<TStateSchema, TContext, TTestStateValue>,\n TEvent,\n TChildren,\n MatchingStateValue<TStateValue, TTestStateValue>,\n TTag,\n _TOutput,\n TMeta,\n TStateSchema\n >;\n matches(partialStateValue: StateValue): boolean;\n\n /**\n * Whether the current state nodes has a state node with the specified `tag`.\n *\n * @param tag\n */\n hasTag: (tag: TTag) => boolean;\n\n /**\n * Determines whether sending the `event` will cause a non-forbidden\n * transition to be selected, even if the transitions have no actions nor\n * change the state value.\n *\n * @param event The event to test\n * @returns Whether the event will cause a transition\n */\n can: (event: TEvent) => boolean;\n\n getMeta: () => Record<\n StateId<TStateSchema> & string,\n TMeta | undefined // States might not have meta defined\n >;\n\n /**\n * Returns the inputs for the current active state nodes, keyed by state node\n * id.\n */\n getInputs: () => StateIdInputs<TStateSchema>;\n\n toJSON: () => unknown;\n}\n\ninterface ActiveMachineSnapshot<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TStateValue extends StateValue,\n TTag extends string,\n TOutput,\n TMeta extends MetaObject,\n TStateSchema extends StateSchema\n> extends MachineSnapshotBase<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TStateSchema\n> {\n status: 'active';\n output: undefined;\n error: undefined;\n}\n\ninterface DoneMachineSnapshot<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TStateValue extends StateValue,\n TTag extends string,\n TOutput,\n TMeta extends MetaObject,\n TStateSchema extends StateSchema\n> extends MachineSnapshotBase<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TStateSchema\n> {\n status: 'done';\n output: TOutput;\n error: undefined;\n}\n\ninterface ErrorMachineSnapshot<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TStateValue extends StateValue,\n TTag extends string,\n TOutput,\n TMeta extends MetaObject,\n TStateSchema extends StateSchema\n> extends MachineSnapshotBase<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TStateSchema\n> {\n status: 'error';\n output: undefined;\n error: unknown;\n}\n\ninterface StoppedMachineSnapshot<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TStateValue extends StateValue,\n TTag extends string,\n TOutput,\n TMeta extends MetaObject,\n TStateSchema extends StateSchema\n> extends MachineSnapshotBase<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TStateSchema\n> {\n status: 'stopped';\n output: undefined;\n error: undefined;\n}\n\nexport type MachineSnapshot<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TStateValue extends StateValue,\n TTag extends string,\n TOutput,\n TMeta extends MetaObject,\n TStateSchema extends StateSchema\n> =\n | ActiveMachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TStateSchema\n >\n | DoneMachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TStateSchema\n >\n | ErrorMachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TStateSchema\n >\n | StoppedMachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TStateSchema\n >;\n\nconst machineSnapshotMatches = function matches(\n this: AnyMachineSnapshot,\n testValue: StateValue\n) {\n return matchesState(testValue, this.value);\n};\n\nconst machineSnapshotHasTag = function hasTag(\n this: AnyMachineSnapshot,\n tag: string\n) {\n return this.tags.has(tag);\n};\n\nconst machineSnapshotCan = function can(\n this: AnyMachineSnapshot,\n event: EventObject\n) {\n if (isDevelopment && !this.machine) {\n console.warn(\n `state.can(...) used outside of a machine-created State object; this will always return false.`\n );\n }\n\n // The dry-run logic lives on the machine so that non-machine bundles\n // (e.g. `createFSM`) don't pay for the transition-resolution machinery.\n return this.machine?._canTransition(this, event) ?? false;\n};\n\nconst machineSnapshotToJSON = function toJSON(this: AnyMachineSnapshot) {\n const {\n nodes,\n _stateInputs,\n tags,\n machine,\n getMeta,\n getInputs,\n toJSON,\n can,\n hasTag,\n matches,\n ...jsonValues\n } = this;\n return { ...jsonValues, tags: Array.from(tags) };\n};\n\nconst machineSnapshotGetMeta = function getMeta(this: AnyMachineSnapshot) {\n const meta: Record<string, any> = {};\n for (const stateNode of this.nodes) {\n if (stateNode.meta !== undefined) {\n meta[stateNode.id] = stateNode.meta;\n }\n }\n return meta;\n};\n\nconst machineSnapshotGetInputs = function getInputs<\n TStateSchema extends StateSchema\n>(\n this: AnyMachineSnapshot & {\n _stateInputs: StateIdInputs<TStateSchema>;\n }\n): StateIdInputs<TStateSchema> {\n return this._stateInputs;\n};\n\nfunction collectTags(stateNodes: Array<AnyStateNode>): Set<string> {\n const tags = new Set<string>();\n for (const stateNode of stateNodes) {\n for (const tag of stateNode.tags) {\n tags.add(tag);\n }\n }\n return tags;\n}\n\nexport function createMachineSnapshot<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TStateValue extends StateValue,\n TTag extends string,\n TMeta extends MetaObject,\n TStateSchema extends StateSchema\n>(\n config: StateConfig<TContext, TEvent>,\n machine: AnyStateMachine,\n actorRef?: AnyActor\n): MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n undefined,\n TMeta,\n TStateSchema\n> {\n const snapshot = {\n status: config.status as never,\n output: config.output,\n error: config.error,\n machine,\n context: config.context,\n nodes: config._nodes,\n value: (config.value ??\n getStateValue(machine.root, config._nodes)) as never,\n tags: collectTags(config._nodes),\n children: compactSnapshotRecord(config.children) as TChildren,\n timers: compactSnapshotRecord(config.timers),\n historyValue: compactSnapshotRecord(config.historyValue),\n _stateInputs: compactSnapshotRecord(config._stateInputs),\n _nextTimerId: config._nextTimerId ?? 0,\n _nextActorIds: config._nextActorIds,\n matches: machineSnapshotMatches as never,\n hasTag: machineSnapshotHasTag,\n can: machineSnapshotCan,\n getMeta: machineSnapshotGetMeta,\n getInputs: machineSnapshotGetInputs,\n toJSON: machineSnapshotToJSON\n };\n if (actorRef) {\n setSnapshotActorRef(snapshot, actorRef);\n }\n return snapshot;\n}\n\nexport function cloneMachineSnapshot<TState extends AnyMachineSnapshot>(\n snapshot: TState,\n config: Partial<StateConfig<any, any>> = {}\n): TState {\n const configWithSnapshot = {\n ...snapshot,\n ...config\n } as StateConfig<any, any>;\n\n if ((config._nodes ?? snapshot.nodes) === snapshot.nodes) {\n const clonedSnapshot = {\n status: configWithSnapshot.status as never,\n output: configWithSnapshot.output,\n error: configWithSnapshot.error,\n machine: snapshot.machine,\n context: configWithSnapshot.context,\n nodes: snapshot.nodes,\n value: snapshot.value,\n tags: snapshot.tags,\n children: compactSnapshotRecord(configWithSnapshot.children),\n timers: compactSnapshotRecord(configWithSnapshot.timers),\n historyValue: compactSnapshotRecord(configWithSnapshot.historyValue),\n _stateInputs: compactSnapshotRecord(configWithSnapshot._stateInputs),\n _nextTimerId: configWithSnapshot._nextTimerId ?? 0,\n _nextActorIds: configWithSnapshot._nextActorIds,\n matches: machineSnapshotMatches as never,\n hasTag: machineSnapshotHasTag,\n can: machineSnapshotCan,\n getMeta: machineSnapshotGetMeta,\n getInputs: machineSnapshotGetInputs,\n toJSON: machineSnapshotToJSON\n } as unknown as TState;\n copySnapshotActorRef(snapshot, clonedSnapshot);\n return clonedSnapshot;\n }\n\n const clonedSnapshot = createMachineSnapshot(\n {\n ...configWithSnapshot,\n value: undefined\n },\n snapshot.machine\n ) as unknown as TState;\n copySnapshotActorRef(snapshot, clonedSnapshot);\n return clonedSnapshot;\n}\n\nfunction serializeHistoryValue(\n historyValue: HistoryValue\n): PersistedHistoryValue {\n const result: PersistedHistoryValue = {};\n\n for (const key in historyValue) {\n const value = historyValue[key];\n if (Array.isArray(value)) {\n result[key] = value.map((item) => ({ id: item.id }));\n }\n }\n\n return result;\n}\n\nexport function getPersistedSnapshot<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TStateValue extends StateValue,\n TTag extends string,\n TOutput,\n TMeta extends MetaObject\n>(\n snapshot: MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n any // state schema\n >,\n options?: unknown\n): Snapshot<unknown> {\n const {\n nodes,\n _stateInputs,\n tags,\n machine,\n children,\n timers,\n context,\n can,\n hasTag,\n matches,\n getMeta,\n getInputs,\n toJSON,\n ...jsonValues\n } = snapshot;\n\n const childrenJson: Record<string, unknown> = {};\n const timersJson: Record<string, unknown> = {};\n\n const embedChildren =\n (options as { embedChildren?: boolean } | undefined)?.embedChildren !==\n false;\n for (const id in children) {\n const child = children[id] as any;\n if (\n typeof child.src !== 'string' &&\n (!options || !('__unsafeAllowInlineActors' in (options as object)))\n ) {\n throw new Error('An inline child actor cannot be persisted.');\n }\n // Children are referenced by their logical address. Embedding the child\n // state is the co-locating runtime's whole-tree checkpoint capability;\n // remote handles never embed — their state lives with another runtime.\n const embed = embedChildren && !isRemoteActorRef(child);\n if (!embed && typeof child.src !== 'string') {\n // Fail where it is actionable: a by-address reference without a\n // registered source key could be persisted but never restored.\n throw new Error(\n `Unable to persist child '${id}' by address: it requires a registered source key.`\n );\n }\n childrenJson[id as keyof typeof childrenJson] = {\n address: child.address,\n // The explicit marker disambiguates a by-address reference from a child\n // whose own persisted snapshot happens to be undefined.\n ...(embed\n ? { snapshot: child.getPersistedSnapshot(options) }\n : {\n remote: true,\n // A remote handle's sessionId IS the host-supplied incarnation\n // token, round-tripped verbatim. A local child persisted by\n // address never stamps its own sessionId: that value is this\n // incarnation's, not a durable identity, and it would make\n // persisted snapshots nondeterministic across replays.\n incarnation: isRemoteActorRef(child) ? child.sessionId : undefined\n }),\n src: child.src,\n registryKey: child.registryKey,\n syncSnapshot: child._syncSnapshot\n };\n }\n\n const snapshotActor = getSnapshotActorRef(snapshot)?.actor;\n // Only the wall clock is stamped into persisted timers: a custom clock's\n // readings (a simulated clock, a monotonic counter) are meaningless in any\n // other process, and restoring them under the wall clock would fire every\n // pending delay instantly. Pure-transition snapshots have no local\n // schedule and persist no timestamp.\n const scheduledTimers = snapshotActor?.system?._clock?.now\n ? undefined\n : snapshotActor?.system?._snapshot?._scheduledTimers;\n for (const id in timers) {\n const timer = timers[id];\n let event = timer.event;\n if (event.type === 'xstate.timeout.actor') {\n event = { ...event };\n delete (event as EventObject & { sessionId?: string }).sessionId;\n }\n let target: string | { type: 'parent' };\n if (timer.target === 'self') {\n target = 'self';\n } else {\n const childId = Object.entries(children).find(\n ([, child]) => child === timer.target\n )?.[0];\n if (childId) {\n target = childId;\n } else if (\n timer.target === getSnapshotActorRef(snapshot)?.actor._parent\n ) {\n target = { type: 'parent' };\n } else {\n throw new Error(\n `Unable to persist timer '${id}': target actor '${timer.target.id}' is no longer addressable from this snapshot.`\n );\n }\n }\n // A live runtime knows when the timer is due; persist the wall-clock\n // start (dueAt - declared delay) so restore can honor the absolute\n // deadline. Derived from dueAt, not the scheduling moment, so repeated\n // persist/restore cycles keep the same deadline. Without a live schedule\n // (a restored-but-never-started actor, a pure-transition snapshot) the\n // timer's carried-in start — which only a wall-clock actor ever stamped —\n // passes through, so re-persisting cannot push the deadline back.\n const scheduled = scheduledTimers?.[`${snapshotActor!.sessionId}.${id}`];\n const startedAt = scheduled\n ? scheduled.dueAt - timer.delay\n : timer.startedAt;\n timersJson[id] = {\n id: timer.id,\n delay: timer.delay,\n type: timer.type,\n event,\n target,\n ...(startedAt !== undefined && { startedAt })\n };\n }\n\n const persisted: Record<string, unknown> = {\n ...jsonValues,\n context: persistContext(context) as any,\n children: childrenJson,\n timers: timersJson,\n historyValue: serializeHistoryValue(jsonValues.historyValue)\n };\n\n if (_stateInputs && Object.keys(_stateInputs).length > 0) {\n persisted.stateInputs = _stateInputs;\n }\n\n if (machine.version !== undefined) {\n persisted.machine = {\n id: machine.id,\n version: machine.version\n };\n persisted.version = machine.version;\n }\n\n return persisted as Snapshot<unknown>;\n}\n\nfunction persistContext(contextPart: Record<string, unknown>) {\n let copy: typeof contextPart | undefined;\n for (const key in contextPart) {\n const value = contextPart[key];\n if (value && typeof value === 'object') {\n if ('sessionId' in value && 'send' in value && 'ref' in value) {\n copy ??= Array.isArray(contextPart)\n ? (contextPart.slice() as typeof contextPart)\n : { ...contextPart };\n copy[key] = {\n xstate$type: ACTOR_REF_TYPE,\n id: (value as any as AnyActor).id\n };\n } else {\n const result = persistContext(value as typeof contextPart);\n if (result !== value) {\n copy ??= Array.isArray(contextPart)\n ? (contextPart.slice() as typeof contextPart)\n : { ...contextPart };\n copy[key] = result;\n }\n }\n }\n }\n return copy ?? contextPart;\n}\n","import {\n XSTATE_LOGIC_EFFECT_REJECT,\n XSTATE_LOGIC_EFFECT_RESOLVE,\n XSTATE_LOGIC_EFFECT_START\n} from './constants.ts';\nimport type { ActorTermination, AnyActor, AnyEventObject } from './types.ts';\n\ntype StepEffects = Record<\n string,\n | { status: 'active' }\n | { status: 'done'; output: unknown }\n | { status: 'error'; error: unknown }\n>;\n\nfunction getStepEffect(actor: AnyActor, key: string) {\n return (actor.getSnapshot() as { effects?: StepEffects }).effects?.[key];\n}\n\nfunction waitForStep<TStepOutput>(\n actor: AnyActor,\n key: string\n): Promise<TStepOutput> {\n return new Promise((resolve, reject) => {\n const subscription = actor.subscribe((snapshot) => {\n const effect = (snapshot as { effects?: StepEffects }).effects?.[key];\n if (effect?.status === 'done') {\n subscription.unsubscribe();\n resolve(effect.output as TStepOutput);\n } else if (effect?.status === 'error') {\n subscription.unsubscribe();\n reject(effect.error as Error);\n }\n });\n });\n}\n\n/**\n * Runs one keyed step of an async actor with the built-in journal: the\n * result is memoized in the actor's own snapshot (`effects[key]`), so a\n * restored actor skips completed steps when its logic function re-runs.\n * Custom runtimes that implement `runStep` use this for the default local\n * behavior, the same way `deliverEvent` exposes local delivery.\n *\n * @experimental\n */\nexport async function runStep<TStepOutput>(\n actor: AnyActor,\n key: string,\n exec: () => TStepOutput | PromiseLike<TStepOutput>,\n sendSelf: (event: AnyEventObject) => void = (event) =>\n void actor.system.sendEvent(actor, actor, event)\n): Promise<TStepOutput> {\n const effect = getStepEffect(actor, key);\n if (effect?.status === 'done') {\n return effect.output as TStepOutput;\n }\n if (effect?.status === 'error') {\n throw effect.error;\n }\n if (effect?.status === 'active') {\n return waitForStep(actor, key);\n }\n\n sendSelf({ type: XSTATE_LOGIC_EFFECT_START, key });\n try {\n const output = await exec();\n sendSelf({ type: XSTATE_LOGIC_EFFECT_RESOLVE, key, output });\n return output;\n } catch (error) {\n sendSelf({ type: XSTATE_LOGIC_EFFECT_REJECT, key, error });\n throw error;\n }\n}\n\n/**\n * Delivers an event directly to a target actor, bypassing any installed host\n * runtime. Custom runtimes use this for the default local delivery behavior\n * inside their own `sendEvent` implementations.\n *\n * @experimental\n */\nexport function deliverEvent(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n): void {\n if (rejectUndeliverableEvent(source, target, event)) {\n return;\n }\n const runtimeTarget = target as AnyActor & {\n _lastSourceRef?: AnyActor;\n _send(event: AnyEventObject): void;\n };\n\n runtimeTarget._lastSourceRef = source;\n runtimeTarget._send(event);\n}\n\n/**\n * Returns the boundary error preventing this delivery, if any: an internal\n * event type cannot cross an actor boundary from an external sender.\n */\nfunction getEventBoundaryError(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n): Error | undefined {\n const runtimeTarget = target as AnyActor & {\n logic?: { isInternalEventType?: (eventType: string) => boolean };\n };\n\n if (\n source !== target &&\n runtimeTarget.logic?.isInternalEventType?.(event.type)\n ) {\n return new Error(\n `Internal event \"${event.type}\" cannot be sent to actor \"${target.id}\" from outside.`\n );\n }\n return undefined;\n}\n\n/**\n * Rejects an event that must not cross the delivery boundary — an internal\n * event type sent from outside its owning actor — by reporting it as a dead\n * letter. Returns `true` when the event was rejected and must not be\n * delivered. Host runtimes must call this before taking ownership of\n * delivery.\n */\nexport function rejectUndeliverableEvent(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n): boolean {\n const error = getEventBoundaryError(source, target, event);\n if (error) {\n void target.system.deadLetter(source, target, event, 'internalEvent', {\n error\n });\n return true;\n }\n return false;\n}\n\n/**\n * Publishes an actor's terminal result, notifying its parent and observers.\n * Custom runtimes use this for the default local behavior inside their own\n * `terminateActor` implementations.\n *\n * @experimental\n */\nexport function terminateActor(\n actor: AnyActor,\n termination: ActorTermination\n): void {\n (\n actor as AnyActor & { _terminate(termination: ActorTermination): void }\n )._terminate(termination);\n}\n\n/**\n * Stops an actor without producing a completion result. Custom runtimes use\n * this for the default local behavior inside their own `stopActor`\n * implementations.\n *\n * @experimental\n */\nexport function stopActor(actor: AnyActor): void {\n (actor as AnyActor & { _stop(): void })._stop();\n}\n","import isDevelopment from '#is-development';\nimport type { InspectionEvent, SentRecord } from './inspection.ts';\nimport type { StandardSchemaV1 } from './schema.types.ts';\nimport {\n AnyEventObject,\n ActorTermination,\n ActorSystemInfo,\n AnyActor,\n Observer,\n HomomorphicOmit,\n EventObject,\n Subscription,\n AnyActorLogic,\n ActorOptions\n} from './types.ts';\nimport { XSTATE_TIMER } from './constants.ts';\nimport { toObserver } from './utils.ts';\nimport { getAmbientInspector } from './inspectionAmbient.ts';\nimport { markSystemSnapshotDirty } from './snapshotActorRef.ts';\nimport {\n rejectUndeliverableEvent,\n deliverEvent,\n stopActor as stopActorLocally,\n terminateActor as terminateActorLocally,\n runStep\n} from './runtimeHelpers.ts';\n\ninterface ScheduledTimer {\n id: string;\n scheduledAt: number;\n dueAt: number;\n delay: number;\n source: AnyActor;\n}\n\nexport interface Clock {\n /** Returns the clock's current time in milliseconds. */\n now?(): number;\n setTimeout(fn: (...args: any[]) => void, timeout: number): any;\n clearTimeout(id: any): void;\n}\n\ninterface Scheduler {\n schedule(source: AnyActor, id: string, delay: number): void;\n cancel(source: AnyActor, id: string): void;\n cancelAll(actor: AnyActor): void;\n}\n\nlet systemIdPrefix: string | undefined;\nlet nextSystemId = 0;\n\n/** @internal */\nexport const transitionEffectSignal = new Error('Transition effect');\n/** @internal */\nexport const transitionEffectTargets: AnyActor[] = [];\n\nfunction createSystemIdPrefix(): string {\n let crypto: Crypto | undefined;\n try {\n crypto = globalThis.crypto;\n } catch {\n // Use the process-local fallback below.\n }\n\n if (crypto?.getRandomValues) {\n try {\n const values = new Uint32Array(4);\n crypto.getRandomValues(values);\n return Array.from(values, (value) =>\n value.toString(36).padStart(7, '0')\n ).join('');\n } catch {\n // Try randomUUID next.\n }\n }\n\n if (crypto?.randomUUID) {\n try {\n return crypto.randomUUID().replaceAll('-', '');\n } catch {\n // Use the process-local fallback below.\n }\n }\n\n return `xstate-${Date.now().toString(36)}-${Math.random()\n .toString(36)\n .slice(2)}`;\n}\n\nfunction createSystemId(): string {\n systemIdPrefix ??= createSystemIdPrefix();\n return `${systemIdPrefix}:${(nextSystemId++).toString(36)}`;\n}\n\n/**\n * The identity a durable execution pins on every system its transitions\n * create. Shared across all transitions (and replays) of one execution, so\n * session ids become a deterministic function of actor-creation order:\n * `<executionId>:0`, `<executionId>:1`, … A replayed execution re-creates\n * the same session ids, so journaled completion events (which carry the\n * producing incarnation's `sessionId`) still match the children the replay\n * re-creates.\n */\nexport interface ExecutionIdentity {\n systemId: string;\n nextSessionId: number;\n}\n\nlet ambientExecutionIdentity: ExecutionIdentity | undefined;\n\n/** @internal Runs `fn` with systems it creates pinned to `identity`. */\nexport function withExecutionIdentity<T>(\n identity: ExecutionIdentity | undefined,\n fn: () => T\n): T {\n if (!identity) {\n return fn();\n }\n const previous = ambientExecutionIdentity;\n ambientExecutionIdentity = identity;\n try {\n return fn();\n } finally {\n ambientExecutionIdentity = previous;\n }\n}\n\nexport {\n hasAmbientInspector,\n withSystemInspector\n} from './inspectionAmbient.ts';\n\n/**\n * Derives the deterministic id prefix for a generated actor id from its actor\n * source: the registered source key when the source is a string, the logic's\n * own `id` otherwise, with `x` as the last-resort prefix.\n *\n * @internal\n */\nexport function getActorIdPrefix(\n src: string | AnyActorLogic | undefined\n): string {\n if (typeof src === 'string') {\n return src;\n }\n const logicId = (src as { id?: unknown } | undefined)?.id;\n // Anonymous machines get the placeholder id '(machine)'; only named logic\n // earns a named id prefix.\n return typeof logicId === 'string' &&\n logicId.length &&\n logicId !== '(machine)'\n ? logicId\n : 'x';\n}\n\n/**\n * Encodes one actor id as an address segment. `/` separates segments, so it\n * is percent-encoded, and the escape character `%` is escaped first so the\n * encoding stays injective: the ids 'a/b' and 'a%2Fb' must not produce the\n * same address.\n *\n * @internal\n */\nexport function encodeAddressSegment(id: string): string {\n return id.includes('/') || id.includes('%')\n ? id.replaceAll('%', '%25').replaceAll('/', '%2F')\n : id;\n}\n\n/**\n * Parses a generated-shaped actor id (`prefix:<n>`). This single definition is\n * the determinism contract for id reservation: live allocation, replay, and\n * restore must all agree on what counts as generated-shaped. Deliberately\n * broader than ids a generated allocation could produce — over-reserving\n * skips numbers, which is harmless, while under-reserving could collide.\n *\n * @internal\n */\nexport function parseGeneratedActorId(\n id: string\n): { prefix: string; index: number } | undefined {\n const separator = id.lastIndexOf(':');\n if (separator <= 0 || separator === id.length - 1) {\n return undefined;\n }\n const index = Number(id.slice(separator + 1));\n return Number.isSafeInteger(index) && index >= 0\n ? { prefix: id.slice(0, separator), index }\n : undefined;\n}\n\n/**\n * The id (and address root segment) of the first parentless actor of a logic:\n * the logic's own name, or `x:0` for anonymous logic.\n *\n * @internal\n */\nexport function getRootActorId(\n src: string | AnyActorLogic | undefined\n): string {\n const prefix = getActorIdPrefix(src);\n return prefix === 'x' ? 'x:0' : prefix;\n}\n\nfunction getActorIdCounterKey(\n parent: AnyActor | undefined,\n prefix: string\n): string {\n return `${parent ? parent.address : ''}|${prefix}`;\n}\n\nfunction bumpActorIdCounter(\n system: AnyActorSystem,\n counterKey: string,\n next: number\n): void {\n const counters = system._snapshot._nextActorIds;\n if ((counters[counterKey] ?? 0) >= next) {\n return;\n }\n // Copy-on-write: snapshot systems share this record by shallow `_snapshot`\n // copies, so branches must not observe each other's allocations.\n system._snapshot._nextActorIds = { ...counters, [counterKey]: next };\n markSystemSnapshotDirty(system);\n}\n\n/** @internal */\nexport function resolveActorId(\n system: AnyActorSystem,\n requestedId: string | undefined,\n options?: {\n parent?: AnyActor;\n src?: string | AnyActorLogic;\n }\n): string {\n if (requestedId !== undefined) {\n const generated = parseGeneratedActorId(requestedId);\n if (generated) {\n bumpActorIdCounter(\n system,\n getActorIdCounterKey(options?.parent, generated.prefix),\n generated.index + 1\n );\n } else if (!options?.parent) {\n // Reserve a restored root's bare name so a later parentless actor of\n // the same logic in this system numbers past it.\n bumpActorIdCounter(\n system,\n getActorIdCounterKey(undefined, requestedId),\n 1\n );\n }\n return requestedId;\n }\n\n const prefix = getActorIdPrefix(options?.src);\n const counterKey = getActorIdCounterKey(options?.parent, prefix);\n const counter = system._snapshot._nextActorIds[counterKey] ?? 0;\n bumpActorIdCounter(system, counterKey, counter + 1);\n // The first parentless actor of a logic gets the logic's own name; later\n // parentless actors of the same logic in a shared system get numbered so\n // addresses stay unique.\n return !options?.parent && prefix !== 'x' && counter === 0\n ? prefix\n : `${prefix}:${counter}`;\n}\n\n/** @internal */\nexport function bookSessionId(system: AnyActorSystem): string {\n return `${system._identity.systemId}:${system._identity.nextSessionId++}`;\n}\n\n/**\n * Runtime operations used to execute effects.\n *\n * XState calculates pure transitions; a runtime executes their effects. The\n * built-in local runtime is one implementation at the same level as any\n * other: install a different one via `system.runtime` (for durable hosts,\n * through `createDurable`'s adapter runtime operations).\n */\n/**\n * Why an event was not delivered: `'invalidEvent'` (payload failed its\n * declared schema), `'internalEvent'` (an internal event type sent from\n * outside its owning actor) or `'stopped'` (the target actor already\n * stopped). Hosts may report additional reasons.\n */\nexport type EventRejectionReason =\n | 'invalidEvent'\n | 'internalEvent'\n | 'stopped'\n | (string & {});\n\n/** Extra detail attached to a dead letter. */\nexport interface DeadLetterDetail {\n /** Standard Schema issues for `invalidEvent` rejections. */\n issues?: readonly StandardSchemaV1.Issue[];\n /** The underlying error describing the rejection. */\n error?: Error;\n}\n\n/**\n * Describes an event that was rejected at the delivery boundary instead of\n * being delivered to its target actor (a dead letter).\n */\nexport interface EventRejection extends DeadLetterDetail {\n /** The event that was rejected. */\n event: AnyEventObject;\n /** The actor the event was addressed to. */\n targetRef: AnyActor | undefined;\n /** The `id` of the target actor. */\n targetId: string | undefined;\n /** The actor that sent the event, or `undefined` for an external send. */\n sourceRef: AnyActor | undefined;\n /** Whether the event came from outside the system or from another actor. */\n eventOrigin: 'external' | 'actor';\n reason: EventRejectionReason;\n}\n\nexport interface ActorSystemRuntime {\n /** Publishes a newly created actor to the runtime. */\n spawnActor(\n source: AnyActor | undefined,\n actor: AnyActor\n ): void | PromiseLike<void>;\n /** Starts an actor. */\n startActor(actor: AnyActor): void | PromiseLike<void>;\n /** Stops an actor without producing a completion result. */\n stopActor(actor: AnyActor): void | PromiseLike<void>;\n /** Completes or errors an actor and publishes its terminal result. */\n terminateActor(\n actor: AnyActor,\n termination: ActorTermination\n ): void | PromiseLike<void>;\n /** Delivers an event between actors. */\n sendEvent(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n ): void | PromiseLike<void>;\n /** Publishes an emitted event. */\n emitEvent(source: AnyActor, event: EventObject): void | PromiseLike<void>;\n /** Schedules a logical timer. */\n scheduleTimer(\n source: AnyActor,\n id: string,\n delay: number\n ): void | PromiseLike<void>;\n /** Cancels one logical timer. */\n cancelTimer(source: AnyActor, id: string): void | PromiseLike<void>;\n /**\n * Runs an async actor's entire body as one durable unit. The actor is the\n * natural journal entry: its identity — `address`, string `src` key and\n * serializable `input` — crosses any boundary, so a host can wrap `exec`\n * in its own step primitive, or ignore `exec` entirely and re-run the\n * registered logic on a remote executor from `(src, input)` alone. The\n * default runs the body in this process, unjournaled.\n *\n * Like `runStep`, this is an orchestration frame: it may span external\n * events and must never be serialized behind other runtime operations.\n */\n runLogic(\n actor: AnyActor,\n exec: () => PromiseLike<unknown>\n ): PromiseLike<unknown>;\n /**\n * Runs one keyed step of an async actor (`enq.step`). The default journals\n * the result in the actor's own snapshot; a durable host implements this\n * to journal steps in its own journal instead — memoized results replay\n * without re-running `exec`.\n *\n * Unlike other runtime operations, a step is an orchestration frame that\n * may itself await runtime operations, so implementations must not\n * serialize it behind them.\n */\n runStep(\n actor: AnyActor,\n key: string,\n exec: () => unknown | PromiseLike<unknown>\n ): unknown | PromiseLike<unknown>;\n /**\n * Reports an undeliverable event. Delivery stays at-most-once — this is\n * observability, not retry: the default logs in development, emits an\n * inspection event and calls the root actor's `onRejectedEvent` hook.\n * `detail` carries validation issues and the underlying error for events\n * rejected at the delivery boundary.\n */\n deadLetter(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject,\n reason: EventRejectionReason,\n detail?: DeadLetterDetail\n ): void | PromiseLike<void>;\n /** Cancels all logical timers owned by an actor. */\n cancelAllTimers(source: AnyActor): void | PromiseLike<void>;\n}\n\n/** @internal Every operation of `ActorSystemRuntime`, for runtime wrappers. */\nexport const RUNTIME_OPERATIONS = [\n 'spawnActor',\n 'startActor',\n 'stopActor',\n 'terminateActor',\n 'emitEvent',\n 'scheduleTimer',\n 'cancelTimer',\n 'cancelAllTimers',\n 'deadLetter'\n // `runLogic`, `runStep` and `sendEvent` are deliberately absent: durable\n // executions wire them separately, since logic bodies and steps await\n // other runtime operations and root-addressed sends are captured per\n // batch.\n] as const satisfies readonly (keyof ActorSystemRuntime)[];\n\ntype ScheduledTimerId = string & { __scheduledTimerId: never };\n\nconst emptyScheduledTimers = Object.freeze(\n {}\n) as ActorSystem<any>['_snapshot']['_scheduledTimers'];\n\nfunction createScheduledTimerId(actor: AnyActor, id: string): ScheduledTimerId {\n return `${actor.sessionId}.${id}` as ScheduledTimerId;\n}\n\nexport interface ActorSystem<\n T extends ActorSystemInfo\n> extends ActorSystemRuntime {\n /** @internal Allocates an actor reference during snapshot calculation. */\n createActorRef(\n logic: AnyActorLogic,\n options: ActorOptions<AnyActorLogic>\n ): AnyActor;\n /** @internal */\n children: Map<string, AnyActor>;\n /** @internal Avoids materializing the registered-actor map. */\n _getRootActor?: () => AnyActor | undefined;\n /** @internal Avoids materializing the registered-actor map. */\n _peekChildren?: () => Map<string, AnyActor> | undefined;\n /** @internal */\n reverseKeyedActors: WeakMap<AnyActor, keyof T['actors']>;\n /** @internal */\n keyedActors: Map<keyof T['actors'], AnyActor | undefined>;\n /** @internal */\n _peekKeyedActors?: () =>\n | Map<keyof T['actors'], AnyActor | undefined>\n | undefined;\n /** @internal */\n _register: (sessionId: string, actor: AnyActor) => string;\n /** @internal */\n _unregister: (actor: AnyActor) => void;\n /** @internal */\n _set: <K extends keyof T['actors']>(key: K, actor: AnyActor) => void;\n get: <K extends keyof T['actors']>(key: K) => T['actors'][K] | undefined;\n getAll: () => Partial<T['actors']>;\n\n inspect: (\n observer:\n | Observer<InspectionEvent>\n | ((inspectionEvent: InspectionEvent) => void)\n ) => Subscription;\n /** @internal Avoids collecting inspection-only transition metadata. */\n _hasInspectionObservers?: () => boolean;\n /** @internal */\n _sendInspectionEvent: (\n event: HomomorphicOmit<InspectionEvent, 'rootId'>\n ) => void;\n /** @internal */\n _relay: (\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n ) => void | PromiseLike<void>;\n scheduler: Scheduler;\n getSnapshot: () => {\n _scheduledTimers: Record<string, ScheduledTimer>;\n };\n /**\n * Runtime identity shared by every snapshot view of this actor system.\n *\n * @internal\n */\n _identity: {\n systemId: string;\n nextSessionId: number;\n };\n /** @internal */\n _snapshot: {\n _scheduledTimers: Record<ScheduledTimerId, ScheduledTimer>;\n /** Deterministic generated-id counters keyed by `${parentAddress}|${srcPrefix}`. */\n _nextActorIds: Record<string, number>;\n };\n /** @internal */\n _snapshotVersion: number;\n start: () => void;\n _clock: Clock;\n _logger: (...args: any[]) => void;\n /**\n * The runtime executing this system's effects. When unset, the built-in\n * local in-memory runtime runs them; `createActor(machine).start()` is just\n * that built-in runtime. A host runtime installed here applies to every\n * actor in the system — snapshot-scoped views and children created later\n * included — and may implement any subset of operations, with the rest\n * keeping the built-in behavior.\n *\n * An operation that returns a promise owns its own failure handling: the\n * paths that hand work to a runtime do not await it. `createDurable`\n * tracks its adapter's operations and fails `executeEffects` when one\n * rejects.\n *\n * Durable hosts should provide this through `createDurable`'s\n * adapter runtime operations rather than assigning it directly.\n */\n runtime?: Partial<ActorSystemRuntime>;\n}\n\nexport type AnyActorSystem = ActorSystem<any>;\n\n// These optional lazy fields intentionally have no emitted initializers.\n// oxlint-disable-next-line typescript/no-unsafe-declaration-merging\ninterface RuntimeSystem<T extends ActorSystemInfo> {\n runtime?: Partial<ActorSystemRuntime>;\n _children?: Map<string, AnyActor>;\n _keyedActors?: Map<keyof T['actors'], AnyActor | undefined>;\n _reverseKeyedActors?: WeakMap<AnyActor, keyof T['actors']>;\n _inspectionObservers?: Set<Observer<InspectionEvent>>;\n _timerMap?: { [id: ScheduledTimerId]: number };\n _onRejectedEvent?: (rejection: EventRejection) => void;\n}\n\nclass RuntimeSystem<T extends ActorSystemInfo> implements ActorSystem<T> {\n public _identity = ambientExecutionIdentity ?? {\n systemId: createSystemId(),\n nextSessionId: 0\n };\n public _snapshot: ActorSystem<T>['_snapshot'];\n public _snapshotVersion = 0;\n public scheduler: Scheduler = this;\n public _clock: Clock;\n public _logger: (...args: any[]) => void;\n public createActorRef: ActorSystem<T>['createActorRef'];\n\n public get children(): Map<string, AnyActor> {\n const children = (this._children ??= new Map());\n if (this._getRootActor()) {\n children.set(this._rootActor.sessionId, this._rootActor);\n }\n return children;\n }\n\n public set children(children: Map<string, AnyActor>) {\n this._children = children;\n }\n\n public _getRootActor(): AnyActor | undefined {\n return this._rootActor._isRunning() ? this._rootActor : undefined;\n }\n\n public _peekChildren(): Map<string, AnyActor> | undefined {\n return this._children;\n }\n\n public get keyedActors(): Map<keyof T['actors'], AnyActor | undefined> {\n return (this._keyedActors ??= new Map());\n }\n\n public set keyedActors(actors: Map<keyof T['actors'], AnyActor | undefined>) {\n this._keyedActors = actors;\n }\n\n public get reverseKeyedActors(): WeakMap<AnyActor, keyof T['actors']> {\n return (this._reverseKeyedActors ??= new WeakMap());\n }\n\n public set reverseKeyedActors(actors: WeakMap<AnyActor, keyof T['actors']>) {\n this._reverseKeyedActors = actors;\n }\n\n /** @internal Avoids materializing the receptionist for empty systems. */\n public _peekKeyedActors():\n | Map<keyof T['actors'], AnyActor | undefined>\n | undefined {\n return this._keyedActors;\n }\n\n constructor(\n private _rootActor: AnyActor,\n options: {\n clock: Clock;\n logger: (...args: any[]) => void;\n snapshot?: unknown;\n createActorRef: ActorSystem<T>['createActorRef'];\n onRejectedEvent?: (rejection: EventRejection) => void;\n }\n ) {\n this._onRejectedEvent = options.onRejectedEvent;\n const restoredSnapshot =\n typeof options.snapshot === 'object' && options.snapshot !== null\n ? (options.snapshot as {\n scheduler?: Record<ScheduledTimerId, ScheduledTimer>;\n })\n : undefined;\n this._clock = options.clock;\n this._logger = options.logger;\n this.createActorRef = options.createActorRef;\n const ambientInspector = getAmbientInspector();\n if (ambientInspector) {\n this.inspect(ambientInspector);\n }\n this._snapshot = {\n _scheduledTimers: restoredSnapshot?.scheduler ?? emptyScheduledTimers,\n // System-level counters are process-local backstops; per-actor\n // counters persist on each machine snapshot, and restored explicit ids\n // reserve their numbering here via `resolveActorId`.\n _nextActorIds: {}\n };\n }\n\n // Records a send on the *sender's* transition for the `sent[]` inspection\n // facet. Captures the send when it is initiated (including delayed sends that\n // may never deliver), keyed to the source actor's in-flight transition.\n private _recordSent(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject,\n delay?: number,\n id?: string\n ): void {\n if (!this._inspectionObservers?.size || !source) {\n return;\n }\n const inspectionSource = source as AnyActor & {\n _collectedSent?: SentRecord[];\n };\n const collected = (inspectionSource._collectedSent ??= []);\n collected.push({\n targetRef: target,\n targetId: target.id,\n event,\n delay,\n id\n });\n }\n\n public schedule(source: AnyActor, id: string, delay: number): void {\n const existingId = createScheduledTimerId(source, id);\n if (this._timerMap?.[existingId] !== undefined) {\n this.cancel(source, id);\n }\n\n const timer = source.getSnapshot()?.timers?.[id];\n if (timer) {\n const target = timer.target === 'self' ? source : timer.target;\n this._recordSent(source, target, timer.event, delay, id);\n }\n\n const scheduledAt = this._clock.now?.() ?? Date.now();\n const scheduledTimer: ScheduledTimer = {\n source,\n delay,\n id,\n scheduledAt,\n dueAt: scheduledAt + delay\n };\n const scheduledTimerId = createScheduledTimerId(source, id);\n if (this._snapshot._scheduledTimers === emptyScheduledTimers) {\n this._snapshot._scheduledTimers = {};\n }\n this._snapshot._scheduledTimers[scheduledTimerId] = scheduledTimer;\n markSystemSnapshotDirty(this);\n\n const timeout = this._clock.setTimeout(() => {\n if (this._timerMap) {\n delete this._timerMap[scheduledTimerId];\n }\n delete this._snapshot._scheduledTimers[scheduledTimerId];\n markSystemSnapshotDirty(this);\n\n this._deliver(source, source, { type: XSTATE_TIMER, id });\n }, delay);\n\n (this._timerMap ??= {})[scheduledTimerId] = timeout;\n }\n\n public cancel(source: AnyActor, id: string): void {\n const scheduledTimerId = createScheduledTimerId(source, id);\n const timeout = this._timerMap?.[scheduledTimerId];\n\n if (this._timerMap) {\n delete this._timerMap[scheduledTimerId];\n }\n if (this._snapshot._scheduledTimers !== emptyScheduledTimers) {\n delete this._snapshot._scheduledTimers[scheduledTimerId];\n }\n markSystemSnapshotDirty(this);\n\n if (timeout !== undefined) {\n this._clock.clearTimeout(timeout);\n }\n }\n\n public cancelAll(actor: AnyActor): void {\n for (const scheduledTimerId in this._snapshot._scheduledTimers) {\n const scheduledTimer =\n this._snapshot._scheduledTimers[scheduledTimerId as ScheduledTimerId];\n if (scheduledTimer.source === actor) {\n this.cancel(actor, scheduledTimer.id);\n }\n }\n }\n\n // Delivers an event to the target actor. Used by both `_relay` (which also\n // records the send) and the scheduler's timer (which already recorded it).\n private _deliver(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n ): void {\n deliverEvent(source, target, event);\n }\n\n public _register(sessionId: string, actor: AnyActor): string {\n if (actor === this._rootActor) {\n this._children?.set(sessionId, actor);\n } else {\n (this._children ??= new Map()).set(sessionId, actor);\n }\n markSystemSnapshotDirty(this);\n return sessionId;\n }\n\n public _unregister(actor: AnyActor): void {\n let changed: boolean;\n // Remote handles have no sessionId and are never in the session map;\n // their registry cleanup happens through the keyed-actor path below.\n if (actor === this._rootActor) {\n changed = this._getRootActor() !== undefined;\n changed =\n (actor.sessionId !== undefined &&\n (this._children?.delete(actor.sessionId) ?? false)) ||\n changed;\n } else {\n changed =\n actor.sessionId !== undefined &&\n (this._children?.delete(actor.sessionId) ?? false);\n }\n const registryKey = this._reverseKeyedActors?.get(actor);\n\n if (registryKey !== undefined) {\n if (this._keyedActors?.get(registryKey) === actor) {\n this._keyedActors.delete(registryKey);\n changed = true;\n }\n this._reverseKeyedActors?.delete(actor);\n }\n if (changed) {\n markSystemSnapshotDirty(this);\n }\n }\n\n public get<K extends keyof T['actors']>(\n registryKey: K\n ): T['actors'][K] | undefined {\n return this._keyedActors?.get(registryKey) as T['actors'][K] | undefined;\n }\n\n public getAll(): Partial<T['actors']> {\n return Object.fromEntries(this._keyedActors?.entries() ?? []) as Partial<\n T['actors']\n >;\n }\n\n public _set<K extends keyof T['actors']>(\n registryKey: K,\n actor: AnyActor\n ): void {\n const existing = this._keyedActors?.get(registryKey);\n if (existing && existing !== actor) {\n throw new Error(\n `Actor with registry key '${registryKey as string}' already exists.`\n );\n }\n\n (this._keyedActors ??= new Map()).set(registryKey, actor);\n (this._reverseKeyedActors ??= new WeakMap()).set(actor, registryKey);\n if (existing !== actor) {\n markSystemSnapshotDirty(this);\n }\n }\n\n public inspect(\n observerOrFn:\n | Observer<InspectionEvent>\n | ((inspectionEvent: InspectionEvent) => void)\n ): Subscription {\n const observer = toObserver(observerOrFn);\n (this._inspectionObservers ??= new Set()).add(observer);\n\n return {\n unsubscribe: () => {\n this._inspectionObservers?.delete(observer);\n }\n };\n }\n\n public _hasInspectionObservers(): boolean {\n return !!this._inspectionObservers?.size;\n }\n\n public _sendInspectionEvent(\n event: HomomorphicOmit<InspectionEvent, 'rootId'>\n ): void {\n if (!this._inspectionObservers?.size) {\n return;\n }\n const resolvedInspectionEvent: InspectionEvent = {\n ...event,\n rootId: this._rootActor.sessionId!\n };\n this._inspectionObservers.forEach((observer) =>\n observer.next?.(resolvedInspectionEvent)\n );\n }\n\n // Unlike the other operations, spawn has no local work: local actors\n // register with the system when they are constructed, so this only\n // notifies a host runtime.\n public spawnActor(\n source: AnyActor | undefined,\n actor: AnyActor\n ): void | PromiseLike<void> {\n return this.runtime?.spawnActor?.(source, actor);\n }\n\n public startActor(actor: AnyActor): void | PromiseLike<void> {\n const override = this.runtime?.startActor;\n if (override) {\n return override(actor);\n }\n actor.start();\n }\n\n public stopActor(actor: AnyActor): void | PromiseLike<void> {\n const override = this.runtime?.stopActor;\n if (override) {\n return override(actor);\n }\n stopActorLocally(actor);\n }\n\n public terminateActor(\n actor: AnyActor,\n termination: ActorTermination\n ): void | PromiseLike<void> {\n const override = this.runtime?.terminateActor;\n if (override) {\n return override(actor, termination);\n }\n terminateActorLocally(actor, termination);\n }\n\n public sendEvent(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n ): void | PromiseLike<void> {\n if (rejectUndeliverableEvent(source, target, event)) {\n return;\n }\n // Record for the inspection `sent[]` facet regardless of which runtime\n // delivers, so host runtimes keep inspection parity.\n this._recordSent(source, target, event);\n const override = this.runtime?.sendEvent;\n if (override) {\n return override(source, target, event);\n }\n this._deliver(source, target, event);\n }\n\n public emitEvent(\n source: AnyActor,\n event: EventObject\n ): void | PromiseLike<void> {\n const override = this.runtime?.emitEvent;\n if (override) {\n return override(source, event);\n }\n (source as AnyActor & { _emit(value: EventObject): void })._emit(event);\n }\n\n public deadLetter(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject,\n reason: EventRejectionReason,\n detail?: DeadLetterDetail\n ): void | PromiseLike<void> {\n this._sendInspectionEvent({\n type: '@xstate.deadletter',\n actorRef: target,\n sourceRef: source,\n event,\n reason,\n issues: detail?.issues,\n error: detail?.error\n });\n this._onRejectedEvent?.({\n event,\n targetRef: target,\n targetId: target.id,\n sourceRef: source,\n eventOrigin: source ? 'actor' : 'external',\n reason,\n issues: detail?.issues,\n error: detail?.error\n });\n const override = this.runtime?.deadLetter;\n if (override) {\n return override(source, target, event, reason, detail);\n }\n if (isDevelopment) {\n console.warn(\n `Event \"${event.type}\" to actor \"${target.id}\" was not delivered (${reason}).`\n );\n }\n }\n\n public runStep(\n actor: AnyActor,\n key: string,\n exec: () => unknown | PromiseLike<unknown>\n ): unknown | PromiseLike<unknown> {\n const override = this.runtime?.runStep;\n if (override) {\n return override(actor, key, exec);\n }\n return runStep(actor, key, exec);\n }\n\n public runLogic(\n actor: AnyActor,\n exec: () => PromiseLike<unknown>\n ): PromiseLike<unknown> {\n const override = this.runtime?.runLogic;\n if (override) {\n return override(actor, exec);\n }\n return exec();\n }\n\n public scheduleTimer(\n source: AnyActor,\n id: string,\n delay: number\n ): void | PromiseLike<void> {\n const override = this.runtime?.scheduleTimer;\n if (override) {\n // The local scheduler records delayed sends for inspection inside\n // `schedule`; keep that parity for host runtimes.\n const timer = source.getSnapshot()?.timers?.[id];\n if (timer) {\n const target = timer.target === 'self' ? source : timer.target;\n this._recordSent(source, target, timer.event, delay, id);\n }\n return override(source, id, delay);\n }\n this.schedule(source, id, delay);\n }\n\n public cancelTimer(source: AnyActor, id: string): void | PromiseLike<void> {\n const override = this.runtime?.cancelTimer;\n if (override) {\n return override(source, id);\n }\n this.cancel(source, id);\n }\n\n public cancelAllTimers(source: AnyActor): void | PromiseLike<void> {\n const override = this.runtime?.cancelAllTimers;\n if (override) {\n return override(source);\n }\n this.cancelAll(source);\n }\n\n public _relay(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n ): void | PromiseLike<void> {\n if (\n transitionEffectTargets.length &&\n transitionEffectTargets.includes(target)\n ) {\n throw transitionEffectSignal;\n }\n // Returned so callers that can observe a host runtime's asynchronous\n // delivery do; the built-in runtime delivers synchronously.\n return this.sendEvent(source, target, event);\n }\n\n public getSnapshot(): {\n _scheduledTimers: Record<string, ScheduledTimer>;\n } {\n return {\n _scheduledTimers: { ...this._snapshot._scheduledTimers }\n };\n }\n\n public start(): void {\n const scheduledTimers = this._snapshot._scheduledTimers;\n let resetScheduledTimers = true;\n for (const scheduledId in scheduledTimers) {\n if (resetScheduledTimers) {\n this._snapshot._scheduledTimers = {};\n resetScheduledTimers = false;\n }\n const { source, dueAt, id } =\n scheduledTimers[scheduledId as ScheduledTimerId];\n this.scheduleTimer(\n source,\n id,\n Math.max(0, dueAt - (this._clock.now?.() ?? Date.now()))\n );\n }\n }\n}\n\nexport function createRuntimeSystem<T extends ActorSystemInfo>(\n rootActor: AnyActor,\n options: {\n clock: Clock;\n logger: (...args: any[]) => void;\n snapshot?: unknown;\n createActorRef: ActorSystem<T>['createActorRef'];\n onRejectedEvent?: (rejection: EventRejection) => void;\n }\n): ActorSystem<T> {\n return new RuntimeSystem(rootActor, options);\n}\n","import isDevelopment from '#is-development';\nimport type { ActionRecord, SentRecord } from './inspection.ts';\nimport { Mailbox } from './Mailbox.ts';\nimport { XSTATE_STOP } from './constants.ts';\nimport {\n createDoneActorEvent,\n createErrorActorEvent,\n createInitEvent\n} from './eventUtils.ts';\nimport { reportUnhandledError } from './reportUnhandledError.ts';\nimport { symbolObservable } from './symbolObservable.ts';\nimport {\n encodeAddressSegment,\n AnyActorSystem,\n bookSessionId,\n Clock,\n createRuntimeSystem,\n resolveActorId\n} from './system.ts';\n\n// those are needed to make JSDoc `@link` work properly\n// oxlint-disable no-unused-vars\nimport type {\n createObservableLogic,\n createEventObservableLogic\n} from './actors/observable.ts';\nimport type { createCallbackLogic } from './actors/callback.ts';\nimport type { createLogic } from './actors/logic.ts';\nimport type { createAsyncLogic } from './actors/promise.ts';\nimport type { createMachine } from './createMachine.ts';\n// oxlint-enable no-unused-vars\n\nlet executingCustomAction: boolean = false;\n\nimport type {\n ActorTermination,\n ActorScope,\n ActorTrigger,\n AnyActor,\n AnyActorLogic,\n EmittedFrom,\n EventFromLogic,\n SendableEventFromLogic,\n InputFrom,\n PersistedSnapshotFor,\n Snapshot,\n SnapshotFrom,\n AnyTransitionDefinition,\n ExecutableActionObject,\n Readable,\n ActorLogicTransitionResult\n} from './types.ts';\nimport {\n ActorOptions,\n ActorInstance,\n ActorRef,\n EventObject,\n InteropSubscribable,\n Observer,\n Subscription\n} from './types.ts';\nimport { toObserver } from './utils.ts';\nimport { finalizeTransitionResult } from './transitionActions.ts';\nimport {\n refreshSnapshotActorRefRoot,\n setSnapshotActorRef\n} from './snapshotActorRef.ts';\n\n/**\n * Marks a serialized object as an actor reference (`xstate$type` in JSON\n * output and persisted context).\n */\nexport const ACTOR_REF_TYPE = 'actorRef';\n\nconst emptyInspectionRecords = Object.freeze([]) as unknown as never[];\n\n// those values are currently used by @xstate/react directly so it's important to keep the assigned values in sync\nexport enum ProcessingStatus {\n NotStarted = 0,\n Running = 1,\n Stopped = 2\n}\n\nconst defaultOptions = Object.freeze({\n clock: {\n setTimeout: (fn, ms) => {\n return setTimeout(fn, ms);\n },\n clearTimeout: (id) => {\n return clearTimeout(id);\n }\n } as Clock,\n logger: console.log.bind(console)\n});\n\nfunction safeCall<T>(fn: ((arg: T) => void) | undefined, arg?: T) {\n try {\n fn?.(arg as T);\n } catch (err) {\n reportUnhandledError(err);\n }\n}\n\nfunction executeExecutableEffects(\n effects: readonly ExecutableActionObject[] | undefined,\n actorScope: ActorScope<any, any, any, any>\n): void {\n if (!effects?.length) {\n return;\n }\n\n for (const effect of effects) {\n actorScope.actionExecutor(effect);\n }\n}\n\nfunction createActorRef(\n logic: AnyActorLogic,\n options: ActorOptions<AnyActorLogic>\n): AnyActor {\n return new Actor(logic, options);\n}\n\n/**\n * An Actor is a running process that can receive events, send events and change\n * its behavior based on the events it receives, which can cause effects outside\n * of the actor. When you run a state machine, it becomes an actor.\n *\n * An `Actor` is the concrete runtime instance with lifecycle methods and\n * system-owned internals. It also satisfies the narrower `ActorRef` contract,\n * so consumer APIs should accept `ActorRef` when they only need to send events\n * or read snapshots.\n */\nexport class Actor<TLogic extends AnyActorLogic> implements ActorInstance<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>,\n EmittedFrom<TLogic>,\n SendableEventFromLogic<TLogic>\n> {\n /** The current internal state of the actor. */\n private _snapshot!: SnapshotFrom<TLogic>;\n /**\n * The clock that is responsible for setting and clearing timeouts, such as\n * delayed events and transitions.\n */\n public clock: Clock;\n public options: Readonly<ActorOptions<TLogic>>;\n\n /** The unique identifier for this actor relative to its parent. */\n public id: string;\n\n private _boundProcess?: (event: EventFromLogic<TLogic>) => void;\n private mailbox?: Mailbox<EventFromLogic<TLogic>>;\n private _mailboxStarted = false;\n\n private observers?: Set<Observer<SnapshotFrom<TLogic>>>;\n private eventListeners:\n | Map<string, Set<(emittedEvent: EmittedFrom<TLogic>) => void>>\n | undefined;\n private logger: (...args: any[]) => void;\n\n /** @internal */\n public _processingStatus: ProcessingStatus = ProcessingStatus.NotStarted;\n private _forceDeferredActions = false;\n\n // Actor Ref\n public _parent?: AnyActor;\n /** @internal */\n public _syncSnapshot?: boolean;\n public ref: ActorRef<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>,\n EmittedFrom<TLogic>,\n SendableEventFromLogic<TLogic>\n >;\n // TODO: add typings for system\n private _actorScope: ActorScope<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>,\n AnyActorSystem,\n EmittedFrom<TLogic>,\n SendableEventFromLogic<TLogic>\n >;\n\n /** @internal */\n public _lastSourceRef?: AnyActor;\n /** @internal */\n public _collectedMicrosteps: AnyTransitionDefinition[] | undefined;\n /** @internal Actions executed during the in-flight transition. */\n public _collectedActions: ActionRecord[] | undefined;\n /** @internal Events relayed to other actors during the in-flight transition. */\n public _collectedSent: SentRecord[] | undefined;\n private _initialEffects: ExecutableActionObject[] | undefined;\n public registryKey: string | undefined;\n\n /** The globally unique process ID for this invocation. */\n public sessionId: string;\n\n private _address?: string;\n /**\n * The deterministic logical address of this actor within its system: the\n * `/`-joined path of actor ids from the root. Stable across persistence and\n * restore, unlike `sessionId`, which identifies one incarnation.\n *\n * `/` separates segments, so an id containing one (a state name with a\n * slash reaches its invoked child's id) is percent-encoded to keep the\n * path unambiguous.\n */\n public get address(): string {\n // `id` and `_parent` never change after construction, so the whole chain\n // memoizes to O(1) amortized.\n return (this._address ??= this._parent\n ? `${this._parent.address}/${encodeAddressSegment(this.id)}`\n : encodeAddressSegment(this.id));\n }\n\n /** The system to which this actor belongs. */\n public system: AnyActorSystem;\n\n private _trigger?: ActorTrigger<SendableEventFromLogic<TLogic>>;\n\n public get trigger(): ActorTrigger<SendableEventFromLogic<TLogic>> {\n return (this._trigger ??= new Proxy({} as Actor<TLogic>['trigger'], {\n get: (_, eventType: string) => {\n return (payload?: Record<PropertyKey, unknown>) => {\n this.send({\n ...payload,\n type: eventType\n } as SendableEventFromLogic<TLogic>);\n };\n }\n }) as ActorTrigger<SendableEventFromLogic<TLogic>>);\n }\n\n private _boundSend?: ActorRef<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>,\n EmittedFrom<TLogic>,\n SendableEventFromLogic<TLogic>\n >['send'];\n\n public get send(): ActorRef<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>,\n EmittedFrom<TLogic>,\n SendableEventFromLogic<TLogic>\n >['send'] {\n return (this._boundSend ??= this._sendPublic.bind(this));\n }\n\n public src: string | AnyActorLogic;\n\n /**\n * Creates a new actor instance for the given logic with the provided options,\n * if any.\n *\n * @param logic The logic to create an actor from\n * @param options Actor options\n */\n constructor(\n public logic: TLogic,\n options?: ActorOptions<TLogic>\n ) {\n const resolvedOptions = (\n options ? { ...defaultOptions, ...options } : defaultOptions\n ) as ActorOptions<TLogic> & typeof defaultOptions;\n\n const { clock, logger, parent, syncSnapshot, id, registryKey, inspect } =\n resolvedOptions;\n\n this.system = parent\n ? parent.system\n : (resolvedOptions._systemRef?.current ??\n createRuntimeSystem(this, {\n clock,\n logger,\n snapshot: resolvedOptions.snapshot ?? resolvedOptions.state,\n createActorRef,\n onRejectedEvent: resolvedOptions.onRejectedEvent\n }));\n\n if (\n !parent &&\n resolvedOptions._systemRef &&\n !resolvedOptions._systemRef.current\n ) {\n resolvedOptions._systemRef.current = this.system;\n }\n\n if (inspect && !parent) {\n // Always inspect at the system-level\n this.system.inspect(toObserver(inspect));\n }\n\n this.sessionId = resolvedOptions._sessionId ?? bookSessionId(this.system);\n this.id = resolveActorId(this.system, id, {\n parent,\n src: resolvedOptions.src ?? logic\n });\n this.logger = options?.logger ?? this.system._logger;\n this.clock = options?.clock ?? this.system._clock;\n this._parent = parent;\n this._syncSnapshot = syncSnapshot;\n this.options = resolvedOptions as ActorOptions<TLogic> &\n typeof defaultOptions;\n this.src = resolvedOptions.src ?? logic;\n this.ref = this;\n this._actorScope = this as unknown as typeof this._actorScope;\n\n if (registryKey) {\n this.registryKey = registryKey;\n this.system._set(registryKey, this);\n }\n\n // prepare to collect initial microsteps during initialTransition\n this._collectedMicrosteps = undefined;\n const persistedState = options?.snapshot ?? options?.state;\n this._restored = persistedState !== undefined;\n try {\n if (persistedState) {\n this._setSnapshot(\n this.logic.restoreSnapshot\n ? this.logic.restoreSnapshot(persistedState, this._actorScope)\n : persistedState\n );\n } else if (options?._inert) {\n // Inert actors (createInertActorScope) only anchor a scope for pure\n // transition functions; computing an initial snapshot here would run\n // init-time side effects (context factories, entry) a second time.\n } else {\n const [snapshot, effects] = finalizeTransitionResult(\n this._actorScope,\n undefined,\n this.logic.initialTransition(this.options?.input, this._actorScope)\n );\n this._setSnapshot(snapshot);\n this._initialEffects = effects.length ? effects : undefined;\n }\n } catch (err) {\n // if we get here then it means that we assign a value to this._snapshot that is not of the correct type\n // we can't get the true `TSnapshot & { status: 'error'; }`, it's impossible\n // so right now this is a lie of sorts\n this._setSnapshot({\n status: 'error',\n output: undefined,\n error: err\n } as SnapshotFrom<TLogic>);\n // discard any functions deferred during the failed initial snapshot\n // computation so they can't run against an inconsistent actor\n if (this._deferred) {\n this._deferred.length = 0;\n }\n }\n\n if (\n registryKey &&\n (this._snapshot as Snapshot<unknown>).status !== 'active'\n ) {\n this.system._unregister(this);\n }\n\n // Announce actor topology: emitted once for every actor (root and every\n // spawned/invoked child) so the actor graph can be drawn before any\n // transitions occur. This is the only place actor identity is announced.\n if (this.system._hasInspectionObservers?.() ?? true) {\n this.system._sendInspectionEvent({\n type: '@xstate.actor',\n actorRef: this,\n parentRef: this._parent,\n id: this.id,\n src: this.src,\n snapshot: this._snapshot\n });\n }\n }\n\n // array of functions to defer\n private _deferred: Array<() => void> | undefined;\n\n private _restored = false;\n\n /** @internal */\n public _getLogger(): ActorScope<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>\n >['logger'] {\n return this.logger;\n }\n\n private get self(): Actor<TLogic> {\n return this;\n }\n\n private get defer(): (fn: () => void) => void {\n const defer = (fn: () => void) => this._defer(fn);\n Object.defineProperty(this, 'defer', { value: defer });\n return defer;\n }\n\n private get stopChild(): (child: AnyActor) => void {\n const stopChild = (child: AnyActor) => this._stopChild(child);\n Object.defineProperty(this, 'stopChild', { value: stopChild });\n return stopChild;\n }\n\n private get emit(): (event: EmittedFrom<TLogic>) => void | PromiseLike<void> {\n const emit = (event: EmittedFrom<TLogic>) =>\n this.system.emitEvent(this, event);\n Object.defineProperty(this, 'emit', { value: emit });\n return emit;\n }\n\n private get actionExecutor(): (action: ExecutableActionObject) => void {\n const actionExecutor = (action: ExecutableActionObject) =>\n this._executeAction(action);\n Object.defineProperty(this, 'actionExecutor', { value: actionExecutor });\n return actionExecutor;\n }\n\n /** @internal */\n public _isRunning(): boolean {\n return this._processingStatus === ProcessingStatus.Running;\n }\n\n /** @internal */\n public _defer(fn: () => void): void {\n (this._deferred ??= []).push(fn);\n }\n\n /** @internal */\n public _stopChild(child: AnyActor): void {\n if (child._parent !== this) {\n throw new Error(\n isDevelopment\n ? `Cannot stop child actor ${child.id} of ${this.id} because it is not a child`\n : `Cannot stop non-child actor ${child.id}`\n );\n }\n (child as Actor<AnyActorLogic>)._stop();\n }\n\n /** @internal */\n public _executeAction(action: ExecutableActionObject): void {\n const exec = () => {\n // Record every executed action for the '@xstate.transition' inspection\n // event's `actions[]` facet (replaces the v5 '@xstate.action' event).\n if (this.system._hasInspectionObservers?.() ?? true) {\n (this._collectedActions ??= []).push({\n type: action.type,\n params: action.params\n });\n }\n const saveExecutingCustomAction = executingCustomAction;\n try {\n executingCustomAction = true;\n void action.exec();\n } finally {\n executingCustomAction = saveExecutingCustomAction;\n }\n };\n if (\n this._processingStatus === ProcessingStatus.Running &&\n !this._forceDeferredActions\n ) {\n exec();\n } else {\n (this._deferred ??= []).push(exec);\n }\n }\n\n /** Associates each live snapshot with this actor for later pure transitions. */\n private _setSnapshot(snapshot: SnapshotFrom<TLogic>): void {\n const previousSnapshot = this._snapshot;\n this._snapshot = snapshot;\n setSnapshotActorRef(snapshot, this, this.system, previousSnapshot);\n }\n\n private _setErrorSnapshot(\n err: unknown,\n snapshot: SnapshotFrom<TLogic> = this._snapshot\n ) {\n this._setSnapshot({\n ...(snapshot as Snapshot<unknown>),\n status: 'error',\n error: err\n } as SnapshotFrom<TLogic>);\n }\n\n /** Recover via the logic's error event if possible; otherwise error out. */\n private _recoverOrError(\n err: unknown,\n snapshot?: SnapshotFrom<TLogic>\n ): boolean {\n if (this._tryHandleExecutionError(err, snapshot)) {\n return true;\n }\n this._setErrorSnapshot(err);\n this._error(err);\n return false;\n }\n\n private _tryHandleExecutionError(\n err: unknown,\n snapshot: SnapshotFrom<TLogic> = this._snapshot\n ): boolean {\n // Machine logic can recover from execution errors via `onError`\n // transitions; the logic decides (so the actor stays logic-agnostic).\n const errorEvent = this.logic.getExecutionErrorEvent?.(snapshot, err) as\n | EventFromLogic<TLogic>\n | undefined;\n if (!errorEvent) {\n return false;\n }\n\n try {\n const [nextSnapshot, effects] = finalizeTransitionResult(\n this._actorScope,\n snapshot,\n this.logic.transition(snapshot, errorEvent, this._actorScope)\n );\n this._setSnapshot(nextSnapshot);\n executeExecutableEffects(effects, this._actorScope);\n this.update(nextSnapshot, errorEvent);\n return true;\n } catch {\n return false;\n }\n }\n\n private _next(snapshot: SnapshotFrom<TLogic>) {\n for (const observer of this.observers ?? emptyInspectionRecords) {\n safeCall(observer.next, snapshot);\n }\n }\n\n private update(snapshot: SnapshotFrom<TLogic>, event: EventObject): void {\n // Update state\n this._setSnapshot(snapshot);\n\n // Execute deferred effects\n const deferred = this._deferred;\n for (let i = 0; i < (deferred?.length ?? 0); i++) {\n const deferredFn = deferred![i];\n try {\n deferredFn();\n } catch (err) {\n // this error can only be caught when executing *initial* actions\n // it's the only time when we call actions provided by the user through those deferreds\n // when the actor is already running we always execute them synchronously while transitioning\n // no \"builtin deferred\" should actually throw an error since they are either safe\n // or the control flow is passed through the mailbox and errors should be caught by the `_process` used by the mailbox\n deferred!.length = 0;\n if (this._tryHandleExecutionError(err, snapshot)) {\n return;\n }\n this._setErrorSnapshot(err, snapshot);\n this._error(err);\n break;\n }\n }\n if (deferred) {\n deferred.length = 0;\n }\n\n switch ((this._snapshot as Snapshot<unknown>).status) {\n case 'active':\n this._next(snapshot);\n break;\n case 'done':\n case 'error':\n // Terminal lifecycle is represented by the ordered\n // `@xstate.terminate` effect returned by the actor logic.\n break;\n }\n this._inspectTransition(this._snapshot, event);\n }\n\n /** @internal Emits the transition inspection event; used by the pure\n * `transition()` path for snapshots driven outside a live actor. */\n public _inspectTransition(\n snapshot: SnapshotFrom<TLogic>,\n event: EventObject\n ): void {\n if (this.system._hasInspectionObservers?.() ?? true) {\n this.system._sendInspectionEvent({\n type: '@xstate.transition',\n actorRef: this,\n event,\n sourceRef: this._lastSourceRef,\n targetRef: this,\n snapshot,\n microsteps: this._collectedMicrosteps ?? emptyInspectionRecords,\n actions: this._collectedActions ?? emptyInspectionRecords,\n sent: this._collectedSent ?? emptyInspectionRecords,\n eventType: event.type\n });\n }\n this._collectedMicrosteps = undefined;\n this._collectedActions = undefined;\n this._collectedSent = undefined;\n }\n\n private _flushInitialEffects(): boolean {\n if (!this._initialEffects?.length) {\n return true;\n }\n this._forceDeferredActions = true;\n try {\n executeExecutableEffects(this._initialEffects, this._actorScope);\n this._initialEffects = undefined;\n return true;\n } catch (err) {\n this._initialEffects = undefined;\n if (this._deferred) {\n this._deferred.length = 0;\n }\n this._recoverOrError(err);\n return (this._snapshot as Snapshot<unknown>).status === 'active';\n } finally {\n this._forceDeferredActions = false;\n }\n }\n\n /**\n * Subscribe an observer to an actor’s snapshot values.\n *\n * @remarks\n * The observer will receive the actor’s snapshot value when it is emitted.\n * The observer can be:\n *\n * - A plain function that receives the latest snapshot, or\n * - An observer object whose `.next(snapshot)` method receives the latest\n * snapshot\n *\n * @example\n *\n * ```ts\n * // Observer as a plain function\n * const subscription = actor.subscribe((snapshot) => {\n * console.log(snapshot);\n * });\n * ```\n *\n * @example\n *\n * ```ts\n * // Observer as an object\n * const subscription = actor.subscribe({\n * next(snapshot) {\n * console.log(snapshot);\n * },\n * error(err) {\n * // ...\n * },\n * complete() {\n * // ...\n * }\n * });\n * ```\n *\n * The return value of `actor.subscribe(observer)` is a subscription object\n * that has an `.unsubscribe()` method. You can call\n * `subscription.unsubscribe()` to unsubscribe the observer:\n *\n * @example\n *\n * ```ts\n * const subscription = actor.subscribe((snapshot) => {\n * // ...\n * });\n *\n * // Unsubscribe the observer\n * subscription.unsubscribe();\n * ```\n *\n * When the actor is stopped, all of its observers will automatically be\n * unsubscribed.\n *\n * @param observer - Either a plain function that receives the latest\n * snapshot, or an observer object whose `.next(snapshot)` method receives\n * the latest snapshot\n */\n public subscribe(observer: Observer<SnapshotFrom<TLogic>>): Subscription;\n public subscribe(\n nextListener?: (snapshot: SnapshotFrom<TLogic>) => void,\n errorListener?: (error: any) => void,\n completeListener?: () => void\n ): Subscription;\n public subscribe(\n nextListenerOrObserver?:\n | ((snapshot: SnapshotFrom<TLogic>) => void)\n | Observer<SnapshotFrom<TLogic>>,\n errorListener?: (error: any) => void,\n completeListener?: () => void\n ): Subscription {\n const observer = toObserver(\n nextListenerOrObserver,\n errorListener,\n completeListener\n );\n\n if (this._processingStatus !== ProcessingStatus.Stopped) {\n (this.observers ??= new Set()).add(observer);\n } else {\n switch ((this._snapshot as Snapshot<unknown>).status) {\n case 'done':\n safeCall(observer.complete);\n break;\n case 'error': {\n const err = (this._snapshot as Snapshot<unknown>).error;\n if (!observer.error) {\n reportUnhandledError(err);\n } else {\n safeCall(observer.error, err);\n }\n break;\n }\n }\n }\n\n return {\n unsubscribe: () => {\n this.observers?.delete(observer);\n }\n };\n }\n\n public on<TType extends EmittedFrom<TLogic>['type'] | '*'>(\n type: TType,\n handler: (\n emitted: EmittedFrom<TLogic> &\n (TType extends '*' ? unknown : { type: TType })\n ) => void\n ): Subscription {\n let listeners = this.eventListeners?.get(type);\n if (!listeners) {\n listeners = new Set();\n (this.eventListeners ??= new Map()).set(type, listeners);\n }\n listeners.add(handler as (emittedEvent: EmittedFrom<TLogic>) => void);\n\n return {\n unsubscribe: () => {\n listeners.delete(\n handler as (emittedEvent: EmittedFrom<TLogic>) => void\n );\n }\n };\n }\n\n public select<TSelected>(\n selector: (snapshot: SnapshotFrom<TLogic>) => TSelected,\n equalityFn: (a: TSelected, b: TSelected) => boolean = Object.is\n ): Readable<TSelected> {\n return {\n subscribe: (\n observerOrFn:\n | Observer<TSelected>\n | ((value: TSelected) => void)\n | undefined,\n errorListener?: (error: any) => void,\n completeListener?: () => void\n ) => {\n const observer = toObserver(\n observerOrFn,\n errorListener,\n completeListener\n );\n let selected = selector(this.getSnapshot());\n return this.subscribe({\n next: (snapshot) => {\n const next = selector(snapshot);\n if (!equalityFn(selected, next)) {\n selected = next;\n observer.next?.(next);\n }\n },\n error: observer.error,\n complete: observer.complete\n });\n },\n get: () => selector(this.getSnapshot())\n };\n }\n\n /** Starts the Actor from the initial state */\n public start(): this {\n if (this._processingStatus === ProcessingStatus.Running) {\n // Do not restart the service if it is already started\n return this;\n }\n\n if (this._processingStatus === ProcessingStatus.Stopped) {\n return this;\n }\n\n if (this._syncSnapshot) {\n this.subscribe({\n next: (snapshot: Snapshot<unknown>) => {\n if (snapshot.status === 'active') {\n this.system._relay(this, this._parent!, {\n type: 'xstate.snapshot.actor',\n actorId: this.id,\n sessionId: this.sessionId,\n snapshot\n });\n }\n },\n error: () => {}\n });\n }\n\n this.system._register(this.sessionId, this);\n if (this.registryKey) {\n this.system._set(this.registryKey, this);\n }\n this._processingStatus = ProcessingStatus.Running;\n\n this._lastSourceRef = this._parent;\n\n const status = (this._snapshot as Snapshot<unknown>).status;\n\n switch (status) {\n case 'done':\n // a state machine can be \"done\" upon initialization (it could reach a final state using initial microsteps)\n // we still need to complete observers, flush deferreds etc\n if (this._restored) {\n // Restoration does not replay the transition that originally\n // terminated the actor, and must not notify the parent again.\n this._next(this._snapshot);\n this._stopProcedure();\n this._complete();\n return this;\n }\n if (!this._flushInitialEffects()) {\n return this;\n }\n this.update(\n this._snapshot,\n createInitEvent(\n this.options.input\n ) as unknown as EventFromLogic<TLogic>\n );\n // TODO: rethink cleanup of observers, mailbox, etc\n return this;\n case 'error':\n this._error((this._snapshot as Snapshot<unknown>).error);\n return this;\n }\n\n if (!this._parent) {\n this.system.start();\n }\n\n if (!this._flushInitialEffects()) {\n return this;\n }\n\n if (this.logic.start) {\n try {\n this.logic.start(this._snapshot, this._actorScope, {\n restored: this._restored\n });\n } catch (err) {\n this._setErrorSnapshot(err);\n this._error(err);\n return this;\n }\n }\n\n if (\n !this._restored &&\n !this._deferred?.length &&\n !this.observers?.size &&\n !(this.system._hasInspectionObservers?.() ?? true)\n ) {\n // Starting changes the registered system view associated with the\n // snapshot, even when there is nothing to publish or execute.\n if (!refreshSnapshotActorRefRoot(this._snapshot, this, this.system)) {\n this._setSnapshot(this._snapshot);\n }\n this._collectedMicrosteps = undefined;\n this._collectedActions = undefined;\n this._collectedSent = undefined;\n } else {\n this.update(\n this._snapshot,\n createInitEvent(this.options.input) as unknown as EventFromLogic<TLogic>\n );\n }\n\n if (this._restored) {\n type RestoredTimer = { id: string; delay: number; startedAt?: number };\n const timers =\n (\n this._snapshot as unknown as {\n timers?: Record<string, RestoredTimer>;\n }\n ).timers ?? {};\n // startedAt is only persisted from — and only meaningful under — the\n // wall clock; a custom clock (a simulated clock, a monotonic counter)\n // restores every timer with its declared delay. The clamp bounds\n // remaining time by the declared delay in case the wall clock moved\n // backwards between persist and restore.\n const wallClock = !this.system._clock.now;\n const now = Date.now();\n for (const timer of Object.values(timers)) {\n // A timer persisted from a live runtime carries its wall-clock start;\n // honor the absolute deadline instead of restarting the full delay.\n // Without a start (a pure-transition snapshot, or an older snapshot)\n // the declared delay is all there is.\n const delay =\n wallClock && timer.startedAt !== undefined\n ? Math.min(\n timer.delay,\n Math.max(0, timer.startedAt + timer.delay - now)\n )\n : timer.delay;\n this.system.scheduleTimer(this, timer.id, delay);\n }\n this._restored = false;\n }\n\n this._mailboxStarted = true;\n this.mailbox?.start();\n\n return this;\n }\n\n private _process(event: EventFromLogic<TLogic>) {\n let nextState: ActorLogicTransitionResult<SnapshotFrom<TLogic>> | undefined;\n let caughtError;\n try {\n nextState = finalizeTransitionResult(\n this._actorScope,\n this._snapshot,\n this.logic.transition(this._snapshot, event, this._actorScope)\n );\n } catch (err) {\n // we wrap it in a box so we can rethrow it later even if falsy value gets caught here\n caughtError = { err };\n }\n\n if (caughtError) {\n this._collectedMicrosteps = undefined;\n this._collectedActions = undefined;\n this._collectedSent = undefined;\n if (!this._recoverOrError(caughtError.err)) {\n this._inspectTransition(this._snapshot, event);\n }\n return;\n }\n if (!nextState) {\n return;\n }\n\n let snapshot = this._snapshot;\n try {\n const [nextSnapshot, effects] = nextState;\n snapshot = nextSnapshot;\n this._setSnapshot(snapshot);\n executeExecutableEffects(effects, this._actorScope);\n this.update(snapshot, event);\n } catch (err) {\n if (!this._recoverOrError(err, snapshot)) {\n this._inspectTransition(this._snapshot, event);\n }\n return;\n }\n\n if (event.type === XSTATE_STOP) {\n this._stopProcedure();\n this._complete();\n }\n }\n\n /** @internal */\n public _emit(event: EmittedFrom<TLogic>): void {\n for (const listeners of [\n this.eventListeners?.get(event.type),\n this.eventListeners?.get('*')\n ]) {\n if (listeners) {\n for (const handler of listeners) {\n safeCall(handler, event);\n }\n }\n }\n }\n\n /** @internal */\n public _terminate(termination: ActorTermination): void {\n if (termination.status === 'done') {\n // The terminal snapshot is published before observer completion and the\n // parent notification, matching actor lifecycle order.\n this._next(this._snapshot);\n this._stopProcedure();\n this._complete();\n if (this._parent) {\n this.system._relay(\n this,\n this._parent,\n createDoneActorEvent(this.id, termination.output, this.sessionId)\n );\n }\n return;\n }\n if (termination.status === 'error') {\n this._error(termination.error);\n }\n }\n\n /** @internal */\n public _stop(): this {\n if (this._processingStatus === ProcessingStatus.Stopped) {\n return this;\n }\n this.mailbox?.clear();\n if (this._processingStatus === ProcessingStatus.NotStarted) {\n this._processingStatus = ProcessingStatus.Stopped;\n this.system._unregister(this);\n return this;\n }\n this._send({ type: XSTATE_STOP } as EventFromLogic<TLogic>);\n this.system._unregister(this);\n\n return this;\n }\n\n /** Stops the Actor and unsubscribe all listeners. */\n public stop(): this {\n if (this._parent) {\n throw new Error('A non-root actor cannot be stopped directly.');\n }\n return this._stop();\n }\n private _complete(): void {\n for (const observer of this.observers ?? emptyInspectionRecords) {\n safeCall(observer.complete);\n }\n this.observers?.clear();\n this.eventListeners?.clear();\n }\n\n private _error(err: unknown): void {\n this._stopProcedure();\n if (!this.observers?.size) {\n if (!this._parent) {\n reportUnhandledError(err);\n }\n } else {\n let reportError = false;\n\n for (const observer of this.observers) {\n const errorListener = observer.error;\n reportError ||= !errorListener;\n safeCall(errorListener, err);\n }\n this.observers.clear();\n if (reportError) {\n reportUnhandledError(err);\n }\n }\n this.eventListeners?.clear();\n\n if (this._parent) {\n this.system._relay(\n this,\n this._parent,\n createErrorActorEvent(this.id, err, this.sessionId)\n );\n }\n }\n // TODO: atm children don't belong entirely to the actor so\n // in a way - it's not even super aware of them\n // so we can't stop them from here but we really should!\n // right now, they are being stopped within the machine's transition\n // but that could throw and leave us with \"orphaned\" active actors\n private _stopProcedure(): void {\n if (this._processingStatus !== ProcessingStatus.Running) {\n // Actor already stopped; do nothing\n return;\n }\n\n // Cancel all delayed events\n this.system.cancelAllTimers(this);\n\n // TODO: mailbox.reset\n this.mailbox?.clear();\n this.mailbox = undefined;\n this._boundProcess = undefined;\n this._mailboxStarted = false;\n\n this._processingStatus = ProcessingStatus.Stopped;\n this.system._unregister(this);\n }\n\n /** @internal */\n public _send(event: EventFromLogic<TLogic>) {\n if (this._processingStatus === ProcessingStatus.Stopped) {\n this.system.deadLetter(\n this._lastSourceRef,\n this as AnyActor,\n event,\n 'stopped'\n );\n return;\n }\n\n let mailbox = this.mailbox;\n if (!mailbox) {\n this._boundProcess ??= this._process.bind(this);\n mailbox = this.mailbox = new Mailbox(this._boundProcess);\n if (this._mailboxStarted) {\n mailbox.start();\n }\n }\n mailbox.enqueue(event);\n }\n\n /**\n * Sends an event to the running Actor to trigger a transition.\n *\n * @param event The event to send\n */\n private _sendPublic(event: SendableEventFromLogic<TLogic>) {\n if (isDevelopment && typeof event === 'string') {\n throw new Error(\n `Only event objects may be sent to actors; use .send({ type: \"${event}\" }) instead`\n );\n }\n this.system._relay(undefined, this, event);\n }\n\n /**\n * Returns the actor's serializable logical identity: its `id`, `address`,\n * and registered source key (when the actor was created from one).\n */\n public toJSON() {\n return {\n xstate$type: ACTOR_REF_TYPE,\n id: this.id,\n address: this.address,\n src: typeof this.src === 'string' ? this.src : undefined\n };\n }\n\n /**\n * Obtain the internal state of the actor, which can be persisted.\n *\n * @remarks\n * The internal state can be persisted from any actor, not only machines.\n *\n * Note that the persisted state is not the same as the snapshot from\n * {@link Actor.getSnapshot}. Persisted state represents the internal state of\n * the actor, while snapshots represent the actor's last emitted value.\n *\n * Can be restored with {@link ActorOptions.state}\n * @see https://stately.ai/docs/persistence\n */\n public getPersistedSnapshot(options?: {\n /**\n * Whether persisted machine children embed their own persisted state\n * (the co-locating runtime's whole-tree checkpoint) or are referenced by\n * logical address only, leaving each child's state with the runtime that\n * owns it. Defaults to `true`.\n */\n embedChildren?: boolean;\n }): Snapshot<unknown> & PersistedSnapshotFor<TLogic>;\n public getPersistedSnapshot(\n options?: unknown\n ): Snapshot<unknown> & PersistedSnapshotFor<TLogic> {\n return this.logic.getPersistedSnapshot(\n this._snapshot,\n options\n ) as Snapshot<unknown> & PersistedSnapshotFor<TLogic>;\n }\n\n public [symbolObservable](): InteropSubscribable<SnapshotFrom<TLogic>> {\n return this;\n }\n\n /**\n * Read an actor’s snapshot synchronously.\n *\n * @remarks\n * The snapshot is the last value the actor published, not a query of its\n * private state: the actor emits a snapshot when it transitions, and this\n * returns that cached last emission. The read is coherent within one\n * synchronous transition turn because event processing runs to completion;\n * across asynchronous boundaries it may be stale, like any observed value.\n *\n * Only co-located actors publish full snapshots. A location-transparent\n * remote handle exposes lifecycle only ({ status, output?, error? }): while\n * the handle exists among its parent's children the child is presumed\n * `active`, and its terminal result arrives as a completion event.\n *\n * Note that some actors, such as callback actors generated with\n * `createCallbackLogic`, will not emit snapshots.\n * @see {@link Actor.subscribe} to subscribe to an actor’s snapshot values.\n * @see {@link Actor.getPersistedSnapshot} to persist the internal state of an actor (which is more than just a snapshot).\n */\n public getSnapshot(): SnapshotFrom<TLogic> {\n if (isDevelopment && !this._snapshot) {\n throw new Error(\n `Snapshot can't be read while the actor initializes itself`\n );\n }\n return this._snapshot;\n }\n}\n\nexport type RequiredActorOptionsKeys<TLogic extends AnyActorLogic> =\n undefined extends InputFrom<TLogic> ? never : 'input';\n\n/**\n * Creates a new actor instance for the given actor logic with the provided\n * options, if any.\n *\n * @remarks\n * When you create an actor from actor logic via `createActor(logic)`, you\n * implicitly create an actor system where the created actor is the root actor.\n * Any actors spawned from this root actor and its descendants are part of that\n * actor system.\n * @example\n *\n * ```ts\n * import { createActor } from 'xstate';\n * import { someActorLogic } from './someActorLogic.ts';\n *\n * // Creating the actor, which implicitly creates an actor system with itself as the root actor\n * const actor = createActor(someActorLogic);\n *\n * actor.subscribe((snapshot) => {\n * console.log(snapshot);\n * });\n *\n * // Actors must be started by calling `actor.start()`, which will also start the actor system.\n * actor.start();\n *\n * // Actors can receive events\n * actor.send({ type: 'someEvent' });\n *\n * // You can stop root actors by calling `actor.stop()`, which will also stop the actor system and all actors in that system.\n * actor.stop();\n * ```\n *\n * @param logic - The actor logic to create an actor from. For a state machine\n * actor logic creator, see {@link createMachine}. Other actor logic creators\n * include {@link createCallbackLogic}, {@link createEventObservableLogic},\n * {@link createObservableLogic}, {@link createLogic}, and\n * {@link createAsyncLogic}.\n * @param options - Actor options\n */\nexport function createActor<TLogic extends AnyActorLogic>(\n logic: TLogic,\n options?: ActorOptions<TLogic> & {\n [K in RequiredActorOptionsKeys<TLogic>]: unknown;\n }\n): Actor<TLogic> {\n return new Actor(logic, options);\n}\n","const cache = new WeakMap<any, any>();\n\nexport function memo<T>(object: any, key: string, fn: () => T): T {\n let memoizedData = cache.get(object);\n\n if (!memoizedData) {\n memoizedData = { [key]: fn() };\n cache.set(object, memoizedData);\n } else if (!(key in memoizedData)) {\n memoizedData[key] = fn();\n }\n\n return memoizedData[key];\n}\n","import isDevelopment from '#is-development';\nimport { NULL_EVENT, STATE_DELIMITER } from './constants.ts';\nimport type { SetupStateSchemas } from './schema.types.ts';\nimport { createInvokeTimeoutEventId } from './eventUtils.ts';\nimport { memo } from './memo.ts';\nimport {\n evaluateCandidate,\n formatTransition,\n getCandidates,\n getEventDescriptorKey,\n getDelayedTransitions,\n matchesActorSession,\n type TransitionSelectionResults\n} from './stateUtils.ts';\nimport type {\n DelayedTransitionDefinition,\n EventObject,\n InitialTransitionDefinition,\n MachineContext,\n Mapper,\n StateNodesConfig,\n TransitionDefinition,\n TransitionDefinitionMap,\n AnyStateMachine,\n AnyStateNodeConfig,\n NonReducibleUnknown,\n EventDescriptor,\n AnyActorScope,\n AnyStateNode,\n AnyEventObject,\n AnyAction,\n AnyTransitionConfig,\n AnyTransitionDefinition,\n AnyMachineSnapshot,\n AnyInvokeDefinition\n} from './types.ts';\nimport {\n createInvokeId,\n mapValues,\n toArray,\n toTransitionConfigArray\n} from './utils.ts';\n\nconst EMPTY_OBJECT = {};\nconst CHOICE_CONFIG_KEYS = [\n 'invoke',\n 'after',\n 'on',\n 'entry',\n 'exit',\n 'always',\n 'states',\n 'initial',\n 'onDone',\n 'timeout',\n 'onTimeout',\n 'history',\n 'target',\n 'output'\n] as const;\n\ninterface StateNodeOptions<\n TContext extends MachineContext,\n TEvent extends EventObject\n> {\n _key: string;\n _parent?: StateNode<TContext, TEvent>;\n _machine: AnyStateMachine;\n}\n\nexport class StateNode<\n TContext extends MachineContext = MachineContext,\n TEvent extends EventObject = EventObject\n> {\n /**\n * The relative key of the state node, which represents its location in the\n * overall state value.\n */\n public key: string;\n /** The unique ID of the state node. */\n public id: string;\n /**\n * The type of this state node:\n *\n * - `'atomic'` - no child state nodes\n * - `'compound'` - nested child state nodes (XOR)\n * - `'parallel'` - orthogonal nested child state nodes (AND)\n * - `'history'` - history state node\n * - `'choice'` - pure routing decision state node\n * - `'final'` - final state node\n */\n public type:\n | 'atomic'\n | 'compound'\n | 'parallel'\n | 'final'\n | 'history'\n | 'choice';\n /** The string path from the root machine node to this node. */\n public path: string[];\n /** The child state nodes. */\n public states: StateNodesConfig<any, any>;\n /**\n * The type of history on this state node. Can be:\n *\n * - `'shallow'` - recalls only top-level historical state value\n * - `'deep'` - recalls historical state value at all levels\n */\n public history: false | 'shallow' | 'deep';\n /** The action(s) to be executed upon entering the state node. */\n public entry: AnyAction | undefined;\n /** The action(s) to be executed upon exiting the state node. */\n public exit: AnyAction | undefined;\n /** The parent state node. */\n public parent?: StateNode<any, any>;\n /** The root machine node. */\n public machine: AnyStateMachine;\n /**\n * The meta data associated with this state node, which will be returned in\n * State instances.\n */\n public meta?: any;\n /**\n * The output data sent with the `xstate.done.state` event if this is a final\n * state node.\n */\n public output?:\n | Mapper<MachineContext, EventObject, unknown, EventObject>\n | NonReducibleUnknown;\n\n /**\n * The order this state node appears. Corresponds to the implicit document\n * order.\n */\n public order: number = -1;\n\n public description?: string;\n\n public schemas: SetupStateSchemas | undefined;\n\n public tags: string[] = [];\n public transitions!: Map<string, AnyTransitionDefinition[]>;\n public always?: Array<AnyTransitionDefinition>;\n public invoke: Array<AnyInvokeDefinition>;\n public on!: TransitionDefinitionMap<any, any>;\n public after!: Array<DelayedTransitionDefinition<any, any>>;\n public events!: Array<EventDescriptor<any>>;\n public ownEvents!: Array<EventDescriptor<any>>;\n private _candidateCache?: Map<string, AnyTransitionDefinition[]>;\n\n constructor(\n /** The raw config used to create the machine. */\n public config: AnyStateNodeConfig,\n options: StateNodeOptions<TContext, TEvent>\n ) {\n this.parent = options._parent;\n this.key = options._key;\n this.machine = options._machine;\n this.path = this.parent ? this.parent.path.concat(this.key) : [];\n const firstStateKey = this.config.states\n ? Object.keys(this.config.states)[0]\n : undefined;\n this.id =\n this.config.id || [this.machine.id, ...this.path].join(STATE_DELIMITER);\n this.type =\n this.config.type ||\n (firstStateKey !== undefined\n ? 'compound'\n : this.config.history\n ? 'history'\n : 'atomic');\n this.description = this.config.description;\n this.schemas = this.config.schemas;\n\n validateStateNodeConfig(this);\n\n this.order = this.machine.idMap.size;\n this.machine.idMap.set(this.id, this);\n\n this.states = (\n this.config.states\n ? mapValues(\n this.config.states,\n (stateConfig: AnyStateNodeConfig, key) => {\n const stateNode = new StateNode(stateConfig, {\n _parent: this,\n _key: key,\n _machine: this.machine\n });\n return stateNode;\n }\n )\n : EMPTY_OBJECT\n ) as StateNodesConfig<TContext, TEvent>;\n\n if (this.type === 'compound' && !this.config.initial) {\n throw new Error(\n isDevelopment\n ? `No initial state specified for compound state node \"#${\n this.id\n }\". Try adding { initial: \"${firstStateKey}\" } to the state config.`\n : `No initial state specified for compound state node \"#${this.id}\".`\n );\n }\n\n // History config\n this.history =\n this.config.history === true ? 'shallow' : this.config.history || false;\n\n this.entry = this.config.entry as AnyAction | undefined;\n this.exit = this.config.exit as AnyAction | undefined;\n\n if (this.entry) {\n // @ts-expect-error _special is an internal marker not on the Action type\n this.entry._special = true;\n }\n\n if (this.exit) {\n // @ts-expect-error _special is an internal marker not on the Action type\n this.exit._special = true;\n }\n\n this.meta = this.config.meta;\n this.output =\n this.type === 'final' || !this.parent ? this.config.output : undefined;\n this.tags = toArray(config.tags).slice();\n this.invoke = toArray(this.config.invoke).map((invokeConfig, i) => {\n const { src, registryKey } = invokeConfig;\n const invokeId = createInvokeId(this.id, i);\n const resolvedId = invokeConfig.id ?? invokeId;\n // Referenced (string) actors keep their logical name so persisted\n // snapshots reference `src: 'fetchUser'` rather than a positional id;\n // only inline logic gets the synthetic source name.\n const sourceName =\n typeof src === 'string' ? src : `xstate.invoke.${invokeId}`;\n\n return {\n ...invokeConfig,\n src: sourceName,\n logic: src,\n id: resolvedId,\n registryKey\n } as AnyInvokeDefinition;\n });\n }\n\n /** @internal */\n public _initialize() {\n this.after = getDelayedTransitions(this) as any;\n this.transitions = formatTransitions(this);\n if (this.type === 'choice') {\n this.always = formatChoiceTransitions(this);\n } else if (this.config.always) {\n this.always = mapTransitionConfigs(this.config.always, (transition) =>\n formatTransition(this, NULL_EVENT, transition)\n );\n }\n\n for (const key of Object.keys(this.states)) {\n this.states[key]._initialize();\n }\n\n this._refreshEventMetadata();\n }\n\n /** @internal */\n public _refreshEventMetadata() {\n const on = {} as TransitionDefinitionMap<TContext, TEvent>;\n const ownEvents: EventDescriptor<any>[] = [];\n for (const [descriptor, transitions] of this.transitions) {\n (on as any)[descriptor] = transitions.slice();\n if (\n transitions.some(\n (transition) =>\n transition.target || transition.reenter || transition.to\n )\n ) {\n ownEvents.push(descriptor);\n }\n }\n this.on = on;\n this.ownEvents = ownEvents;\n\n const events = new Set<EventDescriptor<any>>(ownEvents);\n for (const state of Object.values(this.states)) {\n for (const event of state.events) {\n events.add(event);\n }\n }\n this.events = Array.from(events);\n }\n\n public get initial(): InitialTransitionDefinition {\n return memo(this, 'initial', () =>\n formatInitialTransition(this, this.config.initial)\n );\n }\n\n /** @internal */\n public next(\n snapshot: AnyMachineSnapshot,\n event: AnyEventObject,\n actorScope: AnyActorScope,\n selectionResults?: TransitionSelectionResults\n ): Array<AnyTransitionDefinition> | undefined {\n const descriptorKey = getEventDescriptorKey(event);\n let candidates = this._candidateCache?.get(descriptorKey);\n if (!candidates) {\n candidates = getCandidates(this, event);\n (this._candidateCache ??= new Map()).set(descriptorKey, candidates);\n }\n\n for (const candidate of candidates) {\n const guardPassed = evaluateCandidate(\n candidate,\n event,\n snapshot,\n this,\n actorScope,\n selectionResults\n );\n\n if (guardPassed) {\n return [candidate];\n }\n }\n\n return undefined;\n }\n}\n\nfunction validateStateNodeConfig(stateNode: AnyStateNode) {\n const config = stateNode.config as any;\n\n if (\n stateNode.type === 'history' &&\n !(\n (typeof config.target === 'string' && config.target.trim().length > 0) ||\n (Array.isArray(config.target) &&\n config.target.length > 0 &&\n config.target.every(\n (target: unknown) =>\n typeof target === 'string' && target.trim().length > 0\n ))\n )\n ) {\n throw new Error(\n isDevelopment\n ? `History state \"${stateNode.id}\" must declare a non-empty \\`target\\`.`\n : `Missing history target on \"${stateNode.id}\"`\n );\n }\n\n if (stateNode.type !== 'choice') {\n if (isDevelopment && config.choice !== undefined) {\n throw new Error(\n `State \"${stateNode.id}\" has \\`choice\\`, but \\`choice\\` can only be used with \\`type: 'choice'\\`.`\n );\n }\n return;\n }\n\n if (typeof config.choice !== 'function') {\n throw new Error(\n isDevelopment\n ? `Choice state \"${stateNode.id}\" must declare a \\`choice\\` function.`\n : `Missing \\`choice\\` function on \"${stateNode.id}\"`\n );\n }\n\n if (isDevelopment) {\n for (const key of CHOICE_CONFIG_KEYS) {\n if (config[key] !== undefined) {\n throw new Error(\n `Choice state \"${stateNode.id}\" cannot declare \\`${key}\\`.`\n );\n }\n }\n }\n}\n\nfunction formatChoiceTransitions(\n stateNode: AnyStateNode\n): AnyTransitionDefinition[] {\n const choice = (stateNode.config as any).choice;\n const validateChoiceResult = (result: any): AnyTransitionConfig => {\n if (!result || result.target === undefined) {\n throw new Error(\n isDevelopment\n ? `Choice state \"${stateNode.id}\" must resolve to a target.`\n : `Choice \"${stateNode.id}\" has no target`\n );\n }\n if (isDevelopment) {\n for (const key of ['actions', 'to'] as const) {\n if (result[key] !== undefined) {\n throw new Error(\n `Choice state \"${stateNode.id}\" cannot declare \\`${key}\\` on a choice.`\n );\n }\n }\n }\n return result;\n };\n\n return [\n formatTransition(stateNode, NULL_EVENT, {\n to: (args: any) => validateChoiceResult(choice(args))\n } as AnyTransitionConfig)\n ];\n}\n\nfunction mapTransitionConfigs<T>(\n transitionsConfig: unknown,\n mapper: (transition: AnyTransitionConfig) => T\n): T[] {\n const transitionConfigs = toTransitionConfigArray(transitionsConfig as any);\n const transitions = new Array<T>(transitionConfigs.length);\n\n for (let i = 0; i < transitionConfigs.length; i++) {\n transitions[i] = mapper(transitionConfigs[i]);\n }\n\n return transitions;\n}\n\nfunction formatTransitions<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(\n stateNode: AnyStateNode\n): Map<string, TransitionDefinition<TContext, TEvent>[]> {\n const transitions = new Map<\n string,\n TransitionDefinition<TContext, AnyEventObject>[]\n >();\n const addTransitions = (\n descriptor: string,\n additions: AnyTransitionDefinition[]\n ) => {\n transitions.set(descriptor, [\n ...(transitions.get(descriptor) ?? []),\n ...additions\n ]);\n };\n if (stateNode.config.on) {\n for (const descriptor of Object.keys(stateNode.config.on)) {\n if (descriptor === NULL_EVENT) {\n throw new Error(\n isDevelopment\n ? 'Null events (\"\") cannot be specified as a transition key. Use `always: { ... }` instead.'\n : 'Null event transition key'\n );\n }\n const transitionsConfig = stateNode.config.on[descriptor];\n transitions.set(\n descriptor,\n mapTransitionConfigs(transitionsConfig, (transition) =>\n formatTransition(stateNode, descriptor, transition)\n )\n );\n }\n }\n if (stateNode.config.onDone) {\n const descriptor = 'xstate.done.state';\n addTransitions(\n descriptor,\n mapTransitionConfigs(stateNode.config.onDone, (transition) =>\n formatTransition(stateNode, descriptor, {\n ...transition,\n matches: { ...transition.matches, stateId: stateNode.id }\n })\n )\n );\n }\n if (stateNode.config.onError) {\n const descriptor = 'xstate.error.*';\n transitions.set(\n descriptor,\n mapTransitionConfigs(stateNode.config.onError, (transition) =>\n formatTransition(stateNode, descriptor, transition)\n )\n );\n }\n const createCancelInvokeTimeoutTransition = (\n descriptor: string,\n timeoutEventId: string,\n actorId: string\n ): AnyTransitionDefinition =>\n formatTransition(stateNode, descriptor, {\n matches: { actorId },\n _eventMatcher: (event: EventObject, snapshot: AnyMachineSnapshot) =>\n matchesActorSession(event, snapshot, actorId),\n to: (_args: any, enq: any) => {\n enq.cancel(timeoutEventId);\n return {};\n }\n } as AnyTransitionConfig);\n const formatInvokeCompletionTransition = (\n descriptor: string,\n transitionConfig: AnyTransitionConfig,\n timeoutEventId: string\n ): AnyTransitionDefinition => {\n const { target, to, reenter, ...rest } = transitionConfig;\n\n return formatTransition(stateNode, descriptor, {\n ...rest,\n reenter,\n to: (args: any, enq: any) => {\n if (to) {\n let didEnqueue = false;\n const trackingEnqueue = new Proxy(enq, {\n apply(target, thisArg, argArray) {\n didEnqueue = true;\n return Reflect.apply(target, thisArg, argArray);\n },\n get(target, prop, receiver) {\n const value = Reflect.get(target, prop, receiver);\n\n if (typeof value !== 'function') {\n return value;\n }\n\n return (...argArray: any[]) => {\n didEnqueue = true;\n return value.apply(target, argArray);\n };\n }\n });\n const result = to(args, trackingEnqueue);\n\n if (result !== undefined || didEnqueue) {\n enq.cancel(timeoutEventId);\n }\n\n return result;\n }\n\n enq.cancel(timeoutEventId);\n return {\n target,\n reenter\n };\n }\n } as AnyTransitionConfig);\n };\n for (const invokeDef of stateNode.invoke) {\n const withInvokeMatch = (transition: AnyTransitionConfig) => ({\n ...transition,\n matches: { ...transition.matches, actorId: invokeDef.id },\n _eventMatcher: (event: EventObject, snapshot: AnyMachineSnapshot) =>\n matchesActorSession(event, snapshot, invokeDef.id)\n });\n const invokeTimeoutEventId =\n invokeDef.timeout !== undefined\n ? createInvokeTimeoutEventId(invokeDef.id)\n : undefined;\n\n if (invokeDef.onDone) {\n const descriptor = 'xstate.done.actor';\n const invokeDoneTransitions = mapTransitionConfigs(\n invokeDef.onDone,\n (rawTransition) => {\n const transition = withInvokeMatch(rawTransition);\n return invokeTimeoutEventId\n ? formatInvokeCompletionTransition(\n descriptor,\n transition,\n invokeTimeoutEventId\n )\n : formatTransition(stateNode, descriptor, transition);\n }\n );\n\n if (invokeTimeoutEventId) {\n invokeDoneTransitions.push(\n createCancelInvokeTimeoutTransition(\n descriptor,\n invokeTimeoutEventId,\n invokeDef.id\n )\n );\n }\n\n addTransitions(descriptor, invokeDoneTransitions);\n } else if (invokeTimeoutEventId) {\n const descriptor = 'xstate.done.actor';\n addTransitions(descriptor, [\n createCancelInvokeTimeoutTransition(\n descriptor,\n invokeTimeoutEventId,\n invokeDef.id\n )\n ]);\n }\n if (invokeDef.onError) {\n const descriptor = 'xstate.error.actor';\n addTransitions(\n descriptor,\n mapTransitionConfigs(invokeDef.onError, (rawTransition) => {\n const transition = withInvokeMatch(rawTransition);\n return invokeTimeoutEventId\n ? formatInvokeCompletionTransition(\n descriptor,\n transition,\n invokeTimeoutEventId\n )\n : formatTransition(stateNode, descriptor, transition);\n })\n );\n }\n if (invokeDef.onSnapshot) {\n const descriptor = 'xstate.snapshot.actor';\n addTransitions(\n descriptor,\n mapTransitionConfigs(invokeDef.onSnapshot, (transition) =>\n formatTransition(stateNode, descriptor, withInvokeMatch(transition))\n )\n );\n }\n }\n for (const delayedTransition of stateNode.after) {\n let existing = transitions.get(delayedTransition.eventType);\n if (!existing) {\n existing = [];\n transitions.set(delayedTransition.eventType, existing);\n }\n existing.push(\n delayedTransition as TransitionDefinition<TContext, AnyEventObject>\n );\n }\n return transitions as Map<string, TransitionDefinition<TContext, any>[]>;\n}\n\nfunction formatInitialTransition(\n stateNode: AnyStateNode,\n _target:\n | string\n | { target: string | string[]; input?: any; to?: (...args: any[]) => any }\n | undefined\n): InitialTransitionDefinition {\n const targetString =\n typeof _target === 'object' && _target !== null ? _target.target : _target;\n const input =\n typeof _target === 'object' && _target !== null ? _target.input : undefined;\n const to =\n typeof _target === 'object' && _target !== null ? _target.to : undefined;\n const targetStrings = Array.isArray(targetString)\n ? targetString\n : targetString\n ? [targetString]\n : [];\n const resolvedTargets = targetStrings.map((target) =>\n target.startsWith('#')\n ? stateNode.machine.getStateNodeById(target.slice(1))\n : stateNode.states[target]\n );\n if (resolvedTargets.some((target) => !target)) {\n throw new Error(\n isDevelopment\n ? `Initial state node \"${targetStrings.find((_, index) => !resolvedTargets[index])}\" not found on parent state node #${stateNode.id}`\n : `Initial state not found on \"#${stateNode.id}\"`\n );\n }\n const transition: InitialTransitionDefinition = {\n source: stateNode,\n target: resolvedTargets.length\n ? (resolvedTargets as AnyStateNode[])\n : undefined,\n input,\n to\n };\n\n return transition;\n}\n","import type {\n ActorLogicValidator,\n ActorValidationRequest\n} from './validation.types.ts';\n\nexport function assertValid(\n validator: ActorLogicValidator,\n request: ActorValidationRequest\n): void {\n const error = validator.check(request);\n if (error) {\n throw error;\n }\n}\n","import isDevelopment from '#is-development';\nimport { ACTOR_REF_TYPE, createActor } from './createActor.ts';\nimport {\n createErrorPlatformEvent,\n createInitEvent,\n createInvokeTimeoutEvent\n} from './eventUtils.ts';\nimport { XSTATE_TIMER } from './constants.ts';\nimport { parseGeneratedActorId } from './system.ts';\nimport { createRemoteActorRef } from './remoteActorRef.ts';\n\nimport { createSpawner } from './spawn.ts';\nimport {\n attachSnapshotActorRef,\n createInertActorScope,\n isInertActorScope,\n setInertActorScopeSnapshot\n} from './getNextSnapshot.ts';\nimport { withActorSelf } from './actorScope.ts';\nimport {\n createMachineSnapshot,\n cloneMachineSnapshot,\n getPersistedSnapshot,\n MachineSnapshot\n} from './State.ts';\nimport { setSnapshotActorRef } from './snapshotActorRef.ts';\nimport { StateNode } from './StateNode.ts';\nimport {\n formatRouteTransitions,\n getAllStateNodes,\n getStateNodeByPath,\n getStateNodes,\n getTransitionResult,\n hasEffect,\n initialMicrostep,\n isInFinalState,\n isStateId,\n macrostep,\n resolveStateValue,\n transitionNode,\n type TransitionSelectionResults\n} from './stateUtils.ts';\nimport {\n beginSpawnAllocation,\n createDeadLetterEffect,\n createSpawnEffect,\n resolveActionsWithContext,\n mergeActorIdCounters,\n takeSpawnAllocationCounters\n} from './transitionActions.ts';\nimport { AnyActorSystem, type DeadLetterDetail } from './system.ts';\nimport type {\n ActorLogic,\n ActorLogicTransitionResult,\n ActorScope,\n AnyActor,\n AnyActorLogic,\n AnyActorRef,\n AnyActorScope,\n AnyEventObject,\n AnyMachineSnapshot,\n AnyTransitionDefinition,\n Equals,\n EventDescriptor,\n EmittedFrom,\n EventObject,\n EventFromLogic,\n ExecutableActionObject,\n ExecutableActionObjectFromLogic,\n HistoryValue,\n InputFrom,\n IsAny,\n LogicalTimer,\n MachineContext,\n MetaObject,\n OutputFrom,\n Snapshot,\n SnapshotFrom,\n StateValue,\n StateSchema,\n SnapshotStatus,\n AnyStateNode\n} from './types.ts';\nimport {\n AnyMachineSchemas,\n DelaySourceMap,\n GuardSourceMap,\n Sources,\n Next_MachineConfig,\n MachineOptions\n} from './types.v6.ts';\nimport {\n matchesEventDescriptor,\n resolveReferencedActor,\n toStatePath\n} from './utils.ts';\nimport { assertValid } from './validation.ts';\nimport type { ActorLogicValidator } from './validation.types.ts';\nimport type { StandardSchemaV1 } from './schema.types.ts';\nimport type { PersistedMachineSnapshot } from './machineVersion.types.ts';\n\nconst STATE_IDENTIFIER = '#';\n\nfunction findEventSchema(\n schemas: Record<string, StandardSchemaV1> | undefined,\n eventType: string\n): StandardSchemaV1 | undefined {\n if (!schemas) {\n return undefined;\n }\n\n if (Object.hasOwn(schemas, eventType)) {\n return schemas[eventType];\n }\n\n const descriptor = Object.keys(schemas).find((key) =>\n matchesEventDescriptor(eventType, key)\n );\n return descriptor === undefined ? undefined : schemas[descriptor];\n}\n\nlet emptyCanActor: AnyActor | undefined;\nlet emptyCanActorScope: AnyActorScope | undefined;\n\nfunction getEmptyCanActor(): AnyActor {\n // A minimal inert actor used purely as the `self`/`parent` argument when\n // dry-running transitions for `snapshot.can(...)`. Intentionally not built\n // on `createLogic` so `can()` does not pull that machinery into bundles.\n return (emptyCanActor ??= createActor({\n transition: (snapshot: any) => [snapshot, []],\n initialTransition: () => [\n { status: 'active', output: undefined, error: undefined },\n []\n ],\n getInitialSnapshot: () => ({\n status: 'active',\n output: undefined,\n error: undefined\n }),\n getPersistedSnapshot: (snapshot: any) => snapshot\n } as any) as AnyActor);\n}\n\nfunction getEmptyCanActorScope(): AnyActorScope {\n if (emptyCanActorScope) {\n return emptyCanActorScope;\n }\n\n const actor = getEmptyCanActor();\n emptyCanActorScope = {\n self: actor,\n logger: () => {},\n id: '',\n sessionId: '',\n defer: () => {},\n system: actor.system,\n stopChild: () => {},\n emit: () => {},\n actionExecutor: () => {}\n };\n return emptyCanActorScope;\n}\n\ntype CompatibleProvidedActorSource<\n TExpected extends AnyActorLogic,\n TActual extends AnyActorLogic\n> =\n IsAny<TActual> extends true\n ? TActual\n : [OutputFrom<TActual>] extends [OutputFrom<TExpected>]\n ? [Omit<SnapshotFrom<TActual>, 'input'>] extends [\n Omit<SnapshotFrom<TExpected>, 'input'>\n ]\n ? [InputFrom<TExpected>] extends [InputFrom<TActual>]\n ? [EventFromLogic<TExpected>] extends [EventFromLogic<TActual>]\n ? [EmittedFrom<TActual>] extends [EmittedFrom<TExpected>]\n ? TActual\n : never\n : never\n : never\n : never\n : never;\n\ntype ProvidedActors<\n TExpectedActorMap extends Sources['actors'],\n TProvidedActorMap extends Partial<\n Record<keyof TExpectedActorMap & string, AnyActorLogic>\n >\n> = {\n [K in keyof TProvidedActorMap]: K extends keyof TExpectedActorMap\n ? TProvidedActorMap[K] extends AnyActorLogic\n ? CompatibleProvidedActorSource<\n TExpectedActorMap[K],\n TProvidedActorMap[K]\n >\n : never\n : never;\n};\n\nexport class StateMachine<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TStateValue extends StateValue,\n TTag extends string,\n TInput,\n TOutput,\n TEmitted extends EventObject,\n TMeta extends MetaObject,\n TConfig extends StateSchema,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays'],\n TInternalEvent extends EventObject = never\n> implements ActorLogic<\n MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n TEvent,\n TInput,\n AnyActorSystem,\n TEmitted\n> {\n /**\n * @internal Type-only marker for the actor's internal event protocol. Not\n * `declare` (the build's babel pipeline rejects declare class fields); the\n * one `undefined` property this emits per machine instance is inert.\n */\n readonly _internalEventType!: TInternalEvent;\n\n /** The machine's own version. */\n public version?: string;\n\n public schemas: AnyMachineSchemas | undefined;\n\n /** Standard Schema for snapshots persisted by this machine version. */\n public readonly snapshotSchema: StandardSchemaV1<\n unknown,\n Snapshot<unknown> & PersistedMachineSnapshot & { context: TContext }\n >;\n\n /** Standard Schema for complete events accepted by this machine version. */\n public readonly eventSchema: StandardSchemaV1<unknown, TEvent>;\n\n public sources: Sources;\n\n /** Runtime options for machine execution. */\n public options: MachineOptions;\n\n /** @internal */\n public idMap: Map<string, AnyStateNode> = new Map();\n\n public root: StateNode<TContext, TEvent>;\n\n public id: string;\n\n public states: StateNode<TContext, TEvent>['states'];\n public events: Array<EventDescriptor<TEvent>>;\n public internalEventDescriptors: ReadonlyArray<string>;\n /** @internal Skips eventless-selection scans for machines without `always`. */\n public _hasEventlessTransitions: boolean;\n constructor(\n /** The raw config used to create the machine. */\n public config: Next_MachineConfig<\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any // TEmitted\n > & {\n schemas?: AnyMachineSchemas;\n internalEvents?: readonly string[];\n },\n sources?: Sources,\n public validator?: ActorLogicValidator\n ) {\n this.id = config.id || '(machine)';\n this.sources = {\n actors: config.actors ?? {},\n actions: config.actions ?? {},\n delays: (config.delays ?? {}) as Sources['delays'],\n guards: config.guards ?? {},\n ...sources\n };\n if (isDevelopment) {\n // The `@xstate.` prefix is reserved for built-in serialized action and\n // guard descriptors — user source names must not collide.\n for (const kind of ['actions', 'guards', 'actors', 'delays'] as const) {\n for (const key of Object.keys(this.sources[kind])) {\n if (key.startsWith('@xstate.')) {\n throw new Error(\n `Invalid ${kind} name '${key}': the '@xstate.' prefix is reserved for built-in descriptors.`\n );\n }\n }\n }\n }\n this.version = this.config.version;\n this.schemas = this.config.schemas;\n this.snapshotSchema = {\n '~standard': {\n version: 1,\n vendor: 'xstate',\n validate: async (value) => {\n if (value === null || typeof value !== 'object') {\n return { issues: [{ message: 'Expected a persisted snapshot.' }] };\n }\n const snapshot: Record<string, unknown> = {\n historyValue: {},\n timers: {},\n ...(value as Record<string, unknown>)\n };\n const contextSchema = this.schemas?.context;\n let context = snapshot.context;\n if (contextSchema) {\n const result = await contextSchema['~standard'].validate(context);\n if (result.issues) {\n return {\n issues: [\n {\n message: `Invalid context for machine '${this.id}' version '${this.version}': ${result.issues[0]?.message}`\n }\n ]\n };\n }\n context = result.value;\n }\n for (const key of ['value', 'children'] as const) {\n if (!(key in snapshot)) {\n return {\n issues: [{ message: `Persisted snapshot is missing '${key}'.` }]\n };\n }\n }\n if (\n !['active', 'done', 'error', 'stopped'].includes(\n snapshot.status as string\n )\n ) {\n return {\n issues: [{ message: 'Persisted snapshot has invalid status.' }]\n };\n }\n for (const key of ['children', 'historyValue', 'timers'] as const) {\n if (\n snapshot[key] === null ||\n typeof snapshot[key] !== 'object' ||\n Array.isArray(snapshot[key])\n ) {\n return {\n issues: [\n { message: `Persisted snapshot has invalid '${key}'.` }\n ]\n };\n }\n }\n try {\n this.resolveState({\n value: snapshot.value as StateValue,\n context\n } as any);\n } catch (error) {\n return {\n issues: [\n {\n message:\n error instanceof Error\n ? error.message\n : 'Persisted snapshot has invalid state value.'\n }\n ]\n };\n }\n return {\n value: { ...snapshot, context } as Snapshot<unknown> &\n PersistedMachineSnapshot & { context: TContext }\n };\n }\n }\n };\n this.eventSchema = {\n '~standard': {\n version: 1,\n vendor: 'xstate',\n validate: async (value) => {\n if (\n value === null ||\n typeof value !== 'object' ||\n typeof (value as EventObject).type !== 'string'\n ) {\n return { issues: [{ message: 'Expected an event object.' }] };\n }\n const event = value as EventObject;\n const eventSchemas = this.schemas?.events;\n const internalEventSchemas = this.schemas?.internalEvents;\n const isFrameworkEvent =\n event.type.startsWith('xstate.') ||\n event.type.startsWith('@xstate.');\n const schema =\n findEventSchema(internalEventSchemas, event.type) ??\n findEventSchema(eventSchemas, event.type);\n if (\n (eventSchemas || internalEventSchemas) &&\n !schema &&\n !isFrameworkEvent\n ) {\n return {\n issues: [\n {\n message: `Unknown event '${event.type}' for machine '${this.id}' version '${this.version}'.`\n }\n ]\n };\n }\n if (!schema) {\n return { value: event as TEvent };\n }\n const { type, ...payload } = event;\n const result = await schema['~standard'].validate(payload);\n if (result.issues) {\n return result;\n }\n if (result.value === null || typeof result.value !== 'object') {\n return { issues: [{ message: 'Expected an event payload.' }] };\n }\n return { value: { ...result.value, type } as TEvent };\n }\n }\n };\n this.internalEventDescriptors = [\n ...Object.keys(this.schemas?.internalEvents ?? {}),\n ...(this.config.internalEvents ?? [])\n ];\n this.options = {\n maxIterations: Infinity,\n ...this.config.options\n };\n\n this.transition = this.transition.bind(this);\n this.initialTransition = this.initialTransition.bind(this);\n this.getInitialSnapshot = this.getInitialSnapshot.bind(this);\n this.getPersistedSnapshot = this.getPersistedSnapshot.bind(this);\n this.restoreSnapshot = this.restoreSnapshot.bind(this);\n this.start = this.start.bind(this);\n\n this.root = new StateNode(config as any, {\n _key: this.id,\n _machine: this as any\n });\n\n this.root._initialize();\n formatRouteTransitions(this.root);\n this.root._refreshEventMetadata();\n this._hasEventlessTransitions = Array.from(this.idMap.values()).some(\n (stateNode) => !!stateNode.always?.length\n );\n\n this.states = this.root.states; // TODO: remove!\n this.events = this.root.events;\n }\n\n /**\n * Clones this state machine with the provided sources.\n *\n * @param sources Options (`actions`, `guards`, `actors`, `delays`) to\n * recursively merge with the existing options.\n * @returns A new `StateMachine` instance with the provided sources.\n */\n public provide<\n const TProvidedActorMap extends Partial<\n Record<keyof TActorMap & string, AnyActorLogic>\n > = {}\n >(sources: {\n actions?: Partial<TActionMap>;\n actors?: TProvidedActorMap & ProvidedActors<TActorMap, TProvidedActorMap>;\n // Mapped over the known names (not an index signature) so unknown source\n // names are still rejected, while entries keep typed args/return values.\n guards?: Partial<TGuardMap> & {\n [K in keyof TGuardMap]?: GuardSourceMap<TContext, TEvent>[string];\n };\n // Delays are widened to `number | fn` per entry (not Partial<TDelayMap>)\n // so a fixed delay can be swapped for a computed one and vice versa.\n delays?: {\n [K in keyof TDelayMap]?: DelaySourceMap<TContext, TEvent>[string];\n };\n }): this {\n const { actions, guards, actors, delays } = this.sources;\n\n const provided = new StateMachine(\n this.config,\n {\n actions: {\n ...actions,\n ...sources.actions\n } as Sources['actions'],\n guards: {\n ...guards,\n ...sources.guards\n } as Sources['guards'],\n actors: {\n ...actors,\n ...sources.actors\n } as Sources['actors'],\n delays: {\n ...delays,\n ...sources.delays\n } as Sources['delays']\n },\n this.validator\n ) as unknown as this;\n // Providing sources does not change the serializable definition.\n provided._json = this._json;\n return provided;\n }\n\n public resolveState(\n config: {\n value: StateValue;\n context?: TContext;\n historyValue?: HistoryValue;\n status?: SnapshotStatus;\n output?: TOutput;\n error?: unknown;\n } & ([TContext] extends [never]\n ? {}\n : Equals<TContext, MachineContext> extends false\n ? { context: unknown }\n : {})\n ): MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n > {\n const resolvedStateValue = resolveStateValue(this.root, config.value);\n const nodeSet = getAllStateNodes(\n getStateNodes(this.root, resolvedStateValue)\n );\n const nodes = [...nodeSet];\n\n return createMachineSnapshot(\n {\n _nodes: nodes,\n value: resolvedStateValue,\n context: config.context || ({} as TContext),\n children: {},\n status: isInFinalState(nodeSet, this.root)\n ? 'done'\n : config.status || 'active',\n output: config.output,\n error: config.error,\n historyValue: config.historyValue\n },\n this\n ) as MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >;\n }\n\n /**\n * Determines the next snapshot given the current `snapshot` and received\n * `event`. Calculates a full macrostep from all microsteps.\n *\n * @param snapshot The current snapshot\n * @param event The received event\n */\n public transition(\n snapshot: MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n event: TEvent,\n actorScope?: ActorScope<typeof snapshot, TEvent, AnyActorSystem, TEmitted>\n ): ActorLogicTransitionResult<\n MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n ExecutableActionObjectFromLogic<this>\n > {\n const usesInertScope = !actorScope;\n const resolvedActorScope = (actorScope ??\n createInertActorScope(\n this,\n snapshot as SnapshotFrom<this>\n )) as NonNullable<typeof actorScope>;\n if (usesInertScope) {\n setInertActorScopeSnapshot(resolvedActorScope, snapshot, false);\n }\n if (this.validator) {\n const sourceRef = actorScope && (actorScope.self as any)._lastSourceRef;\n const eventOrigin = sourceRef ? 'actor' : 'external';\n const error = this.validator.check({\n kind: 'event',\n logic: this,\n event,\n eventOrigin\n });\n if (error) {\n // Boundary fault: an invalid event arriving from outside the machine\n // is rejected (never delivered), not routed to the error channel. The\n // snapshot is returned unchanged; the rejection is represented as an\n // effect so hosts and the actor runtime can report it.\n return [\n snapshot,\n [\n createDeadLetterEffect(\n resolvedActorScope,\n sourceRef,\n event,\n 'invalidEvent',\n {\n issues: (error as { issues?: DeadLetterDetail['issues'] })\n .issues,\n error\n }\n ) as ExecutableActionObjectFromLogic<this>\n ]\n ];\n }\n }\n beginSpawnAllocation(resolvedActorScope);\n const fastSnapshot = this._transitionFast(\n snapshot,\n event,\n resolvedActorScope\n );\n if (fastSnapshot) {\n if (usesInertScope) {\n setInertActorScopeSnapshot(resolvedActorScope, fastSnapshot, false);\n }\n const returnedSnapshot =\n usesInertScope && fastSnapshot !== snapshot\n ? attachSnapshotActorRef(resolvedActorScope, fastSnapshot)\n : this._attachPureActorRef(fastSnapshot, resolvedActorScope);\n if (this.validator) {\n assertValid(this.validator, {\n kind: 'result',\n logic: this,\n snapshot: returnedSnapshot,\n effects: []\n });\n }\n return [returnedSnapshot, []];\n }\n\n const { snapshot: nextSnapshot, microsteps } = macrostep(\n snapshot,\n event,\n resolvedActorScope,\n []\n );\n\n if (usesInertScope) {\n setInertActorScopeSnapshot(resolvedActorScope, nextSnapshot, false);\n }\n const returnedSnapshot = usesInertScope\n ? nextSnapshot === snapshot\n ? nextSnapshot\n : attachSnapshotActorRef(resolvedActorScope, nextSnapshot)\n : this._attachPureActorRef(nextSnapshot, resolvedActorScope);\n const effects = this._collectEffects(microsteps);\n if (this.validator) {\n assertValid(this.validator, {\n kind: 'result',\n logic: this,\n snapshot: returnedSnapshot,\n effects\n });\n }\n return [\n returnedSnapshot as MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n effects\n ];\n }\n\n private _collectEffects(\n microsteps: ReadonlyArray<\n readonly [unknown, ReadonlyArray<ExecutableActionObject>]\n >\n ): ExecutableActionObjectFromLogic<this>[] {\n return microsteps.flatMap(\n ([, actions]) => actions\n ) as ExecutableActionObjectFromLogic<this>[];\n }\n\n private _attachPureActorRef<TSnapshot extends AnyMachineSnapshot>(\n snapshot: TSnapshot,\n actorScope: AnyActorScope,\n skipInitializingActor = false\n ): TSnapshot {\n if (isInertActorScope(actorScope)) {\n return snapshot;\n }\n if (\n skipInitializingActor &&\n (\n actorScope.self as AnyActor & {\n _actorScope?: AnyActorScope;\n _snapshot?: unknown;\n }\n )._actorScope === actorScope &&\n (actorScope.self as AnyActor & { _snapshot?: unknown })._snapshot ===\n undefined\n ) {\n return snapshot;\n }\n setSnapshotActorRef(snapshot, actorScope.self, actorScope.system);\n return snapshot;\n }\n\n private _transitionFast(\n snapshot: MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n event: TEvent,\n actorScope: ActorScope<typeof snapshot, TEvent, AnyActorSystem, TEmitted>\n ):\n | MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >\n | undefined {\n if (\n snapshot.status !== 'active' ||\n typeof snapshot.value !== 'string' ||\n this.root.always?.length\n ) {\n return undefined;\n }\n\n const sourceNode = this.root.states[snapshot.value];\n if (\n !sourceNode ||\n sourceNode.type !== 'atomic' ||\n sourceNode.exit ||\n sourceNode.invoke.length ||\n sourceNode.always?.length ||\n sourceNode.after?.length\n ) {\n return undefined;\n }\n\n const transitions = sourceNode.transitions.get(event.type);\n if (transitions?.length !== 1) {\n return undefined;\n }\n\n const selected = transitions[0];\n if (\n selected.guard ||\n selected.actions ||\n selected.to ||\n selected.reenter ||\n selected.input ||\n typeof selected.context === 'function' ||\n (selected.target && selected.target.length !== 1)\n ) {\n return undefined;\n }\n\n const targetNode = selected.target?.[0] ?? sourceNode;\n const stateChanged = targetNode !== sourceNode;\n if (\n targetNode.parent !== this.root ||\n targetNode.type !== 'atomic' ||\n (stateChanged &&\n (targetNode.entry ||\n targetNode.invoke.length ||\n targetNode.always?.length ||\n targetNode.after?.length))\n ) {\n return undefined;\n }\n\n const context =\n selected.context !== undefined\n ? ({ ...snapshot.context, ...selected.context } as TContext)\n : snapshot.context;\n\n if (\n !isInertActorScope(actorScope) &&\n (actorScope.system._hasInspectionObservers?.() ?? true)\n ) {\n const collectedMicrosteps =\n ((actorScope.self as any)._collectedMicrosteps as any[]) || [];\n collectedMicrosteps.push(selected);\n (actorScope.self as any)._collectedMicrosteps = collectedMicrosteps;\n }\n\n return cloneMachineSnapshot(snapshot, {\n ...(context !== snapshot.context ? { context } : {}),\n ...(stateChanged ? { _nodes: [this.root, targetNode] } : {})\n });\n }\n\n /**\n * Determines the next state given the current `state` and `event`. Calculates\n * a microstep.\n *\n * @param state The current state\n * @param event The received event\n */\n public microstep(\n snapshot: MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n event: TEvent,\n actorScope: AnyActorScope\n ): Array<\n MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >\n > {\n const { microsteps } = macrostep(snapshot, event, actorScope, []);\n const snapshots = new Array(microsteps.length);\n\n for (let i = 0; i < microsteps.length; i++) {\n snapshots[i] = microsteps[i][0];\n }\n\n return snapshots;\n }\n\n public getTransitionData(\n snapshot: MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n event: TEvent,\n actorScope: AnyActorScope,\n selectionResults?: TransitionSelectionResults\n ): Array<AnyTransitionDefinition> {\n return (\n transitionNode(\n this.root,\n snapshot.value,\n snapshot,\n event,\n actorScope,\n selectionResults\n ) || []\n );\n }\n\n public isInternalEventType(eventType: string): boolean {\n if (eventType === XSTATE_TIMER) {\n return true;\n }\n for (const descriptor of this.internalEventDescriptors) {\n if (matchesEventDescriptor(eventType, descriptor)) {\n return true;\n }\n }\n\n return false;\n }\n\n /**\n * Determines whether sending the `event` to the given snapshot would select a\n * non-forbidden transition. Backs `snapshot.can(...)`; lives here so that\n * non-machine bundles don't pay for the transition-resolution machinery.\n *\n * @internal\n */\n public _canTransition(snapshot: AnyMachineSnapshot, event: TEvent): boolean {\n const emptyActorScope = getEmptyCanActorScope();\n const transitionData = this.getTransitionData(\n snapshot as any,\n event,\n emptyActorScope\n );\n\n if (!transitionData?.length) {\n return false;\n }\n\n // Check that at least one transition is not forbidden\n for (const transition of transitionData) {\n if (transition.target !== undefined) {\n return true;\n }\n\n const res = getTransitionResult(\n transition,\n snapshot,\n event,\n emptyActorScope,\n { resolveActions: false }\n );\n if (\n res.targets?.length ||\n res.context ||\n hasEffect(\n transition,\n snapshot.context,\n event,\n snapshot,\n emptyActorScope\n )\n ) {\n return true;\n }\n }\n\n return false;\n }\n\n /**\n * Returns the error event that the actor should transition with to recover\n * from an execution error, if any active state node declares `onError`.\n *\n * @internal\n */\n public getExecutionErrorEvent(\n snapshot: MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n error: unknown\n ): TEvent | undefined {\n if (\n (snapshot as any)?.status !== 'active' ||\n !snapshot.nodes?.some((stateNode) => stateNode.config.onError)\n ) {\n return undefined;\n }\n return createErrorPlatformEvent('execution', error) as unknown as TEvent;\n }\n\n /**\n * The initial state _before_ evaluating any microsteps. This \"pre-initial\"\n * state is provided to initial actions executed in the initial state.\n *\n * @internal\n */\n _getPreInitialState(\n actorScope: AnyActorScope,\n initEvent: any\n ): MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n > {\n const { context } = this.config;\n\n const preInitial = createMachineSnapshot(\n {\n context:\n typeof context !== 'function' && context ? context : ({} as TContext),\n _nodes: [this.root],\n children: {},\n status: 'active'\n },\n this\n );\n\n if (typeof context === 'function') {\n const children = {};\n const spawn = createSpawner(actorScope, this.sources.actors, children);\n const resolvedContext = context(\n withActorSelf(\n {\n spawn,\n input: initEvent.input,\n actors: this.sources.actors\n },\n actorScope\n )\n );\n const [nextState] = resolveActionsWithContext(\n preInitial,\n initEvent,\n actorScope,\n []\n ) as any;\n if (resolvedContext) {\n nextState.context = resolvedContext;\n }\n if (Object.keys(children).length > 0) {\n nextState.children = {\n ...nextState.children,\n ...children\n };\n // Commit the transaction counters so context-factory allocations\n // persist with the snapshot: a freed id is never handed out again\n // after a restore or in a fresh replay process. (The spawner already\n // registered each child for string-id resolution.)\n const counters = takeSpawnAllocationCounters(actorScope);\n if (counters) {\n nextState._nextActorIds = mergeActorIdCounters(\n nextState._nextActorIds,\n counters\n );\n }\n }\n return nextState as SnapshotFrom<this>;\n }\n\n return preInitial as SnapshotFrom<this>;\n }\n\n /**\n * Returns the initial `State` instance, with reference to `self` as an\n * `ActorRef`.\n */\n public getInitialSnapshot(\n actorScope?: ActorScope<\n MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n TEvent,\n AnyActorSystem,\n TEmitted\n >,\n input?: TInput\n ): MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n > {\n return this.initialTransition(input, actorScope)[0];\n }\n\n public initialTransition(\n input: TInput | undefined,\n actorScope?: ActorScope<\n MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n TEvent,\n AnyActorSystem,\n TEmitted\n >\n ): ActorLogicTransitionResult<\n MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n ExecutableActionObjectFromLogic<this>\n > {\n if (this.validator) {\n assertValid(this.validator, {\n kind: 'input',\n logic: this,\n input\n });\n }\n const usesInertScope = !actorScope;\n const resolvedActorScope = (actorScope ??\n createInertActorScope(this)) as NonNullable<typeof actorScope>;\n beginSpawnAllocation(resolvedActorScope);\n const initEvent = createInitEvent(input) as unknown as TEvent; // TODO: fix;\n const internalQueue: AnyEventObject[] = [];\n const preInitialState = this._getPreInitialState(\n resolvedActorScope,\n initEvent\n );\n const contextSpawnEffects = Object.values(preInitialState.children)\n .filter(Boolean)\n .map((actor) => createSpawnEffect(actor as AnyActor));\n const finalizeInitialResult = (\n macroState: AnyMachineSnapshot,\n microsteps: ReadonlyArray<\n readonly [unknown, ReadonlyArray<ExecutableActionObject>]\n >\n ): ActorLogicTransitionResult<\n SnapshotFrom<this>,\n ExecutableActionObjectFromLogic<this>\n > => {\n if (usesInertScope) {\n setInertActorScopeSnapshot(resolvedActorScope, macroState, false);\n }\n const returnedSnapshot = usesInertScope\n ? attachSnapshotActorRef(resolvedActorScope, macroState)\n : this._attachPureActorRef(macroState, resolvedActorScope, true);\n const effects = this._collectEffects(microsteps);\n if (this.validator) {\n assertValid(this.validator, {\n kind: 'result',\n logic: this,\n snapshot: returnedSnapshot,\n effects\n });\n }\n return [returnedSnapshot as SnapshotFrom<this>, effects];\n };\n\n try {\n const [nextState, initialActions] = initialMicrostep(\n this.root,\n preInitialState,\n resolvedActorScope,\n initEvent,\n internalQueue\n );\n\n const { snapshot: macroState, microsteps } = macrostep(\n nextState,\n initEvent as AnyEventObject,\n resolvedActorScope,\n internalQueue,\n [\n [nextState, [...contextSpawnEffects, ...initialActions]] as [\n AnyMachineSnapshot,\n ExecutableActionObject[]\n ]\n ]\n );\n return finalizeInitialResult(macroState, microsteps);\n } catch (err) {\n if (!this.root.config.onError) {\n throw err;\n }\n const errorEvent = createErrorPlatformEvent('execution', err);\n const errorMacrostep = macrostep(\n preInitialState,\n errorEvent,\n resolvedActorScope,\n [],\n [\n [preInitialState, contextSpawnEffects] as [\n AnyMachineSnapshot,\n ExecutableActionObject[]\n ]\n ]\n );\n return finalizeInitialResult(\n errorMacrostep.snapshot,\n errorMacrostep.microsteps\n );\n }\n }\n\n public start(\n snapshot?: MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >\n ): void {\n // Start rehydrated children that were active when persisted. Freshly\n // invoked/spawned children are NOT started here — they start via deferred\n // `@xstate.start` actions so sync start errors route to `onError`.\n if (!snapshot?.children) {\n return;\n }\n const children = snapshot.children as unknown as Record<string, AnyActor>;\n for (const childId in children) {\n if (!Object.hasOwn(children, childId)) {\n continue;\n }\n const child = children[childId];\n if (\n (child as any)._rehydrated &&\n (child as any).getSnapshot?.().status === 'active'\n ) {\n (child as any).start();\n }\n }\n }\n\n public getStateNodeById(stateId: string): StateNode<TContext, TEvent> {\n const fullPath = toStatePath(stateId);\n const relativePath = fullPath.slice(1);\n const resolvedStateId = isStateId(fullPath[0])\n ? fullPath[0].slice(STATE_IDENTIFIER.length)\n : fullPath[0];\n\n const stateNode = this.idMap.get(resolvedStateId);\n if (!stateNode) {\n throw new Error(\n `Child state node '#${resolvedStateId}' does not exist on machine '${this.id}'`\n );\n }\n return getStateNodeByPath(stateNode, relativePath) as StateNode<\n TContext,\n TEvent\n >;\n }\n\n public getPersistedSnapshot(\n snapshot: MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n options?: unknown\n ) {\n return getPersistedSnapshot(snapshot, options);\n }\n\n /**\n * The original JSON definition this machine was created from (set by\n * `createMachineFromConfig`), if any. Used by `serializeMachine` for lossless\n * round-trips.\n *\n * @internal\n */\n public _json?: Record<string, unknown>;\n\n public restoreSnapshot(\n snapshot: Snapshot<unknown>,\n actorScope?: ActorScope<\n MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n TEvent,\n AnyActorSystem,\n TEmitted\n >\n ): MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n > {\n const usesInertScope = !actorScope;\n const resolvedActorScope = (actorScope ??\n createInertActorScope(this)) as NonNullable<typeof actorScope>;\n const snapshotMachine = (snapshot as any).machine;\n // A live machine snapshot carries its producing machine so helpers such as\n // `matches()` can resolve state nodes. That runtime association is not the\n // persisted `{ id, version }` identity written by getPersistedSnapshot().\n const persistedMachine =\n snapshotMachine &&\n typeof snapshotMachine === 'object' &&\n typeof snapshotMachine.transition === 'function' &&\n 'root' in snapshotMachine\n ? undefined\n : snapshotMachine;\n const legacyPersistedVersion: string | undefined = (snapshot as any)\n .version;\n const persistedVersion: string | undefined =\n typeof persistedMachine?.version === 'string'\n ? persistedMachine.version\n : legacyPersistedVersion;\n if (\n legacyPersistedVersion !== undefined &&\n persistedMachine?.version !== undefined &&\n persistedMachine.version !== legacyPersistedVersion\n ) {\n throw new Error(\n `Persisted snapshot version '${legacyPersistedVersion}' conflicts with machine version '${persistedMachine.version}'.`\n );\n }\n if (\n persistedMachine &&\n typeof persistedMachine.id === 'string' &&\n persistedMachine.id !== this.id\n ) {\n throw new Error(\n isDevelopment\n ? `Machine ID mismatch: persisted snapshot was created by machine '${persistedMachine.id}', but machine '${this.id}' was provided.`\n : `Machine ID mismatch: persisted snapshot machine '${persistedMachine.id}' does not match '${this.id}'.`\n );\n }\n if (persistedVersion !== this.version) {\n const migrate = (this.config as any).migrate;\n if (typeof migrate !== 'function') {\n throw new Error(\n isDevelopment\n ? `Persisted snapshot version '${persistedVersion}' does not match machine version '${this.version}' for machine '${this.id}'. Provide a \\`migrate(persistedSnapshot, fromVersion)\\` function in the machine config to migrate old snapshots.`\n : `Persisted snapshot version '${persistedVersion}' does not match machine version '${this.version}'.`\n );\n }\n snapshot = migrate(snapshot, persistedVersion);\n }\n\n const snapshotData = snapshot as any;\n const children: Record<string, AnyActor> = {};\n const snapshotChildren: Record<\n string,\n {\n src: string | AnyActorLogic;\n snapshot?: Snapshot<unknown>;\n address?: string;\n remote?: boolean;\n incarnation?: string;\n syncSnapshot?: boolean;\n registryKey?: string;\n }\n > = snapshotData.children;\n\n for (const actorId of Object.keys(snapshotChildren)) {\n const actorData = snapshotChildren[actorId];\n\n if (actorData.remote === true && actorData.address !== undefined) {\n if (typeof actorData.src !== 'string') {\n // Fail loudly instead of fabricating a source key that hosts would\n // route by.\n throw new Error(\n `Unable to restore remote child '${actorId}': a child referenced by address requires a registered source key.`\n );\n }\n // The child's state lives with another runtime; restore a\n // location-transparent handle constructed from its identity alone.\n // The handle keeps its persisted address verbatim: the owning\n // runtime's identity for the child wins over the local parent chain.\n const handle = createRemoteActorRef(resolvedActorScope.system, {\n id: actorId,\n address: actorData.address,\n src: actorData.src,\n parent: resolvedActorScope.self,\n registryKey: actorData.registryKey,\n syncSnapshot: actorData.syncSnapshot,\n incarnation: actorData.incarnation\n });\n if (actorData.registryKey) {\n resolvedActorScope.system._set(actorData.registryKey, handle);\n }\n children[actorId] = handle;\n continue;\n }\n\n const childState = actorData.snapshot;\n const src = actorData.src;\n\n const logic =\n typeof src === 'string' ? resolveReferencedActor(this, src) : src;\n\n if (!logic) {\n const sourceId = typeof src === 'string' ? src : '<unknown>';\n throw new Error(\n `Unable to restore child actor '${actorId}': child source '${sourceId}' is not provided in machine '${this.id}'.`\n );\n }\n\n const actor = resolvedActorScope.system.createActorRef(logic, {\n id: actorId,\n parent: resolvedActorScope.self,\n syncSnapshot: actorData.syncSnapshot,\n snapshot: childState,\n src,\n registryKey: actorData.registryKey\n });\n // Mark so `start()` knows to start this child (freshly invoked/spawned\n // children are started via deferred `@xstate.start` actions instead).\n (actor as any)._rehydrated = true;\n\n children[actorId] = actor;\n }\n\n const timers: Record<string, LogicalTimer> = {};\n const persistedTimers: Record<\n string,\n {\n id: string;\n delay: number;\n type: '@xstate.raise' | '@xstate.sendTo';\n event: EventObject;\n target: string | { type: 'parent' };\n }\n > = snapshotData.timers ?? {};\n for (const [id, timer] of Object.entries(persistedTimers)) {\n let event = timer.event;\n if (event.type === 'xstate.timeout.actor') {\n const actorId = (event as AnyEventObject).actorId as string;\n const child = children[actorId];\n if (child) {\n event = createInvokeTimeoutEvent(actorId, child.sessionId);\n }\n }\n const target =\n typeof timer.target === 'string'\n ? timer.target === 'self'\n ? 'self'\n : children[timer.target]\n : resolvedActorScope.self._parent;\n if (!target) {\n const targetDescription =\n typeof timer.target === 'string' ? timer.target : timer.target.type;\n throw new Error(\n `Unable to restore timer '${id}': target actor '${targetDescription}' is unavailable.`\n );\n }\n timers[id] = { ...timer, event, target };\n }\n\n const reviveHistoryValue = (\n historyValue: Record<\n string,\n ({ id: string } | StateNode<TContext, TEvent>)[]\n >\n ): HistoryValue => {\n if (!historyValue || typeof historyValue !== 'object') {\n return {};\n }\n const revived: HistoryValue = {};\n for (const key of Object.keys(historyValue)) {\n const arr = historyValue[key];\n\n for (const item of arr) {\n let resolved: StateNode<TContext, TEvent> | undefined;\n\n if (item instanceof StateNode) {\n resolved = item;\n } else {\n try {\n resolved = this.root.machine.getStateNodeById(item.id);\n } catch {\n if (isDevelopment) {\n console.warn(`Could not resolve StateNode for id: ${item.id}`);\n }\n }\n }\n\n if (!resolved) {\n continue;\n }\n\n revived[key] ??= [];\n revived[key].push(resolved);\n }\n }\n return revived;\n };\n\n const revivedHistoryValue = reviveHistoryValue(snapshotData.historyValue);\n\n const validateStateValue = (\n stateValue: StateValue,\n node: AnyStateNode,\n path: string[]\n ): void => {\n const missingStateError = (statePath: string[]) =>\n new Error(\n `Persisted snapshot references state '${statePath.join('.')}' which does not exist on machine '${this.id}'.`\n );\n if (typeof stateValue === 'string') {\n if (!node.states[stateValue]) {\n throw missingStateError(path.concat(stateValue));\n }\n return;\n }\n if (!stateValue || typeof stateValue !== 'object') {\n return;\n }\n for (const key of Object.keys(stateValue)) {\n const childNode = node.states[key];\n if (!childNode) {\n throw missingStateError(path.concat(key));\n }\n validateStateValue(stateValue[key]!, childNode, path.concat(key));\n }\n };\n validateStateValue(snapshotData.value, this.root, []);\n\n const nodes = Array.from(\n getAllStateNodes(getStateNodes(this.root, snapshotData.value))\n );\n\n const {\n version: _persistedSnapshotVersion,\n // The legacy system-wide counter: superseded by per-snapshot\n // `_nextActorIds` plus the child-id fold below; dropped so old and new\n // snapshots round-trip to the same shape.\n _nextActorId: _legacyNextActorId,\n ...persistedRest\n } = snapshot as any;\n // Fold generated-shaped child ids into the counters as a floor: snapshots\n // persisted before per-actor counters (or hand-crafted ones) still must\n // never reuse a live child's id.\n let restoredCounters: Record<string, number> | undefined =\n persistedRest._nextActorIds;\n for (const childId of Object.keys(snapshotChildren)) {\n const generated = parseGeneratedActorId(childId);\n if (\n generated &&\n (restoredCounters?.[generated.prefix] ?? 0) <= generated.index\n ) {\n restoredCounters = {\n ...restoredCounters,\n [generated.prefix]: generated.index + 1\n };\n }\n }\n const restoredSnapshot = createMachineSnapshot(\n {\n ...persistedRest,\n children,\n timers,\n _nextActorIds: restoredCounters,\n _nodes: nodes,\n value: snapshotData.value,\n historyValue: revivedHistoryValue,\n _stateInputs: snapshotData.stateInputs ?? {}\n },\n this,\n resolvedActorScope.self\n ) as MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >;\n\n const seen = new WeakSet<Record<string, unknown>>();\n\n function reviveContext(contextPart: Record<string, unknown>) {\n if (seen.has(contextPart)) {\n return;\n }\n seen.add(contextPart);\n for (const key of Object.keys(contextPart)) {\n const value: unknown = contextPart[key];\n\n if (value && typeof value === 'object') {\n if ('xstate$type' in value && value.xstate$type === ACTOR_REF_TYPE) {\n contextPart[key] = children[(value as any).id];\n continue;\n }\n reviveContext(value as typeof contextPart);\n }\n }\n }\n\n reviveContext(restoredSnapshot.context);\n\n if (usesInertScope) {\n setInertActorScopeSnapshot(resolvedActorScope, restoredSnapshot, false);\n return attachSnapshotActorRef(resolvedActorScope, restoredSnapshot);\n }\n\n return this._attachPureActorRef(restoredSnapshot, resolvedActorScope);\n }\n}\n","import {\n allocateChildId,\n assertChildIdFree,\n reserveChildId\n} from './transitionActions.ts';\nimport { resolveRegisteredActorSource } from './actorSource.ts';\nimport {\n ActorFromLogic,\n AnyActorLogic,\n AnyActorRef,\n AnyActorScope,\n ConditionalRequired,\n InputFrom,\n IsNotNever,\n RegistryKeyForLogic,\n SystemRegistry,\n type RequiredLogicInput\n} from './types.ts';\n\nexport type Spawner<TSystemRegistry extends SystemRegistry = SystemRegistry> = <\n TLogic extends AnyActorLogic\n>(\n src: TLogic,\n ...[options]: ConditionalRequired<\n [\n options?: {\n id?: string;\n registryKey?: RegistryKeyForLogic<TLogic, TSystemRegistry>;\n input?: InputFrom<TLogic>;\n syncSnapshot?: boolean;\n } & { [K in RequiredLogicInput<TLogic>]: unknown }\n ],\n IsNotNever<RequiredLogicInput<TLogic>>\n >\n) => ActorFromLogic<TLogic>;\n\nexport function createSpawner(\n actorScope: AnyActorScope,\n actors: Record<string, AnyActorLogic>,\n spawnedChildren: Record<string, AnyActorRef>\n): Spawner {\n return ((src, options) => {\n const referencedSrc = resolveRegisteredActorSource(actors, src);\n // Generated ids come from the same transaction allocator as `enq.spawn`,\n // so context-factory allocations persist with the snapshot and never\n // collide with later spawns.\n const id =\n options?.id ?? allocateChildId(actorScope, referencedSrc ?? src).id;\n if (options?.id !== undefined) {\n assertChildIdFree(actorScope, options.id);\n reserveChildId(actorScope, options.id);\n }\n const actor = actorScope.system.createActorRef(src, {\n id,\n parent: actorScope.self,\n syncSnapshot: options?.syncSnapshot,\n input: options?.input,\n src: referencedSrc ?? src,\n registryKey: options?.registryKey\n });\n spawnedChildren[actor.id] = actor;\n return actor;\n }) as Spawner;\n}\n","import {\n Action,\n AnyActorLogic,\n AnyActorRef,\n AnyEventObject,\n AnyStateMachine,\n EventObject,\n MachineContext,\n MetaObject\n} from '../types';\nimport { Next_StateNodeConfig } from '../types.v6';\nimport { createMachine } from '../createMachine';\nimport { parseDelayToMilliseconds } from '../delay';\n\nfunction delayToMs(delay: string | number): number {\n const parsedDelay = parseDelayToMilliseconds(delay);\n if (parsedDelay !== undefined) return parsedDelay;\n return typeof delay === 'string' ? parseFloat(delay) || 0 : delay;\n}\n\nfunction normalizeScxmlEventType(eventType: string): string {\n return /^error(\\.|$)/.test(eventType) ? `xstate.${eventType}` : eventType;\n}\n\nfunction toScxmlEventName(eventType: string): string {\n return eventType.startsWith('xstate.error.')\n ? eventType.slice('xstate.'.length)\n : eventType;\n}\n\nfunction matchesScxmlEventDescriptor(\n descriptor: string,\n event: EventObject\n): boolean {\n if (descriptor === '*') return true;\n if (descriptor.endsWith('.*')) {\n const prefix = descriptor.slice(0, -2);\n return event.type === prefix || event.type.startsWith(`${prefix}.`);\n }\n if (descriptor.startsWith('xstate.done.actor.')) {\n return (\n event.type === 'xstate.done.actor' &&\n (event as any).actorId === descriptor.slice('xstate.done.actor.'.length)\n );\n }\n if (descriptor.startsWith('xstate.done.state.')) {\n return (\n event.type === 'xstate.done.state' &&\n (event as any).stateId === descriptor.slice('xstate.done.state.'.length)\n );\n }\n return event.type === descriptor || event.type.startsWith(`${descriptor}.`);\n}\n\nexport interface RaiseJSON {\n type: '@xstate.raise';\n event: EventObject;\n id?: string;\n delay?: number;\n}\n\nexport interface CancelJSON {\n type: '@xstate.cancel';\n id: string;\n}\n\ninterface LogJSON {\n type: '@xstate.log';\n args: any[];\n}\n\nexport interface ScxmlLogJSON {\n type: 'scxml.log';\n label?: string;\n expr?: string;\n}\n\ninterface EmitJSON {\n type: '@xstate.emit';\n event: AnyEventObject;\n}\n\ninterface AssignJSON {\n type: '@xstate.assign';\n context: MachineContext;\n}\n\ninterface ScxmlAssignJSON {\n type: 'scxml.assign';\n /** SCXML location attribute - the context property to assign to */\n location: string;\n /** SCXML expr attribute - expression to evaluate */\n expr: string;\n}\n\nexport interface ScxmlRaiseJSON {\n type: 'scxml.raise';\n /** Event type, or undefined if using eventexpr */\n event?: string;\n /** Expression to evaluate for event type */\n eventexpr?: string;\n /** Params with expressions to evaluate */\n params?: Array<{ name: string; expr?: string; location?: string }>;\n namelist?: string[];\n id?: string;\n idlocation?: string;\n delay?: number;\n /** Expression for delay */\n delayexpr?: string;\n /** Static target (e.g. '#_parent') */\n target?: string;\n /** Expression for target */\n targetexpr?: string;\n processorType?: string;\n content?: ScxmlContentJSON;\n}\n\nexport interface ScxmlXmlJSON {\n name: string;\n attributes?: Record<string, string>;\n children?: ScxmlXmlJSON[];\n}\n\nexport interface ScxmlContentJSON {\n expr?: string;\n text?: string;\n xml?: ScxmlXmlJSON;\n}\n\ninterface ScxmlScriptJSON {\n type: 'scxml.script';\n /** The script code to execute */\n code: string;\n global?: boolean;\n}\n\nexport interface ScxmlForeachJSON {\n type: 'scxml.foreach';\n array: string;\n item: string;\n index?: string;\n actions: ActionJSON[];\n}\n\nexport interface ScxmlCancelJSON {\n type: 'scxml.cancel';\n sendidexpr: string;\n}\n\nexport interface ScxmlDonedataJSON {\n params?: Array<{ name: string; expr: string }>;\n contentExpr?: string;\n contentText?: string;\n}\n\nexport interface ScxmlDataJSON {\n id: string;\n expr?: string;\n content?: string;\n src?: string;\n xml?: ScxmlXmlJSON;\n}\n\n/**\n * Isolated executable-content block. Errors in nested actions stop this block\n * but do not propagate to the surrounding action list. Used to model SCXML's\n * separate <onentry>/<onexit> blocks: each is its own block per spec.\n */\ninterface ScxmlBlockJSON {\n type: 'scxml.block';\n actions: ActionJSON[];\n}\n\ninterface ScxmlDatamodelJSON {\n type: 'scxml.datamodel';\n data: ScxmlDataJSON[];\n}\n\ninterface ScxmlForwardJSON {\n type: 'scxml.forward';\n invokeId: string;\n}\n\ninterface ScxmlFinalizeJSON {\n type: 'scxml.finalize';\n invokeId: string;\n actions: ActionJSON[];\n}\n\ninterface ScxmlIfJSON {\n type: 'scxml.if';\n branches: Array<{\n cond?: string;\n actions: ActionJSON[];\n }>;\n}\n\ntype BuiltInActionJSON =\n | RaiseJSON\n | CancelJSON\n | LogJSON\n | EmitJSON\n | AssignJSON;\n\ninterface CustomActionJSON {\n type: string;\n params?: unknown;\n}\n\nexport type ActionJSON =\n | CustomActionJSON\n | RaiseJSON\n | CancelJSON\n | LogJSON\n | EmitJSON\n | AssignJSON\n | ScxmlAssignJSON\n | ScxmlRaiseJSON\n | ScxmlScriptJSON\n | ScxmlIfJSON\n | ScxmlForeachJSON\n | ScxmlCancelJSON\n | ScxmlLogJSON\n | ScxmlBlockJSON\n | ScxmlDatamodelJSON\n | ScxmlForwardJSON\n | ScxmlFinalizeJSON\n | ExpressionJSON\n | CodeJSON;\n\nexport interface GuardJSON {\n type: string;\n params?: unknown;\n}\n\ninterface ExpressionJSON {\n '@expr': string;\n '@lang'?: string;\n}\n\ninterface CodeJSON {\n '@code': string;\n '@lang'?: string;\n}\n\ntype ResolvableJSON = ExpressionJSON | CodeJSON;\n\ntype ConditionJSON = GuardJSON | ResolvableJSON;\n\ninterface ChoiceBranchJSON {\n when?: ConditionJSON;\n target: string | string[];\n context?: MachineContext;\n input?: unknown;\n description?: string;\n reenter?: boolean;\n meta?: MetaObject;\n}\n\nexport interface InvokeJSON {\n id?: string;\n registryKey?: string;\n src: string;\n input?: unknown;\n onDone?: TransitionConfigJSON | TransitionConfigJSON[];\n onError?: TransitionConfigJSON | TransitionConfigJSON[];\n onSnapshot?: TransitionConfigJSON | TransitionConfigJSON[];\n timeout?: number | string | ResolvableJSON;\n onTimeout?: TransitionConfigJSON | TransitionConfigJSON[];\n /** @internal SCXML invocation input expressions. */\n _scxmlInput?: {\n namelist?: string[];\n params?: Array<{ name: string; expr?: string; location?: string }>;\n };\n}\n\nexport interface TransitionJSON {\n target?: string | string[];\n matches?: Record<string, unknown>;\n context?: MachineContext;\n actions?: ActionJSON[];\n guard?: ConditionJSON;\n description?: string;\n reenter?: boolean;\n meta?: MetaObject;\n input?: unknown;\n /** @internal Strict semantics for transitions produced by the SCXML converter. */\n _scxml?: {\n type?: 'internal' | 'external';\n eventDescriptors?: string[];\n finalize?: Array<{ invokeId: string; actions: ActionJSON[] }>;\n };\n}\n\ntype TransitionConfigJSON = TransitionJSON | ResolvableJSON;\n\nexport interface StateNodeJSON {\n id?: string;\n key?: string;\n type?: 'atomic' | 'compound' | 'parallel' | 'final' | 'history' | 'choice';\n initial?: string;\n states?: Record<string, StateNodeJSON>;\n on?: Record<string, TransitionConfigJSON | TransitionConfigJSON[]>;\n onError?: TransitionConfigJSON | TransitionConfigJSON[];\n after?: Record<string, TransitionConfigJSON | TransitionConfigJSON[]>;\n always?: TransitionConfigJSON | TransitionConfigJSON[];\n choice?: ChoiceBranchJSON[] | ResolvableJSON;\n /**\n * JSON route config. Unlike the authoring API (a function), the JSON layer\n * allows an object form whose `guard` may be a named guard reference (string)\n * resolved against the machine's `guards` sources.\n */\n route?:\n | {\n description?: string;\n reenter?: boolean;\n meta?: MetaObject;\n guard?: string;\n input?: Record<string, unknown>;\n }\n | ResolvableJSON;\n invoke?: InvokeJSON | InvokeJSON[];\n entry?: ActionJSON | ActionJSON[];\n exit?: ActionJSON | ActionJSON[];\n meta?: MetaObject;\n description?: string;\n tags?: string[];\n input?: unknown;\n timeout?: number | string | ResolvableJSON;\n onTimeout?: TransitionConfigJSON | TransitionConfigJSON[];\n history?: 'shallow' | 'deep';\n target?: string | [string, ...string[]];\n output?: unknown;\n context?: Record<string, unknown>;\n _scxmlDonedata?: ScxmlDonedataJSON;\n /** @internal Initial transition emitted by the SCXML converter. */\n _scxmlInitial?: {\n targets: string[];\n actions?: ActionJSON[];\n };\n /** @internal Executable content on an SCXML history default transition. */\n _scxmlHistoryActions?: ActionJSON[];\n /** @internal Datamodel declarations initialized on entry. */\n _scxmlData?: ScxmlDataJSON[];\n}\nexport interface ScxmlIR extends StateNodeJSON {\n '@exprLang'?: string;\n version?: string;\n /** @internal All declared SCXML datamodel identifiers. */\n _scxmlDataIds?: string[];\n actions?: Record<string, ActionJSON | ActionJSON[]>;\n guards?: Record<string, { when: ConditionJSON }>;\n actors?: Record<string, unknown>;\n delays?: Record<\n string,\n number | string | { duration: number | string | ResolvableJSON }\n >;\n schemas?: Record<string, unknown>;\n}\n\ntype EvaluatorSlot =\n | 'context'\n | 'guard'\n | 'choice'\n | 'action'\n | 'actionParams'\n | 'transition'\n | 'input'\n | 'output'\n | 'delay'\n | 'transitionContext'\n | 'unknown';\n\ntype EvaluatorKind = 'expr' | 'code';\n\ninterface EvaluatorArgs {\n source: string;\n kind: EvaluatorKind;\n slot: EvaluatorSlot;\n scope: Record<string, unknown>;\n path: string;\n}\n\ninterface MachineSources {\n actions?: Record<string, (...args: any[]) => unknown>;\n guards?: Record<string, (...args: any[]) => boolean>;\n actors?: Record<string, AnyActorLogic>;\n delays?: Record<string, number | ((...args: any[]) => number)>;\n evaluators?: Record<string, (args: EvaluatorArgs) => unknown>;\n}\n\ntype ProvidedSources = Required<MachineSources>;\n\nfunction isExpression(value: unknown): value is ExpressionJSON {\n return (\n !!value &&\n typeof value === 'object' &&\n typeof (value as any)['@expr'] === 'string'\n );\n}\n\nfunction isCode(value: unknown): value is CodeJSON {\n return (\n !!value &&\n typeof value === 'object' &&\n typeof (value as any)['@code'] === 'string'\n );\n}\n\nfunction isResolvable(value: unknown): value is ResolvableJSON {\n return isExpression(value) || isCode(value);\n}\n\nfunction isBuiltInActionType(type: string): boolean {\n return type.startsWith('@xstate.');\n}\n\nfunction isScxmlActionType(type: string): boolean {\n return type.startsWith('scxml.');\n}\n\nfunction toPath(parent: string, key: string | number): string {\n return typeof key === 'number' ? `${parent}[${key}]` : `${parent}.${key}`;\n}\n\nfunction extractSerializableDelays(\n delays: ScxmlIR['delays'] | undefined\n): Record<string, number> {\n const result: Record<string, number> = {};\n if (!delays) {\n return result;\n }\n for (const key of Object.keys(delays)) {\n const value = delays[key];\n if (typeof value === 'number') {\n result[key] = value;\n } else if (\n value &&\n typeof value === 'object' &&\n typeof value.duration === 'number'\n ) {\n result[key] = value.duration;\n }\n }\n return result;\n}\n\nfunction mergeSources(json: ScxmlIR, sources: MachineSources): ProvidedSources {\n return {\n actions: sources.actions ?? {},\n guards: sources.guards ?? {},\n actors: sources.actors ?? {},\n delays: {\n ...extractSerializableDelays(json.delays),\n ...(sources.delays ?? {})\n },\n evaluators: sources.evaluators ?? {}\n };\n}\n\ninterface ExpressionResolver {\n evaluateResolvable: (\n value: ResolvableJSON,\n slot: EvaluatorSlot,\n scope: Record<string, unknown>,\n path: string\n ) => unknown;\n resolveValue: (\n value: unknown,\n slot: EvaluatorSlot,\n scope: Record<string, unknown>,\n path: string\n ) => unknown;\n makeScope: (\n x: any,\n extra?: Record<string, unknown>\n ) => Record<string, unknown>;\n getDurationConfig: (value: unknown, path: string) => unknown;\n assertResolvable: (value: unknown, path: string) => void;\n}\n\nfunction createExpressionResolver(\n expressionLanguage: string | undefined,\n sources: ProvidedSources\n): ExpressionResolver {\n function getEvaluator(value: ResolvableJSON, path: string) {\n const lang = value['@lang'] ?? expressionLanguage;\n if (!lang) {\n throw new Error(`Missing @exprLang for expression at ${path}`);\n }\n const evaluator = sources.evaluators[lang];\n if (!evaluator) {\n throw new Error(`Missing evaluator for @lang '${lang}' at ${path}`);\n }\n return evaluator;\n }\n\n function evaluateResolvable(\n value: ResolvableJSON,\n slot: EvaluatorSlot,\n scope: Record<string, unknown>,\n path: string\n ) {\n const kind = isExpression(value) ? 'expr' : 'code';\n const source = isExpression(value) ? value['@expr'] : value['@code'];\n return getEvaluator(\n value,\n path\n )({\n source,\n kind,\n slot,\n scope,\n path\n });\n }\n\n function resolveValue(\n value: unknown,\n slot: EvaluatorSlot,\n scope: Record<string, unknown>,\n path: string\n ): unknown {\n if (isResolvable(value)) {\n return evaluateResolvable(value, slot, scope, path);\n }\n if (Array.isArray(value)) {\n return value.map((item, index) =>\n resolveValue(item, slot, scope, toPath(path, index))\n );\n }\n if (!value || typeof value !== 'object') {\n return value;\n }\n const result: Record<string, unknown> = {};\n for (const key of Object.keys(value)) {\n result[key] = resolveValue(\n (value as Record<string, unknown>)[key],\n slot,\n scope,\n toPath(path, key)\n );\n }\n return result;\n }\n\n function makeScope(x: any, extra?: Record<string, unknown>) {\n return {\n context: x.context,\n event: x.event,\n input: x.input,\n self: x.self,\n children: x.children,\n params: x.params,\n ...extra\n };\n }\n\n function getDurationConfig(value: unknown, path: string) {\n if (!isResolvable(value)) {\n return value;\n }\n return (args: any) =>\n delayToMs(\n resolveValue(value, 'delay', makeScope(args), path) as string | number\n );\n }\n\n function assertResolvable(value: unknown, path: string) {\n if (isResolvable(value)) {\n getEvaluator(value, path);\n return;\n }\n if (Array.isArray(value)) {\n value.forEach((item, index) =>\n assertResolvable(item, toPath(path, index))\n );\n return;\n }\n if (!value || typeof value !== 'object') {\n return;\n }\n for (const key of Object.keys(value)) {\n assertResolvable(\n (value as Record<string, unknown>)[key],\n toPath(path, key)\n );\n }\n }\n\n return {\n evaluateResolvable,\n resolveValue,\n makeScope,\n getDurationConfig,\n assertResolvable\n };\n}\n\nfunction toActionArray(\n actions: ActionJSON | ActionJSON[] | undefined\n): ActionJSON[] {\n return actions === undefined\n ? []\n : Array.isArray(actions)\n ? actions\n : [actions];\n}\n\nfunction validateChoiceConfig(choice: StateNodeJSON['choice'], path: string) {\n if (!Array.isArray(choice)) {\n return;\n }\n choice.forEach((branch, index) => {\n if (branch.when === undefined && index !== choice.length - 1) {\n throw new Error(\n `Choice fallback branch at ${path}[${index}] must be last.`\n );\n }\n });\n}\n\nfunction assertMachineJSON(\n json: ScxmlIR,\n resolvedSources: ProvidedSources,\n expressionResolver: ExpressionResolver\n) {\n const { assertResolvable } = expressionResolver;\n\n function assertCondition(condition: ConditionJSON | undefined, path: string) {\n if (!condition) {\n return;\n }\n if (isResolvable(condition)) {\n assertResolvable(condition, path);\n return;\n }\n assertResolvable(condition.params, `${path}.params`);\n if (json.guards?.[condition.type]) {\n assertCondition(\n json.guards[condition.type].when,\n `$.guards.${condition.type}.when`\n );\n return;\n }\n if (\n !resolvedSources.guards[condition.type] &&\n !['scxml.cond', 'xstate.stateIn', 'xstate.not'].includes(condition.type)\n ) {\n throw new Error(`Missing guard source \"${condition.type}\"`);\n }\n }\n\n function assertAction(\n action: ActionJSON,\n path: string,\n stack: string[] = []\n ) {\n if (isResolvable(action)) {\n assertResolvable(action, path);\n return;\n }\n if (!action || typeof action.type !== 'string') {\n throw new Error(`Invalid action at ${path}`);\n }\n assertResolvable((action as CustomActionJSON).params, `${path}.params`);\n if (isBuiltInActionType(action.type) || isScxmlActionType(action.type)) {\n assertResolvable(action, path);\n return;\n }\n const definition = json.actions?.[action.type];\n if (definition) {\n if (stack.includes(action.type)) {\n throw new Error(\n `Circular action reference: ${stack.concat(action.type).join(' -> ')}`\n );\n }\n const definitions = Array.isArray(definition) ? definition : [definition];\n definitions.forEach((item, index) =>\n assertAction(\n item,\n `${path}.actions.${action.type}${definitions.length > 1 ? `[${index}]` : ''}`,\n stack.concat(action.type)\n )\n );\n return;\n }\n if (!resolvedSources.actions[action.type]) {\n throw new Error(`Missing action source \"${action.type}\"`);\n }\n }\n\n function assertActions(\n actions: ActionJSON | ActionJSON[] | undefined,\n path: string\n ) {\n toActionArray(actions).forEach((action, index) =>\n assertAction(action, `${path}[${index}]`)\n );\n }\n\n function assertTransition(\n transition: TransitionConfigJSON | TransitionConfigJSON[] | undefined,\n path: string\n ) {\n const transitions = Array.isArray(transition)\n ? transition\n : transition\n ? [transition]\n : [];\n transitions.forEach((t, index) => {\n const transitionPath = Array.isArray(transition)\n ? `${path}[${index}]`\n : path;\n if (isResolvable(t)) {\n assertResolvable(t, transitionPath);\n return;\n }\n assertCondition(t.guard, `${transitionPath}.guard`);\n assertActions(t.actions, `${transitionPath}.actions`);\n assertResolvable(t.context, `${transitionPath}.context`);\n assertResolvable(t.input, `${transitionPath}.input`);\n });\n }\n\n function assertStateNode(node: StateNodeJSON, path: string) {\n if (\n (node.type === 'history' || node.history !== undefined) &&\n !(\n (typeof node.target === 'string' && node.target.trim().length > 0) ||\n (Array.isArray(node.target) &&\n node.target.length > 0 &&\n node.target.every((target) => target.trim().length > 0))\n )\n ) {\n throw new Error(\n `History state at ${path} must declare a non-empty target.`\n );\n }\n assertResolvable(node.context, `${path}.context`);\n assertResolvable(node.input, `${path}.input`);\n assertResolvable(node.output, `${path}.output`);\n assertResolvable(node.timeout, `${path}.timeout`);\n assertActions(node.entry, `${path}.entry`);\n assertActions(node.exit, `${path}.exit`);\n if (node.type === 'choice') {\n if (!node.choice) {\n throw new Error(`Choice state at ${path} must declare choice.`);\n }\n if (Array.isArray(node.choice)) {\n validateChoiceConfig(node.choice, `${path}.choice`);\n node.choice.forEach((branch, index) => {\n assertCondition(branch.when, `${path}.choice[${index}].when`);\n assertResolvable(branch.context, `${path}.choice[${index}].context`);\n assertResolvable(branch.input, `${path}.choice[${index}].input`);\n });\n } else {\n assertResolvable(node.choice, `${path}.choice`);\n }\n }\n if (isResolvable(node.route)) {\n assertResolvable(node.route, `${path}.route`);\n }\n if (node.invoke) {\n const invokes = Array.isArray(node.invoke) ? node.invoke : [node.invoke];\n invokes.forEach((invoke, index) => {\n const invokePath = `${path}.invoke${Array.isArray(node.invoke) ? `[${index}]` : ''}`;\n const extInv = invoke as InvokeJSON & {\n _nestedScxmlIR?: ScxmlIR;\n };\n if (!extInv._nestedScxmlIR && !resolvedSources.actors[invoke.src]) {\n throw new Error(`Missing actor source \"${invoke.src}\"`);\n }\n assertResolvable(invoke.input, `${invokePath}.input`);\n assertResolvable(invoke.timeout, `${invokePath}.timeout`);\n assertTransition(invoke.onDone, `${invokePath}.onDone`);\n assertTransition(invoke.onError, `${invokePath}.onError`);\n assertTransition(invoke.onSnapshot, `${invokePath}.onSnapshot`);\n assertTransition(invoke.onTimeout, `${invokePath}.onTimeout`);\n });\n }\n if (node.on) {\n for (const descriptor of Object.keys(node.on)) {\n assertTransition(node.on[descriptor], `${path}.on.${descriptor}`);\n }\n }\n if (node.after) {\n for (const delay of Object.keys(node.after)) {\n if (\n Number.isNaN(Number(delay)) &&\n parseDelayToMilliseconds(delay) === undefined &&\n !json.delays?.[delay] &&\n !resolvedSources.delays[delay]\n ) {\n throw new Error(`Missing delay source \"${delay}\"`);\n }\n assertTransition(node.after[delay], `${path}.after.${delay}`);\n }\n }\n assertTransition(node.always, `${path}.always`);\n assertTransition(node.onError, `${path}.onError`);\n assertTransition(node.onTimeout, `${path}.onTimeout`);\n if (node.states) {\n for (const key of Object.keys(node.states)) {\n assertStateNode(node.states[key], `${path}.states.${key}`);\n }\n }\n }\n\n if (json.actions) {\n for (const key of Object.keys(json.actions)) {\n const actions = Array.isArray(json.actions[key])\n ? json.actions[key]\n : [json.actions[key]];\n actions.forEach((action, index) =>\n assertAction(\n action,\n `$.actions.${key}${actions.length > 1 ? `[${index}]` : ''}`,\n [key]\n )\n );\n }\n }\n if (json.guards) {\n for (const key of Object.keys(json.guards)) {\n assertCondition(json.guards[key].when, `$.guards.${key}.when`);\n }\n }\n if (json.delays) {\n for (const key of Object.keys(json.delays)) {\n const delay = json.delays[key];\n assertResolvable(\n delay && typeof delay === 'object' && 'duration' in delay\n ? delay.duration\n : delay,\n `$.delays.${key}`\n );\n }\n }\n assertStateNode(json, '$');\n}\n\nconst SCXML_SYSTEM_VARIABLES = new Set([\n '_sessionid',\n '_name',\n '_ioprocessors',\n '_event',\n '_xstateScxmlInputKeys'\n]);\nconst scxmlScriptEnvironments = new WeakMap<\n AnyActorRef,\n { declarations: string[] }\n>();\nconst scxmlMachineNames = new WeakMap<AnyActorRef, string>();\nconst scxmlIoProcessors = new WeakMap<AnyActorRef, object>();\nconst scxmlEvents = new WeakMap<object, object>();\nconst scxmlEnteringStates = new WeakMap<AnyActorRef, string[]>();\n\nfunction getScxmlIoProcessors(self: AnyActorRef, sessionId: string): object {\n let processors = scxmlIoProcessors.get(self);\n if (!processors) {\n const processor = { location: `#_scxml_${sessionId}` };\n processors = {\n scxml: processor,\n 'http://www.w3.org/TR/scxml/#SCXMLEventProcessor': processor\n };\n scxmlIoProcessors.set(self, processors);\n }\n return processors;\n}\n\nfunction getFunctionDeclarations(code: string): string[] {\n const declarations: string[] = [];\n const pattern = /\\bfunction\\s+[$_a-zA-Z][$_a-zA-Z0-9]*\\s*\\([^)]*\\)\\s*\\{/g;\n for (const match of code.matchAll(pattern)) {\n let depth = 1;\n let index = match.index! + match[0].length;\n while (index < code.length && depth) {\n if (code[index] === '{') depth++;\n if (code[index] === '}') depth--;\n index++;\n }\n declarations.push(code.slice(match.index, index));\n }\n return declarations;\n}\n\n/** Evaluates an SCXML expression with context variables available via `with`. */\nfunction evaluateExpr(\n context: MachineContext,\n expr: string,\n event: AnyEventObject | null,\n self?: AnyActorRef\n): unknown {\n const normalizedExpr = expr.replace(/;+\\s*$/, '');\n const sessionId = (self as any)?.sessionId ?? 'session_scxml';\n const machineName = self\n ? (scxmlMachineNames.get(self) ?? '(machine)')\n : '(machine)';\n const dataContext = Object.fromEntries(\n Object.entries(context).filter(([key]) => !SCXML_SYSTEM_VARIABLES.has(key))\n );\n const fnBody = `\n${self ? (scxmlScriptEnvironments.get(self)?.declarations.join('\\n') ?? '') : ''}\nwith (context) {\n return (${normalizedExpr});\n}\n `.trim();\n // eslint-disable-next-line @typescript-eslint/no-implied-eval\n const fn = new Function(\n 'context',\n '_event',\n '_sessionid',\n '_name',\n '_ioprocessors',\n 'In',\n fnBody\n );\n const In = (stateId: string) => {\n if (!self) return false;\n const sanitized = stateId.replace(/\\./g, '$');\n if (\n scxmlEnteringStates\n .get(self)\n ?.some((id) => id === sanitized || id.endsWith('.' + sanitized))\n ) {\n return true;\n }\n try {\n const snap = (self as any).getSnapshot?.();\n if (snap?.nodes) {\n return snap.nodes.some(\n (node: any) =>\n node.id === sanitized || node.id.endsWith('.' + sanitized)\n );\n }\n } catch {\n // ignore\n }\n return false;\n };\n const SCXML_ORIGIN = `#_scxml_${sessionId}`;\n const SCXML_ORIGIN_TYPE = 'http://www.w3.org/TR/scxml/#SCXMLEventProcessor';\n const isExternal = event && (event as any)._scxmlExternal;\n const isInitEvent = event && event.type === '@xstate.init';\n // Per SCXML spec, _event has these fields. Fields that don't apply to a\n // particular event are present with value `undefined` (so `'name' in _event`\n // is true but `typeof _event.name === 'undefined'` for unset fields).\n // For xstate.done.* events, _event.data is the `output` payload (matches\n // SCXML's done event semantics where data is the donedata).\n const isDoneEvent =\n event &&\n typeof event.type === 'string' &&\n event.type.startsWith('xstate.done.');\n const explicitType =\n event && ((event as any)._scxmlEventType as string | undefined);\n let scxmlEvent: object | undefined;\n if (event && !isInitEvent) {\n scxmlEvent = scxmlEvents.get(event);\n if (!scxmlEvent) {\n scxmlEvent = {\n name:\n ((event as any)._scxmlEventName as string | undefined) ??\n toScxmlEventName(event.type),\n type: explicitType || (isExternal ? 'external' : 'internal'),\n sendid: (event as any)._scxmlSendId as string | undefined,\n origin: isExternal ? SCXML_ORIGIN : undefined,\n origintype: isExternal ? SCXML_ORIGIN_TYPE : undefined,\n invokeid:\n ((event as any)._scxmlInvokeId as string | undefined) ??\n ((event as any).actorId as string | undefined),\n data: isDoneEvent\n ? (event as any).output\n : (event as any)._scxmlEventData !== undefined\n ? (event as any)._scxmlEventData\n : event\n };\n scxmlEvents.set(event, scxmlEvent);\n }\n }\n const result = fn(\n dataContext,\n scxmlEvent,\n sessionId,\n machineName,\n self\n ? getScxmlIoProcessors(self, sessionId)\n : { scxml: { location: `#_scxml_${sessionId}` } },\n In\n );\n\n return result;\n}\n\n/** Executes an SCXML script block and returns updated context values. */\nfunction executeScript(\n context: MachineContext,\n code: string,\n self: AnyActorRef,\n global: boolean\n): Record<string, unknown> {\n // Create a proxy to track which properties are modified\n const updates: Record<string, unknown> = {};\n const contextKeys = Object.keys(context);\n const mutableContextKeys = contextKeys.filter(\n (key) => !SCXML_SYSTEM_VARIABLES.has(key)\n );\n\n // Build variable declarations and reassignment capture\n const varDeclarations = mutableContextKeys\n .map((k) => `var ${k} = context.${k};`)\n .join('\\n');\n const captureUpdates = mutableContextKeys\n .map((k) => `updates.${k} = ${k};`)\n .join('\\n');\n const codeWithoutComments = code.replace(/\\/\\/.*$/gm, '');\n const declarations = getFunctionDeclarations(code);\n const codeWithoutFunctions = declarations.reduce(\n (source, declaration) => source.replace(declaration, ''),\n codeWithoutComments\n );\n const declaredVariables = global\n ? [\n ...codeWithoutFunctions.matchAll(/\\bvar\\s+([$_a-zA-Z][$_a-zA-Z0-9]*)/g)\n ].map((match) => match[1])\n : [];\n const captureVariables = declaredVariables\n .filter(\n (name) => !contextKeys.includes(name) && !SCXML_SYSTEM_VARIABLES.has(name)\n )\n .map((name) => `updates.${name} = ${name};`)\n .join('\\n');\n const environment = scxmlScriptEnvironments.get(self) ?? {\n declarations: []\n };\n scxmlScriptEnvironments.set(self, environment);\n for (const declaration of declarations) {\n if (!environment.declarations.includes(declaration)) {\n environment.declarations.push(declaration);\n }\n }\n\n const fnBody = `\n${varDeclarations}\n${environment.declarations.join('\\n')}\n${code}\n${captureUpdates}\n${captureVariables}\nreturn updates;\n `;\n const sessionId = (self as any).sessionId;\n const machineName = scxmlMachineNames.get(self) ?? '(machine)';\n // eslint-disable-next-line @typescript-eslint/no-implied-eval\n const fn = new Function(\n 'context',\n 'updates',\n '_sessionid',\n '_name',\n '_ioprocessors',\n fnBody\n );\n return fn(\n context,\n updates,\n sessionId,\n machineName,\n getScxmlIoProcessors(self, sessionId)\n );\n}\n\nfunction createScxmlDomElement(element: ScxmlXmlJSON): any {\n const children = (element.children ?? []).map(createScxmlDomElement);\n return {\n tagName: element.name,\n getAttribute: (name: string) => element.attributes?.[name] ?? null,\n getElementsByTagName: (name: string): any[] => [\n ...(element.name === name ? [createScxmlDomElement(element)] : []),\n ...children.flatMap((child: any) => child.getElementsByTagName(name))\n ]\n };\n}\n\nexport function createMachineFromSCXMLConfig(\n json: ScxmlIR,\n sources: MachineSources = {}\n): AnyStateMachine {\n const resolvedSources = mergeSources(json, sources);\n const expressionResolver = createExpressionResolver(\n json['@exprLang'],\n resolvedSources\n );\n const { evaluateResolvable, resolveValue, makeScope, getDurationConfig } =\n expressionResolver;\n const sendCounters = new WeakMap<AnyActorRef, number>();\n\n type ResolvedCondition = ((args: any) => boolean) | undefined;\n\n function resolveCondition(\n condition: ConditionJSON | undefined,\n slot: 'guard' | 'choice',\n path: string\n ): ResolvedCondition {\n if (!condition) {\n return undefined;\n }\n if (isResolvable(condition)) {\n return (args: any) =>\n !!evaluateResolvable(condition, slot, makeScope(args), path);\n }\n return (args: any) => {\n const params = resolveValue(\n condition.params,\n slot,\n makeScope(args),\n `${path}.params`\n );\n const declarativeGuard = json.guards?.[condition.type];\n if (declarativeGuard) {\n const guard = resolveCondition(\n declarativeGuard.when,\n 'guard',\n `$.guards.${condition.type}.when`\n );\n return !!guard?.({ ...args, params });\n }\n const guardImpl = args.guards?.[condition.type];\n if (!guardImpl) {\n throw new Error(\n getMissingGuardMessage(condition.type, args.guards ?? {})\n );\n }\n return guardImpl(args, params);\n };\n }\n\n function makeChoiceConfig(choice: StateNodeJSON['choice'], path: string) {\n if (!choice) {\n return undefined;\n }\n if (isResolvable(choice)) {\n return (args: any) =>\n evaluateResolvable(choice, 'choice', makeScope(args), path);\n }\n validateChoiceConfig(choice, path);\n return (args: any) => {\n for (let index = 0; index < choice.length; index++) {\n const branch = choice[index];\n const guard = resolveCondition(\n branch.when,\n 'choice',\n `${path}[${index}].when`\n );\n if (!guard || guard(args)) {\n return {\n target: branch.target,\n context: branch.context\n ? resolveValue(\n branch.context,\n 'transitionContext',\n makeScope(args),\n `${path}[${index}].context`\n )\n : undefined,\n input:\n branch.input !== undefined\n ? resolveValue(\n branch.input,\n 'input',\n makeScope(args),\n `${path}[${index}].input`\n )\n : undefined,\n description: branch.description,\n reenter: branch.reenter,\n meta: branch.meta\n };\n }\n }\n throw new Error(`Choice state at ${path} did not match any branch.`);\n };\n }\n\n // Pending transition actions: set by .to functions, consumed by entry functions.\n // This bridges SCXML's exit→transition→entry action ordering with XState's\n // .to function receiving pre-exit context.\n // Map keyed by target state ID so parallel transitions don't overwrite each other.\n const pendingTransitionActionsMap: Record<string, ActionJSON[]> = {};\n\n // Ordered queue of ALL transition actions (targeted + targetless) for parallel\n // context sharing. In SCXML, all transition actions execute sequentially in\n // document order with a shared evolving data model.\n const allTransitionActions: ActionJSON[][] = [];\n // Pre-transition context saved when a targetless .to executes. Used by entry\n // functions to re-execute all transition actions from scratch when parallel\n // targetless transitions coexist with targeted transitions.\n let contextBeforeTargetless: MachineContext | null = null;\n let targetlessEvent: AnyEventObject | null = null;\n // Platform errors collected during transition selection (e.g., failing\n // <transition cond>). Drained by the next state's entry into the internal\n // event queue so they're processed before any external events.\n const pendingPlatformErrors: Array<Record<string, unknown>> = [];\n const scxmlDonedataValues = new WeakMap<AnyActorRef, Map<string, unknown>>();\n\n function evaluateDonedataValue(\n donedata: ScxmlDonedataJSON,\n context: MachineContext,\n event: AnyEventObject,\n self: AnyActorRef\n ): unknown {\n if (donedata.params?.length) {\n const out: Record<string, unknown> = {};\n for (const param of donedata.params) {\n out[param.name] = evaluateExpr(context, param.expr, event, self);\n }\n return out;\n }\n if (donedata.contentExpr !== undefined) {\n return evaluateExpr(context, donedata.contentExpr, event, self);\n }\n if (donedata.contentText !== undefined) {\n try {\n return evaluateExpr(context, donedata.contentText, event, self);\n } catch {\n return donedata.contentText;\n }\n }\n return undefined;\n }\n\n function getMissingGuardMessage(type: string, guards: Record<string, any>) {\n return `Guard '${type}' is not implemented in machine '${json.id ?? '(machine)'}'. Available guards: ${\n Object.keys(guards)\n .map((key) => `'${key}'`)\n .join(', ') || '(none)'\n }.`;\n }\n\n function resolveRouteConfig(route: StateNodeJSON['route'], path: string) {\n if (!route || typeof route === 'function') {\n return route;\n }\n if (isResolvable(route)) {\n return (args: any) =>\n evaluateResolvable(route, 'transition', makeScope(args), path);\n }\n const { guard, ...routeConfig } = route;\n if (!guard) {\n return routeConfig;\n }\n const resolvedGuard = resolveCondition({ type: guard }, 'guard', path);\n return (args: any) => (resolvedGuard!(args) ? routeConfig : undefined);\n }\n\n function iterNode(\n node: StateNodeJSON,\n nodeKey?: string,\n ancestorIds: string[] = []\n ) {\n const originalEntryActions: ActionJSON[] = [\n ...(node._scxmlData?.length\n ? [{ type: 'scxml.datamodel' as const, data: node._scxmlData }]\n : []),\n ...toActionArray(node.entry)\n ];\n const stateId = node.id || nodeKey;\n\n // Wrap entry to first execute any pending transition actions, then normal entry.\n // This ensures SCXML execution order: exit → transition_actions → entry_actions\n // because pending transition actions are set by .to (before exit) but executed\n // in entry (after exit), thus seeing post-exit context.\n const entryFn: Action<any, any, any, any, any, any, any> | undefined = (\n x,\n enq\n ) => {\n scxmlMachineNames.set(x.self, json.id ?? '(machine)');\n if (stateId) {\n scxmlEnteringStates.set(x.self, [...ancestorIds, stateId]);\n }\n // Drain any platform errors queued during transition selection (e.g.,\n // failing <transition cond=\"...\"> evaluations). These must be raised\n // internally so they're processed before subsequent external events.\n while (pendingPlatformErrors.length) {\n const err = pendingPlatformErrors.shift()!;\n enq.raise({\n type: 'xstate.error.execution',\n error: err,\n _scxmlEventType: 'platform',\n _scxmlEventName: 'error.execution',\n _scxmlEventData: err\n } as AnyEventObject);\n }\n\n let context: MachineContext | undefined;\n\n // If targetless transitions were interleaved with targeted transitions\n // (parallel state), re-execute ALL transition actions from the original\n // pre-transition context. This overrides any .to-produced context with\n // the correct SCXML document-order sequential execution.\n // Only trigger when BOTH targeted (pending in map) and targetless fired\n // in the same microstep — prevents stale data from previous events.\n if (\n contextBeforeTargetless &&\n targetlessEvent === x.event &&\n allTransitionActions.length > 0 &&\n Object.keys(pendingTransitionActionsMap).length > 0\n ) {\n let ctx = contextBeforeTargetless;\n for (const actions of allTransitionActions) {\n const mergedX = { ...x, context: ctx };\n const result = executeActions(actions, mergedX, enq);\n if (result.context) {\n ctx = result.context;\n }\n }\n allTransitionActions.length = 0;\n contextBeforeTargetless = null;\n targetlessEvent = null;\n // Clear per-target map since we re-processed everything\n for (const key of Object.keys(pendingTransitionActionsMap)) {\n delete pendingTransitionActionsMap[key];\n }\n context = ctx;\n } else {\n // Normal path: consume pending transition actions for THIS state.\n // In parallel states, each target gets its own pending actions.\n const transActions = stateId\n ? pendingTransitionActionsMap[stateId]\n : undefined;\n if (transActions) {\n delete pendingTransitionActionsMap[stateId!];\n const result = executeActions(transActions, x, enq);\n if (result.context) {\n context = result.context;\n }\n }\n // Clear stale targetless data from previous microsteps\n contextBeforeTargetless = null;\n targetlessEvent = null;\n allTransitionActions.length = 0;\n }\n\n // Execute normal entry actions\n if (originalEntryActions.length) {\n const mergedX = context ? { ...x, context } : x;\n const result = executeActions(originalEntryActions, mergedX, enq);\n if (result.context) {\n context = result.context;\n }\n }\n\n if (node._scxmlDonedata && stateId) {\n let values = scxmlDonedataValues.get(x.self);\n if (!values) {\n values = new Map();\n scxmlDonedataValues.set(x.self, values);\n }\n try {\n values.set(\n stateId,\n evaluateDonedataValue(\n node._scxmlDonedata,\n context ?? x.context,\n x.event,\n x.self\n )\n );\n } catch (err) {\n values.set(stateId, undefined);\n raiseErrorExecution(\n { enq, self: x.self, errored: false },\n 'donedata',\n err\n );\n }\n }\n\n scxmlEnteringStates.delete(x.self);\n return { context };\n };\n\n const nodeConfig: any = {\n id: node.id,\n initial: node._scxmlInitial\n ? {\n target: node._scxmlInitial.targets,\n to: node._scxmlInitial.actions\n ? (x: any, enq: any) => ({\n ...executeActions(node._scxmlInitial!.actions!, x, enq),\n target: node._scxmlInitial!.targets\n })\n : undefined\n }\n : node.initial,\n type: node.type,\n history: node.history,\n target: node.target,\n _historyDefaultTransition: node._scxmlHistoryActions\n ? (x: any, enq: any) => ({\n ...executeActions(node._scxmlHistoryActions!, x, enq),\n target: node.target\n })\n : undefined,\n description: node.description,\n tags: node.tags,\n input: node.input,\n timeout: getDurationConfig(node.timeout, `$.states.${nodeKey}.timeout`),\n states: node.states\n ? Object.entries(node.states).reduce(\n (acc, [key, value]) => {\n acc[key] = iterNode(\n value,\n key,\n stateId ? [...ancestorIds, stateId] : ancestorIds\n );\n return acc;\n },\n {} as Record<\n string,\n Next_StateNodeConfig<\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any\n >\n >\n )\n : undefined,\n on: node.on\n ? Object.entries(node.on).reduce(\n (acc, [key, value]) => {\n acc[key] = getTransitionConfig(value);\n return acc;\n },\n {} as Record<string, any>\n )\n : undefined,\n always: node.always ? getTransitionConfig(node.always) : undefined,\n onError: node.onError ? getTransitionConfig(node.onError) : undefined,\n choice: makeChoiceConfig(node.choice, `$.states.${nodeKey}.choice`),\n route: resolveRouteConfig(node.route, `$.states.${nodeKey}.route`),\n after: node.after\n ? Object.entries(node.after).reduce(\n (acc, [key, value]) => {\n acc[key] = getTransitionConfig(value);\n return acc;\n },\n {} as Record<string, any>\n )\n : undefined,\n onTimeout: node.onTimeout\n ? getTransitionConfig(node.onTimeout)\n : undefined,\n entry: node.type === 'choice' ? undefined : (entryFn as any),\n exit: node.exit\n ? (iterActions(toActionArray(node.exit)) as any)\n : undefined,\n invoke: node.invoke ? iterInvokeConfigs(node.invoke) : undefined,\n meta: node.meta,\n output: node._scxmlDonedata\n ? makeDonedataOutput(stateId!)\n : isResolvable(node.output)\n ? ({ context, event, self }: any) =>\n evaluateResolvable(\n node.output as ResolvableJSON,\n 'output',\n { context, event, self },\n `$.states.${nodeKey}.output`\n )\n : node.output\n };\n\n return nodeConfig;\n }\n\n function makeDonedataOutput(stateId: string) {\n return ({ self }: any) => scxmlDonedataValues.get(self)?.get(stateId);\n }\n\n function iterInvokeConfigs(invokes: InvokeJSON | InvokeJSON[]): any {\n const invokeArray = Array.isArray(invokes) ? invokes : [invokes];\n return invokeArray.map((inv) => {\n const extInv = inv as InvokeJSON & { _nestedScxmlIR?: ScxmlIR };\n // Create child machine from nested SCXML JSON\n let src: any;\n if (extInv._nestedScxmlIR) {\n src = createMachineFromSCXMLConfig(\n extInv._nestedScxmlIR,\n resolvedSources\n );\n } else {\n src = resolvedSources.actors[inv.src] ?? inv.src;\n }\n return {\n src,\n id: inv.id,\n registryKey: inv.registryKey,\n input: inv._scxmlInput\n ? ({ context, event, self }: any) => {\n const input: Record<string, unknown> = {};\n for (const name of inv._scxmlInput!.namelist ?? []) {\n if (!(name in context)) {\n throw new ReferenceError(`${name} is not defined`);\n }\n input[name] = context[name];\n }\n for (const param of inv._scxmlInput!.params ?? []) {\n input[param.name] = param.expr\n ? evaluateExpr(context, param.expr, event, self)\n : param.location\n ? evaluateExpr(context, param.location, event, self)\n : undefined;\n }\n return input;\n }\n : inv.input !== undefined\n ? (args: any) =>\n resolveValue(\n inv.input,\n 'input',\n makeScope(args),\n '$.invoke.input'\n )\n : undefined,\n onDone: inv.onDone ? getTransitionConfig(inv.onDone) : undefined,\n onError: inv.onError ? getTransitionConfig(inv.onError) : undefined,\n onSnapshot: inv.onSnapshot\n ? getTransitionConfig(inv.onSnapshot)\n : undefined,\n timeout: getDurationConfig(inv.timeout, '$.invoke.timeout'),\n onTimeout: inv.onTimeout\n ? getTransitionConfig(inv.onTimeout)\n : undefined\n };\n });\n }\n\n /**\n * Raise an SCXML error.execution platform event onto the internal queue. Per\n * spec, error.execution is type='platform' and _event.data contains error\n * info. The surrounding block of executable content stops.\n */\n function raiseErrorExecution(\n state: ExecState,\n tagname: string,\n err: unknown,\n sendId?: string\n ) {\n const message =\n err instanceof Error\n ? err.message\n : typeof err === 'string'\n ? err\n : 'unknown error';\n const errorEvent = {\n type: 'xstate.error.execution',\n error: {\n tagname,\n message,\n line: 0,\n column: 0,\n reason: message\n },\n _scxmlEventType: 'platform',\n _scxmlEventName: 'error.execution',\n ...(sendId ? { _scxmlSendId: sendId } : {}),\n _scxmlEventData: {\n tagname,\n message,\n line: 0,\n column: 0,\n reason: message\n }\n } as AnyEventObject;\n state.enq.raise(errorEvent);\n state.errored = true;\n }\n\n interface ExecState {\n enq: any;\n self: AnyActorRef;\n errored: boolean;\n }\n\n function executeActionDefinition(\n action: CustomActionJSON,\n x: any,\n enq: any,\n params: unknown,\n parentState: ExecState,\n stack: string[]\n ): { context: MachineContext | undefined; errored: boolean } {\n const definition = json.actions?.[action.type];\n if (!definition) {\n enq(x.actions[action.type], params);\n return { context: undefined, errored: parentState.errored };\n }\n if (stack.includes(action.type)) {\n raiseErrorExecution(\n parentState,\n 'action',\n new Error(\n `Circular action reference: ${stack.concat(action.type).join(' -> ')}`\n )\n );\n return { context: undefined, errored: true };\n }\n const definitions = Array.isArray(definition) ? definition : [definition];\n return executeActions(\n definitions,\n { ...x, params },\n enq,\n parentState,\n stack.concat(action.type)\n );\n }\n\n /** Execute an array of SCXML action JSON descriptors with context and enqueue. */\n function executeActions(\n actions: ActionJSON[],\n x: any,\n enq: any,\n parentState?: ExecState,\n stack: string[] = []\n ): { context: MachineContext | undefined; errored: boolean } {\n const state: ExecState = parentState ?? {\n enq,\n self: x.self,\n errored: false\n };\n let context: MachineContext | undefined;\n for (const action of actions) {\n if (state.errored) break;\n if (isResolvable(action)) {\n const result = evaluateResolvable(\n action,\n 'action',\n makeScope(x, { params: x.params, enq }),\n '$.actions'\n );\n if (\n result &&\n typeof result === 'object' &&\n 'context' in result &&\n (result as { context?: MachineContext }).context\n ) {\n context ??= {};\n Object.assign(\n context,\n (result as { context: MachineContext }).context\n );\n }\n } else if (isBuiltInActionJSON(action)) {\n switch (action.type) {\n case '@xstate.raise': {\n // Tag as external if it has a delay (from <send>, not <raise>).\n // Attach _scxmlSendId so _event.sendid can be read in expressions.\n const isExternal = action.delay !== undefined;\n const resolvedEvent = resolveValue(\n action.event,\n 'actionParams',\n makeScope(x, { params: x.params }),\n '$.actions.event'\n ) as EventObject;\n const event =\n isExternal || action.id !== undefined\n ? {\n ...resolvedEvent,\n ...(isExternal ? { _scxmlExternal: true } : {}),\n ...(action.id !== undefined\n ? { _scxmlSendId: action.id }\n : {})\n }\n : resolvedEvent;\n enq.raise(event, {\n id: action.id,\n delay: action.delay\n });\n break;\n }\n case '@xstate.cancel':\n enq.cancel(action.id);\n break;\n case '@xstate.log':\n enq.log(...action.args);\n break;\n case '@xstate.emit':\n enq.emit(\n resolveValue(\n action.event,\n 'actionParams',\n makeScope(x, { params: x.params }),\n '$.actions.event'\n )\n );\n break;\n case '@xstate.assign':\n context ??= {};\n Object.assign(\n context,\n resolveValue(\n action.context,\n 'transitionContext',\n makeScope(x, { params: x.params }),\n '$.actions.context'\n )\n );\n break;\n default:\n throw new Error(`Unknown built-in action: ${(action as any).type}`);\n }\n } else if (action.type === 'scxml.finalize') {\n const finalize = action as ScxmlFinalizeJSON;\n const invokeId =\n (x.event as any)._scxmlInvokeId ?? (x.event as any).actorId;\n if (invokeId === finalize.invokeId) {\n const result = executeActions(\n finalize.actions,\n { ...x, context: { ...x.context, ...context } },\n enq,\n state\n );\n if (result.context) {\n context = result.context;\n }\n }\n } else if (action.type === 'scxml.forward') {\n const child = x.children?.[(action as ScxmlForwardJSON).invokeId];\n if (child) {\n enq.sendTo(child, {\n ...x.event,\n _scxmlExternal: true\n });\n }\n } else if (action.type === 'scxml.log') {\n const scxmlAction = action as ScxmlLogJSON;\n try {\n const value = scxmlAction.expr\n ? evaluateExpr(\n { ...x.context, ...context },\n scxmlAction.expr,\n x.event,\n x.self\n )\n : undefined;\n enq.log(\n ...(scxmlAction.label ? [scxmlAction.label, value] : [value])\n );\n } catch (err) {\n raiseErrorExecution(state, 'log', err);\n }\n } else if (action.type === 'scxml.assign') {\n const scxmlAction = action as ScxmlAssignJSON;\n const mergedContext = { ...x.context, ...context };\n let value: unknown;\n try {\n value = evaluateExpr(\n mergedContext,\n scxmlAction.expr,\n x.event,\n x.self\n );\n } catch (err) {\n raiseErrorExecution(state, 'assign', err);\n continue;\n }\n if (SCXML_SYSTEM_VARIABLES.has(scxmlAction.location.split('.')[0])) {\n raiseErrorExecution(\n state,\n 'assign',\n new Error(\n `Cannot assign to SCXML system variable: ${scxmlAction.location}`\n )\n );\n continue;\n }\n if (scxmlAction.location.includes('.')) {\n const path = scxmlAction.location.split('.');\n const root = path.shift()!;\n let target = mergedContext[root];\n if (!target || typeof target !== 'object') {\n raiseErrorExecution(\n state,\n 'assign',\n new Error(`Invalid assign location: ${scxmlAction.location}`)\n );\n continue;\n }\n const clonedRoot = Array.isArray(target)\n ? [...target]\n : { ...target };\n target = clonedRoot;\n for (const segment of path.slice(0, -1)) {\n const child = (target as Record<string, unknown>)[segment];\n if (!child || typeof child !== 'object') {\n raiseErrorExecution(\n state,\n 'assign',\n new Error(`Invalid assign location: ${scxmlAction.location}`)\n );\n break;\n }\n const clonedChild = Array.isArray(child)\n ? [...child]\n : { ...child };\n (target as Record<string, unknown>)[segment] = clonedChild;\n target = clonedChild;\n }\n if (state.errored) continue;\n (target as Record<string, unknown>)[path.at(-1)!] = value;\n context ??= {};\n context[root] = clonedRoot;\n continue;\n }\n context ??= {};\n context[scxmlAction.location] = value;\n } else if (action.type === 'scxml.datamodel') {\n const scxmlAction = action as ScxmlDatamodelJSON;\n context ??= {};\n for (const data of scxmlAction.data) {\n if (\n Array.isArray(x.context._xstateScxmlInputKeys) &&\n x.context._xstateScxmlInputKeys.includes(data.id)\n ) {\n continue;\n }\n if (data.src) {\n raiseErrorExecution(\n state,\n 'data',\n new Error(`Unresolved data resource: ${data.src}`)\n );\n break;\n }\n if (data.expr !== undefined) {\n try {\n context[data.id] = evaluateExpr(\n { ...x.context, ...context },\n data.expr,\n x.event,\n x.self\n );\n } catch (err) {\n raiseErrorExecution(state, 'data', err);\n break;\n }\n } else if (data.content !== undefined) {\n try {\n context[data.id] = evaluateExpr(\n { ...x.context, ...context },\n data.content,\n x.event,\n x.self\n );\n } catch {\n context[data.id] = data.content.replace(/\\s+/g, ' ').trim();\n }\n } else if (data.xml) {\n context[data.id] = createScxmlDomElement(data.xml);\n } else {\n if (x.context[data.id] === undefined) {\n context[data.id] = undefined;\n }\n }\n }\n } else if (action.type === 'scxml.raise') {\n const scxmlAction = action as ScxmlRaiseJSON;\n const mergedContext = { ...x.context, ...context };\n\n let eventType: string;\n let eventData: Record<string, unknown>;\n let target: string | undefined;\n let delay: number | undefined;\n try {\n if (\n scxmlAction.processorType &&\n ![\n 'scxml',\n 'http://www.w3.org/TR/scxml/#SCXMLEventProcessor'\n ].includes(scxmlAction.processorType)\n ) {\n throw new Error(\n `Unsupported send type: ${scxmlAction.processorType}`\n );\n }\n eventType = scxmlAction.eventexpr\n ? (evaluateExpr(\n mergedContext,\n scxmlAction.eventexpr,\n x.event,\n x.self\n ) as string)\n : scxmlAction.event || 'unknown';\n eventType = normalizeScxmlEventType(eventType);\n\n eventData = {\n type: eventType,\n _scxmlEventName: toScxmlEventName(eventType)\n };\n const payload: Record<string, unknown> = {};\n if (scxmlAction.namelist) {\n for (const name of scxmlAction.namelist) {\n payload[name] = evaluateExpr(\n mergedContext,\n name,\n x.event,\n x.self\n );\n }\n }\n if (scxmlAction.params) {\n for (const param of scxmlAction.params) {\n payload[param.name] = evaluateExpr(\n mergedContext,\n param.expr ?? param.location!,\n x.event,\n x.self\n );\n }\n }\n if (scxmlAction.content) {\n const content = scxmlAction.content;\n let contentValue: unknown;\n if (content.expr !== undefined) {\n contentValue = evaluateExpr(\n mergedContext,\n content.expr,\n x.event,\n x.self\n );\n } else if (content.xml) {\n contentValue = createScxmlDomElement(content.xml);\n } else {\n const text = content.text?.replace(/\\s+/g, ' ').trim() ?? '';\n try {\n contentValue = evaluateExpr(\n mergedContext,\n text,\n x.event,\n x.self\n );\n } catch {\n contentValue = text;\n }\n }\n eventData._scxmlEventData = contentValue;\n } else if (Object.keys(payload).length) {\n Object.assign(eventData, payload);\n eventData._scxmlEventData = payload;\n }\n\n if (scxmlAction.idlocation) {\n const nextId = (sendCounters.get(x.self) ?? 0) + 1;\n sendCounters.set(x.self, nextId);\n const generatedId = `${x.self.sessionId}.send.${nextId}`;\n context ??= {};\n context[scxmlAction.idlocation] = generatedId;\n eventData._scxmlSendId = generatedId;\n }\n\n target = scxmlAction.targetexpr\n ? (evaluateExpr(\n mergedContext,\n scxmlAction.targetexpr,\n x.event,\n x.self\n ) as string)\n : scxmlAction.target;\n\n const isInternalTarget = target === '#_internal';\n delay = scxmlAction.delayexpr\n ? delayToMs(\n evaluateExpr(\n mergedContext,\n scxmlAction.delayexpr,\n x.event,\n x.self\n ) as string | number\n )\n : isInternalTarget\n ? undefined\n : scxmlAction.delay;\n } catch (err) {\n raiseErrorExecution(state, 'send', err);\n continue;\n }\n\n const isInternalTarget = target === '#_internal';\n const isParentTarget = target === '#_parent';\n if (!isInternalTarget) {\n (eventData as any)._scxmlExternal = true;\n }\n if (isParentTarget) {\n (eventData as any)._scxmlInvokeId = x.self.id;\n }\n\n // Validate target. SCXML targets must be '#_internal', '#_parent',\n // or '#_<id>'. A bare string without the '#_' prefix is invalid and\n // raises error.execution.\n if (\n typeof target === 'string' &&\n target.length > 0 &&\n !target.startsWith('#_')\n ) {\n raiseErrorExecution(\n state,\n 'send',\n new Error(`Invalid send target: ${target}`),\n eventData._scxmlSendId as string | undefined\n );\n continue;\n }\n // Attach send id so _event.sendid can be read in expressions.\n if (\n scxmlAction.id !== undefined &&\n eventData._scxmlSendId === undefined\n ) {\n (eventData as any)._scxmlSendId = scxmlAction.id;\n }\n // Resolve target at runtime: parent, child, or self\n if (isParentTarget && x.parent) {\n // Send to parent via sendTo; pass delay if present\n enq.sendTo(\n x.parent,\n eventData as AnyEventObject,\n delay !== undefined ? { delay } : undefined\n );\n } else if (\n typeof target === 'string' &&\n target.startsWith('#_') &&\n !isParentTarget &&\n !isInternalTarget\n ) {\n // #_<invokeId> → try to send to child actor, fall back to self-raise\n const childId = target.slice(2); // strip '#_'\n const childRef = x.children?.[childId];\n if (childRef) {\n enq.sendTo(childRef, eventData as AnyEventObject);\n } else if (\n childId.startsWith('scxml_') &&\n childId !== `scxml_${x.self.sessionId}`\n ) {\n const message = `Unable to dispatch event to target: ${target}`;\n enq.raise({\n type: 'xstate.error.communication',\n error: {\n tagname: 'send',\n message,\n line: NaN,\n column: NaN,\n reason: message\n },\n _scxmlEventType: 'platform',\n _scxmlEventName: 'error.communication',\n _scxmlEventData: {\n tagname: 'send',\n message,\n line: NaN,\n column: NaN,\n reason: message\n }\n } as AnyEventObject);\n } else {\n // This SCXML session id uses the external event queue.\n (eventData as any)._scxmlExternal = true;\n enq.sendTo(x.self, eventData as AnyEventObject, {\n id: scxmlAction.id,\n delay\n });\n }\n } else {\n // #_internal uses the internal queue; self-send/no target use the\n // external event queue.\n if (isInternalTarget) {\n enq.raise(eventData as AnyEventObject, {\n id: scxmlAction.id,\n delay\n });\n } else {\n (eventData as any)._scxmlExternal = true;\n enq.sendTo(x.self, eventData as AnyEventObject, {\n id: scxmlAction.id,\n delay\n });\n }\n }\n } else if (action.type === 'scxml.cancel') {\n const scxmlAction = action as ScxmlCancelJSON;\n const mergedContext = { ...x.context, ...context };\n try {\n const sendId = evaluateExpr(\n mergedContext,\n scxmlAction.sendidexpr,\n x.event,\n x.self\n ) as string;\n if (sendId) {\n enq.cancel(sendId);\n }\n } catch {\n // ignore evaluation errors\n }\n } else if (action.type === 'scxml.script') {\n const scxmlAction = action as ScxmlScriptJSON;\n const mergedContext = { ...x.context, ...context };\n try {\n const updatedContext = executeScript(\n mergedContext,\n scxmlAction.code,\n x.self,\n scxmlAction.global ?? false\n );\n context ??= {};\n Object.assign(context, updatedContext);\n } catch (err) {\n raiseErrorExecution(state, 'script', err);\n }\n } else if (action.type === 'scxml.foreach') {\n const scxmlAction = action as ScxmlForeachJSON;\n const mergedContext = { ...x.context, ...context };\n // SCXML: `item` (and `index` if present) must be valid datamodel\n // locations — i.e. legal identifiers. Reject things like 'continue'\n // (string literal) or '7' (number).\n const isLegalIdentifier = (s: string) =>\n /^[$_a-zA-Z][$_a-zA-Z0-9]*$/.test(s);\n if (\n !isLegalIdentifier(scxmlAction.item) ||\n (scxmlAction.index && !isLegalIdentifier(scxmlAction.index))\n ) {\n raiseErrorExecution(\n state,\n 'foreach',\n new Error('foreach item/index is not a legal location')\n );\n continue;\n }\n let arr: unknown;\n try {\n arr = evaluateExpr(mergedContext, scxmlAction.array, x.event, x.self);\n } catch (err) {\n raiseErrorExecution(state, 'foreach', err);\n continue;\n }\n if (!Array.isArray(arr)) {\n raiseErrorExecution(\n state,\n 'foreach',\n new Error('foreach array is not iterable')\n );\n continue;\n }\n context ??= {};\n for (let i = 0; i < arr.length; i++) {\n context[scxmlAction.item] = arr[i];\n if (scxmlAction.index) {\n context[scxmlAction.index] = i;\n }\n const iterX = { ...x, context: { ...x.context, ...context } };\n const iterResult = executeActions(\n scxmlAction.actions,\n iterX,\n enq,\n state\n );\n if (iterResult.context) {\n Object.assign(context, iterResult.context);\n }\n if (state.errored) break;\n }\n } else if (action.type === 'scxml.block') {\n const scxmlAction = action as ScxmlBlockJSON;\n const blockX = { ...x, context: { ...x.context, ...context } };\n // Block has its own ExecState — errors don't propagate to parent.\n const blockResult = executeActions(scxmlAction.actions, blockX, enq);\n if (blockResult.context) {\n context ??= {};\n for (const key of Object.keys(blockResult.context)) {\n if (blockResult.context[key] !== x.context[key]) {\n context[key] = blockResult.context[key];\n }\n }\n }\n } else if (action.type === 'scxml.if') {\n const scxmlAction = action as ScxmlIfJSON;\n const mergedContext = { ...x.context, ...context };\n for (const branch of scxmlAction.branches) {\n let condResult: boolean;\n if (branch.cond) {\n try {\n condResult = !!evaluateExpr(\n mergedContext,\n branch.cond,\n x.event,\n x.self\n );\n } catch (err) {\n raiseErrorExecution(state, 'if', err);\n condResult = false;\n }\n } else {\n condResult = true;\n }\n if (condResult) {\n if (branch.actions.length) {\n const branchX = { ...x, context: mergedContext };\n const branchResult = executeActions(\n branch.actions,\n branchX,\n enq,\n state\n );\n if (branchResult.context) {\n context ??= {};\n for (const key of Object.keys(branchResult.context)) {\n if (branchResult.context[key] !== x.context[key]) {\n context[key] = branchResult.context[key];\n }\n }\n }\n }\n break;\n }\n }\n } else {\n const params = resolveValue(\n (action as CustomActionJSON).params,\n 'actionParams',\n makeScope(x, { params: x.params }),\n '$.actions.params'\n );\n const result = executeActionDefinition(\n action,\n x,\n enq,\n params,\n state,\n stack\n );\n if (result.context) {\n context ??= {};\n Object.assign(context, result.context);\n }\n }\n }\n return {\n context: context ? { ...x.context, ...context } : undefined,\n errored: state.errored\n };\n }\n\n function iterActions(\n actions: ActionJSON[]\n ): Action<any, any, any, any, any, any, any> {\n return (x, enq) => executeActions(actions, x, enq);\n }\n\n function getFinalizedGuardContext(\n context: MachineContext,\n event: AnyEventObject,\n self: AnyActorRef,\n finalizers: NonNullable<TransitionJSON['_scxml']>['finalize']\n ): MachineContext {\n const invokeId = (event as any)._scxmlInvokeId ?? (event as any).actorId;\n const finalized = { ...context };\n for (const finalizer of finalizers ?? []) {\n if (finalizer.invokeId !== invokeId) continue;\n for (const action of finalizer.actions) {\n if (!('type' in action) || action.type !== 'scxml.assign') continue;\n const assignAction = action as ScxmlAssignJSON;\n finalized[assignAction.location] = evaluateExpr(\n finalized,\n assignAction.expr,\n event,\n self\n );\n }\n }\n return finalized;\n }\n\n function getTransitionConfig(\n transition: TransitionConfigJSON | TransitionConfigJSON[]\n ): any {\n const transitions = Array.isArray(transition) ? transition : [transition];\n\n // Return an array of transition configs. Each SCXML transition becomes\n // a separate XState transition with its own guard and optional .to.\n // This ensures guards are evaluated by XState's evaluateCandidate (once,\n // with pre-exit context) and NOT re-evaluated in computeEntrySet.\n return transitions.map((t, index) => {\n if (isResolvable(t)) {\n return (x: any, enq: any) =>\n evaluateResolvable(\n t,\n 'transition',\n makeScope(x, { enq }),\n `$.transition${transitions.length > 1 ? `[${index}]` : ''}`\n );\n }\n const target = Array.isArray(t.target) ? t.target[0] : t.target;\n const targetConfig = t.target;\n const resolvedGuard = resolveCondition(\n t.guard,\n 'guard',\n '$.transition.guard'\n );\n const guard =\n resolvedGuard && t._scxml?.finalize?.length\n ? (args: any) =>\n resolvedGuard({\n ...args,\n context: getFinalizedGuardContext(\n args.context,\n args.event,\n args.self,\n t._scxml!.finalize\n )\n })\n : resolvedGuard;\n const resolveTransitionContext = (x: any) =>\n t.context\n ? (resolveValue(\n t.context,\n 'transitionContext',\n makeScope(x),\n '$.transition.context'\n ) as MachineContext)\n : undefined;\n const resolveTransitionInput = (x: any) =>\n t.input !== undefined\n ? resolveValue(t.input, 'input', makeScope(x), '$.transition.input')\n : undefined;\n const eventMatcher = t._scxml?.eventDescriptors\n ? (event: EventObject) =>\n t._scxml!.eventDescriptors!.some((descriptor) =>\n matchesScxmlEventDescriptor(descriptor, event)\n )\n : undefined;\n\n // No guard and no actions: simple static config\n if (!guard && !t.actions?.length) {\n if (t.context) {\n return {\n matches: t.matches,\n _transitionDomain: t._scxml?.type,\n _eventMatcher: eventMatcher,\n to: (x: any) => ({\n target: targetConfig,\n context: resolveTransitionContext(x),\n reenter: t.reenter\n }),\n description: t.description,\n meta: t.meta,\n input: t.input !== undefined ? resolveTransitionInput : undefined\n };\n }\n return {\n matches: t.matches,\n _transitionDomain: t._scxml?.type,\n _eventMatcher: eventMatcher,\n target: targetConfig,\n description: t.description,\n reenter: t.reenter,\n meta: t.meta,\n input: t.input !== undefined ? resolveTransitionInput : undefined\n };\n }\n\n // Guard but no actions: static config with guard\n if (guard && !t.actions?.length) {\n if (t.context) {\n return {\n matches: t.matches,\n _transitionDomain: t._scxml?.type,\n _eventMatcher: eventMatcher,\n guard,\n to: (x: any) => ({\n target: targetConfig,\n context: resolveTransitionContext(x),\n reenter: t.reenter\n }),\n description: t.description,\n meta: t.meta,\n input: t.input !== undefined ? resolveTransitionInput : undefined\n };\n }\n return {\n matches: t.matches,\n _transitionDomain: t._scxml?.type,\n _eventMatcher: eventMatcher,\n target: targetConfig,\n guard,\n description: t.description,\n reenter: t.reenter,\n meta: t.meta,\n input: t.input !== undefined ? resolveTransitionInput : undefined\n };\n }\n\n // Targetless transitions: execute actions directly in .to AND track for\n // parallel re-execution. For non-parallel, .to result is used directly.\n // For parallel (entries exist), first entry re-executes all in document order.\n if (!target) {\n return {\n matches: t.matches,\n _transitionDomain: t._scxml?.type,\n _eventMatcher: eventMatcher,\n guard,\n description: t.description,\n reenter: t.reenter,\n meta: t.meta,\n input: t.input !== undefined ? resolveTransitionInput : undefined,\n to: (x: any, enq: any) => {\n const context = resolveTransitionContext(x);\n if (t.actions?.length) {\n // Track for parallel re-execution (dedup by reference)\n if (!allTransitionActions.includes(t.actions)) {\n allTransitionActions.push(t.actions);\n }\n // Save pre-transition context for parallel override\n contextBeforeTargetless ??= x.context;\n targetlessEvent ??= x.event;\n // Execute immediately (fallback for non-parallel case)\n const result = executeActions(t.actions, x, enq);\n if (result.context) {\n return { context: { ...context, ...result.context } };\n }\n }\n return context ? { context } : {};\n }\n };\n }\n\n // Has target + actions: use guard (for XState evaluation) + .to (for pending actions).\n // The .to function does NOT re-check the guard — XState's evaluateCandidate\n // already validated it. The .to just stores actions for entry to execute.\n // Map by target state ID so parallel transitions each get their own actions.\n return {\n matches: t.matches,\n _transitionDomain: t._scxml?.type,\n _eventMatcher: eventMatcher,\n guard,\n description: t.description,\n reenter: t.reenter,\n meta: t.meta,\n input: t.input !== undefined ? resolveTransitionInput : undefined,\n to: (_x: any, _enq: any) => {\n const context = resolveTransitionContext(_x);\n if (t.actions?.length) {\n const targetId = target.replace(/^#/, '');\n pendingTransitionActionsMap[targetId] = t.actions;\n // Track for parallel re-execution (dedup by reference)\n if (!allTransitionActions.includes(t.actions)) {\n allTransitionActions.push(t.actions);\n }\n }\n return {\n target: targetConfig,\n context,\n reenter: t.reenter\n };\n }\n };\n });\n }\n\n if (json.delays) {\n for (const key of Object.keys(json.delays)) {\n const delay = json.delays[key];\n if (typeof delay === 'number') {\n resolvedSources.delays[key] = delay;\n } else if (typeof delay === 'string') {\n resolvedSources.delays[key] = delayToMs(delay);\n } else if (delay && typeof delay === 'object') {\n resolvedSources.delays[key] = (args: any) =>\n delayToMs(\n resolveValue(\n delay.duration,\n 'delay',\n makeScope(args),\n `$.delays.${key}.duration`\n ) as string | number\n );\n }\n }\n }\n\n assertMachineJSON(json, resolvedSources, expressionResolver);\n\n const rootNodeConfig = iterNode(json);\n const contextConfig =\n json.context || json._scxmlDataIds?.length\n ? {\n context: (args: any) => ({\n ...Object.fromEntries(\n (json._scxmlDataIds ?? []).map((id) => [id, undefined])\n ),\n ...(json.context\n ? (resolveValue(\n json.context,\n 'context',\n args,\n '$.context'\n ) as MachineContext)\n : {}),\n ...(json._scxmlDataIds?.length &&\n args.input &&\n typeof args.input === 'object'\n ? args.input\n : {}),\n ...(json._scxmlDataIds?.length &&\n args.input &&\n typeof args.input === 'object'\n ? { _xstateScxmlInputKeys: Object.keys(args.input) }\n : {})\n })\n }\n : {};\n\n const machine = createMachine({\n ...rootNodeConfig,\n ...contextConfig,\n version: json.version\n }) as unknown as AnyStateMachine;\n\n // Register SCXML guard sources\n const providedGuards: Record<string, (args: any, params: any) => boolean> = {\n 'scxml.cond': ({ context, event, self }: any, params: any) => {\n const expr = params?.expr as string;\n if (!expr) return true;\n try {\n return !!evaluateExpr(context, expr, event, self);\n } catch (err) {\n // Per SCXML spec, a cond that fails to evaluate is treated as false\n // AND raises error.execution. We can't enqueue from a guard, so\n // queue it for the next entry to drain.\n const message =\n err instanceof Error\n ? err.message\n : typeof err === 'string'\n ? err\n : 'unknown error';\n pendingPlatformErrors.push({\n tagname: 'cond',\n message,\n line: NaN,\n column: NaN,\n reason: message\n });\n return false;\n }\n },\n 'xstate.stateIn': (args: any, params: any) => {\n const stateId = params?.stateId as string;\n if (!stateId) return false;\n const normalizedId = stateId.replace(/^#/, '');\n const snapshot = args._snapshot;\n if (snapshot?.nodes) {\n return snapshot.nodes.some((node: any) => node.id === normalizedId);\n }\n return false;\n },\n 'xstate.not': (args: any, params: any) => {\n const inner = params?.guard;\n const innerImpl = inner && args.guards?.[inner.type];\n if (!innerImpl) {\n throw new Error(\n `Guard '${inner?.type}' referenced by 'xstate.not' is not implemented.`\n );\n }\n return !innerImpl(args, inner.params);\n }\n };\n const provided = machine.provide({\n actions: resolvedSources.actions,\n actors: resolvedSources.actors,\n guards: {\n ...providedGuards,\n ...resolvedSources.guards\n },\n delays: resolvedSources.delays\n });\n\n // Keep the original JSON so `serializeMachine(machine)`\n // round-trip losslessly.\n (provided as any)._json = json;\n return provided;\n}\n\nfunction isBuiltInActionJSON(action: ActionJSON): action is BuiltInActionJSON {\n return !isResolvable(action) && action.type.startsWith('@xstate.');\n}\n","import { StandardSchemaV1 } from './schema.types.ts';\nimport { StateMachine } from './StateMachine.ts';\nimport {\n AnyActorRef,\n EventObject,\n AnyEventObject,\n Cast,\n MachineContext,\n ProvidedActor,\n StateValueFromStateSchema,\n ToChildren,\n MetaObject,\n StateSchema,\n DoNotInfer,\n RoutableStateId,\n Compute\n} from './types.ts';\nimport {\n Sources,\n DelayMapFromNames,\n InferChildren,\n InferOutput,\n SchemaOrConfigOutput,\n InferEvents,\n InferInternalEvents,\n Next_MachineConfig,\n Next_StateNodeConfig,\n ValidateDelayReferences,\n ValidateHistoryDefaults,\n ValidateStateTargets,\n ValidateTopLevelFinalOutputs,\n WidenLiterals,\n WithDefault\n} from './types.v6.ts';\n\ntype MergeChildren<\n TChildren extends Record<string, AnyActorRef | undefined>,\n TActor extends ProvidedActor\n> = [keyof TChildren] extends [never]\n ? Compute<ToChildren<TActor>>\n : Compute<TChildren>;\n\ntype MachineIdentity<TConfig> = {\n readonly id: TConfig extends { id: infer TId extends string }\n ? TId\n : '(machine)';\n readonly version: TConfig extends { version: infer TVersion extends string }\n ? TVersion\n : undefined;\n};\n\ntype TestValue =\n | string\n | {\n [k: string]: TestValue | undefined;\n };\n\ntype _GroupTestValues<TTestValue extends string | TestValue> =\n TTestValue extends string\n ? TTestValue extends `${string}.${string}`\n ? [never, never]\n : [TTestValue, never]\n : [never, TTestValue];\n\n/**\n * Creates a state machine (statechart) with the given configuration.\n *\n * The state machine represents the pure logic of a state machine actor.\n *\n * @example\n *\n * ```ts\n * import { createMachine } from 'xstate';\n *\n * const lightMachine = createMachine({\n * id: 'light',\n * initial: 'green',\n * states: {\n * green: {\n * on: {\n * TIMER: { target: 'yellow' }\n * }\n * },\n * yellow: {\n * on: {\n * TIMER: { target: 'red' }\n * }\n * },\n * red: {\n * on: {\n * TIMER: { target: 'green' }\n * }\n * }\n * }\n * });\n *\n * const lightActor = createActor(lightMachine);\n * lightActor.start();\n *\n * lightActor.send({ type: 'TIMER' });\n * ```\n *\n * @param config The state machine configuration.\n * @param options DEPRECATED: use `setup({ ... })` or `machine.provide({ ... })`\n * to provide machine sources instead.\n */\n// Overload 1: With schemas.context — context type inferred from schema\nexport function createMachine<\n TContextSchema extends StandardSchemaV1,\n const TEventSchemaMap extends Record<string, StandardSchemaV1>,\n const TInternalEventSchemaMap extends Record<string, StandardSchemaV1>,\n TEmittedSchemaMap extends Record<string, StandardSchemaV1>,\n TInputSchema extends StandardSchemaV1,\n const TOutputSchema extends StandardSchemaV1,\n TMetaSchema extends StandardSchemaV1,\n TTagSchema extends StandardSchemaV1,\n const TChildrenSchemaMap extends Record<string, StandardSchemaV1>,\n _TEvent extends EventObject,\n TActor extends ProvidedActor,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays'],\n TDelays extends string,\n TTag extends StandardSchemaV1.InferOutput<TTagSchema> & string,\n TInput,\n const TSS extends StateSchema\n>(\n config: TSS &\n ValidateDelayReferences<TSS> &\n ValidateHistoryDefaults<TSS> &\n ValidateStateTargets<TSS> &\n Next_MachineConfig<\n TContextSchema,\n TEventSchemaMap,\n TInternalEventSchemaMap,\n TEmittedSchemaMap,\n TInputSchema,\n TOutputSchema,\n TMetaSchema,\n TTagSchema,\n TChildrenSchemaMap,\n InferOutput<TContextSchema, MachineContext>,\n | InferEvents<TEventSchemaMap>\n | InferInternalEvents<TInternalEventSchemaMap>,\n Cast<\n MergeChildren<InferChildren<TChildrenSchemaMap>, TActor>,\n Record<string, AnyActorRef | undefined>\n >,\n TDelays,\n TTag,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap\n > & {\n schemas: { context: TContextSchema; children?: TChildrenSchemaMap };\n } & ValidateTopLevelFinalOutputs<\n TSS,\n InferOutput<TContextSchema, MachineContext>,\n | InferEvents<TEventSchemaMap>\n | InferInternalEvents<TInternalEventSchemaMap>\n >\n): StateMachine<\n InferOutput<TContextSchema, MachineContext>,\n | (\n | InferEvents<TEventSchemaMap>\n | InferInternalEvents<TInternalEventSchemaMap>\n )\n | ([RoutableStateId<TSS>] extends [never]\n ? never\n : {\n type: 'xstate.route';\n to: RoutableStateId<TSS>;\n }),\n Cast<\n MergeChildren<InferChildren<TChildrenSchemaMap>, TActor>,\n Record<string, AnyActorRef | undefined>\n >,\n StateValueFromStateSchema<TSS>,\n TTag & string,\n TInput,\n SchemaOrConfigOutput<TOutputSchema, TSS>,\n WithDefault<InferEvents<TEmittedSchemaMap>, AnyEventObject>,\n InferOutput<TMetaSchema, MetaObject>, // TMeta\n TSS, // TStateSchema\n TActionMap,\n TActorMap,\n TGuardMap,\n DelayMapFromNames<TDelays, TDelayMap>,\n InferInternalEvents<TInternalEventSchemaMap>\n> & {\n states: TSS;\n} & MachineIdentity<TSS>;\n\n// Overload 2: Without schemas.context — context type inferred from config.context\nexport function createMachine<\n TContext extends MachineContext = never,\n const TEventSchemaMap extends Record<string, StandardSchemaV1> = Record<\n string,\n StandardSchemaV1\n >,\n TEmittedSchemaMap extends Record<string, StandardSchemaV1> = Record<\n string,\n StandardSchemaV1\n >,\n TInputSchema extends StandardSchemaV1 = StandardSchemaV1,\n const TOutputSchema extends StandardSchemaV1 = StandardSchemaV1,\n TMetaSchema extends StandardSchemaV1 = StandardSchemaV1,\n TTagSchema extends StandardSchemaV1 = StandardSchemaV1,\n const TChildrenSchemaMap extends Record<string, StandardSchemaV1> = Record<\n string,\n StandardSchemaV1\n >,\n const TInternalEventSchemaMap extends Record<string, StandardSchemaV1> = {},\n _TEvent extends EventObject = EventObject,\n TActor extends ProvidedActor = ProvidedActor,\n TActionMap extends Sources['actions'] = Sources['actions'],\n TActorMap extends Sources['actors'] = Sources['actors'],\n TGuardMap extends Sources['guards'] = Sources['guards'],\n TDelayMap extends Sources['delays'] = Sources['delays'],\n TDelays extends string = string,\n TTag extends StandardSchemaV1.InferOutput<TTagSchema> & string =\n StandardSchemaV1.InferOutput<TTagSchema> & string,\n TInput = unknown,\n const TSS extends StateSchema = StateSchema\n>(\n config: TSS &\n ValidateDelayReferences<TSS> &\n ValidateHistoryDefaults<TSS> &\n ValidateStateTargets<TSS> &\n Next_MachineConfig<\n StandardSchemaV1,\n TEventSchemaMap,\n TInternalEventSchemaMap,\n TEmittedSchemaMap,\n TInputSchema,\n TOutputSchema,\n TMetaSchema,\n TTagSchema,\n TChildrenSchemaMap,\n WidenLiterals<TContext>,\n | InferEvents<TEventSchemaMap>\n | InferInternalEvents<TInternalEventSchemaMap>,\n Cast<\n MergeChildren<InferChildren<TChildrenSchemaMap>, TActor>,\n Record<string, AnyActorRef | undefined>\n >,\n TDelays,\n TTag,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n false\n > & {\n schemas?: { context?: never };\n // TContext inference site: the `const` state-schema inference above\n // suppresses literal widening, so context is widened explicitly via\n // WidenLiterals before being consumed by handlers and the snapshot.\n context?:\n | TContext\n | ((_: {\n spawn: any;\n actors: TActorMap;\n input: InferOutput<TInputSchema, unknown>;\n self: any;\n }) => TContext);\n } & ValidateTopLevelFinalOutputs<\n TSS,\n WidenLiterals<TContext>,\n | InferEvents<TEventSchemaMap>\n | InferInternalEvents<TInternalEventSchemaMap>\n >\n): StateMachine<\n WidenLiterals<TContext>,\n | (\n | InferEvents<TEventSchemaMap>\n | InferInternalEvents<TInternalEventSchemaMap>\n )\n | ([RoutableStateId<TSS>] extends [never]\n ? never\n : {\n type: 'xstate.route';\n to: RoutableStateId<TSS>;\n }),\n Cast<\n MergeChildren<InferChildren<TChildrenSchemaMap>, TActor>,\n Record<string, AnyActorRef | undefined>\n >,\n StateValueFromStateSchema<TSS>,\n TTag & string,\n TInput,\n SchemaOrConfigOutput<TOutputSchema, TSS>,\n WithDefault<InferEvents<TEmittedSchemaMap>, AnyEventObject>,\n InferOutput<TMetaSchema, MetaObject>, // TMeta\n TSS, // TStateSchema\n TActionMap,\n TActorMap,\n TGuardMap,\n DelayMapFromNames<TDelays, TDelayMap>,\n InferInternalEvents<TInternalEventSchemaMap>\n> & {\n states: TSS;\n} & MachineIdentity<TSS>;\n\n// Implementation\nexport function createMachine(config: any): any {\n return new StateMachine<\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any, // TEmitted\n any, // TMeta\n any, // TStateSchema\n any,\n any,\n any,\n any\n >(config) as any;\n}\n\nexport function createStateConfig<\n TContextSchema extends StandardSchemaV1,\n TEventSchema extends StandardSchemaV1,\n TEmittedSchema extends StandardSchemaV1,\n _TInputSchema extends StandardSchemaV1,\n const TOutputSchema extends StandardSchemaV1,\n TMetaSchema extends StandardSchemaV1,\n TTagSchema extends StandardSchemaV1,\n // TContext extends MachineContext,\n _TEvent extends StandardSchemaV1.InferOutput<TEventSchema> & EventObject, // TODO: consider using a stricter `EventObject` here\n _TActor extends ProvidedActor,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays'],\n TDelays extends string,\n _TTag extends StandardSchemaV1.InferOutput<TTagSchema> & string,\n _TInput,\n const TSS extends StateSchema\n>(\n config: TSS &\n Next_StateNodeConfig<\n InferOutput<TContextSchema, MachineContext>,\n DoNotInfer<StandardSchemaV1.InferOutput<TEventSchema> & EventObject>,\n DoNotInfer<TDelays>,\n DoNotInfer<StandardSchemaV1.InferOutput<TTagSchema> & string>,\n DoNotInfer<StandardSchemaV1.InferOutput<TOutputSchema>>,\n DoNotInfer<StandardSchemaV1.InferOutput<TEmittedSchema> & EventObject>,\n DoNotInfer<InferOutput<TMetaSchema, MetaObject>>,\n DoNotInfer<Record<string, AnyActorRef | undefined>>,\n DoNotInfer<TActionMap>,\n DoNotInfer<TActorMap>,\n DoNotInfer<TGuardMap>,\n DoNotInfer<TDelayMap>\n >\n): typeof config {\n return config;\n}\n","import type { MachineSnapshot } from './State.ts';\nimport type { StateMachine } from './StateMachine.ts';\nimport type { StateNode } from './StateNode.ts';\nimport { AsyncActorLogic } from './actors/promise.ts';\nimport type { Actor, ProcessingStatus } from './createActor.ts';\nimport { InspectionEvent } from './inspection.ts';\nimport { Spawner } from './spawn.ts';\nimport type {\n ActorSystemRuntime,\n AnyActorSystem,\n Clock,\n DeadLetterDetail,\n EventRejection,\n EventRejectionReason\n} from './system.ts';\n\n// this is needed to make JSDoc `@link` work properly\n// oxlint-disable-next-line no-unused-vars\nimport type { SimulatedClock } from './SimulatedClock.ts';\nimport { Sources, Next_StateNodeConfig } from './types.v6.ts';\nimport { StandardSchemaV1 } from './schema.types.ts';\nimport { builtInActions } from './actions.ts';\n\nexport type Identity<T> = { [K in keyof T]: T[K] };\n\nexport type HomomorphicPick<T, K extends keyof any> = {\n [P in keyof T as P & K]: T[P];\n};\nexport type HomomorphicOmit<T, K extends keyof any> = {\n [P in keyof T as Exclude<P, K>]: T[P];\n};\n\nexport type Invert<T extends Record<PropertyKey, PropertyKey>> = {\n [K in keyof T as T[K]]: K;\n};\n\nexport type GetParameterizedParams<T extends ParameterizedObject | undefined> =\n T extends any ? ('params' extends keyof T ? T['params'] : undefined) : never;\n\n/**\n * @remarks\n * `T | unknown` reduces to `unknown` and that can be problematic when it comes\n * to contextual typing. It especially is a problem when the union has a\n * function member, like here:\n *\n * ```ts\n * declare function test(\n * cbOrVal: ((arg: number) => unknown) | unknown\n * ): void;\n * test((arg) => {}); // oops, implicit any\n * ```\n *\n * This type can be used to avoid this problem. This union represents the same\n * value space as `unknown`.\n */\nexport type NonReducibleUnknown = {} | null | undefined;\nexport type AnyFunction = (...args: any[]) => any;\n\ntype ReturnTypeOrValue<T> = T extends AnyFunction ? ReturnType<T> : T;\n\n// https://github.com/microsoft/TypeScript/issues/23182#issuecomment-379091887\nexport type IsNever<T> = [T] extends [never] ? true : false;\nexport type IsNotNever<T> = [T] extends [never] ? false : true;\n\nexport type Compute<A> = { [K in keyof A]: A[K] } & unknown;\nexport type Prop<T, K> = K extends keyof T ? T[K] : never;\nexport type Values<T> = T[keyof T];\nexport type Elements<T> = T[keyof T & `${number}`];\nexport type Merge<M, N> = Omit<M, keyof N> & N;\nexport type IndexByProp<T extends Record<P, string>, P extends keyof T> = {\n [E in T as E[P]]: E;\n};\n\nexport type IndexByType<T extends { type: string }> = IndexByProp<T, 'type'>;\n\nexport type IsEmptyObject<T> = keyof T extends never ? true : false;\n\nexport type Equals<A1, A2> =\n (<A>() => A extends A2 ? true : false) extends <A>() => A extends A1\n ? true\n : false\n ? true\n : false;\nexport type IsAny<T> = Equals<T, any>;\nexport type Cast<A, B> = A extends B ? A : B;\n// @TODO: we can't use native `NoInfer` as we need those:\n// https://github.com/microsoft/TypeScript/pull/61092\n// https://github.com/microsoft/TypeScript/pull/61077\n// but even with those fixes native NoInfer still doesn't work - further issues have to be reproduced and fixed\nexport type DoNotInfer<T> = [T][T extends any ? 0 : any];\n/** @deprecated Use the built-in `NoInfer` type instead */\nexport type NoInfer<T> = DoNotInfer<T>;\nexport type LowInfer<T> = T & NonNullable<unknown>;\n\nexport type MetaObject = Record<string, any>;\n\nexport type Lazy<T> = () => T;\nexport type MaybeLazy<T> = T | Lazy<T>;\n\n/** The full definition of an event, with a string `type`. */\nexport type EventObject = {\n /** The type of event that is sent. */\n type: string;\n};\n\nexport type EventPayloadPattern<TEvent extends EventObject> = TEvent extends any\n ? Partial<Omit<TEvent, 'type'>>\n : never;\n\nexport interface AnyEventObject extends EventObject {\n [key: string]: any;\n}\n\nexport interface ParameterizedObject {\n type: string;\n params?: NonReducibleUnknown;\n}\n\nexport type UnifiedArg<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TEvent extends EventObject\n> = {\n context: TContext;\n event: TExpressionEvent;\n self: ActorSelf<\n MachineSnapshot<\n TContext,\n TEvent,\n Record<string, AnyActorRef | undefined>, // TODO: this should be replaced with `TChildren`\n StateValue,\n string,\n unknown,\n TODO, // TMeta\n TODO // State schema\n >,\n TEvent,\n AnyEventObject\n >;\n system: AnyActorSystem;\n} & OutputArg<TExpressionEvent>;\n\nexport type MachineContext = Record<string, any>;\n\ntype DoneEventType = 'xstate.done.actor' | 'xstate.done.state';\n\nexport type OutputArg<TEvent extends EventObject> = TEvent extends {\n type: DoneEventType;\n output: infer TOutput;\n}\n ? { output: TOutput }\n : { output: undefined };\n\nexport type ActionArgs<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TEvent extends EventObject\n> = UnifiedArg<TContext, TExpressionEvent, TEvent> & {\n children: Record<string, AnyActor>;\n};\n\nexport type InputFrom<T> =\n // Resolve the actor-logic contract first. Setup-created machines intersect\n // StateMachine with literal identity metadata; inferring StateMachine's\n // generic parameters through that intersection widens optional input.\n T extends ActorLogic<\n infer _TSnapshot,\n infer _TEvent,\n infer TInput,\n infer _TSystem,\n infer _TEmitted\n >\n ? TInput\n : T extends StateMachine<\n infer _TContext,\n infer _TEvent,\n infer _TChildren,\n infer _TStateValue,\n infer _TTag,\n infer TInput,\n infer _TOutput,\n infer _TEmitted,\n infer _TMeta,\n infer _TStateSchema,\n infer _TActionMap,\n infer _TActorMap,\n infer _TGuardMap,\n infer _TDelayMap\n >\n ? TInput\n : never;\n\nexport type OutputFrom<T> =\n T extends ActorLogic<\n infer TSnapshot,\n infer _TEvent,\n infer _TInput,\n infer _TSystem,\n infer _TEmitted\n >\n ? (TSnapshot & { status: 'done' })['output']\n : T extends ActorRef<infer TSnapshot, infer _TEvent, infer _TEmitted>\n ? (TSnapshot & { status: 'done' })['output']\n : never;\n\nexport type NoRequiredParams<T extends ParameterizedObject> = T extends any\n ? undefined extends T['params']\n ? T['type']\n : never\n : never;\n\nexport type ConditionalRequired<\n T,\n Condition extends boolean\n> = Condition extends true ? Required<T> : T;\n\nexport type WithDynamicParams<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n T extends ParameterizedObject\n> = T extends any\n ? ConditionalRequired<\n {\n type: T['type'];\n params?:\n | T['params']\n | (({\n context,\n event,\n output\n }: {\n context: TContext;\n event: TExpressionEvent;\n } & OutputArg<TExpressionEvent>) => T['params']);\n },\n undefined extends T['params'] ? false : true\n >\n : never;\n\nexport type StateKey = string | AnyMachineSnapshot;\n\nexport interface StateValueMap {\n [key: string]: StateValue | undefined;\n}\n\n/**\n * The string or object representing the state value relative to the parent\n * state node.\n *\n * @remarks\n * - For a child atomic state node, this is a string, e.g., `\"pending\"`.\n * - For complex state nodes, this is an object, e.g., `{ success:\n * \"someChildState\" }`.\n */\nexport type StateValue = string | StateValueMap;\n\nexport type TransitionTarget = SingleOrArray<string>;\n\nexport type TransitionContextPatch<TContext extends MachineContext> =\n Partial<TContext> & {\n call?: never;\n apply?: never;\n bind?: never;\n };\n\nexport type TransitionContextMapper<\n TContext extends MachineContext,\n TCurrentEvent extends EventObject,\n TEvent extends EventObject,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays'],\n _TCtx extends MachineContext = [TContext] extends [never] ? any : TContext\n> = (\n args: TransitionFunctionArgs<\n _TCtx,\n TCurrentEvent,\n TEvent,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap\n >\n) => TransitionContextPatch<_TCtx>;\n\nexport interface TransitionConfig<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TEvent extends EventObject,\n TEmitted extends EventObject,\n TMeta extends MetaObject,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays']\n> {\n actions?: never;\n /** A shallow partial event pattern that must match before guards run. */\n matches?: EventPayloadPattern<TExpressionEvent>;\n guard?: unknown;\n reenter?: boolean;\n target?: TransitionTarget | undefined;\n context?:\n | TransitionContextPatch<TContext>\n | TransitionContextMapper<\n TContext,\n TExpressionEvent,\n TEvent,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap\n >;\n to?: TransitionConfigFunction<\n TContext,\n TExpressionEvent,\n TEvent,\n TEmitted,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TMeta\n >;\n meta?: TMeta;\n description?: string;\n /** @internal Overrides transition-domain selection for compiled formats. */\n _transitionDomain?: 'internal' | 'external';\n}\n\nexport interface InitialTransitionConfig<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TEmitted extends EventObject,\n TMeta extends MetaObject,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays']\n> extends TransitionConfig<\n TContext,\n TEvent,\n TEvent,\n TEmitted,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap\n> {\n target: string;\n}\n\nexport type AnyTransitionConfig = TransitionConfig<\n any, // TContext\n any, // TExpressionEvent\n any, // TEvent\n any, // TEmitted\n any, // TMeta\n any, // TActionMap\n any, // TActorMap\n any, // TGuardMap\n any // TDelayMap\n>;\n\nexport interface InvokeDefinition<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TEmitted extends EventObject,\n TMeta extends MetaObject,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays']\n> {\n id: string;\n\n registryKey: string | undefined;\n\n logic:\n | string\n | AnyActorLogic\n | (({\n actors,\n context,\n event,\n self\n }: {\n actors: TActorMap;\n context: TContext;\n event: TEvent;\n self: AnyActorRef;\n }) => string | AnyActorLogic);\n /** The source of the actor logic to be invoked */\n src: AnyActorLogic | string;\n\n input?:\n | Mapper<TContext, TEvent, NonReducibleUnknown, TEvent>\n | NonReducibleUnknown;\n /**\n * The transition to take upon the invoked child machine reaching its final\n * top-level state.\n */\n onDone?:\n | string\n | SingleOrArray<\n TransitionConfig<\n TContext,\n DoneActorEvent<unknown>,\n TEvent,\n TEmitted,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap\n >\n >;\n /**\n * The transition to take upon the invoked child machine sending an error\n * event.\n */\n onError?:\n | string\n | SingleOrArray<\n TransitionConfig<\n TContext,\n ErrorActorEvent,\n TEvent,\n TEmitted,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap\n >\n >;\n\n onSnapshot?:\n | string\n | SingleOrArray<\n TransitionConfig<\n TContext,\n SnapshotEvent,\n TEvent,\n TEmitted,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap\n >\n >;\n /**\n * The duration (in ms) after which this invocation times out if it has not\n * completed.\n */\n timeout?: number | ((args: { context: TContext; event: TEvent }) => number);\n /** The transition to take when the invoke-level `timeout` expires. */\n onTimeout?:\n | string\n | SingleOrArray<\n TransitionConfig<\n TContext,\n ActorTimeoutEvent,\n TEvent,\n TEmitted,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap\n >\n >;\n}\n\nexport type AnyInvokeDefinition = InvokeDefinition<\n MachineContext,\n EventObject,\n EventObject,\n MetaObject,\n Sources['actions'],\n Sources['actors'],\n Sources['guards'],\n Sources['delays']\n>;\n\ntype Delay<TDelay extends string> = TDelay | number;\n\nexport type DelayedTransitions<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TEmitted extends EventObject,\n TMeta extends MetaObject,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays']\n> = {\n [K in Delay<keyof TDelayMap & string>]?:\n | string\n | SingleOrArray<\n TransitionConfig<\n TContext,\n TEvent,\n TEvent,\n TEmitted,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap\n >\n >\n | TransitionConfigFunction<\n TContext,\n TEvent,\n TEvent,\n TODO,\n any,\n any,\n any,\n any,\n any\n >;\n};\n\nexport type StateTypes =\n | 'atomic'\n | 'compound'\n | 'parallel'\n | 'final'\n | 'choice'\n | 'history'\n | ({} & string);\n\nexport type SingleOrArray<T> = readonly T[] | T;\n\nexport type StateNodesConfig<\n TContext extends MachineContext,\n TEvent extends EventObject\n> = {\n [K in string]: StateNode<TContext, TEvent>;\n};\n\nexport type TransitionConfigTarget = string | undefined;\n\nexport type TransitionConfigOrTarget<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TEvent extends EventObject,\n TEmitted extends EventObject,\n TMeta extends MetaObject,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays']\n> = SingleOrArray<\n | TransitionConfigTarget\n | TransitionConfig<\n TContext,\n TExpressionEvent,\n TEvent,\n TEmitted,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap\n >\n | TransitionConfigFunction<\n TContext,\n TExpressionEvent,\n TEvent,\n TEmitted,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TMeta\n >\n>;\n\nexport type TransitionConfigFunction<\n TContext extends MachineContext,\n TCurrentEvent extends EventObject,\n TEvent extends EventObject,\n TEmitted extends EventObject,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays'],\n TMeta extends MetaObject,\n TInput = undefined,\n _TCtx extends MachineContext = [TContext] extends [never] ? any : TContext\n> = (\n args: TransitionFunctionArgs<\n _TCtx,\n TCurrentEvent,\n TEvent,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap\n > & { input: TInput },\n enq: EnqueueObject<TEvent, TEmitted, SystemRegistry, TActorMap>\n) => {\n target?: string | string[];\n // target?: keyof TSS['states'];\n context?: TransitionContextPatch<_TCtx>;\n reenter?: boolean;\n meta?: TMeta;\n input?: Record<string, unknown>;\n} | void;\n\ntype TransitionFunctionArgs<\n TContext,\n TCurrentEvent extends EventObject,\n TEvent extends EventObject,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays']\n> = {\n context: TContext;\n event: TCurrentEvent;\n self: ActorSelf<\n MachineSnapshot<\n TContext & MachineContext,\n TEvent,\n TODO,\n TODO,\n TODO,\n TODO,\n TODO,\n TODO\n >,\n TEvent\n >;\n parent: UnknownActorRef | undefined;\n value: StateValue;\n children: Record<string, AnyActor>;\n system: AnyActorSystem;\n actions: TActionMap;\n actors: TActorMap;\n guards: TGuardMap;\n delays: TDelayMap;\n} & OutputArg<TCurrentEvent>;\n\nexport type AnyTransitionConfigFunction = TransitionConfigFunction<\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any\n>;\n\nexport type TransitionsConfig<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TEmitted extends EventObject,\n TMeta extends MetaObject,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays']\n> = {\n [K in EventDescriptor<TEvent>]?: TransitionConfigOrTarget<\n TContext,\n ExtractEvent<TEvent, K>,\n TEvent,\n TEmitted,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap\n >;\n};\n\ntype PartialEventDescriptor<TEventType extends string> =\n TEventType extends `${infer TLeading}.${infer TTail}`\n ? `${TLeading}.*` | `${TLeading}.${PartialEventDescriptor<TTail>}`\n : never;\n\nexport type EventDescriptor<TEvent extends EventObject> =\n | TEvent['type']\n | PartialEventDescriptor<TEvent['type']>\n | '*';\n\nexport type NormalizeDescriptor<TDescriptor extends string> =\n TDescriptor extends '*'\n ? string\n : TDescriptor extends `${infer TLeading}.*`\n ? `${TLeading}.${string}`\n : TDescriptor;\n\ntype EventTypeMatchesDescriptor<\n TEventType extends string,\n TDescriptor extends string\n> = TEventType extends NormalizeDescriptor<TDescriptor> ? true : false;\n\ntype IsInternalEventType<\n TEventType extends string,\n TDescriptors extends string\n> =\n // Descriptors that collapsed to broad `string` (an untyped machine's\n // config) cannot classify anything: without the guard they would match\n // every event type and reduce the sendable events to `never`.\n string extends TDescriptors\n ? false\n : true extends (\n TDescriptors extends any\n ? EventTypeMatchesDescriptor<TEventType, TDescriptors>\n : never\n )\n ? true\n : false;\n\ntype ExcludeInternalEvents<\n TEvent extends EventObject,\n TDescriptors extends string\n> = TEvent extends any\n ? IsInternalEventType<TEvent['type'], TDescriptors> extends true\n ? never\n : TEvent\n : never;\n\ntype InternalEventDescriptorsFromConfig<\n TEvent extends EventObject,\n TConfig\n> = TConfig extends { internalEvents?: readonly EventDescriptor<TEvent>[] }\n ? TConfig['internalEvents'] extends readonly (infer TDesc)[]\n ? Extract<TDesc, string>\n : never\n : never;\n\ntype InternalEventTypes<TInternalEvent extends EventObject> =\n TInternalEvent extends any ? TInternalEvent['type'] : never;\n\ntype SendableEventFromMachine<\n TEvent extends EventObject,\n TInternalEvent extends EventObject,\n TConfig\n> =\n IsAny<TInternalEvent> extends true\n ? TEvent\n : ExcludeInternalEvents<\n TEvent,\n | InternalEventTypes<TInternalEvent>\n | InternalEventDescriptorsFromConfig<TEvent, TConfig>\n >;\n\nexport type IsLiteralString<T extends string> = string extends T ? false : true;\n\ntype ActorsBySrc<TActor extends ProvidedActor> = {\n [A in TActor as A['src']]: A['logic'];\n};\n\ntype DistributeActors<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TActor extends ProvidedActor,\n _TAction extends ParameterizedObject,\n _TGuard extends ParameterizedObject,\n _TDelay extends string,\n TEmitted extends EventObject,\n TMeta extends MetaObject,\n TSpecificActor extends ProvidedActor\n> = TSpecificActor extends { src: infer TSrc }\n ?\n | Compute<\n {\n registryKey?: string;\n /** The source of the machine to be invoked, or the machine itself. */\n src:\n | TSrc\n | (({\n actors,\n context,\n event,\n self\n }: {\n actors: ActorsBySrc<TActor>;\n context: TContext;\n event: TEvent;\n self: AnyActorRef;\n }) => TSrc | TSpecificActor['logic']);\n\n /**\n * The unique identifier for the invoked machine. If not specified,\n * this will be the machine's own `id`, or the URL (from `src`).\n */\n id?: TSpecificActor['id'];\n\n // TODO: currently we do not enforce required inputs here\n // in a sense, we shouldn't - they could be provided within the `sources` object\n // how do we verify if the required input has been provided?\n input?:\n | Mapper<\n TContext,\n TEvent,\n InputFrom<TSpecificActor['logic']>,\n TEvent\n >\n | InputFrom<TSpecificActor['logic']>;\n /**\n * The transition to take upon the invoked child machine reaching\n * its final top-level state.\n */\n onDone?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n DoneActorEvent<OutputFrom<TSpecificActor['logic']>>,\n TEvent,\n TEmitted,\n TMeta,\n any,\n any,\n any,\n any\n >\n >;\n /**\n * The transition to take upon the invoked child machine sending an\n * error event.\n */\n onError?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n ErrorActorEvent,\n TEvent,\n TEmitted,\n TMeta,\n any,\n any,\n any,\n any\n >\n >;\n\n onSnapshot?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n SnapshotEvent<SnapshotFrom<TSpecificActor['logic']>>,\n TEvent,\n TEmitted,\n TMeta,\n any,\n any,\n any,\n any\n >\n >;\n timeout?:\n | number\n | ((args: { context: TContext; event: TEvent }) => number);\n onTimeout?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n ActorTimeoutEvent,\n TEvent,\n TEmitted,\n TMeta,\n any,\n any,\n any,\n any\n >\n >;\n } & { [K in RequiredActorOptions<TSpecificActor>]: unknown }\n >\n | {\n id?: never;\n registryKey?: string;\n src:\n | string\n | AnyActorLogic\n | (({\n actors,\n context,\n event,\n self\n }: {\n actors: ActorsBySrc<TActor>;\n context: TContext;\n event: TEvent;\n self: AnyActorRef;\n }) => string | AnyActorLogic);\n input?:\n | Mapper<TContext, TEvent, NonReducibleUnknown, TEvent>\n | NonReducibleUnknown;\n onDone?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n DoneActorEvent<unknown>,\n TEvent,\n TEmitted,\n TMeta,\n any,\n any,\n any,\n any\n >\n >;\n onError?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n ErrorActorEvent,\n TEvent,\n TEmitted,\n TMeta,\n any,\n any,\n any,\n any\n >\n >;\n\n onSnapshot?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n SnapshotEvent,\n TEvent,\n TEmitted,\n TMeta,\n any,\n any,\n any,\n any\n >\n >;\n timeout?:\n | number\n | ((args: { context: TContext; event: TEvent }) => number);\n onTimeout?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n ActorTimeoutEvent,\n TEvent,\n TEmitted,\n TMeta,\n any,\n any,\n any,\n any\n >\n >;\n }\n : never;\n\nexport type InvokeConfig<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TActor extends ProvidedActor,\n TAction extends ParameterizedObject,\n TGuard extends ParameterizedObject,\n TDelay extends string,\n TEmitted extends EventObject,\n TMeta extends MetaObject\n> =\n IsLiteralString<TActor['src']> extends true\n ? DistributeActors<\n TContext,\n TEvent,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted,\n TMeta,\n TActor\n >\n : {\n /**\n * The unique identifier for the invoked machine. If not specified, this\n * will be the machine's own `id`, or the URL (from `src`).\n */\n id?: string;\n\n registryKey?: string;\n /** The source of the machine to be invoked, or the machine itself. */\n src:\n | string\n | AnyActorLogic\n | (({\n actors,\n context,\n event,\n self\n }: {\n actors: ActorsBySrc<TActor>;\n context: TContext;\n event: TEvent;\n self: AnyActorRef;\n }) => string | AnyActorLogic);\n\n input?:\n | Mapper<TContext, TEvent, NonReducibleUnknown, TEvent>\n | NonReducibleUnknown;\n /**\n * The transition to take upon the invoked child machine reaching its\n * final top-level state.\n */\n onDone?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n DoneActorEvent<unknown>,\n TEvent,\n TEmitted,\n TMeta,\n any,\n any,\n any,\n any\n >\n >;\n /**\n * The transition to take upon the invoked child machine sending an\n * error event.\n */\n onError?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n ErrorActorEvent,\n TEvent,\n TEmitted,\n TMeta,\n any,\n any,\n any,\n any\n >\n >;\n\n onSnapshot?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n SnapshotEvent,\n TEvent,\n TEmitted,\n TMeta,\n any,\n any,\n any,\n any\n >\n >;\n timeout?:\n | number\n | ((args: { context: TContext; event: TEvent }) => number);\n onTimeout?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n ActorTimeoutEvent,\n TEvent,\n TEmitted,\n TMeta,\n any,\n any,\n any,\n any\n >\n >;\n };\n\nexport type AnyInvokeConfig = InvokeConfig<\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any // TMeta\n>;\n\nexport type AnyStateNodeConfig = Next_StateNodeConfig<\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any\n>;\n\n// Accept any StateNode instance regardless of generic parameters\n// Using a union type to handle variance issues with machine.resolveState\nexport type AnyStateNode =\n | StateNode<any, any>\n | StateNode<never, EventObject>\n | StateNode<any, EventObject>\n | StateNode<never, any>;\n\ntype LoosenMachineSnapshot<TSnapshot> =\n TSnapshot extends MachineSnapshot<any, any, any, any, any, any, any, any>\n ? Omit<TSnapshot, 'matches' | 'can'> & {\n matches(partialStateValue: StateValue): boolean;\n can(event: any): boolean;\n }\n : never;\n\nexport type AnyMachineSnapshot = LoosenMachineSnapshot<\n MachineSnapshot<any, any, any, any, any, any, any, any>\n>;\n\nexport interface AnyStateMachine extends AnyActorLogic {\n id: string;\n root: AnyStateNode;\n /** @internal */\n _hasEventlessTransitions?: boolean;\n /** @internal */\n idMap: Map<string, AnyStateNode>;\n options?: { maxIterations?: number };\n states: StateNodesConfig<any, any>;\n events: Array<EventDescriptor<any>>;\n sources: Sources;\n config: any;\n version?: string;\n schemas?: import('./types.v6.ts').AnyMachineSchemas;\n snapshotSchema: import('./machineVersion.types.ts').MachineSnapshotSchema;\n eventSchema: import('./machineVersion.types.ts').MachineEventSchema;\n provide(sources: any): AnyStateMachine;\n resolveState(config: any): any;\n /** @internal */\n _getPreInitialState(actorScope: AnyActorScope, initEvent: EventObject): any;\n getTransitionData(\n snapshot: any,\n event: any,\n actorScope: AnyActorScope,\n selectionResults?: Map<AnyTransitionDefinition, unknown>\n ): AnyTransitionDefinition[];\n /** @internal */\n _canTransition(snapshot: AnyMachineSnapshot, event: any): boolean;\n getStateNodeById(stateId: string): AnyStateNode;\n getPersistedSnapshot(snapshot: any, options?: unknown): Snapshot<unknown>;\n}\n\nexport type AnyStateConfig = StateConfig<any, AnyEventObject>;\n\nexport type DelayConfig<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject\n> = number | DelayExpr<TContext, TExpressionEvent>;\n\nexport type InitialContext<\n TContext extends MachineContext,\n TActorMap extends Sources['actors'],\n TInput,\n TEvent extends EventObject\n> = TContext | ContextFactory<TContext, TActorMap, TInput, TEvent>;\n\nexport type ContextFactory<\n TContext extends MachineContext,\n TActorMap extends Sources['actors'],\n TInput,\n TEvent extends EventObject = EventObject\n> = ({\n spawn,\n actors,\n input,\n self\n}: {\n spawn: Spawner;\n actors: TActorMap;\n input: TInput;\n self: ActorSelf<\n MachineSnapshot<\n [TContext] extends [never] ? any : TContext,\n TEvent,\n Record<string, AnyActorRef | undefined>, // TODO: this should be replaced with `TChildren`\n StateValue,\n string,\n unknown,\n TODO, // TMeta\n TODO // State schema\n >,\n TEvent,\n AnyEventObject\n >;\n}) => [TContext] extends [never] ? MachineContext : TContext;\n\nexport interface ProvidedActor {\n src: string;\n logic: UnknownActorLogic;\n id?: string | undefined; // `| undefined` is required here for compatibility with `exactOptionalPropertyTypes`, see #4613\n}\n\nexport interface SetupTypes<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildrenMap extends Record<string, string>,\n TTag extends string,\n TInput,\n TOutput,\n TEmitted extends EventObject,\n TMeta extends MetaObject\n> {\n context?: TContext;\n events?: TEvent;\n children?: TChildrenMap;\n tags?: TTag;\n input?: TInput;\n output?: TOutput;\n emitted?: TEmitted;\n meta?: TMeta;\n}\n\nexport interface MachineTypes<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TActor extends ProvidedActor,\n TAction extends ParameterizedObject,\n TGuard extends ParameterizedObject,\n TDelay extends string,\n TTag extends string,\n TInput,\n TOutput,\n TEmitted extends EventObject,\n TMeta extends MetaObject\n> extends SetupTypes<\n TContext,\n TEvent,\n // in machine types we currently don't support `TChildren`\n // and IDs can still be configured through `TActor['id']`\n never,\n TTag,\n TInput,\n TOutput,\n TEmitted,\n TMeta\n> {\n actors?: TActor;\n actions?: TAction;\n guards?: TGuard;\n delays?: TDelay;\n meta?: TMeta;\n}\n\nexport interface HistoryStateNode<\n TContext extends MachineContext\n> extends StateNode<TContext> {\n history: 'shallow' | 'deep';\n target: string | undefined;\n}\n\nexport type HistoryValue = Record<string, Array<AnyStateNode>>;\n\nexport type PersistedHistoryValue = Record<string, Array<{ id: string }>>;\n\nexport type AnyHistoryValue = HistoryValue;\n\nexport type StateFrom<\n T extends AnyStateMachine | ((...args: any[]) => AnyStateMachine)\n> = T extends AnyStateMachine\n ? StateSnapshotFromMachine<T>\n : T extends (...args: any[]) => AnyStateMachine\n ? StateSnapshotFromMachine<ReturnType<T>>\n : never;\n\nexport type StateValueFromStateSchema<T extends StateSchema> =\n StateSchema extends T\n ? StateValue\n : ToStateValue<T> extends infer TStateValue\n ? TStateValue extends StateValue\n ? TStateValue\n : StateValue\n : StateValue;\n\ntype MatchingStateValueForStateFrom<\n TStateValue extends StateValue,\n TTestStateValue extends StateValue\n> = TStateValue extends unknown\n ? TTestStateValue extends string\n ? TStateValue extends string\n ? TTestStateValue extends TStateValue\n ? TTestStateValue\n : Extract<TStateValue, TTestStateValue>\n : TStateValue extends StateValueMap\n ? TStateValue & Record<TTestStateValue, StateValue | undefined>\n : never\n : TTestStateValue extends StateValueMap\n ? TStateValue extends StateValueMap\n ? MatchingStateValueMapForStateFrom<TStateValue, TTestStateValue>\n : never\n : never\n : never;\n\ntype MatchingStateValueMapForStateFrom<\n TStateValue extends StateValueMap,\n TTestStateValue extends StateValueMap\n> = false extends {\n [K in keyof TTestStateValue & string]: K extends keyof TStateValue\n ? IsNever<\n MatchingStateValueForStateFrom<\n NonNullable<TStateValue[K]>,\n NonNullable<TTestStateValue[K]>\n >\n > extends true\n ? false\n : true\n : false;\n}[keyof TTestStateValue & string]\n ? never\n : {\n [K in keyof TStateValue]: K extends keyof TTestStateValue\n ? MatchingStateValueForStateFrom<\n NonNullable<TStateValue[K]>,\n NonNullable<TTestStateValue[K]>\n >\n : TStateValue[K];\n };\n\ntype StateSnapshotFromStateValue<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TStateValue extends StateValue,\n TTag extends string,\n TOutput,\n TMeta extends MetaObject,\n TStateSchema extends StateSchema,\n TAllStateValue extends StateValue = TStateValue\n> = TStateValue extends unknown\n ? Omit<\n MachineSnapshot<\n StateContextFromStateValue<TStateSchema, TContext, TStateValue>,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TStateSchema\n >,\n 'matches'\n > & {\n matches<const TTestStateValue extends string>(\n partialStateValue: TTestStateValue,\n ...args: string extends TTestStateValue ? [never] : []\n ): this is StateSnapshotFromStateValue<\n StateContextFromStateValue<TStateSchema, TContext, TTestStateValue>,\n TEvent,\n TChildren,\n MatchingStateValueForStateFrom<TAllStateValue, TTestStateValue>,\n TTag,\n TOutput,\n TMeta,\n TStateSchema,\n TAllStateValue\n >;\n matches<const TTestStateValue extends StateValueMap>(\n partialStateValue: TTestStateValue,\n ...args: string extends keyof TTestStateValue ? [never] : []\n ): this is StateSnapshotFromStateValue<\n StateContextFromStateValue<TStateSchema, TContext, TTestStateValue>,\n TEvent,\n TChildren,\n MatchingStateValueForStateFrom<TAllStateValue, TTestStateValue>,\n TTag,\n TOutput,\n TMeta,\n TStateSchema,\n TAllStateValue\n >;\n matches(partialStateValue: StateValue): boolean;\n }\n : never;\n\ntype StateSnapshotFromMachine<T extends AnyStateMachine> =\n SnapshotFrom<T> extends MachineSnapshot<\n infer TContext,\n infer TEvent,\n infer TChildren,\n infer _TStateValue,\n infer TTag,\n infer TOutput,\n infer TMeta,\n infer TStateSchema\n >\n ? StateSnapshotFromStateValue<\n TContext,\n TEvent,\n TChildren,\n StateValueFromStateSchema<TStateSchema>,\n TTag,\n TOutput,\n TMeta,\n TStateSchema,\n StateValueFromStateSchema<TStateSchema>\n >\n : SnapshotFrom<T>;\n\nexport interface DoneActorEvent<\n TOutput = unknown,\n TId extends string = string\n> extends EventObject {\n type: 'xstate.done.actor';\n output: TOutput;\n actorId: TId;\n sessionId: string;\n}\n\nexport interface ErrorActorEvent<\n TErrorData = unknown,\n TId extends string = string\n> extends EventObject {\n type: 'xstate.error.actor';\n error: TErrorData;\n actorId: TId;\n sessionId: string;\n}\n\nexport interface ErrorPlatformEvent<\n TErrorData = unknown,\n TKind extends string = string\n> extends EventObject {\n type: `xstate.error.${TKind}`;\n error: TErrorData;\n}\n\nexport type ErrorEvent = ErrorActorEvent | ErrorPlatformEvent;\n\nexport interface SnapshotEvent<\n TSnapshot extends Snapshot<unknown> = Snapshot<unknown>\n> extends EventObject {\n type: 'xstate.snapshot.actor';\n actorId: string;\n sessionId: string;\n snapshot: TSnapshot;\n}\n\nexport interface DoneStateEvent<\n TOutput = unknown,\n TId extends string = string\n> extends EventObject {\n type: 'xstate.done.state';\n stateId: TId;\n output: TOutput;\n}\n\nexport interface AfterEvent extends EventObject {\n type: 'xstate.after';\n delay: number | string;\n stateId: string;\n}\n\nexport interface TimeoutEvent extends EventObject {\n type: 'xstate.timeout';\n stateId: string;\n}\n\nexport interface ActorTimeoutEvent extends EventObject {\n type: 'xstate.timeout.actor';\n actorId: string;\n sessionId?: string;\n}\n\nexport enum SpecialTargets {\n Internal = '#_internal'\n}\n\nexport type Mapper<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TResult,\n TEvent extends EventObject,\n _TCtx = [TContext] extends [never] ? any : TContext\n> = (\n args: {\n context: _TCtx;\n event: TExpressionEvent;\n input?: Record<string, unknown>;\n self: ActorSelf<\n MachineSnapshot<\n _TCtx & MachineContext,\n TEvent,\n Record<string, AnyActorRef>, // TODO: this should be replaced with `TChildren`\n StateValue,\n string,\n unknown,\n TODO, // TMeta\n TODO // State schema\n >,\n TEvent,\n AnyEventObject\n >;\n } & OutputArg<TExpressionEvent>\n) => TResult;\n\nexport interface TransitionDefinition<\n TContext extends MachineContext,\n TEvent extends EventObject\n> extends Omit<\n TransitionConfig<\n TContext,\n TEvent,\n TEvent,\n TODO,\n TODO,\n TODO,\n TODO,\n TODO, // TEmitted\n TODO // TMeta\n >,\n 'target' | 'to'\n> {\n target: ReadonlyArray<AnyStateNode> | undefined;\n source: AnyStateNode;\n reenter: boolean;\n eventType: EventDescriptor<TEvent>;\n /** @internal Additional runtime matching for generated transitions. */\n _eventMatcher?: (event: EventObject, snapshot: AnyMachineSnapshot) => boolean;\n to?: ((...args: any[]) => any) | undefined;\n input?:\n | Record<string, unknown>\n | ((args: {\n context: any;\n event: any;\n output: any;\n }) => Record<string, unknown>);\n}\n\nexport type AnyTransitionDefinition = TransitionDefinition<any, any>;\n\nexport type InitialTransitionDefinition = {\n source: AnyStateNode;\n target: AnyStateNode[] | undefined;\n reenter?: boolean;\n eventType?: EventDescriptor<any>;\n input?:\n | Record<string, unknown>\n | ((args: {\n context: MachineContext;\n event: EventObject;\n }) => Record<string, unknown>);\n to?: ((...args: any[]) => any) | undefined;\n};\n\nexport type TransitionDefinitionMap<\n TContext extends MachineContext,\n TEvent extends EventObject\n> = {\n [K in EventDescriptor<TEvent>]: Array<\n TransitionDefinition<TContext, ExtractEvent<TEvent, K>>\n >;\n};\n\nexport type DelayExpr<\n TContext extends MachineContext,\n TEvent extends EventObject\n> = (args: {\n context: [TContext] extends [never] ? any : TContext;\n event: TEvent;\n stateNode: AnyStateNode;\n}) => number;\n\nexport interface DelayedTransitionDefinition<\n TContext extends MachineContext,\n TEvent extends EventObject\n> extends TransitionDefinition<TContext, TEvent> {\n delay: number | string | DelayExpr<TContext, TEvent>;\n}\n\nexport interface StateLike<TContext extends MachineContext> {\n value: StateValue;\n context: TContext;\n event: EventObject;\n}\n\nexport interface StateConfig<\n TContext extends MachineContext,\n TEvent extends EventObject\n> {\n context: TContext;\n historyValue?: HistoryValue;\n /** @internal */\n _nodes: Array<AnyStateNode>;\n /** @internal */\n value?: StateValue;\n children: Record<string, AnyActorRef | undefined>;\n timers?: Record<string, LogicalTimer>;\n status: SnapshotStatus;\n output?: any;\n error?: unknown;\n /** @internal */\n _stateInputs?: Record<string, Record<string, unknown>>;\n /** @internal */\n _nextTimerId?: number;\n /**\n * Deterministic generated-child-id counters owned by this snapshot, keyed\n * by src prefix.\n *\n * @internal\n */\n _nextActorIds?: Record<string, number>;\n machine?: StateMachine<\n TContext,\n TEvent,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any\n >;\n}\n\n/** A deterministic delayed-delivery declaration owned by a logic snapshot. */\nexport interface LogicalTimer {\n id: string;\n delay: number;\n type: '@xstate.raise' | '@xstate.sendTo';\n event: EventObject;\n /** `self` or the logical actor that will receive `event`. */\n target: 'self' | AnyActor;\n /**\n * The timer's wall-clock start, stamped at persist time by a running\n * wall-clock actor and carried through restore so re-persisting keeps the\n * original deadline.\n */\n startedAt?: number;\n}\n\n/** The logical input delivered to a timer's source when its runtime delay ends. */\nexport interface TimerEvent extends EventObject {\n type: 'xstate.timer';\n id: string;\n}\n\ndeclare const persistedSnapshotLogic: unique symbol;\n\ntype PersistedSnapshotLogicIdentity<TLogic> = TLogic extends {\n readonly id: infer TId extends string;\n}\n ? {\n readonly id: TId;\n readonly version: TLogic extends {\n readonly version: infer TVersion extends string;\n }\n ? TVersion\n : string;\n }\n : never;\n\n/** A persisted snapshot tied to a versioned actor logic identity. */\nexport type PersistedSnapshotFor<TLogic> = {\n readonly [persistedSnapshotLogic]: PersistedSnapshotLogicIdentity<TLogic>;\n};\n\n/**\n * A persisted snapshot restorable into the given actor logic: any snapshot\n * created by logic with the same machine `id` is accepted, regardless of\n * version (version mismatches are handled at runtime, e.g. by `migrate`).\n */\nexport type RestorablePersistedSnapshotFor<TLogic> = {\n readonly [persistedSnapshotLogic]: TLogic extends {\n readonly id: infer TId extends string;\n }\n ? { readonly id: TId; readonly version: string }\n : never;\n};\n\nexport interface ActorOptions<TLogic extends AnyActorLogic> {\n /**\n * The clock that is responsible for setting and clearing timeouts, such as\n * delayed events and transitions.\n *\n * @remarks\n * You can create your own “clock”. The clock interface supports these\n * methods:\n *\n * - `now` - optional; returns the current time in milliseconds\n * - `setTimeout` - same arguments as `window.setTimeout(fn, timeout)`\n * - `clearTimeout` - same arguments as `window.clearTimeout(id)`\n *\n * By default, `Date.now`, native `setTimeout`, and native `clearTimeout` are\n * used.\n *\n * For testing, XState provides `SimulatedClock`.\n * @see {@link Clock}\n * @see {@link SimulatedClock}\n */\n clock?: Clock;\n /**\n * Specifies the logger to be used for `log(...)` actions. Defaults to the\n * native `console.log(...)` method.\n */\n logger?: (...args: any[]) => void;\n parent?: AnyActor;\n /** @internal */\n syncSnapshot?: boolean;\n /** @internal */\n _systemRef?: { current?: AnyActorSystem };\n /** @internal */\n _sessionId?: string;\n /** @internal */\n _inert?: boolean;\n /** The custom `id` for referencing this service. */\n id?: string;\n /** @deprecated Use `inspect` instead. */\n devTools?: never;\n\n /** The registry key to register this actor under. */\n registryKey?: string;\n /** The input data to pass to the actor. */\n input?: InputFrom<TLogic>;\n\n /**\n * Initializes actor logic from a specific persisted internal state.\n *\n * @remarks\n * If the state is compatible with the actor logic, when the actor is started\n * it will be at that persisted state. Actions from machine actors will not be\n * re-executed, because they are assumed to have been already executed.\n * However, invocations will be restarted, and spawned actors will be restored\n * recursively.\n *\n * Can be generated with {@link Actor.getPersistedSnapshot}.\n * @see https://stately.ai/docs/persistence\n */\n snapshot?: Snapshot<unknown> &\n Partial<RestorablePersistedSnapshotFor<DoNotInfer<TLogic>>>;\n\n /** @deprecated Use `snapshot` instead. */\n state?: Snapshot<unknown>;\n\n /** The source actor logic. */\n src?: string | AnyActorLogic;\n\n /**\n * A callback function or observer object which can be used to inspect actor\n * system updates.\n *\n * @remarks\n * If a callback function is provided, it can accept an inspection event\n * argument. The inspection protocol has three event types:\n *\n * - `@xstate.actor` - An actor ref was created in the system (announces actor\n * topology: identity + parent).\n * - `@xstate.transition` - An actor transitioned. Carries every facet of the\n * transition with flat, always-present fields: `event`, `snapshot`,\n * `sourceRef`, `microsteps`, executed `actions`, and `sent`/scheduled\n * events.\n * - `@xstate.deadletter` - An event could not be delivered: the target actor\n * stopped, the payload failed its declared schema, or an internal event\n * type was sent from outside its owning actor. Carries the `event`,\n * `sourceRef`, `reason`, and — for boundary rejections — `issues` and\n * `error`.\n *\n * @example\n *\n * ```ts\n * import { createMachine } from 'xstate';\n *\n * const machine = createMachine({\n * // ...\n * });\n *\n * const actor = createActor(machine, {\n * inspect: (inspectionEvent) => {\n * if (inspectionEvent.actorRef === actor) {\n * // This event is for the root actor\n * }\n *\n * if (inspectionEvent.type === '@xstate.actor') {\n * console.log(inspectionEvent.actorRef, inspectionEvent.parentRef);\n * }\n *\n * if (inspectionEvent.type === '@xstate.transition') {\n * console.log(inspectionEvent.sourceRef);\n * console.log(inspectionEvent.actorRef);\n * console.log(inspectionEvent.event);\n * console.log(inspectionEvent.snapshot);\n * // flat, always-present facets — no narrowing required\n * console.log(inspectionEvent.actions);\n * console.log(inspectionEvent.sent);\n * console.log(inspectionEvent.microsteps);\n * }\n * }\n * });\n * ```\n *\n * Alternately, an observer object (`{ next?, error?, complete? }`) can be\n * provided:\n *\n * @example\n *\n * ```ts\n * const actor = createActor(machine, {\n * inspect: {\n * next: (inspectionEvent) => {\n * if (inspectionEvent.actorRef === actor) {\n * // This event is for the root actor\n * }\n *\n * if (inspectionEvent.type === '@xstate.actor') {\n * console.log(\n * inspectionEvent.actorRef,\n * inspectionEvent.parentRef\n * );\n * }\n *\n * if (inspectionEvent.type === '@xstate.transition') {\n * console.log(inspectionEvent.sourceRef);\n * console.log(inspectionEvent.actorRef);\n * console.log(inspectionEvent.event);\n * console.log(inspectionEvent.snapshot);\n * console.log(inspectionEvent.actions);\n * console.log(inspectionEvent.sent);\n * console.log(inspectionEvent.microsteps);\n * }\n * }\n * }\n * });\n * ```\n */\n inspect?:\n | Observer<InspectionEvent>\n | ((inspectionEvent: InspectionEvent) => void);\n\n /**\n * A dead-letter hook called whenever an event is rejected at the delivery\n * boundary of this actor system — an invalid external event payload or an\n * internal event type sent from outside its owning actor. Rejected events\n * are never delivered and never error the target actor.\n *\n * Only observed when this actor is the root of its system.\n */\n onRejectedEvent?: (rejection: EventRejection) => void;\n}\n\nexport type AnyActor = ActorInstance<any, any, any, any>;\n\n/** @deprecated Use `AnyActor` instead. */\nexport type AnyInterpreter = AnyActor;\n\n// Based on RxJS types\nexport type Observer<T> = {\n next?: (value: T) => void;\n error?: (err: unknown) => void;\n complete?: () => void;\n};\n\nexport interface Subscription {\n unsubscribe(): void;\n}\n\nexport interface Readable<T> extends Subscribable<T> {\n get: () => T;\n}\n\nexport interface InteropObservable<T> {\n [Symbol.observable]: () => InteropSubscribable<T>;\n}\n\nexport interface InteropSubscribable<T> {\n subscribe(observer: Observer<T>): Subscription;\n}\n\nexport interface Subscribable<T> extends InteropSubscribable<T> {\n subscribe(observer: Observer<T>): Subscription;\n subscribe(\n next: (value: T) => void,\n error?: (error: any) => void,\n complete?: () => void\n ): Subscription;\n}\n\ntype EventDescriptorMatches<\n TEventType extends string,\n TNormalizedDescriptor\n> = TEventType extends TNormalizedDescriptor\n ? true\n : TNormalizedDescriptor extends TEventType\n ? true\n : false;\n\nexport type ExtractEvent<\n TEvent extends EventObject,\n TDescriptor extends EventDescriptor<TEvent>\n> = string extends TEvent['type']\n ? TEvent\n : NormalizeDescriptor<TDescriptor> extends infer TNormalizedDescriptor\n ? TEvent extends any\n ? // true is the check type here to match both true and boolean\n true extends EventDescriptorMatches<\n TEvent['type'],\n TNormalizedDescriptor\n >\n ? TEvent\n : never\n : never\n : never;\n\nexport interface BaseActorRef<TEvent extends EventObject> {\n send: (event: TEvent) => void;\n}\n\nexport interface ActorLike<\n TCurrent,\n TEvent extends EventObject\n> extends Subscribable<TCurrent> {\n send: (event: TEvent) => void;\n}\n\n/**\n * A consumer-facing actor handle.\n *\n * `ActorRef` describes the contract a consumer needs: which events can be sent\n * to the actor, which snapshot it publishes for observation, and which emitted\n * events can be listened to. It intentionally does not expose lifecycle control\n * or runtime internals. A concrete `Actor` satisfies this interface, so APIs\n * should accept `ActorRef` whenever they only need to send events, read\n * snapshots, or listen to emitted events.\n */\nexport interface ActorRef<\n TSnapshot extends Snapshot<unknown>,\n TEvent extends EventObject,\n TEmitted extends EventObject = EventObject,\n TSendEvent extends EventObject = TEvent\n>\n extends Subscribable<TSnapshot>, InteropObservable<TSnapshot> {\n send: (event: TSendEvent) => void;\n getSnapshot: () => TSnapshot;\n on: <TType extends TEmitted['type'] | '*'>(\n type: TType,\n handler: (\n emitted: TEmitted & (TType extends '*' ? unknown : { type: TType })\n ) => void\n ) => Subscription;\n}\n\ntype EventPayload<\n TEvent extends EventObject,\n TType extends TEvent['type']\n> = HomomorphicOmit<ExtractEvent<TEvent, TType>, 'type'>;\n\nexport type ActorTrigger<TEvent extends EventObject> = {\n [K in TEvent['type']]: {} extends EventPayload<TEvent, K>\n ? () => void\n : (payload: EventPayload<TEvent, K>) => void;\n};\n\n/**\n * Runtime-only actor capabilities.\n *\n * These members are needed by the interpreter, scheduler, inspection, and child\n * management code. Public consumer APIs should prefer `ActorRef` unless they\n * genuinely need lifecycle control such as starting, stopping, or accessing\n * system-owned runtime state.\n */\nexport interface ActorRuntime<\n TSnapshot extends Snapshot<unknown>,\n TEvent extends EventObject,\n _TEmitted extends EventObject = EventObject,\n TSendEvent extends EventObject = TEvent\n> {\n /** The unique identifier for this actor relative to its parent. */\n id: string;\n /**\n * The deterministic logical address of this actor within its system: the\n * `/`-joined path of actor ids from the root. Stable across persistence and\n * restore, unlike `sessionId`.\n */\n readonly address: string;\n /**\n * The globally unique process ID for this invocation.\n *\n * @remarks\n * This is only defined once the actor is started.\n */\n sessionId: string | undefined;\n /** @internal */\n _send: (event: TEvent) => void;\n start: () => this;\n getPersistedSnapshot: () => Snapshot<unknown>;\n stop: () => void;\n toJSON?: () => any;\n _parent?: any;\n system: any;\n /** @internal Emits the transition inspection event for `snapshot`. */\n _inspectTransition(snapshot: TSnapshot, event: EventObject): void;\n /** @internal */\n _processingStatus: ProcessingStatus;\n /** @internal */\n _isRunning: () => boolean;\n src: string | AnyActorLogic;\n /** Registry key used by the actor system receptionist. */\n registryKey?: string;\n trigger: ActorTrigger<TSendEvent>;\n select<TSelected>(\n selector: (snapshot: TSnapshot) => TSelected,\n equalityFn?: (a: TSelected, b: TSelected) => boolean\n ): Readable<TSelected>;\n}\n\n/**\n * A concrete actor instance type.\n *\n * `ActorInstance` combines the consumer `ActorRef` contract with runtime\n * lifecycle capabilities. Values returned by `createActor(...)` and\n * `spawn(...)` naturally satisfy narrower `ActorRef` contracts.\n */\nexport interface ActorInstance<\n TSnapshot extends Snapshot<unknown>,\n TEvent extends EventObject,\n TEmitted extends EventObject = EventObject,\n TSendEvent extends EventObject = TEvent\n>\n extends\n ActorRuntime<TSnapshot, TEvent, TEmitted, TSendEvent>,\n ActorRef<TSnapshot, TEvent, TEmitted, TSendEvent> {}\n\n/**\n * The actor's own full self handle.\n *\n * Internals and action/guard sources receive this shape because `self` can\n * participate in runtime-owned behavior while still being usable wherever an\n * `ActorRef` is expected.\n */\nexport type ActorSelf<\n TSnapshot extends Snapshot<unknown>,\n TEvent extends EventObject,\n TEmitted extends EventObject = EventObject,\n TSendEvent extends EventObject = TEvent\n> = ActorRuntime<TSnapshot, TEvent, TEmitted, TSendEvent> &\n ActorRef<TSnapshot, TEvent, TEmitted, TSendEvent>;\n\n// TODO: in v6, this should only accept AnyActorLogic, like ActorRefFromLogic\nexport type ActorRefFrom<T> =\n T extends StateMachine<\n infer TContext,\n infer TEvent,\n infer TChildren,\n infer TStateValue,\n infer TTag,\n infer _TInput,\n infer TOutput,\n infer TEmitted,\n infer TMeta,\n infer TConfig,\n infer _TActionMap,\n infer _TActorMap,\n infer _TGuardMap,\n infer _TDelayMap,\n infer TInternalEvent\n >\n ? ActorRef<\n MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n any //TStateSchema\n >,\n TEvent,\n TEmitted,\n SendableEventFromMachine<TEvent, TInternalEvent, TConfig>\n >\n : T extends Promise<infer U>\n ? ActorRefFrom<AsyncActorLogic<U>>\n : T extends ActorLogic<\n infer TSnapshot,\n infer TEvent,\n infer _TInput,\n infer _TSystem,\n infer TEmitted\n >\n ? ActorRef<TSnapshot, TEvent, TEmitted>\n : never;\n\nexport type SendableEventFromLogic<TLogic extends AnyActorLogic> =\n TLogic extends StateMachine<\n infer _TContext,\n infer TEvent,\n infer _TChildren,\n infer _TStateValue,\n infer _TTag,\n infer _TInput,\n infer _TOutput,\n infer _TEmitted,\n infer _TMeta,\n infer TConfig,\n infer _TActionMap,\n infer _TActorMap,\n infer _TGuardMap,\n infer _TDelayMap,\n infer TInternalEvent\n >\n ? SendableEventFromMachine<TEvent, TInternalEvent, TConfig>\n : EventFromLogic<TLogic>;\n\ntype OpaqueMachineSnapshot<TSnapshot extends Snapshot<unknown>> =\n TSnapshot extends MachineSnapshot<\n infer TContext,\n infer TEvent,\n infer TChildren,\n infer TStateValue,\n infer TTag,\n infer TOutput,\n infer TMeta,\n infer _TStateSchema\n >\n ? MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n any\n >\n : TSnapshot;\n\nexport type ActorRefFromLogic<T extends AnyActorLogic> = ActorRef<\n OpaqueMachineSnapshot<SnapshotFrom<T>>,\n EventFromLogic<T>,\n EmittedFrom<T>,\n SendableEventFromLogic<T>\n>;\n\nexport interface AnyActorRef extends Subscribable<any>, InteropObservable<any> {\n send(event: any): void;\n getSnapshot(): any;\n on(type: string, handler: (emitted: any) => void): Subscription;\n}\n\n/** The concrete actor instance type produced from actor logic. */\nexport type ActorFromLogic<T extends AnyActorLogic> = ActorInstance<\n SnapshotFrom<T>,\n EventFromLogic<T>,\n EmittedFrom<T>,\n SendableEventFromLogic<T>\n>;\n\ntype SendableEventFromActorRef<\n TActorRef,\n TFallback extends EventObject = AnyEventObject\n> = [NonNullable<TActorRef>] extends [never]\n ? TFallback\n : NonNullable<TActorRef> extends infer TNonNullableActorRef\n ? TNonNullableActorRef extends { send: (event: infer TEvent) => void }\n ? [TEvent] extends [never]\n ? TFallback\n : TEvent extends EventObject\n ? TEvent\n : TFallback\n : never\n : never;\n\nexport type ActorRefLike = Pick<AnyActor, 'sessionId' | 'send' | 'getSnapshot'>;\n\nexport type UnknownActorRef = ActorRef<Snapshot<unknown>, EventObject>;\n\nexport type DevToolsAdapter = (service: AnyActor) => void;\n\nexport type MachineSourcesFrom<\n T extends AnyStateMachine | ((...args: any[]) => AnyStateMachine)\n> =\n T extends StateMachine<\n infer _TContext,\n infer _TEvent,\n infer _TChildren,\n infer _TStateValue,\n infer _TTag,\n infer _TInput,\n infer _TOutput,\n infer _TEmitted,\n infer _TMeta,\n infer _TConfig,\n infer TActionMap,\n infer TActorMap,\n infer TGuardMap,\n infer TDelayMap\n >\n ? {\n actions: TActionMap;\n actors: TActorMap;\n guards: TGuardMap;\n delays: TDelayMap;\n }\n : never;\n\nexport interface ActorScope<\n TSnapshot extends Snapshot<unknown>,\n TEvent extends EventObject,\n TSystem extends AnyActorSystem = AnyActorSystem,\n TEmitted extends EventObject = EventObject,\n TSendEvent extends EventObject = TEvent\n> {\n self: ActorSelf<TSnapshot, TEvent, TEmitted, TSendEvent>;\n id: string;\n sessionId: string;\n logger: (...args: any[]) => void;\n defer: (fn: () => void) => void;\n emit: (event: TEmitted) => void | PromiseLike<void>;\n system: TSystem;\n stopChild: (child: AnyActor) => void;\n actionExecutor: ActionExecutor;\n}\n\nexport type AnyActorScope = ActorScope<\n any, // TSnapshot\n any, // TEvent\n AnyActorSystem,\n any, // TEmitted\n any // TSendEvent\n>;\n\nexport type SnapshotStatus = 'active' | 'done' | 'error' | 'stopped';\n\nexport type Snapshot<TOutput> =\n | {\n status: 'active';\n output: undefined;\n error: undefined;\n }\n | {\n status: 'done';\n output: TOutput;\n error: undefined;\n }\n | {\n status: 'error';\n output: undefined;\n error: unknown;\n }\n | {\n status: 'stopped';\n output: undefined;\n error: undefined;\n };\n\nexport type ActorLogicTransitionResult<\n TSnapshot extends Snapshot<unknown>,\n TEffect = ExecutableActionObject\n> = [nextSnapshot: TSnapshot, effects: TEffect[]];\n\n/**\n * Represents logic which can be used by an actor.\n *\n * @template TSnapshot - The type of the snapshot.\n * @template TEvent - The type of the event object.\n * @template TInput - The type of the input.\n * @template TSystem - The type of the actor system.\n */\nexport interface ActorLogic<\n in out TSnapshot extends Snapshot<unknown>, // it's invariant because it's also part of `ActorScope[\"self\"][\"getSnapshot\"]`\n in out TEvent extends EventObject, // it's invariant because it's also part of `ActorScope[\"self\"][\"send\"]`\n in TInput = NonReducibleUnknown,\n TSystem extends AnyActorSystem = AnyActorSystem,\n in out TEmitted extends EventObject = EventObject // it's invariant because it's also aprt of `ActorScope[\"self\"][\"on\"]`\n> {\n /** The initial setup/configuration used to create the actor logic. */\n config?: unknown;\n /** Optional runtime validator for pure calculation boundaries. */\n validator?: import('./validation.types.ts').ActorLogicValidator;\n /**\n * Transition function that processes the current state and an incoming event\n * to produce a new state and effects.\n *\n * @param snapshot - The current state.\n * @param event - The incoming event.\n * @param actorScope - The actor scope.\n * @returns A tuple of the next state and effects.\n */\n transition: (\n snapshot: TSnapshot,\n event: TEvent,\n actorScope: ActorScope<TSnapshot, TEvent, TSystem, TEmitted>\n ) => ActorLogicTransitionResult<TSnapshot>;\n /**\n * Transition function that produces the initial state and effects.\n *\n * @param actorScope - The actor scope.\n * @param input - The input for the initial state.\n * @returns A tuple of the initial state and effects.\n */\n initialTransition: (\n input: TInput,\n actorScope: ActorScope<TSnapshot, TEvent, TSystem, TEmitted>\n ) => ActorLogicTransitionResult<TSnapshot>;\n /**\n * Called to provide the initial state of the actor.\n *\n * @param actorScope - The actor scope.\n * @param input - The input for the initial state.\n * @returns The initial state.\n */\n getInitialSnapshot: (\n actorScope: ActorScope<TSnapshot, TEvent, TSystem, TEmitted>,\n input: TInput\n ) => TSnapshot;\n /**\n * Called when Actor is created to restore the internal state of the actor\n * given a persisted state. The persisted state can be created by\n * `getPersistedSnapshot`.\n *\n * @param persistedState - The persisted state to restore from.\n * @param actorScope - The actor scope.\n * @returns The restored state.\n */\n restoreSnapshot?: (\n persistedState: Snapshot<unknown>,\n actorScope: ActorScope<TSnapshot, TEvent, AnyActorSystem, TEmitted>\n ) => TSnapshot;\n /**\n * Called when the actor is started.\n *\n * @param snapshot - The starting state.\n * @param actorScope - The actor scope.\n * @param options - Start metadata, including whether the snapshot was\n * restored.\n */\n start?: (\n snapshot: TSnapshot,\n actorScope: ActorScope<TSnapshot, TEvent, AnyActorSystem, TEmitted>,\n options?: { restored: boolean }\n ) => void;\n /**\n * Obtains the internal state of the actor in a representation which can be be\n * persisted. The persisted state can be restored by `restoreSnapshot`.\n *\n * @param snapshot - The current state.\n * @returns The a representation of the internal state to be persisted.\n */\n getPersistedSnapshot: (\n snapshot: TSnapshot,\n options?: unknown\n ) => Snapshot<unknown>;\n /**\n * Returns an event that the actor should transition with to recover from an\n * execution error, or `undefined` if the given snapshot cannot handle it.\n * Actor logic without error-recovery semantics can omit this.\n */\n getExecutionErrorEvent?: (\n snapshot: TSnapshot,\n error: unknown\n ) => TEvent | undefined;\n}\n\nexport interface AnyActorLogic {\n config?: unknown;\n validator?: import('./validation.types.ts').ActorLogicValidator;\n transition(\n snapshot: any,\n event: any,\n actorScope: any\n ): ActorLogicTransitionResult<any>;\n initialTransition(\n input: any,\n actorScope: any\n ): ActorLogicTransitionResult<any>;\n getInitialSnapshot(actorScope: any, input: any): any;\n restoreSnapshot?(persistedState: Snapshot<unknown>, actorScope: any): any;\n start?(snapshot: any, actorScope: any, options?: { restored: boolean }): void;\n getPersistedSnapshot(snapshot: any, options?: unknown): Snapshot<unknown>;\n getExecutionErrorEvent?(snapshot: any, error: unknown): any;\n}\n\nexport type UnknownActorLogic = ActorLogic<\n any, // snapshot\n any, // event\n any, // input\n AnyActorSystem,\n any // emitted\n>;\n\nexport type SnapshotFrom<T> =\n ReturnTypeOrValue<T> extends infer R\n ? R extends ActorRef<infer TSnapshot, infer _, infer __>\n ? TSnapshot\n : R extends Actor<infer TLogic>\n ? SnapshotFrom<TLogic>\n : R extends ActorLogic<\n infer TSnapshot,\n infer _TEvent,\n infer _TInput,\n infer _TSystem,\n infer _TEmitted\n >\n ? TSnapshot\n : R extends ActorScope<\n infer TSnapshot,\n infer _TEvent,\n infer _TEmitted,\n infer _TSystem\n >\n ? TSnapshot\n : never\n : never;\n\nexport type EventFromLogic<TLogic extends AnyActorLogic> =\n TLogic extends ActorLogic<\n infer _TSnapshot,\n infer TEvent,\n infer _TInput,\n infer _TSystem,\n infer _TEmitted\n >\n ? TEvent\n : never;\n\nexport type EmittedFrom<TLogic extends AnyActorLogic> =\n TLogic extends StateMachine<\n infer _TContext,\n infer _TEvent,\n infer _TChildren,\n infer _TStateValue,\n infer _TTag,\n infer _TInput,\n infer _TOutput,\n infer TEmitted,\n infer _TMeta,\n infer _TStateSchema,\n infer _TActionMap,\n infer _TActorMap,\n infer _TGuardMap,\n infer _TDelayMap\n >\n ? TEmitted\n : [TLogic] extends [AnyStateMachine]\n ? AnyEventObject\n : TLogic extends ActorLogic<\n infer _TSnapshot,\n infer _TEvent,\n infer _TInput,\n infer _TSystem,\n infer TEmitted\n >\n ? TEmitted\n : AnyEventObject;\n\ntype ResolveEventType<T> = T extends infer R\n ? R extends StateMachine<\n infer _TContext,\n infer TEvent,\n infer _TChildren,\n infer _TStateValue,\n infer _TTag,\n infer _TInput,\n infer _TOutput,\n infer _TEmitted,\n infer _TMeta,\n infer _TConfig,\n infer _TActionMap,\n infer _TActorMap,\n infer _TGuardMap,\n infer _TDelayMap\n >\n ? TEvent\n : R extends MachineSnapshot<\n infer _TContext,\n infer TEvent,\n infer _TChildren,\n infer _TStateValue,\n infer _TTag,\n infer _TOutput,\n infer _TMeta,\n infer _TStateSchema\n >\n ? TEvent\n : R extends ActorRef<infer _TSnapshot, infer TEvent, infer _TEmitted>\n ? TEvent\n : never\n : never;\n\nexport type EventFrom<\n T,\n K extends Prop<TEvent, 'type'> = never,\n TEvent extends EventObject = ResolveEventType<T>\n> = IsNever<K> extends true ? TEvent : ExtractEvent<TEvent, K>;\n\nexport type ContextFrom<T> =\n T extends StateMachine<\n infer TContext,\n infer _TEvent,\n infer _TChildren,\n infer _TStateValue,\n infer _TTag,\n infer _TInput,\n infer _TOutput,\n infer _TEmitted,\n infer _TMeta,\n infer _TConfig,\n infer _TActionMap,\n infer _TActorMap,\n infer _TGuardMap,\n infer _TDelayMap\n >\n ? TContext\n : T extends MachineSnapshot<\n infer TContext,\n infer _TEvent,\n infer _TChildren,\n infer _TStateValue,\n infer _TTag,\n infer _TOutput,\n infer _TMeta,\n infer _TStateSchema\n >\n ? TContext\n : T extends Actor<infer TActorLogic>\n ? TActorLogic extends AnyStateMachine\n ? ContextFrom<TActorLogic>\n : never\n : never;\n\nexport type InferEvent<E extends EventObject> = {\n [T in E['type']]: { type: T } & Extract<E, { type: T }>;\n}[E['type']];\n\nexport type TODO = any;\n\nexport type StateValueFrom<TMachine extends AnyStateMachine> = Parameters<\n StateFrom<TMachine>['matches']\n>[0];\n\nexport type TagsFrom<TMachine extends AnyStateMachine> = Parameters<\n StateFrom<TMachine>['hasTag']\n>[0];\n\nexport interface ActorSystemInfo {\n actors: Record<string, AnyActorRef>;\n}\n\nexport type SystemRegistry = Record<string, AnyActorLogic>;\n\nexport type RegistryKeyForLogic<\n TLogic extends AnyActorLogic,\n TSystemRegistry extends SystemRegistry\n> = string extends keyof TSystemRegistry\n ? string\n : Values<{\n [K in keyof TSystemRegistry &\n string]: ActorRefFromLogic<TLogic> extends ActorRefFromLogic<\n TSystemRegistry[K]\n >\n ? K\n : never;\n }>;\n\nexport type RequiredActorOptions<TActor extends ProvidedActor> =\n | (undefined extends TActor['id'] ? never : 'id')\n | (undefined extends InputFrom<TActor['logic']> ? never : 'input');\n\nexport type RequiredLogicInput<TLogic extends AnyActorLogic> =\n undefined extends InputFrom<TLogic> ? never : 'input';\n\ntype ExtractLiteralString<T extends string | undefined> = T extends string\n ? string extends T\n ? never\n : T\n : never;\n\ntype ToConcreteChildren<TActor extends ProvidedActor> = {\n [A in TActor as ExtractLiteralString<A['id']>]?: ActorFromLogic<A['logic']>;\n};\n\n// Actors that don't have literal string IDs — these are the only ones\n// that should appear in the index signature fallback, since actors with\n// literal IDs are already covered by ToConcreteChildren.\ntype NonConcreteActors<TActor extends ProvidedActor> = TActor extends any\n ? ExtractLiteralString<TActor['id']> extends never\n ? TActor\n : never\n : never;\n\nexport type ToChildren<TActor extends ProvidedActor> =\n // only proceed further if all configured `src`s are literal strings\n string extends TActor['src']\n ? // TODO: replace `AnyActorRef` with `UnknownActorRef`~\n // or maybe even `TActor[\"logic\"]` since it's possible to configure `{ src: string; logic: SomeConcreteLogic }`\n // TODO: consider adding `| undefined` here\n Record<string, AnyActor>\n : Compute<\n ToConcreteChildren<TActor> &\n {\n include: {\n [id: string]: NonConcreteActors<TActor> extends never\n ? AnyActor | undefined\n : NonConcreteActors<TActor> extends any\n ?\n | ActorFromLogic<NonConcreteActors<TActor>['logic']>\n | undefined\n : never;\n };\n exclude: unknown;\n }[NonConcreteActors<TActor> extends never ? 'exclude' : 'include']\n >;\n\nexport type StateSchema = {\n id?: string;\n route?: unknown;\n states?: Record<string, StateSchema>;\n contextSchema?: StandardSchemaV1;\n outputSchema?: StandardSchemaV1;\n input?: unknown;\n initial?: unknown;\n\n // Other types\n // Needed because TS treats objects with all optional properties as a \"weak\" object\n // https://github.com/statelyai/xstate/issues/5031\n type?: unknown;\n history?: unknown;\n target?: unknown;\n invoke?: unknown;\n on?: unknown;\n entry?: unknown;\n exit?: unknown;\n onDone?: unknown;\n onError?: unknown;\n timeout?: unknown;\n onTimeout?: unknown;\n after?: unknown;\n always?: unknown;\n choice?: unknown;\n meta?: unknown;\n output?: unknown;\n tags?: unknown;\n description?: unknown;\n};\n\nexport type StateSchemaFrom<T extends AnyStateMachine> =\n T extends StateMachine<\n infer _TContext,\n infer _TEvent,\n infer _TChildren,\n infer _TStateValue,\n infer _TTag,\n infer _TInput,\n infer _TOutput,\n infer _TEmitted,\n infer _TMeta,\n infer TStateSchema,\n infer _TActionMap,\n infer _TActorMap,\n infer _TGuardMap,\n infer _TDelayMap\n >\n ? TStateSchema\n : never;\n\nexport type StateId<\n TSchema extends StateSchema,\n TKey extends string = '(machine)',\n TParentKey extends string | null = null\n> =\n | (TSchema extends { id: string }\n ? TSchema['id']\n : TParentKey extends null\n ? TKey\n : `${TParentKey}.${TKey}`)\n | (TSchema['states'] extends Record<string, any>\n ? Values<{\n [K in keyof TSchema['states'] & string]: StateId<\n TSchema['states'][K],\n K,\n TParentKey extends string\n ? `${TParentKey}.${TKey}`\n : TSchema['id'] extends string\n ? TSchema['id']\n : TKey\n >;\n }>\n : never);\n\n/** Maps state IDs to their input types based on the StateSchema. */\nexport type StateIdInputs<\n TSchema extends StateSchema,\n TKey extends string = '(machine)',\n TParentKey extends string | null = null\n> = {\n [K in TSchema extends { id: string }\n ? TSchema['id']\n : TParentKey extends null\n ? TKey\n : `${TParentKey}.${TKey}`]: TSchema['input'] extends undefined\n ? undefined\n : TSchema['input'];\n} & (TSchema['states'] extends Record<string, StateSchema>\n ? UnionToIntersection<\n Values<{\n [K in keyof TSchema['states'] & string]: StateIdInputs<\n TSchema['states'][K],\n K,\n TParentKey extends string\n ? `${TParentKey}.${TKey}`\n : TSchema['id'] extends string\n ? TSchema['id']\n : TKey\n >;\n }>\n >\n : {});\n\ntype UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (\n k: infer I\n) => void\n ? I\n : never;\n\ntype ContextFromStateSchema<\n TSchema extends StateSchema,\n TFallbackContext extends MachineContext\n> = TSchema['contextSchema'] extends StandardSchemaV1\n ? StandardSchemaV1.InferOutput<TSchema['contextSchema']> &\n TFallbackContext &\n MachineContext\n : TFallbackContext;\n\ntype ContextFromChildStateValue<\n TChildSchema extends StateSchema,\n TFallbackContext extends MachineContext,\n TChildValue\n> = ContextFromStateSchema<TChildSchema, TFallbackContext> &\n StateContextFromStateValue<\n TChildSchema,\n ContextFromStateSchema<TChildSchema, TFallbackContext>,\n TChildValue\n >;\n\nexport type StateContextFromStateValue<\n TSchema extends StateSchema,\n TFallbackContext extends MachineContext,\n TStateValue\n> = (TSchema['states'] extends Record<string, StateSchema>\n ? TStateValue extends keyof TSchema['states'] & string\n ? ContextFromStateSchema<TSchema['states'][TStateValue], TFallbackContext>\n : TStateValue extends Record<string, unknown>\n ? UnionToIntersection<\n Values<{\n [K in keyof TStateValue &\n keyof TSchema['states'] &\n string]: ContextFromChildStateValue<\n TSchema['states'][K],\n TFallbackContext,\n NonNullable<TStateValue[K]>\n >;\n }>\n >\n : TFallbackContext\n : TFallbackContext) &\n MachineContext;\n\nexport type RoutableStateId<TSchema extends StateSchema> =\n | (TSchema extends { route: any; id: string } ? `#${TSchema['id']}` : never)\n | (TSchema['states'] extends Record<string, any>\n ? Values<{\n [K in keyof TSchema['states'] & string]: RoutableStateId<\n TSchema['states'][K]\n >;\n }>\n : never);\n\nexport interface StateMachineTypes {\n context: MachineContext;\n events: EventObject;\n actors: ProvidedActor;\n actions: ParameterizedObject;\n guards: ParameterizedObject;\n delays: string;\n tags: string;\n emitted: EventObject;\n}\n\n/** @deprecated */\nexport interface ResolvedStateMachineTypes<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TActor extends ProvidedActor,\n TAction extends ParameterizedObject,\n TGuard extends ParameterizedObject,\n TDelay extends string,\n TTag extends string,\n TEmitted extends EventObject = EventObject\n> {\n context: TContext;\n events: TEvent;\n actors: TActor;\n actions: TAction;\n guards: TGuard;\n delays: TDelay;\n tags: TTag;\n emitted: TEmitted;\n}\n\nexport type GetConcreteByKey<\n T,\n TKey extends keyof T,\n TValue extends T[TKey]\n> = T & Record<TKey, TValue>;\n\ntype _GroupStateKeys<\n T extends StateSchema,\n S extends keyof T['states']\n> = S extends any\n ? T['states'][S] extends { type: 'history' }\n ? [never, never]\n : T extends { type: 'parallel' }\n ? [S, never]\n : T['states'][S] extends { states: Record<string, StateSchema> }\n ? [S, never]\n : [never, S]\n : never;\n\ntype GroupStateKeys<T extends StateSchema, S extends keyof T['states']> = {\n nonLeaf: _GroupStateKeys<T, S & string>[0];\n leaf: _GroupStateKeys<T, S & string>[1];\n};\n\nexport type ToStateValue<T extends StateSchema> = T extends {\n states: Record<infer S, any>;\n}\n ? IsNever<S> extends true\n ? {}\n :\n | GroupStateKeys<T, S>['leaf']\n | (IsNever<GroupStateKeys<T, S>['nonLeaf']> extends false\n ? T extends { type: 'parallel' }\n ? {\n [K in GroupStateKeys<T, S>['nonLeaf']]: ToStateValue<\n T['states'][K]\n >;\n }\n : Compute<\n Values<{\n [K in GroupStateKeys<T, S>['nonLeaf']]: {\n [StateKey in K]: ToStateValue<T['states'][K]>;\n };\n }>\n >\n : never)\n : {};\n\nexport interface BaseExecutableActionObject {\n params: NonReducibleUnknown;\n args: unknown[];\n exec(\n runtime?: Partial<ActorSystemRuntime>\n ): void | PromiseLike<void> | undefined;\n}\n\n/** The terminal result published when an actor completes or errors. */\nexport type ActorTermination =\n | { status: 'done'; output: unknown; error: undefined }\n | { status: 'error'; output: undefined; error: unknown };\n\nexport interface CustomExecutableActionObject<\n TType extends string = string & {}\n> extends BaseExecutableActionObject {\n kind: 'action';\n type: TType;\n action: ((...args: any[]) => void | PromiseLike<void>) | undefined;\n}\n\nexport interface EmitExecutableActionObject<\n TType extends string = string & {}\n> extends BaseExecutableActionObject {\n kind: 'emit';\n type: TType;\n source: AnyActor;\n event: EventObject & { type: TType };\n}\n\nexport interface SpawnExecutableActionObject extends BaseExecutableActionObject {\n kind: 'builtin';\n type: '@xstate.spawn';\n source: AnyActor | undefined;\n actor: AnyActor;\n id: string;\n logic: AnyActorLogic;\n src: string | AnyActorLogic;\n input: unknown;\n args: Parameters<(typeof builtInActions)['@xstate.spawn']>;\n}\n\nexport interface StartExecutableActionObject extends BaseExecutableActionObject {\n kind: 'builtin';\n type: '@xstate.start';\n source: AnyActor | undefined;\n actor: AnyActor;\n id: string;\n args: Parameters<(typeof builtInActions)['@xstate.start']>;\n}\n\nexport interface RaiseExecutableActionObject extends BaseExecutableActionObject {\n kind: 'builtin';\n type: '@xstate.raise';\n source: AnyActor;\n event: EventObject;\n id: string | undefined;\n delay: number | undefined;\n args: Parameters<(typeof builtInActions)['@xstate.raise']>;\n}\n\nexport interface SendToExecutableActionObject extends BaseExecutableActionObject {\n kind: 'builtin';\n type: '@xstate.sendTo';\n source: AnyActor;\n target: AnyActor;\n event: EventObject;\n id: string | undefined;\n delay: number | undefined;\n args: Parameters<(typeof builtInActions)['@xstate.sendTo']>;\n}\n\nexport interface CancelExecutableActionObject extends BaseExecutableActionObject {\n kind: 'builtin';\n type: '@xstate.cancel';\n source: AnyActor;\n id: string;\n args: Parameters<(typeof builtInActions)['@xstate.cancel']>;\n}\n\nexport interface StopExecutableActionObject extends BaseExecutableActionObject {\n kind: 'builtin';\n type: '@xstate.stop';\n source: AnyActor;\n actor: AnyActor;\n id: string;\n args: Parameters<(typeof builtInActions)['@xstate.stop']>;\n}\n\n/** An executable effect that publishes an actor's terminal result. */\nexport type TerminateExecutableActionObject = BaseExecutableActionObject & {\n kind: 'builtin';\n type: '@xstate.terminate';\n source: AnyActor;\n actor: AnyActor;\n id: string;\n args: Parameters<(typeof builtInActions)['@xstate.terminate']>;\n} & ActorTermination;\n\n/**\n * An executable effect that reports an event rejected at the delivery boundary\n * (a dead letter). The snapshot paired with this effect is unchanged.\n */\nexport interface DeadLetterExecutableActionObject extends BaseExecutableActionObject {\n kind: 'builtin';\n type: '@xstate.deadLetter';\n /** The actor that sent the event, or `undefined` for an external send. */\n source: AnyActor | undefined;\n /** The actor that rejected the event. */\n target: AnyActor;\n /** The rejected event. */\n event: AnyEventObject;\n /** Why the event was rejected, such as `'invalidEvent'`. */\n reason: EventRejectionReason;\n detail?: DeadLetterDetail;\n args: [];\n}\n\nexport type BuiltInExecutableActionObject = Values<{\n '@xstate.spawn': SpawnExecutableActionObject;\n '@xstate.start': StartExecutableActionObject;\n '@xstate.raise': RaiseExecutableActionObject;\n '@xstate.sendTo': SendToExecutableActionObject;\n '@xstate.cancel': CancelExecutableActionObject;\n '@xstate.stop': StopExecutableActionObject;\n '@xstate.terminate': TerminateExecutableActionObject;\n '@xstate.deadLetter': DeadLetterExecutableActionObject;\n}>;\n\nexport type SpecialExecutableAction = BuiltInExecutableActionObject;\n\ntype TransitionExecutableActionObject<TType extends string = never> =\n | BuiltInExecutableActionObject\n | EmitExecutableActionObject\n | CustomExecutableActionObject<TType | (string & {})>;\n\ntype KnownSourceKeys<TSourceMap> = string extends keyof TSourceMap\n ? never\n : Extract<keyof TSourceMap, string>;\n\nexport type ExecutableActionObjectFromLogic<T extends AnyActorLogic> =\n T extends StateMachine<\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n infer TActionMap,\n any,\n any,\n any\n >\n ? TransitionExecutableActionObject<KnownSourceKeys<TActionMap>>\n : ExecutableActionObject;\n\nexport type ExecutableActionObject<TType extends string = string & {}> =\n | BuiltInExecutableActionObject\n | EmitExecutableActionObject\n | CustomExecutableActionObject<TType>;\n\nexport interface ToExecutableAction<\n T extends ParameterizedObject\n> extends CustomExecutableActionObject<T['type']> {\n type: T['type'];\n params: T['params'];\n action: undefined;\n}\n\nexport type ActionExecutor = (actionToExecute: ExecutableActionObject) => void;\n\n/** Mappers for subscribeTo - maps lifecycle events to machine events */\nexport interface SubscribeToMappers<\n TSnapshot extends Snapshot<unknown>,\n TOutput,\n TMappedEvent extends EventObject\n> {\n snapshot?: (snapshot: TSnapshot) => TMappedEvent;\n done?: (output: TOutput) => TMappedEvent;\n error?: (error: unknown) => TMappedEvent;\n}\n\ntype EnqueueSpawnOptions<\n TLogic extends AnyActorLogic,\n TSystemRegistry extends SystemRegistry\n> = {\n input?: InputFrom<TLogic>;\n id?: string;\n syncSnapshot?: boolean;\n registryKey?: RegistryKeyForLogic<TLogic, TSystemRegistry>;\n};\n\ntype EnqueueSpawnArgs<\n TLogic extends AnyActorLogic,\n TSystemRegistry extends SystemRegistry\n> = ConditionalRequired<\n [\n options?: EnqueueSpawnOptions<TLogic, TSystemRegistry> & {\n [K in RequiredLogicInput<TLogic>]: unknown;\n }\n ],\n IsNotNever<RequiredLogicInput<TLogic>>\n>;\n\ntype EnqueueSpawner<\n TActorMap extends Sources['actors'],\n TSystemRegistry extends SystemRegistry\n> = {\n <TSource extends keyof TActorMap & string>(\n src: TSource,\n ...[options]: EnqueueSpawnArgs<TActorMap[TSource], TSystemRegistry>\n ): ActorFromLogic<TActorMap[TSource]>;\n <TLogic extends AnyActorLogic>(\n logic: TLogic,\n ...[options]: EnqueueSpawnArgs<TLogic, TSystemRegistry>\n ): ActorFromLogic<TLogic>;\n};\n\nexport type EnqueueObject<\n TEvent extends EventObject,\n TEmittedEvent extends EventObject,\n TSystemRegistry extends SystemRegistry = SystemRegistry,\n TActorMap extends Sources['actors'] = Sources['actors']\n> = {\n cancel: (id: string) => void;\n raise: (ev: TEvent, options?: { id?: string; delay?: number }) => void;\n /**\n * Spawns a child actor from a registered source key or logic. Without an\n * explicit `id`, the child gets a deterministic src-keyed id (`worker:0`,\n * `worker:1`, …) allocated from the parent snapshot's own counters, so ids\n * replay identically and persist with the parent.\n */\n spawn: EnqueueSpawner<TActorMap, TSystemRegistry>;\n emit: (emittedEvent: TEmittedEvent) => void;\n <T extends (...args: any[]) => any>(fn: T, ...args: Parameters<T>): void;\n log: (...args: any[]) => void;\n sendTo: <TActorRef extends { send: (...args: any[]) => void } | undefined>(\n actorRef: TActorRef,\n event: SendableEventFromActorRef<NoInfer<TActorRef>>,\n options?: { id?: string; delay?: number }\n ) => void;\n stop: (actor?: AnyActorRef) => void;\n /**\n * Listen to emitted events from an actor. Returns a listener actor that can\n * be stopped via `enq.stop()`.\n *\n * @param actor - The actor to listen to\n * @param eventType - The emitted event type to listen for (supports\n * wildcards: 'event._', '_')\n * @param mapper - Function to transform emitted events into machine events\n */\n listen: <TEmitted extends EventObject, TMappedEvent extends TEvent>(\n actor: AnyActorRef,\n eventType: string,\n mapper: (event: TEmitted) => TMappedEvent\n ) => AnyActor;\n /**\n * Subscribe to lifecycle events (done/error/snapshot) from an actor. Returns\n * a subscription actor that can be stopped via `enq.stop()`.\n *\n * @param actor - The actor to subscribe to\n * @param mappers - Object with done/error/snapshot mappers, or a single\n * snapshot mapper function\n */\n subscribeTo: <TActor extends AnyActorRef, TMappedEvent extends TEvent>(\n actor: TActor,\n mappers:\n | SubscribeToMappers<\n SnapshotFrom<TActor>,\n OutputFrom<TActor>,\n TMappedEvent\n >\n | ((snapshot: SnapshotFrom<TActor>) => TMappedEvent)\n ) => AnyActor;\n};\n\nexport type Action<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TEmittedEvent extends EventObject,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays'],\n TParams = Record<string, unknown> | undefined,\n _TCtx = [TContext] extends [never] ? any : TContext\n> = (\n _: {\n context: _TCtx;\n event: TEvent;\n parent: AnyActorRef | undefined;\n self: ActorSelf<\n MachineSnapshot<\n _TCtx & MachineContext,\n TEvent,\n TODO,\n TODO,\n TODO,\n TODO,\n TODO,\n TODO\n >,\n TEvent\n >;\n children: Record<string, AnyActor | undefined>;\n actions: TActionMap;\n actors: TActorMap;\n guards: TGuardMap;\n delays: TDelayMap;\n system?: AnyActorSystem;\n params: TParams;\n },\n enqueue: EnqueueObject<TEvent, TEmittedEvent, SystemRegistry, TActorMap>\n) => {\n context?: Partial<_TCtx>;\n children?: Record<string, AnyActor | undefined>;\n} | void;\n\nexport type AnyAction =\n | Action<\n MachineContext,\n EventObject,\n EventObject,\n Sources['actions'],\n Sources['actors'],\n Sources['guards'],\n Sources['delays']\n >\n | { action: (...args: any[]) => any; args: any[] }\n | AnyEventObject;\n","/**\n * SCXML machine creation and conversion utilities for the `xstate/scxml`\n * entry point. Only createMachineFromSCXML and SCXMLConversionOptions are\n * public; the compiler representation remains internal.\n */\nimport { SaxesParser } from 'saxes';\nimport {\n ActionJSON,\n CancelJSON,\n GuardJSON,\n InvokeJSON,\n ScxmlIR,\n RaiseJSON,\n ScxmlCancelJSON,\n ScxmlContentJSON,\n ScxmlDataJSON,\n ScxmlDonedataJSON,\n ScxmlForeachJSON,\n ScxmlLogJSON,\n ScxmlRaiseJSON,\n ScxmlXmlJSON,\n StateNodeJSON,\n TransitionJSON,\n createMachineFromSCXMLConfig\n} from './runtime.ts';\nimport { parseDelayToMilliseconds } from '../delay.ts';\nimport { AnyStateMachine, SpecialTargets } from '../types.ts';\n\ninterface XMLElement {\n type?: 'element' | 'text' | 'cdata' | 'comment';\n name?: string;\n attributes?: Record<string, string>;\n elements?: XMLElement[];\n text?: string;\n cdata?: string;\n}\n\nfunction parseXml(xml: string): XMLElement {\n const root: XMLElement = { elements: [] };\n const stack = [root];\n const append = (element: XMLElement) =>\n stack[stack.length - 1].elements!.push(element);\n const parser = new SaxesParser();\n\n parser.on('opentag', (tag) => {\n const attributes = { ...tag.attributes };\n const element: XMLElement = {\n type: 'element',\n name: tag.name,\n ...(Object.keys(attributes).length ? { attributes } : undefined),\n elements: []\n };\n append(element);\n stack.push(element);\n });\n parser.on('closetag', () => {\n const element = stack.pop()!;\n if (!element.elements?.length) {\n delete element.elements;\n }\n });\n parser.on('text', (text) => {\n if (text.trim()) append({ type: 'text', text });\n });\n parser.on('cdata', (cdata) => append({ type: 'cdata', cdata }));\n parser.on('comment', (text) => append({ type: 'comment', text }));\n parser.write(xml).close();\n return root;\n}\n\nexport function sanitizeStateId(id: string) {\n return id.replace(/\\./g, '$');\n}\n\nexport interface SCXMLConversionOptions {\n resolveResource?: (src: string, kind: 'data' | 'script' | 'invoke') => string;\n}\n\nfunction normalizeElementNames(element: XMLElement): XMLElement {\n if (element.name?.includes(':')) {\n element.name = element.name.slice(element.name.lastIndexOf(':') + 1);\n }\n for (const child of element.elements ?? []) {\n normalizeElementNames(child);\n }\n return element;\n}\n\nfunction resolveResource(\n options: SCXMLConversionOptions,\n src: string,\n kind: 'data' | 'script' | 'invoke'\n): string {\n if (!options.resolveResource) {\n throw new Error(`No SCXML resource resolver provided for ${kind}: ${src}`);\n }\n return options.resolveResource(src, kind);\n}\n\nfunction getAttribute(\n element: XMLElement,\n attribute: string\n): string | number | undefined {\n return element.attributes ? element.attributes[attribute] : undefined;\n}\n\nfunction toScxmlXmlJSON(element: XMLElement): ScxmlXmlJSON {\n return {\n name: element.name!,\n ...(element.attributes\n ? {\n attributes: Object.fromEntries(\n Object.entries(element.attributes).map(([key, value]) => [\n key,\n String(value)\n ])\n )\n }\n : undefined),\n ...((element.elements ?? []).some((child) => child.name)\n ? {\n children: (element.elements ?? [])\n .filter((child) => child.name)\n .map(toScxmlXmlJSON)\n }\n : undefined)\n };\n}\n\nfunction getContentDescriptor(element: XMLElement): ScxmlContentJSON {\n if (element.attributes?.expr !== undefined) {\n return { expr: String(element.attributes.expr) };\n }\n const xml = element.elements?.find((child) => child.name);\n if (xml) {\n return { xml: toScxmlXmlJSON(xml) };\n }\n return {\n text: (element.elements ?? [])\n .filter((child) => child.type === 'text' || child.type === 'cdata')\n .map((child) => String(child.text ?? child.cdata ?? ''))\n .join('')\n };\n}\n\nfunction delayToMs(delay?: string | number): number | undefined {\n if (!delay) {\n return undefined;\n }\n\n const parsedDelay = parseDelayToMilliseconds(delay);\n if (parsedDelay !== undefined) {\n return parsedDelay;\n }\n\n throw new Error(`Can't parse \"${delay} delay.\"`);\n}\n\nfunction getTargets(targetAttr?: string | number): string[] | undefined {\n return targetAttr\n ? `${targetAttr}`\n .split(/\\s+/)\n .map((target) => `#${sanitizeStateId(target)}`)\n : undefined;\n}\n\nfunction normalizeScxmlEventType(eventType: string): string {\n return /^error(\\.|$)/.test(eventType) ? `xstate.${eventType}` : eventType;\n}\n\ninterface ScxmlIfBranch {\n cond?: string;\n actions: ActionJSON[];\n}\n\nfunction parseIfElement(\n element: XMLElement,\n options: SCXMLConversionOptions\n): ActionJSON {\n const branches: ScxmlIfBranch[] = [];\n let currentCond: string | undefined = element.attributes?.cond as string;\n let currentActions: ActionJSON[] = [];\n\n if (element.elements) {\n for (const child of element.elements) {\n if (child.type === 'comment') continue;\n if (child.name === 'elseif') {\n branches.push({ cond: currentCond, actions: currentActions });\n currentCond = child.attributes?.cond as string;\n currentActions = [];\n } else if (child.name === 'else') {\n branches.push({ cond: currentCond, actions: currentActions });\n currentCond = undefined; // else has no condition\n currentActions = [];\n } else {\n currentActions.push(mapAction(child, options));\n }\n }\n }\n // Push the last branch\n branches.push({ cond: currentCond, actions: currentActions });\n\n return {\n type: 'scxml.if',\n branches\n } as any;\n}\n\nfunction mapAction(\n element: XMLElement,\n options: SCXMLConversionOptions\n): ActionJSON {\n switch (element.name) {\n case 'raise': {\n const action: RaiseJSON = {\n type: '@xstate.raise',\n event: {\n type: normalizeScxmlEventType(element.attributes!.event as string)\n }\n };\n return action;\n }\n case 'assign': {\n // SCXML assign uses location and expr attributes\n const location = element.attributes!.location as string;\n const expr =\n element.attributes?.expr !== undefined\n ? String(element.attributes.expr)\n : JSON.stringify(\n toScxmlXmlJSON(element.elements!.find((child) => child.name)!)\n );\n return {\n type: 'scxml.assign' as const,\n location,\n expr\n };\n }\n case 'cancel': {\n if ('sendid' in element.attributes!) {\n const action: CancelJSON = {\n type: '@xstate.cancel',\n id: element.attributes.sendid as string\n };\n return action;\n }\n if ('sendidexpr' in element.attributes!) {\n return {\n type: 'scxml.cancel',\n sendidexpr: element.attributes.sendidexpr as string\n } as ScxmlCancelJSON;\n }\n return {\n type: '@xstate.cancel',\n id: ''\n };\n }\n case 'send': {\n const {\n event,\n eventexpr,\n target,\n targetexpr,\n id,\n idlocation,\n delay,\n delayexpr,\n namelist,\n type\n } = element.attributes!;\n\n // Extract params from child elements\n const params: Array<{\n name: string;\n expr?: string;\n location?: string;\n }> = [];\n let content: ScxmlContentJSON | undefined;\n if (element.elements) {\n for (const child of element.elements) {\n if (child.name === 'param') {\n params.push({\n name: child.attributes!.name as string,\n ...(child.attributes!.expr !== undefined\n ? { expr: child.attributes!.expr as string }\n : { location: child.attributes!.location as string })\n });\n } else if (child.name === 'content') {\n content = getContentDescriptor(child);\n }\n }\n }\n\n const isInternal = target === String(SpecialTargets.Internal);\n const resolvedDelay = delay ? delayToMs(delay) : undefined;\n\n // Any send with a special target (except internal), params, or expressions\n // uses ScxmlRaiseJSON. Target resolution happens at runtime in executeActions.\n const hasNonInternalTarget =\n typeof target === 'string' && target.length > 0 && !isInternal;\n if (\n hasNonInternalTarget ||\n params.length ||\n eventexpr ||\n delayexpr ||\n targetexpr ||\n namelist ||\n content ||\n idlocation ||\n type\n ) {\n const action: ScxmlRaiseJSON = {\n type: 'scxml.raise',\n event:\n typeof event === 'string'\n ? normalizeScxmlEventType(event)\n : undefined,\n eventexpr: eventexpr as string | undefined,\n params: params.length ? params : undefined,\n namelist:\n typeof namelist === 'string'\n ? namelist.trim().split(/\\s+/)\n : undefined,\n id: id as string | undefined,\n idlocation: idlocation as string | undefined,\n delay: resolvedDelay,\n delayexpr: delayexpr as string | undefined,\n target: target as string | undefined,\n targetexpr: targetexpr as string | undefined,\n processorType: type as string | undefined,\n content\n };\n return action;\n }\n\n // Simple send (no special target, no expressions)\n const action: ScxmlRaiseJSON = {\n type: 'scxml.raise',\n event: event as string | undefined,\n eventexpr: undefined,\n params: undefined,\n namelist: undefined,\n id: id as string | undefined,\n idlocation: idlocation as string | undefined,\n delay: resolvedDelay,\n target: target as string | undefined,\n targetexpr: undefined,\n processorType: type as string | undefined,\n content\n };\n return action;\n }\n case 'log': {\n const label = element.attributes!.label;\n const expr = element.attributes!.expr;\n const action: ScxmlLogJSON = {\n type: 'scxml.log',\n ...(label !== undefined ? { label: String(label) } : undefined),\n ...(expr !== undefined ? { expr: String(expr) } : undefined)\n };\n return action;\n }\n case 'if': {\n return parseIfElement(element, options);\n }\n case 'foreach': {\n const array = element.attributes!.array as string;\n const item = element.attributes!.item as string;\n const index = element.attributes?.index as string | undefined;\n const actions = element.elements\n ? mapActions(element.elements, options)\n : [];\n const foreach: ScxmlForeachJSON = {\n type: 'scxml.foreach',\n array,\n item,\n index,\n actions\n };\n return foreach;\n }\n case 'script': {\n if (element.attributes?.src) {\n return {\n type: 'scxml.script',\n code: resolveResource(\n options,\n String(element.attributes.src),\n 'script'\n )\n };\n }\n // Get the script text content\n const textElement = element.elements?.find((el) => el.type === 'text');\n const code = (textElement?.text as string) || '';\n return { type: 'scxml.script', code: code.trim() };\n }\n default:\n throw new Error(\n `Conversion of \"${element.name}\" elements is not implemented yet.`\n );\n }\n}\n\nfunction mapActions(\n elements: XMLElement[],\n options: SCXMLConversionOptions\n): ActionJSON[] {\n const mapped: ActionJSON[] = [];\n\n for (const element of elements) {\n if (element.type === 'comment') {\n continue;\n }\n\n mapped.push(mapAction(element, options));\n }\n\n return mapped;\n}\n\nfunction createGuard(cond: string): GuardJSON {\n // Handle In() predicate\n if (cond.startsWith('In')) {\n const inMatch = cond.trim().match(/^In\\('(.*)'\\)/);\n if (inMatch) {\n return {\n type: 'xstate.stateIn',\n params: { stateId: `#${sanitizeStateId(inMatch[1])}` }\n };\n }\n }\n\n // Handle !In() predicate\n if (cond.startsWith('!In')) {\n const notInMatch = cond.trim().match(/^!In\\('(.*)'\\)/);\n if (notInMatch) {\n return {\n type: 'xstate.not',\n params: {\n guard: {\n type: 'xstate.stateIn',\n params: { stateId: `#${sanitizeStateId(notInMatch[1])}` }\n }\n }\n };\n }\n }\n\n // For other conditions, store the expression for runtime evaluation\n return {\n type: 'scxml.cond',\n params: { expr: cond }\n };\n}\n\ntype HistoryAttributeValue = 'shallow' | 'deep' | undefined;\n\nfunction getDataDescriptors(\n element: XMLElement,\n options: SCXMLConversionOptions\n): ScxmlDataJSON[] {\n return (element.elements ?? [])\n .filter((child) => child.name === 'datamodel')\n .flatMap((datamodel) =>\n (datamodel.elements ?? [])\n .filter((child) => child.name === 'data')\n .map((data) => {\n const src = data.attributes?.src;\n const resolvedSource =\n src !== undefined\n ? resolveResource(options, String(src), 'data')\n : undefined;\n const text = (data.elements ?? [])\n .filter((child) => child.type === 'text' || child.type === 'cdata')\n .map((child) => String(child.text ?? child.cdata ?? ''))\n .join('')\n .trim();\n const xml = data.elements?.find((child) => child.name);\n let resourceXml: XMLElement | undefined;\n if (resolvedSource !== undefined) {\n try {\n resourceXml = normalizeElementNames(\n parseXml(resolvedSource)\n ).elements?.find((child) => child.name);\n } catch {\n resourceXml = undefined;\n }\n }\n return {\n id: String(data.attributes!.id),\n ...(data.attributes?.expr !== undefined\n ? { expr: String(data.attributes.expr) }\n : undefined),\n ...(resolvedSource !== undefined && !resourceXml\n ? { content: resolvedSource.trim() }\n : text\n ? { content: text }\n : undefined),\n ...(resourceXml\n ? { xml: toScxmlXmlJSON(resourceXml) }\n : xml\n ? { xml: toScxmlXmlJSON(xml) }\n : undefined)\n };\n })\n );\n}\n\nfunction collectDataDescriptors(\n element: XMLElement,\n options: SCXMLConversionOptions\n): ScxmlDataJSON[] {\n return [\n ...getDataDescriptors(element, options),\n ...(element.elements ?? [])\n .filter((child) =>\n ['state', 'parallel', 'final'].includes(child.name ?? '')\n )\n .flatMap((child) => collectDataDescriptors(child, options))\n ];\n}\n\nfunction toStateNodeJSON(\n nodeJson: XMLElement,\n id: string,\n parentId?: string,\n binding: 'early' | 'late' = 'early',\n options: SCXMLConversionOptions = {}\n): StateNodeJSON {\n const parallel = nodeJson.name === 'parallel';\n let initial = parallel ? undefined : (nodeJson.attributes?.initial as string);\n let initialActions: ActionJSON[] | undefined;\n const hasInitialAttribute = initial !== undefined;\n const { elements } = nodeJson;\n\n const stateId = parentId ? `${parentId}.${id}` : id;\n\n // Handle history states\n if (nodeJson.name === 'history') {\n const history =\n (getAttribute(nodeJson, 'type') as HistoryAttributeValue) || 'shallow';\n if (!elements) {\n return {\n id: sanitizeStateId(id),\n type: 'history',\n history\n };\n }\n\n const [transitionElement] = elements.filter(\n (element) => element.name === 'transition'\n );\n\n const target = getAttribute(transitionElement, 'target');\n\n return {\n id: sanitizeStateId(id),\n type: 'history',\n history,\n target: target ? `#${sanitizeStateId(target as string)}` : undefined,\n ...(transitionElement.elements?.length\n ? {\n _scxmlHistoryActions: mapActions(\n transitionElement.elements,\n options\n )\n }\n : undefined)\n };\n }\n\n if (!nodeJson.elements) {\n return {\n id: sanitizeStateId(id),\n ...(nodeJson.name === 'final' ? { type: 'final' } : undefined)\n };\n }\n\n // Parse <donedata> for final states\n let donedataConfig: ScxmlDonedataJSON | undefined;\n if (nodeJson.name === 'final') {\n const donedataElement = nodeJson.elements.find(\n (el) => el.name === 'donedata'\n );\n if (donedataElement?.elements) {\n const params: Array<{ name: string; expr: string }> = [];\n let contentExpr: string | undefined;\n let contentText: string | undefined;\n for (const child of donedataElement.elements) {\n if (child.name === 'param') {\n params.push({\n name: child.attributes!.name as string,\n expr: String(\n child.attributes?.expr ?? child.attributes?.location ?? ''\n ).trim()\n });\n } else if (child.name === 'content') {\n if (child.attributes?.expr) {\n contentExpr = child.attributes.expr as string;\n } else if (child.elements) {\n const textEl = child.elements.find(\n (el) => el.type === 'text' || el.type === 'cdata'\n );\n contentText = textEl\n ? String(textEl.text ?? textEl.cdata ?? '').trim()\n : '';\n }\n }\n }\n donedataConfig = { params, contentExpr, contentText };\n }\n }\n\n const stateElements = nodeJson.elements.filter(\n (element) =>\n element.name === 'state' ||\n element.name === 'parallel' ||\n element.name === 'final' ||\n element.name === 'history'\n );\n stateElements.forEach((element, index) => {\n if (element.attributes?.id === undefined) {\n element.attributes = {\n ...element.attributes,\n id: `${id}.anonymous.${index}`\n };\n }\n });\n\n const transitionElements = nodeJson.elements.filter(\n (element) => element.name === 'transition'\n );\n\n const invokeElements = nodeJson.elements.filter(\n (element) => element.name === 'invoke'\n );\n\n const onEntryElements = nodeJson.elements.filter(\n (element) => element.name === 'onentry'\n );\n\n const onExitElements = nodeJson.elements.filter(\n (element) => element.name === 'onexit'\n );\n const directScripts = nodeJson.elements\n .filter((element) => element.name === 'script')\n .map((element) => ({\n ...mapAction(element, options),\n global: true\n }));\n\n // Build states object\n const states: Record<string, StateNodeJSON> = {};\n for (const stateElement of stateElements) {\n const childId = sanitizeStateId(`${stateElement.attributes!.id}`);\n states[childId] = toStateNodeJSON(\n stateElement,\n childId,\n stateId,\n binding,\n options\n );\n }\n\n // Determine initial state\n const initialElement = !initial\n ? nodeJson.elements.find((element) => element.name === 'initial')\n : undefined;\n\n if (initialElement && initialElement.elements?.length) {\n const initialTransition = initialElement.elements.find(\n (element) => element.name === 'transition'\n )!;\n initial = initialTransition.attributes!.target as string;\n initialActions = initialTransition.elements?.length\n ? mapActions(initialTransition.elements, options)\n : undefined;\n } else if (!initial && !initialElement && stateElements.length) {\n initial = stateElements[0].attributes!.id as string;\n }\n\n // Build transitions\n const always: TransitionJSON[] = [];\n const on: Record<string, TransitionJSON | TransitionJSON[]> = {};\n\n transitionElements.forEach((value) => {\n const eventTypes = ((getAttribute(value, 'event') as string) || '')\n .trim()\n .split(/\\s+/);\n const targets = getAttribute(value, 'target');\n const internal = getAttribute(value, 'type') === 'internal';\n const hasTarget = targets !== undefined;\n const eventDescriptors = eventTypes.filter(Boolean).map((eventType) => {\n if (/^(error|done\\.state)(\\.|$)/.test(eventType)) {\n return `xstate.${eventType}`;\n }\n if (/^done\\.invoke(\\.|$)/.test(eventType)) {\n return eventType.replace(/^done\\.invoke/, 'xstate.done.actor');\n }\n return eventType;\n });\n const transitionConfig: TransitionJSON = {\n target: getTargets(targets),\n _scxml: {\n ...(hasTarget && { type: internal ? 'internal' : 'external' }),\n ...(eventDescriptors.length && { eventDescriptors })\n },\n ...(value.elements?.length\n ? { actions: mapActions(value.elements, options) }\n : undefined),\n ...(value.attributes?.cond\n ? { guard: createGuard(value.attributes.cond as string) }\n : undefined),\n ...(hasTarget && !internal && { reenter: true })\n };\n\n if (!eventDescriptors.length) {\n always.push(transitionConfig);\n return;\n }\n\n const existing = on['*'];\n if (!existing) {\n on['*'] = transitionConfig;\n } else if (Array.isArray(existing)) {\n existing.push(transitionConfig);\n } else {\n on['*'] = [existing, transitionConfig];\n }\n });\n\n // Build entry/exit actions. Per SCXML, each <onentry>/<onexit> block is a\n // separate executable-content block — errors in one block must not stop\n // execution of subsequent blocks. Wrap each block in scxml.block so the\n // runtime executes them with isolated error state.\n const entry: ActionJSON[] = [\n ...directScripts,\n ...onEntryElements.map((onEntryElement) => ({\n type: 'scxml.block' as const,\n actions: mapActions(onEntryElement.elements || [], options)\n }))\n ];\n\n const exit = onExitElements.length\n ? onExitElements.map((onExitElement) => ({\n type: 'scxml.block' as const,\n actions: mapActions(onExitElement.elements || [], options)\n }))\n : undefined;\n\n // Build invokes\n const invoke: InvokeJSON[] = invokeElements.map((element, invokeIndex) => {\n const invokeType = element.attributes?.type as string | undefined;\n if (\n invokeType !== undefined &&\n ![\n 'scxml',\n 'http://www.w3.org/TR/scxml',\n 'http://www.w3.org/TR/scxml/'\n ].includes(invokeType)\n ) {\n throw new Error(\n `Currently only converting invoke elements of type SCXML is supported (received ${String(invokeType)}).`\n );\n }\n\n const content = element.elements?.find((el) => el.name === 'content');\n\n // Convert nested SCXML content to a machine JSON\n const nestedScxml = content?.elements?.find((el) => el.name === 'scxml');\n\n const findEntryAssignment = (location: string) =>\n onEntryElements\n .flatMap((onEntry) => onEntry.elements ?? [])\n .find(\n (child) =>\n child.name === 'assign' && child.attributes?.location === location\n );\n\n let _nestedScxmlIR: ScxmlIR | undefined;\n if (nestedScxml) {\n // Create a wrapper that looks like parser output: { elements: [scxmlElement] }\n const wrapper: XMLElement = { elements: [nestedScxml] };\n _nestedScxmlIR = compileScxmlElement(wrapper, options);\n } else if (element.attributes?.src) {\n const source = resolveResource(\n options,\n String(element.attributes.src),\n 'invoke'\n );\n _nestedScxmlIR = compileScxmlElement(\n normalizeElementNames(parseXml(source)),\n options\n );\n } else if (element.attributes?.srcexpr) {\n const assignment = findEntryAssignment(\n String(element.attributes.srcexpr)\n );\n const assignedSource = String(assignment?.attributes?.expr ?? '').match(\n /^(['\"])(.*)\\1$/s\n )?.[2];\n if (assignedSource) {\n _nestedScxmlIR = compileScxmlElement(\n normalizeElementNames(\n parseXml(resolveResource(options, assignedSource, 'invoke'))\n ),\n options\n );\n }\n } else if (content?.attributes?.expr) {\n const assignment = findEntryAssignment(String(content.attributes.expr));\n const assignedScxml = assignment?.elements?.find(\n (child) => child.name === 'scxml'\n );\n if (assignedScxml) {\n _nestedScxmlIR = compileScxmlElement(\n { elements: [assignedScxml] },\n options\n );\n }\n }\n\n const invokeId = String(\n element.attributes?.id ?? `${sanitizeStateId(id)}.invoke.${invokeIndex}`\n );\n const params = (element.elements ?? [])\n .filter((child) => child.name === 'param')\n .map((param) => ({\n name: String(param.attributes!.name),\n ...(param.attributes?.expr !== undefined\n ? { expr: String(param.attributes.expr) }\n : undefined),\n ...(param.attributes?.location !== undefined\n ? { location: String(param.attributes.location) }\n : undefined)\n }));\n const namelist = String(element.attributes?.namelist ?? '')\n .trim()\n .split(/\\s+/)\n .filter(Boolean);\n\n if (element.attributes?.idlocation) {\n entry.push({\n type: 'scxml.assign',\n location: String(element.attributes.idlocation),\n expr: JSON.stringify(invokeId)\n });\n }\n\n return {\n id: invokeId,\n src: 'scxml.nested',\n _nestedScxmlIR,\n ...((params.length || namelist.length) && {\n _scxmlInput: {\n ...(params.length ? { params } : undefined),\n ...(namelist.length ? { namelist } : undefined)\n }\n })\n } as InvokeJSON & { _nestedScxmlIR?: ScxmlIR };\n });\n\n const autoForwardIds = invokeElements.flatMap((element, index) =>\n String(element.attributes?.autoforward) === 'true'\n ? [invoke[index].id!]\n : []\n );\n const finalizers = invokeElements.flatMap((element, index) => {\n const finalize = element.elements?.find(\n (child) => child.name === 'finalize'\n );\n return finalize\n ? [\n {\n invokeId: invoke[index].id!,\n actions: mapActions(finalize.elements ?? [], options)\n }\n ]\n : [];\n });\n if (finalizers.length) {\n for (const transitions of Object.values(on)) {\n for (const transition of Array.isArray(transitions)\n ? transitions\n : [transitions]) {\n transition._scxml = {\n ...transition._scxml,\n finalize: finalizers\n };\n transition.actions = [\n ...finalizers.map((finalizer) => ({\n type: 'scxml.finalize',\n ...finalizer\n })),\n ...(transition.actions ?? [])\n ];\n }\n }\n }\n if (autoForwardIds.length) {\n for (const transitions of Object.values(on)) {\n for (const transition of Array.isArray(transitions)\n ? transitions\n : [transitions]) {\n transition.actions = [\n ...autoForwardIds.map((invokeId) => ({\n type: 'scxml.forward',\n invokeId\n })),\n ...(transition.actions ?? [])\n ];\n }\n }\n }\n\n const resolvedInitial = initial && String(initial).split(' ');\n const hasExplicitInitial = hasInitialAttribute || !!initialElement;\n\n return {\n id: sanitizeStateId(id),\n ...(resolvedInitial && !hasExplicitInitial\n ? { initial: sanitizeStateId(resolvedInitial[0]) }\n : undefined),\n ...(resolvedInitial && hasExplicitInitial\n ? {\n _scxmlInitial: {\n targets: resolvedInitial.map(\n (target) => `#${sanitizeStateId(target)}`\n ),\n ...(initialActions?.length\n ? { actions: initialActions }\n : undefined)\n }\n }\n : undefined),\n ...(parallel ? { type: 'parallel' } : undefined),\n ...(nodeJson.name === 'final' ? { type: 'final' } : undefined),\n ...(donedataConfig ? { _scxmlDonedata: donedataConfig } : undefined),\n ...(Object.keys(states).length ? { states } : undefined),\n ...(Object.keys(on).length ? { on } : undefined),\n ...(always.length ? { always } : undefined),\n ...(entry.length ? { entry } : undefined),\n ...(exit?.length ? { exit } : undefined),\n ...(invoke.length ? { invoke } : undefined),\n ...(binding === 'late' && getDataDescriptors(nodeJson, options).length\n ? { _scxmlData: getDataDescriptors(nodeJson, options) }\n : undefined)\n };\n}\n\nfunction compileScxmlElement(\n scxmlJson: XMLElement,\n options: SCXMLConversionOptions\n): ScxmlIR {\n const machineElement = scxmlJson.elements!.find(\n (element) => element.name === 'scxml'\n );\n if (!machineElement) {\n throw new Error('SCXML document must contain an <scxml> root element.');\n }\n\n const binding =\n machineElement.attributes?.binding === 'late' ? 'late' : 'early';\n const data = collectDataDescriptors(machineElement, options);\n const machineId = (machineElement.attributes?.name as string) || '(machine)';\n const stateNodeJSON = toStateNodeJSON(\n machineElement,\n machineId,\n undefined,\n binding,\n options\n );\n const declaredData = new Set(data.map(({ id }) => id));\n const removeStaticallyInvalidInvokes = (node: StateNodeJSON) => {\n if (node.invoke) {\n const invokes = Array.isArray(node.invoke) ? node.invoke : [node.invoke];\n const valid = invokes.filter((invocation) =>\n (invocation._scxmlInput?.namelist ?? []).every((name) =>\n declaredData.has(name)\n )\n );\n node.invoke = valid.length ? valid : undefined;\n }\n for (const child of Object.values(node.states ?? {})) {\n removeStaticallyInvalidInvokes(child);\n }\n };\n removeStaticallyInvalidInvokes(stateNodeJSON);\n\n return {\n ...stateNodeJSON,\n ...(binding === 'early' && data.length ? { _scxmlData: data } : undefined),\n ...(data.length ? { _scxmlDataIds: data.map(({ id }) => id) } : undefined)\n };\n}\n\n/**\n * Converts an SCXML string to a JSON representation that can be used with\n * the SCXML runtime compiler.\n */\nexport function compileSCXML(\n xml: string,\n options: SCXMLConversionOptions = {}\n): ScxmlIR {\n const json = normalizeElementNames(parseXml(xml));\n return compileScxmlElement(json, options);\n}\n\n/**\n * Creates an XState machine from an SCXML document.\n *\n * Expressions and external resources are evaluated using SCXML semantics.\n * Only create machines from trusted SCXML because ECMAScript expressions and\n * script elements execute JavaScript in the current environment.\n */\nexport function createMachineFromSCXML(\n xml: string,\n options: SCXMLConversionOptions = {}\n): AnyStateMachine {\n return createMachineFromSCXMLConfig(compileSCXML(xml, options));\n}\n"],"names":["Object","defineProperty","exports","value","CHAR","S","NAME_START_CHAR","NAME_CHAR","CHAR_RE","RegExp","S_RE","NAME_START_CHAR_RE","NAME_CHAR_RE","NAME_RE","NMTOKEN_RE","isNameStartChar","c","S_LIST","isChar","isS","isNameChar","RESTRICTED_CHAR","RESTRICTED_CHAR_RE","isRestrictedChar","isCharAndNotRestricted","isNCNameStartChar","NC_NAME_START_CHAR","NC_NAME_CHAR","NC_NAME_START_CHAR_RE","NC_NAME_CHAR_RE","NC_NAME_RE","isNCNameChar","SaxesParser","EVENTS","ed5","isChar10","isChar11","ed2","NSed3","XML_NAMESPACE","XMLNS_NAMESPACE","rootNS","__proto__","xml","xmlns","XML_ENTITIES","amp","gt","lt","quot","apos","EOC","NL_LIKE","S_TEXT","S_XML_DECL_ENDING","NL","LESS","EQUAL","GREATER","QUESTION","CLOSE_BRACKET","isQuote","QUOTES","DOCTYPE_TERMINATOR","DTD_TERMINATOR","XML_DECL_NAME_TERMINATOR","ATTRIB_VALUE_UNQUOTED_TERMINATOR","nsPairCheck","parser","prefix","uri","fail","isNCName","name","test","isName","EVENT_NAME_TO_HANDLER_NAME","xmldecl","text","processinginstruction","doctype","comment","opentagstart","attribute","opentag","closetag","cdata","error","end","ready","constructor","opt","this","fragmentOpt","fragment","xmlnsOpt","trackPosition","position","fileName","nameStartCheck","nameCheck","processAttribs","processAttribsNS","pushAttrib","pushAttribNS","ns","assign","additional","additionalNamespaces","mapping","local","keys","nsMappingCheck","processAttribsPlain","pushAttribPlain","stateTable","sBegin","sBeginWhitespace","sDoctype","sDoctypeQuote","sDTD","sDTDQuoted","sDTDOpenWaka","sDTDOpenWakaBang","sDTDComment","sDTDCommentEnding","sDTDCommentEnded","sDTDPI","sDTDPIEnding","sText","sEntity","sOpenWaka","sOpenWakaBang","sComment","sCommentEnding","sCommentEnded","sCData","sCDataEnding","sCDataEnding2","sPIFirstChar","sPIRest","sPIBody","sPIEnding","sXMLDeclNameStart","sXMLDeclName","sXMLDeclEq","sXMLDeclValueStart","sXMLDeclValue","sXMLDeclSeparator","sXMLDeclEnding","sOpenTag","sOpenTagSlash","sAttrib","sAttribName","sAttribNameSawWhite","sAttribValue","sAttribValueQuoted","sAttribValueClosed","sAttribValueUnquoted","sCloseTag","sCloseTagSawWhite","_init","closed","_closed","_a","openWakaBang","piTarget","entity","q","tags","tag","topNS","chunk","chunkPosition","i","prevI","carriedFromPrevious","undefined","forbiddenState","attribList","state","reportedTextBeforeRoot","reportedTextAfterRoot","closedRoot","sawRoot","xmlDeclPossible","xmlDeclExpects","entityReturnState","defaultXMLVersion","forceXMLVersion","Error","setXMLVersion","positionAtNewLine","xmlDecl","version","encoding","standalone","line","column","ENTITIES","create","readyHandler","call","columnIndex","on","handler","off","makeError","message","msg","length","err","errorHandler","write","toString","limit","lastCode","charCodeAt","slice","close","getCode10","code","final","getCode11","next","getCodeNorm","getCode","unget","captureTo","chars","start","isNLLike","includes","captureToChar","char","captureNameChars","skipSpaces","currentXMLVersion","iBefore","doctypeHandler","String","fromCodePoint","owb","handleTextInRoot","handleTextOutsideRoot","loop","parsed","parseEntity","textHandler","commentHandler","cdataHandler","isQuestion","toLowerCase","piHandler","target","body","join","xmldeclHandler","attributes","openTagStartHandler","openTag","openSelfClosingTag","closeTag","scanLoop","nonSpace","outRootLoop","qname","attr","push","attributeHandler","trimmed","trim","_b","pop","endHandler","resolve","index","resolvePrefix","colon","indexOf","JSON","stringify","seen","Set","eqname","has","add","isSelfClosing","openTagHandler","_c","closeTagHandler","l","defined","num","NaN","parseInt","Mailbox","_process","_active","_current","_last","flush","clear","enqueue","event","enqueued","consumed","XSTATE_INIT","XSTATE_SPAWN","XSTATE_STOP","XSTATE_TERMINATE","XSTATE_TIMER","createAfterEvent","delayRef","id","type","delay","stateId","createAfterEventId","createTimeoutEventId","createInvokeTimeoutEvent","invokeId","sessionId","actorId","createInvokeTimeoutEventId","createDoneStateEvent","output","createErrorPlatformEvent","kind","createInitEvent","input","reportUnhandledError","setTimeout","symbolObservable","Symbol","observable","assertSendToEvent","builtInActions","actor","system","spawnActor","_parent","startActor","@xstate.raise","actorScope","_event","options","scheduleTimer","self","@xstate.sendTo","_relay","@xstate.cancel","sendId","cancelTimer","@xstate.stop","stopActor","@xstate.terminate","termination","terminateActor","sourceKeyCaches","WeakMap","resolveRegisteredActorSource","actors","logic","cache","get","Map","key","registeredLogic","set","subscriptions","createAttachedLogic","attach","initialTransition","_","status","getSnapshot","subscription","parentSubscription","torndown","teardown","unsubscribe","parent","subscribe","complete","transition","delete","getInitialSnapshot","getPersistedSnapshot","snapshot","restoreSnapshot","relayMappedToParent","getEvent","createListenerLogic","eventType","mapper","isPartialWildcard","endsWith","emittedEvent","matchesEventDescriptor","listenerLogic","createSubscriptionLogic","mappers","done","onSnapshot","subscriptionLogic","lazyActorScope","isLazyActorScope","getActorScopeParent","withActorScope","args","actorArgs","defineProperties","enumerable","execCustomEffect","action","execEmitEffect","runtime","source","emitEvent","execDeadLetterEffect","deadLetter","reason","detail","createDeadLetterEffect","exec","params","execSpawnEffect","execStartEffect","execStopEffect","execTerminateEffect","execRaiseEffect","execSendToEffect","sendEvent","execCancelEffect","updateLogicalTimers","effect","isBuiltInExecutableAction","timers","nextTimerId","_nextTimerId","mergeContextPatch","context","patch","pushBuiltInAction","actions","actionRecord","mergeActorIdCounters","current","update","merged","Math","max","applyChildUpdate","children","counters","_nextActorIds","owned","_unregister","getTransitionActionRecord","spawnAllocations","createSpawnAllocation","explicitIds","stoppedIds","beginSpawnAllocation","getWorkingSnapshotOf","_snapshot","nextChildIndex","allocation","allocateChildId","src","localAllocation","getActorIdPrefix","assertChildIdFree","existing","occupied","reserveChildId","generated","parseGeneratedActorId","createTransitionEnqueue","internalEvents","actorSubscriptions","createActors","props","cancel","emit","log","logger","raise","raisedEvent","spawn","registeredActors","sources","getRegisteredActors","resolveTransitionSpawnSource","registryKey","createActorRef","childUpdate","pushSpawnedChild","sendTo","stop","actorInstance","recordStoppedChild","listen","listenerActor","subscribeTo","subscriptionActor","createEnqueueObject","getBuiltInActionFields","createStartEffect","createSendToEffect","createTerminationEffect","finalizeTransitionResult","previousSnapshot","nextSnapshot","effects","becameTerminal","wasTerminal","hasTerminationEffect","some","resolveActionsWithContext","currentSnapshot","intermediateSnapshot","executableActions","actionArgs","getEventOutput","machine","isInline","resolvedAction","bind","actionParams","_childUpdate","emittedEventParams","res","emptyEnqueueObject","builtInFields","isEmittedEvent","typedExecutableAction","enqueueFn","fn","noop","emptyActor","parseDurationToMilliseconds","duration","normalizedDuration","millisecondsMatch","match","secondsMatch","wholePart","hasDecimal","fracPart","padEnd","iso8601DurationMatch","groups","weeks","days","hours","minutes","seconds","toNumber","Number","replace","parseDelayToMilliseconds","snapshotActorRefs","lazySnapshotActorRefs","emptyKeyedActors","getKeyedActors","peek","_peekKeyedActors","keyedActors","markSystemSnapshotDirty","_snapshotVersion","getSystemSnapshotVersion","createSnapshotSystem","baseSystem","baseState","root","copyRegisteredActors","reverseKeyedActors","sourceVersion","_register","_set","getAll","fromEntries","_hasInspectionObservers","_sendInspectionEvent","values","getSnapshotActorRef","created","copySnapshotActorRef","ref","setSnapshotActorRef","previousRef","reusableRef","systemState","sourceSystem","capturedActors","_getRootActor","peekedChildren","_peekChildren","size","captureRegisteredActors","baseKeyedActors","child","getSnapshotChildren","setInertActorScopeSnapshot","attachActorRef","lazyState","getLazyInertActorState","materialized","isInertActorScope","_inert","attachSnapshotActorRef","snapshotActorScopes","identityProvider","setLazySnapshotActorRef","lazyInertActorState","materializeInertActorScope","materialize","lazyInertActorScopePrototype","parentKnown","defer","stopChild","actionExecutor","createMaterializedInertActorScope","actorLogic","sourceRef","sourceChildren","sourceSelf","snapshotRef","previousSelf","createActor","_sessionId","_systemRef","_address","_actorScope","_stop","createInertActorScope","sourceActorScope","sourceScope","sourceState","eagerSourceRef","peekSnapshotActorRef","getSnapshotActorRefProvider","isMachineSnapshot","identitySnapshot","identitySourceRef","identitySourceChildren","identityScope","identityRef","getIdentityScope","scope","resolveDelay","delaySource","configuredDelay","referencedDelay","getConfiguredDelayValue","getStateInput","stateNodeId","_stateInputs","isAtomicStateNode","stateNode","getChildren","states","filter","sn","getProperAncestors","toStateNode","ancestors","m","getAllStateNodes","stateNodes","nodeSet","activeParentSet","s","initialStates","getInitialStateNodes","initialStateNode","getStateValue","rootNode","config","adjList","getValueFromAdj","baseNode","childStateNodes","childStateNode","stateValue","isInFinalState","stateNodeSet","every","isStateId","str","getLegacyEventType","matchesActorSession","getCandidates","eventTypes","legacyType","getEventTypeAliases","exactMatches","flatMap","transitions","wildcardCandidates","eventDescriptor","sort","a","b","scheduleDelayedEvent","timerId","resolveEvent","resolveScheduledDelay","oldEntry","entry","x","enq","oldExit","exit","formatTransition","descriptor","transitionConfig","normalizedTarget","normalizeTarget","reenter","resolveTarget","assertLegalTargetSet","toJSON","map","t","isStateNodeDescendantOf","ancestor","getLeastCommonStateNodeAncestor","left","right","leftAncestors","targets","leftIndex","rightIndex","commonAncestor","getStateNodeById","isInternalTarget","getStateNodeByPath","resolvedTarget","resolveHistoryDefaultTransition","initial","to","_historyDefaultTransition","isHistoryNode","iter","descStateNode","initialState","getStateNode","stateKey","result","statePath","arrayStatePath","toStatePath","currentStateNode","shift","getStateNodes","childStateKeys","Array","allStateNodes","subStateNode","transitionNode","selectionResults","subStateKeys","subStateKey","allInnerTransitions","subStateValue","innerTransitions","isDescendant","parentStateNode","marker","hasDescendantState","hasIntersection","s1","s2","s1Size","isArray","s2Size","set1","item","removeConflictingTransitions","enabledTransitions","resolveTransition","filteredTransitions","exitSets","getExitSet","exitSet","computeExitSet","t1","t1Preempted","transitionsToRemove","t2","t3","from","createTransitionResultResolver","resolveActions","getTransitionResult","selectionResult","getEffectiveTargetStates","historyValue","targetSet","targetNode","node","narrowParallelDomain","domain","targetStates","narrowed","region","find","getTransitionDomain","_transitionDomain","head","tail","concat","statesToExit","microstep","isInitial","internalQueue","mutStateNodeSet","nodes","originalContext","getCurrentTransitionResult","changesState","getStateActionsAndContext","transitionFn","updatedContext","guards","delays","_special","nextState","getInvokeStopActions","invokeDef","invoke","exitStates","changedHistory","order","currentStateNodes","exitStateNode","historyNode","predicate","history","stateInput","exitActions","nextContext","cloneMachineSnapshot","resolvedState","resolvedActions","invokeStopActions","stoppedState","stopEffects","transitionActions","toArray","enterStates","getMachineOutput","rootCompletionNode","completionOutput","rootDoneEvent","e","resolveOutput","stateInputMap","parallelDoneEvent","statesToEnter","statesForDefaultEntry","historyDefaultsByParent","addAncestorStatesToEnter","reentrancyDomain","anc","addDescendantStatesToEnter","historyStateNodes","historyDefaultTransition","historyParent","defaults","_statesForDefaultEntry","stateInputsChanged","completedNodes","stateNodeToEnter","invoked","resolveReferencedActor","syncSnapshot","contextChangedByEntry","resultActions","nextInternalEvents","defaultTransitions","Boolean","defaultTransition","initialActions","initialContext","initialInput","initialInternalEvents","ancestorMarker","regionOutput","regionDoneEvent","finalChild","resolvedTransitionState","transitionExecutableActions","nextStateNodes","allExitActions","forEach","stopChildren","withoutTimers","cancelEffects","cancelTimers","_nodes","transitionArgs","getTransitionArgs","reusable","resolvedInput","resolvedContext","macrostep","initialMicrosteps","microsteps","removeTerminatedChild","terminalEvent","lastEffects","at","completeMacrostep","starts","attachedStarts","childStarts","deriveDeferredStarts","shouldTerminate","terminalEffects","lastSnapshot","addMicrostep","step","collectedMicrosteps","_collectedMicrosteps","stoppedChildrenSnapshot","nextEvent","normalizeWithId","idKey","startsWith","normalized","afterPrefix","idMap","delayText","isNaN","normalizeLegacyInternalEvent","timer","currentEvent","isErr","isErrorEvent","getTransitionData","_hasEventlessTransitions","shouldSelectEventlessTransitions","maxIterations","Infinity","iterationCount","microstepCount","selectEventlessTransitions","previousState","hasEffect","evaluateTransitionFunction","enabled","triggerTransitionEffect","transitionEffectSignal","transitionEffectEnqueue","transitionTo","sourceId","transitionEffectTargets","timerIds","enabledTransitionSet","atomicStates","atomicStateNode","always","evaluateCandidate","candidate","matches","pattern","entries","is","matchesEvent","_eventMatcher","guard","guardArgs","withActorSelfAndParent","evaluation","emptySubscription","restoreHint","isRemoteActorRef","actorRef","_remote","remoteSnapshot","freeze","createRemoteActorRef","handle","address","incarnation","_syncSnapshot","send","_send","select","trigger","_isRunning","xstate$type","ACTOR_REF_TYPE","emptySnapshotRecord","compactSnapshotRecord","machineSnapshotMatches","testValue","matchesState","machineSnapshotHasTag","machineSnapshotCan","_canTransition","machineSnapshotToJSON","getMeta","getInputs","can","hasTag","jsonValues","machineSnapshotGetMeta","meta","machineSnapshotGetInputs","collectTags","createMachineSnapshot","configWithSnapshot","clonedSnapshot","serializeHistoryValue","persistContext","contextPart","copy","parentStateId","childStateId","parentStateValue","toStateValue","childStateValue","segment","previous","pathToStateValue","toArrayStrict","isDoneEvent","toTransitionConfigArray","configLike","transitionLike","toObserver","nextHandler","completionHandler","isObserver","indexStr","nodeId","invokeConfig","configSrc","partialEventTokens","split","eventTokens","tokenIndex","partialEventToken","eventToken","async","runStep","sendSelf","getStepEffect","Promise","reject","waitForStep","rejectUndeliverableEvent","runtimeTarget","isInternalEventType","getEventBoundaryError","systemIdPrefix","nextSystemId","createSystemId","crypto","globalThis","getRandomValues","Uint32Array","padStart","randomUUID","replaceAll","Date","now","random","createSystemIdPrefix","logicId","encodeAddressSegment","separator","lastIndexOf","isSafeInteger","getActorIdCounterKey","bumpActorIdCounter","counterKey","emptyScheduledTimers","createScheduledTimerId","RuntimeSystem","_children","_rootActor","_keyedActors","_reverseKeyedActors","_identity","systemId","nextSessionId","scheduler","_clock","_logger","_onRejectedEvent","onRejectedEvent","restoredSnapshot","clock","ambientInspector","getAmbientInspector","_scheduledTimers","_recordSent","_inspectionObservers","inspectionSource","_collectedSent","targetRef","targetId","schedule","existingId","_timerMap","scheduledAt","scheduledTimer","dueAt","scheduledTimerId","timeout","_deliver","clearTimeout","cancelAll","_lastSourceRef","deliverEvent","changed","inspect","observerOrFn","observer","resolvedInspectionEvent","rootId","override","stopActorLocally","_terminate","terminateActorLocally","_emit","issues","eventOrigin","runLogic","cancelAllTimers","scheduledTimers","resetScheduledTimers","scheduledId","executingCustomAction","emptyInspectionRecords","ProcessingStatus","defaultOptions","ms","console","safeCall","arg","executeExecutableEffects","Actor","_trigger","Proxy","payload","_boundSend","_sendPublic","_boundProcess","mailbox","_mailboxStarted","observers","eventListeners","_processingStatus","NotStarted","_forceDeferredActions","_collectedActions","_initialEffects","_deferred","_restored","resolvedOptions","rootActor","createRuntimeSystem","requestedId","counter","resolveActorId","persistedState","_setSnapshot","parentRef","_getLogger","_defer","_stopChild","_executeAction","Running","saveExecutingCustomAction","_setErrorSnapshot","_recoverOrError","_tryHandleExecutionError","_error","errorEvent","getExecutionErrorEvent","_next","deferred","deferredFn","_inspectTransition","sent","_flushInitialEffects","nextListenerOrObserver","errorListener","completeListener","Stopped","listeners","selector","equalityFn","selected","_stopProcedure","_complete","restored","refreshSnapshotActorRefRoot","wallClock","startedAt","min","caughtError","reportError","EMPTY_OBJECT","StateNode","path","description","schemas","after","events","ownEvents","_candidateCache","_key","_machine","firstStateKey","choice","validateStateNodeConfig","collection","iteratee","collectionKeys","mapValues","stateConfig","resolvedId","sourceName","_initialize","afterConfig","timeoutConfig","onTimeoutConfig","onTimeout","invokeDefs","fromDelaysMap","eventMatcher","delayedTransitions","eventPattern","delayedTransition","getDelayedTransitions","addTransitions","additions","transitionsConfig","mapTransitionConfigs","onDone","onError","createCancelInvokeTimeoutTransition","timeoutEventId","_args","formatInvokeCompletionTransition","rest","didEnqueue","trackingEnqueue","apply","thisArg","argArray","Reflect","prop","receiver","withInvokeMatch","invokeTimeoutEventId","invokeDoneTransitions","rawTransition","formatTransitions","validateChoiceResult","formatChoiceTransitions","_refreshEventMetadata","object","memoizedData","memo","_target","targetString","resolvedTargets","formatInitialTransition","descriptorKey","getEventDescriptorKey","candidates","transitionConfigs","assertValid","validator","request","check","findEventSchema","hasOwn","emptyCanActor","emptyCanActorScope","getEmptyCanActorScope","StateMachine","_internalEventType","snapshotSchema","eventSchema","internalEventDescriptors","_json","vendor","validate","contextSchema","resolveState","eventSchemas","internalEventSchemas","isFrameworkEvent","schema","rootStateNode","routeTransitions","collectRoutes","route","routeId","routeConfig","routeMatches","_guard","routeOptions","formatRouteTransitions","provide","provided","resolvedStateValue","usesInertScope","resolvedActorScope","fastSnapshot","_transitionFast","returnedSnapshot","_attachPureActorRef","_collectEffects","skipInitializingActor","sourceNode","stateChanged","snapshots","emptyActorScope","transitionData","_getPreInitialState","initEvent","preInitial","spawnedChildren","referencedSrc","createSpawner","withActorSelf","takeSpawnAllocationCounters","preInitialState","contextSpawnEffects","createSpawnEffect","finalizeInitialResult","macroState","initialStateNodes","collectDefaultEntryStates","other","initialMicrostep","errorMacrostep","childId","_rehydrated","fullPath","relativePath","resolvedStateId","STATE_IDENTIFIER","childrenJson","timersJson","embedChildren","embed","remote","snapshotActor","scheduled","persisted","stateInputs","snapshotMachine","persistedMachine","legacyPersistedVersion","persistedVersion","migrate","snapshotData","snapshotChildren","actorData","childState","persistedTimers","targetDescription","revivedHistoryValue","revived","arr","resolved","reviveHistoryValue","validateStateValue","missingStateError","childNode","_persistedSnapshotVersion","_nextActorId","_legacyNextActorId","persistedRest","restoredCounters","WeakSet","reviveContext","delayToMs","parsedDelay","parseFloat","normalizeScxmlEventType","toScxmlEventName","isExpression","isResolvable","isCode","toPath","extractSerializableDelays","toActionArray","validateChoiceConfig","branch","when","SCXML_SYSTEM_VARIABLES","scxmlScriptEnvironments","scxmlMachineNames","scxmlIoProcessors","scxmlEvents","scxmlEnteringStates","getScxmlIoProcessors","processors","processor","location","scxml","evaluateExpr","expr","normalizedExpr","machineName","dataContext","fnBody","declarations","Function","SCXML_ORIGIN","isExternal","_scxmlExternal","isInitEvent","explicitType","_scxmlEventType","scxmlEvent","_scxmlEventName","sendid","_scxmlSendId","origin","origintype","invokeid","_scxmlInvokeId","data","_scxmlEventData","sanitized","snap","executeScript","global","contextKeys","mutableContextKeys","varDeclarations","k","captureUpdates","codeWithoutComments","matchAll","depth","getFunctionDeclarations","codeWithoutFunctions","reduce","declaration","captureVariables","environment","createScxmlDomElement","element","tagName","getAttribute","getElementsByTagName","createMachineFromSCXMLConfig","json","resolvedSources","evaluators","mergeSources","expressionResolver","expressionLanguage","getEvaluator","lang","evaluator","evaluateResolvable","slot","resolveValue","makeScope","extra","getDurationConfig","assertResolvable","createExpressionResolver","sendCounters","resolveCondition","condition","declarativeGuard","guardImpl","makeChoiceConfig","pendingTransitionActionsMap","allTransitionActions","contextBeforeTargetless","targetlessEvent","pendingPlatformErrors","scxmlDonedataValues","resolveRouteConfig","resolvedGuard","makeDonedataOutput","iterInvokeConfigs","invokes","inv","extInv","_nestedScxmlIR","_scxmlInput","namelist","ReferenceError","param","getTransitionConfig","raiseErrorExecution","tagname","errored","executeActionDefinition","parentState","stack","definition","executeActions","isBuiltInActionJSON","resolvedEvent","finalize","scxmlAction","label","mergedContext","clonedRoot","clonedChild","_xstateScxmlInputKeys","content","eventData","processorType","eventexpr","contentValue","idlocation","nextId","generatedId","targetexpr","delayexpr","isParentTarget","childRef","sendidexpr","isLegalIdentifier","array","iterX","iterResult","blockX","blockResult","branches","condResult","cond","branchX","branchResult","getFinalizedGuardContext","finalizers","finalized","finalizer","assignAction","targetConfig","_scxml","resolveTransitionContext","resolveTransitionInput","eventDescriptors","matchesScxmlEventDescriptor","_x","_enq","assertCondition","assertAction","definitions","assertActions","assertTransition","transitionPath","assertStateNode","invokePath","assertMachineJSON","rootNodeConfig","iterNode","nodeKey","ancestorIds","originalEntryActions","_scxmlData","_scxmlInitial","_scxmlHistoryActions","acc","entryFn","ctx","transActions","mergedX","_scxmlDonedata","donedata","out","contentExpr","contentText","evaluateDonedataValue","contextConfig","_scxmlDataIds","providedGuards","scxml.cond","xstate.stateIn","normalizedId","xstate.not","inner","innerImpl","SpecialTargets","parseXml","elements","append","sanitizeStateId","normalizeElementNames","resolveResource","toScxmlXmlJSON","getContentDescriptor","mapAction","isInternal","Internal","resolvedDelay","currentCond","currentActions","parseIfElement","mapActions","textElement","el","mapped","createGuard","inMatch","notInMatch","getDataDescriptors","datamodel","resolvedSource","resourceXml","collectDataDescriptors","toStateNodeJSON","nodeJson","parentId","binding","parallel","hasInitialAttribute","transitionElement","donedataConfig","donedataElement","textEl","stateElements","transitionElements","invokeElements","onEntryElements","onExitElements","directScripts","stateElement","initialElement","internal","hasTarget","targetAttr","onEntryElement","onExitElement","invokeIndex","invokeType","nestedScxml","findEntryAssignment","onEntry","compileScxmlElement","srcexpr","assignment","assignedSource","assignedScxml","autoForwardIds","autoforward","resolvedInitial","hasExplicitInitial","scxmlJson","machineElement","stateNodeJSON","declaredData","removeStaticallyInvalidInvokes","valid","invocation","compileSCXML"],"mappings":";;;;;;;;AAQAA,OAAOC,eAAeC,EAAS,aAAc,CAAEC,OAAO,IAItDD,EAAYE,KAAG,oBACfF,EAASG,EAAG,UAEZH,EAAuBI,gBAAG,gDAC1BJ,EAAiBK,UAAG,IAAML,EAAQI,gBAAkB,cAIpDJ,EAAAM,QAAkB,IAAIC,OAAO,KAAOP,EAAQE,KAAO,KAAM,KACzDF,EAAAQ,KAAe,IAAID,OAAO,KAAOP,EAAQG,EAAI,MAAO,KACpDH,EAAAS,mBAA6B,IAAIF,OAAO,KAAOP,EAAQI,gBAAkB,KAAM,KAC/EJ,EAAAU,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/7C,MAAM,wDAGlB,MAAM45C,EACmC,SAAvCmC,EAAe33C,YAAYw1C,QAAqB,OAAS,QACrD9L,EAAO0L,GAAuBuC,EAAgBnyC,GAE9CoyC,EAAgBvC,GACpBsC,EAFiBA,EAAe33C,YAAYzL,MAAmB,iBAI/DwG,EACAy6C,EACAhwC,GAEIqyC,EAAe,IAAIp2C,IAAIioC,EAAKvsB,IAAI,EAAG3Z,QAASA,IAC5Cs0C,EAAkC71B,IACtC,GAAIA,EAAK8B,OAAQ,CACf,MACMg0B,GADU14B,MAAMkB,QAAQ0B,EAAK8B,QAAU9B,EAAK8B,OAAS,CAAC9B,EAAK8B,SAC3CzK,OAAQ0+B,IAC3BA,EAAWvK,aAAaC,UAAY,IAAI3yB,MAAOxmB,GAC9CsjD,EAAal2C,IAAIpN,KAGrB0tB,EAAK8B,OAASg0B,EAAM/6C,OAAS+6C,OAAQh9C,CACvC,CACA,IAAK,MAAM0a,KAAS3lB,OAAO0kB,OAAOyN,EAAK5I,QAAU,CAAA,GAC/Cy+B,EAA+BriC,IAKnC,OAFAqiC,EAA+BF,GAExB,IACFA,KACa,UAAZpC,GAAuB9L,EAAK1sC,OAAS,CAAEk1C,WAAYxI,QAAS3uC,KAC5D2uC,EAAK1sC,OAAS,CAAEi2C,cAAevJ,EAAKvsB,IAAI,EAAG3Z,QAASA,SAAQzI,EAEpE,0BAqBO,SACLtI,EACA+S,EAAkC,IAElC,OAAO2lC,GAnBF,SACL14C,EACA+S,EAAkC,IAGlC,OAAOyxC,GADMnD,GAAsBJ,GAASjhD,IACX+S,EACnC,CAasCyyC,CAAaxlD,EAAK+S,GACxD"}
|
|
1
|
+
{"version":3,"file":"xstate-scxml.umd.min.js","sources":["../../../node_modules/.pnpm/xmlchars@2.2.0/node_modules/xmlchars/xml/1.0/ed5.js","../../../node_modules/.pnpm/xmlchars@2.2.0/node_modules/xmlchars/xml/1.1/ed2.js","../../../node_modules/.pnpm/xmlchars@2.2.0/node_modules/xmlchars/xmlns/1.0/ed3.js","../../../node_modules/.pnpm/saxes@6.0.0/node_modules/saxes/saxes.js","../src/Mailbox.ts","../src/constants.ts","../src/eventUtils.ts","../src/reportUnhandledError.ts","../src/symbolObservable.ts","../src/actions.ts","../src/actorSource.ts","../src/actors/attached.ts","../src/actors/listener.ts","../src/actors/subscription.ts","../src/actorScope.ts","../src/transitionActions.ts","../src/delay.ts","../src/snapshotActorRef.ts","../src/getNextSnapshot.ts","../src/stateUtils.ts","../src/utils.ts","../src/remoteActorRef.ts","../src/State.ts","../src/runtimeHelpers.ts","../src/system.ts","../src/createActor.ts","../src/memo.ts","../src/StateNode.ts","../src/validation.ts","../src/StateMachine.ts","../src/spawn.ts","../src/scxml/runtime.ts","../src/createMachine.ts","../src/types.ts","../src/scxml/scxml.ts"],"sourcesContent":["\"use strict\";\n/**\n * Character classes and associated utilities for the 5th edition of XML 1.0.\n *\n * @author Louis-Dominique Dubeau\n * @license MIT\n * @copyright Louis-Dominique Dubeau\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//\n// Fragments.\n//\nexports.CHAR = \"\\t\\n\\r -\\uD7FF\\uE000-\\uFFFD\\uD800\\uDC00-\\uDBFF\\uDFFF\";\nexports.S = \" \\t\\r\\n\";\n// tslint:disable-next-line:max-line-length\nexports.NAME_START_CHAR = \":A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\uD800\\uDC00-\\uDB7F\\uDFFF\";\nexports.NAME_CHAR = \"-\" + exports.NAME_START_CHAR + \".0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040\";\n//\n// Regular expressions.\n//\nexports.CHAR_RE = new RegExp(\"^[\" + exports.CHAR + \"]$\", \"u\");\nexports.S_RE = new RegExp(\"^[\" + exports.S + \"]+$\", \"u\");\nexports.NAME_START_CHAR_RE = new RegExp(\"^[\" + exports.NAME_START_CHAR + \"]$\", \"u\");\nexports.NAME_CHAR_RE = new RegExp(\"^[\" + exports.NAME_CHAR + \"]$\", \"u\");\nexports.NAME_RE = new RegExp(\"^[\" + exports.NAME_START_CHAR + \"][\" + exports.NAME_CHAR + \"]*$\", \"u\");\nexports.NMTOKEN_RE = new RegExp(\"^[\" + exports.NAME_CHAR + \"]+$\", \"u\");\nvar TAB = 9;\nvar NL = 0xA;\nvar CR = 0xD;\nvar SPACE = 0x20;\n//\n// Lists.\n//\n/** All characters in the ``S`` production. */\nexports.S_LIST = [SPACE, NL, CR, TAB];\n/**\n * Determines whether a codepoint matches the ``CHAR`` production.\n *\n * @param c The code point.\n *\n * @returns ``true`` if the codepoint matches ``CHAR``.\n */\nfunction isChar(c) {\n return (c >= SPACE && c <= 0xD7FF) ||\n c === NL || c === CR || c === TAB ||\n (c >= 0xE000 && c <= 0xFFFD) ||\n (c >= 0x10000 && c <= 0x10FFFF);\n}\nexports.isChar = isChar;\n/**\n * Determines whether a codepoint matches the ``S`` (space) production.\n *\n * @param c The code point.\n *\n * @returns ``true`` if the codepoint matches ``S``.\n */\nfunction isS(c) {\n return c === SPACE || c === NL || c === CR || c === TAB;\n}\nexports.isS = isS;\n/**\n * Determines whether a codepoint matches the ``NAME_START_CHAR`` production.\n *\n * @param c The code point.\n *\n * @returns ``true`` if the codepoint matches ``NAME_START_CHAR``.\n */\nfunction isNameStartChar(c) {\n return ((c >= 0x41 && c <= 0x5A) ||\n (c >= 0x61 && c <= 0x7A) ||\n c === 0x3A ||\n c === 0x5F ||\n c === 0x200C ||\n c === 0x200D ||\n (c >= 0xC0 && c <= 0xD6) ||\n (c >= 0xD8 && c <= 0xF6) ||\n (c >= 0x00F8 && c <= 0x02FF) ||\n (c >= 0x0370 && c <= 0x037D) ||\n (c >= 0x037F && c <= 0x1FFF) ||\n (c >= 0x2070 && c <= 0x218F) ||\n (c >= 0x2C00 && c <= 0x2FEF) ||\n (c >= 0x3001 && c <= 0xD7FF) ||\n (c >= 0xF900 && c <= 0xFDCF) ||\n (c >= 0xFDF0 && c <= 0xFFFD) ||\n (c >= 0x10000 && c <= 0xEFFFF));\n}\nexports.isNameStartChar = isNameStartChar;\n/**\n * Determines whether a codepoint matches the ``NAME_CHAR`` production.\n *\n * @param c The code point.\n *\n * @returns ``true`` if the codepoint matches ``NAME_CHAR``.\n */\nfunction isNameChar(c) {\n return isNameStartChar(c) ||\n (c >= 0x30 && c <= 0x39) ||\n c === 0x2D ||\n c === 0x2E ||\n c === 0xB7 ||\n (c >= 0x0300 && c <= 0x036F) ||\n (c >= 0x203F && c <= 0x2040);\n}\nexports.isNameChar = isNameChar;\n//# sourceMappingURL=ed5.js.map","\"use strict\";\n/**\n * Character classes and associated utilities for the 2nd edition of XML 1.1.\n *\n * @author Louis-Dominique Dubeau\n * @license MIT\n * @copyright Louis-Dominique Dubeau\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//\n// Fragments.\n//\nexports.CHAR = \"\\u0001-\\uD7FF\\uE000-\\uFFFD\\uD800\\uDC00-\\uDBFF\\uDFFF\";\nexports.RESTRICTED_CHAR = \"\\u0001-\\u0008\\u000B\\u000C\\u000E-\\u001F\\u007F-\\u0084\\u0086-\\u009F\";\nexports.S = \" \\t\\r\\n\";\n// tslint:disable-next-line:max-line-length\nexports.NAME_START_CHAR = \":A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\uD800\\uDC00-\\uDB7F\\uDFFF\";\nexports.NAME_CHAR = \"-\" + exports.NAME_START_CHAR + \".0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040\";\n//\n// Regular expressions.\n//\nexports.CHAR_RE = new RegExp(\"^[\" + exports.CHAR + \"]$\", \"u\");\nexports.RESTRICTED_CHAR_RE = new RegExp(\"^[\" + exports.RESTRICTED_CHAR + \"]$\", \"u\");\nexports.S_RE = new RegExp(\"^[\" + exports.S + \"]+$\", \"u\");\nexports.NAME_START_CHAR_RE = new RegExp(\"^[\" + exports.NAME_START_CHAR + \"]$\", \"u\");\nexports.NAME_CHAR_RE = new RegExp(\"^[\" + exports.NAME_CHAR + \"]$\", \"u\");\nexports.NAME_RE = new RegExp(\"^[\" + exports.NAME_START_CHAR + \"][\" + exports.NAME_CHAR + \"]*$\", \"u\");\nexports.NMTOKEN_RE = new RegExp(\"^[\" + exports.NAME_CHAR + \"]+$\", \"u\");\nvar TAB = 9;\nvar NL = 0xA;\nvar CR = 0xD;\nvar SPACE = 0x20;\n//\n// Lists.\n//\n/** All characters in the ``S`` production. */\nexports.S_LIST = [SPACE, NL, CR, TAB];\n/**\n * Determines whether a codepoint matches the ``CHAR`` production.\n *\n * @param c The code point.\n *\n * @returns ``true`` if the codepoint matches ``CHAR``.\n */\nfunction isChar(c) {\n return (c >= 0x0001 && c <= 0xD7FF) ||\n (c >= 0xE000 && c <= 0xFFFD) ||\n (c >= 0x10000 && c <= 0x10FFFF);\n}\nexports.isChar = isChar;\n/**\n * Determines whether a codepoint matches the ``RESTRICTED_CHAR`` production.\n *\n * @param c The code point.\n *\n * @returns ``true`` if the codepoint matches ``RESTRICTED_CHAR``.\n */\nfunction isRestrictedChar(c) {\n return (c >= 0x1 && c <= 0x8) ||\n c === 0xB ||\n c === 0xC ||\n (c >= 0xE && c <= 0x1F) ||\n (c >= 0x7F && c <= 0x84) ||\n (c >= 0x86 && c <= 0x9F);\n}\nexports.isRestrictedChar = isRestrictedChar;\n/**\n * Determines whether a codepoint matches the ``CHAR`` production and does not\n * match the ``RESTRICTED_CHAR`` production. ``isCharAndNotRestricted(x)`` is\n * equivalent to ``isChar(x) && !isRestrictedChar(x)``. This function is faster\n * than running the two-call equivalent.\n *\n * @param c The code point.\n *\n * @returns ``true`` if the codepoint matches ``CHAR`` and does not match\n * ``RESTRICTED_CHAR``.\n */\nfunction isCharAndNotRestricted(c) {\n return (c === 0x9) ||\n (c === 0xA) ||\n (c === 0xD) ||\n (c > 0x1F && c < 0x7F) ||\n (c === 0x85) ||\n (c > 0x9F && c <= 0xD7FF) ||\n (c >= 0xE000 && c <= 0xFFFD) ||\n (c >= 0x10000 && c <= 0x10FFFF);\n}\nexports.isCharAndNotRestricted = isCharAndNotRestricted;\n/**\n * Determines whether a codepoint matches the ``S`` (space) production.\n *\n * @param c The code point.\n *\n * @returns ``true`` if the codepoint matches ``S``.\n */\nfunction isS(c) {\n return c === SPACE || c === NL || c === CR || c === TAB;\n}\nexports.isS = isS;\n/**\n * Determines whether a codepoint matches the ``NAME_START_CHAR`` production.\n *\n * @param c The code point.\n *\n * @returns ``true`` if the codepoint matches ``NAME_START_CHAR``.\n */\n// tslint:disable-next-line:cyclomatic-complexity\nfunction isNameStartChar(c) {\n return ((c >= 0x41 && c <= 0x5A) ||\n (c >= 0x61 && c <= 0x7A) ||\n c === 0x3A ||\n c === 0x5F ||\n c === 0x200C ||\n c === 0x200D ||\n (c >= 0xC0 && c <= 0xD6) ||\n (c >= 0xD8 && c <= 0xF6) ||\n (c >= 0x00F8 && c <= 0x02FF) ||\n (c >= 0x0370 && c <= 0x037D) ||\n (c >= 0x037F && c <= 0x1FFF) ||\n (c >= 0x2070 && c <= 0x218F) ||\n (c >= 0x2C00 && c <= 0x2FEF) ||\n (c >= 0x3001 && c <= 0xD7FF) ||\n (c >= 0xF900 && c <= 0xFDCF) ||\n (c >= 0xFDF0 && c <= 0xFFFD) ||\n (c >= 0x10000 && c <= 0xEFFFF));\n}\nexports.isNameStartChar = isNameStartChar;\n/**\n * Determines whether a codepoint matches the ``NAME_CHAR`` production.\n *\n * @param c The code point.\n *\n * @returns ``true`` if the codepoint matches ``NAME_CHAR``.\n */\nfunction isNameChar(c) {\n return isNameStartChar(c) ||\n (c >= 0x30 && c <= 0x39) ||\n c === 0x2D ||\n c === 0x2E ||\n c === 0xB7 ||\n (c >= 0x0300 && c <= 0x036F) ||\n (c >= 0x203F && c <= 0x2040);\n}\nexports.isNameChar = isNameChar;\n//# sourceMappingURL=ed2.js.map","\"use strict\";\n/**\n * Character class utilities for XML NS 1.0 edition 3.\n *\n * @author Louis-Dominique Dubeau\n * @license MIT\n * @copyright Louis-Dominique Dubeau\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//\n// Fragments.\n//\n// tslint:disable-next-line:max-line-length\nexports.NC_NAME_START_CHAR = \"A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\uD800\\uDC00-\\uDB7F\\uDFFF\";\nexports.NC_NAME_CHAR = \"-\" + exports.NC_NAME_START_CHAR + \".0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040\";\n//\n// Regular expressions.\n//\nexports.NC_NAME_START_CHAR_RE = new RegExp(\"^[\" + exports.NC_NAME_START_CHAR + \"]$\", \"u\");\nexports.NC_NAME_CHAR_RE = new RegExp(\"^[\" + exports.NC_NAME_CHAR + \"]$\", \"u\");\nexports.NC_NAME_RE = new RegExp(\"^[\" + exports.NC_NAME_START_CHAR + \"][\" + exports.NC_NAME_CHAR + \"]*$\", \"u\");\n/**\n * Determines whether a codepoint matches [[NC_NAME_START_CHAR]].\n *\n * @param c The code point.\n *\n * @returns ``true`` if the codepoint matches.\n */\n// tslint:disable-next-line:cyclomatic-complexity\nfunction isNCNameStartChar(c) {\n return ((c >= 0x41 && c <= 0x5A) ||\n c === 0x5F ||\n (c >= 0x61 && c <= 0x7A) ||\n (c >= 0xC0 && c <= 0xD6) ||\n (c >= 0xD8 && c <= 0xF6) ||\n (c >= 0x00F8 && c <= 0x02FF) ||\n (c >= 0x0370 && c <= 0x037D) ||\n (c >= 0x037F && c <= 0x1FFF) ||\n (c >= 0x200C && c <= 0x200D) ||\n (c >= 0x2070 && c <= 0x218F) ||\n (c >= 0x2C00 && c <= 0x2FEF) ||\n (c >= 0x3001 && c <= 0xD7FF) ||\n (c >= 0xF900 && c <= 0xFDCF) ||\n (c >= 0xFDF0 && c <= 0xFFFD) ||\n (c >= 0x10000 && c <= 0xEFFFF));\n}\nexports.isNCNameStartChar = isNCNameStartChar;\n/**\n * Determines whether a codepoint matches [[NC_NAME_CHAR]].\n *\n * @param c The code point.\n *\n * @returns ``true`` if the codepoint matches.\n */\nfunction isNCNameChar(c) {\n return isNCNameStartChar(c) ||\n (c === 0x2D ||\n c === 0x2E ||\n (c >= 0x30 && c <= 0x39) ||\n c === 0x00B7 ||\n (c >= 0x0300 && c <= 0x036F) ||\n (c >= 0x203F && c <= 0x2040));\n}\nexports.isNCNameChar = isNCNameChar;\n//# sourceMappingURL=ed3.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.SaxesParser = exports.EVENTS = void 0;\nconst ed5 = require(\"xmlchars/xml/1.0/ed5\");\nconst ed2 = require(\"xmlchars/xml/1.1/ed2\");\nconst NSed3 = require(\"xmlchars/xmlns/1.0/ed3\");\nvar isS = ed5.isS;\nvar isChar10 = ed5.isChar;\nvar isNameStartChar = ed5.isNameStartChar;\nvar isNameChar = ed5.isNameChar;\nvar S_LIST = ed5.S_LIST;\nvar NAME_RE = ed5.NAME_RE;\nvar isChar11 = ed2.isChar;\nvar isNCNameStartChar = NSed3.isNCNameStartChar;\nvar isNCNameChar = NSed3.isNCNameChar;\nvar NC_NAME_RE = NSed3.NC_NAME_RE;\nconst XML_NAMESPACE = \"http://www.w3.org/XML/1998/namespace\";\nconst XMLNS_NAMESPACE = \"http://www.w3.org/2000/xmlns/\";\nconst rootNS = {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment\n __proto__: null,\n xml: XML_NAMESPACE,\n xmlns: XMLNS_NAMESPACE,\n};\nconst XML_ENTITIES = {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment\n __proto__: null,\n amp: \"&\",\n gt: \">\",\n lt: \"<\",\n quot: \"\\\"\",\n apos: \"'\",\n};\n// EOC: end-of-chunk\nconst EOC = -1;\nconst NL_LIKE = -2;\nconst S_BEGIN = 0; // Initial state.\nconst S_BEGIN_WHITESPACE = 1; // leading whitespace\nconst S_DOCTYPE = 2; // <!DOCTYPE\nconst S_DOCTYPE_QUOTE = 3; // <!DOCTYPE \"//blah\nconst S_DTD = 4; // <!DOCTYPE \"//blah\" [ ...\nconst S_DTD_QUOTED = 5; // <!DOCTYPE \"//blah\" [ \"foo\nconst S_DTD_OPEN_WAKA = 6;\nconst S_DTD_OPEN_WAKA_BANG = 7;\nconst S_DTD_COMMENT = 8; // <!--\nconst S_DTD_COMMENT_ENDING = 9; // <!-- blah -\nconst S_DTD_COMMENT_ENDED = 10; // <!-- blah --\nconst S_DTD_PI = 11; // <?\nconst S_DTD_PI_ENDING = 12; // <?hi \"there\" ?\nconst S_TEXT = 13; // general stuff\nconst S_ENTITY = 14; // & and such\nconst S_OPEN_WAKA = 15; // <\nconst S_OPEN_WAKA_BANG = 16; // <!...\nconst S_COMMENT = 17; // <!--\nconst S_COMMENT_ENDING = 18; // <!-- blah -\nconst S_COMMENT_ENDED = 19; // <!-- blah --\nconst S_CDATA = 20; // <![CDATA[ something\nconst S_CDATA_ENDING = 21; // ]\nconst S_CDATA_ENDING_2 = 22; // ]]\nconst S_PI_FIRST_CHAR = 23; // <?hi, first char\nconst S_PI_REST = 24; // <?hi, rest of the name\nconst S_PI_BODY = 25; // <?hi there\nconst S_PI_ENDING = 26; // <?hi \"there\" ?\nconst S_XML_DECL_NAME_START = 27; // <?xml\nconst S_XML_DECL_NAME = 28; // <?xml foo\nconst S_XML_DECL_EQ = 29; // <?xml foo=\nconst S_XML_DECL_VALUE_START = 30; // <?xml foo=\nconst S_XML_DECL_VALUE = 31; // <?xml foo=\"bar\"\nconst S_XML_DECL_SEPARATOR = 32; // <?xml foo=\"bar\"\nconst S_XML_DECL_ENDING = 33; // <?xml ... ?\nconst S_OPEN_TAG = 34; // <strong\nconst S_OPEN_TAG_SLASH = 35; // <strong /\nconst S_ATTRIB = 36; // <a\nconst S_ATTRIB_NAME = 37; // <a foo\nconst S_ATTRIB_NAME_SAW_WHITE = 38; // <a foo _\nconst S_ATTRIB_VALUE = 39; // <a foo=\nconst S_ATTRIB_VALUE_QUOTED = 40; // <a foo=\"bar\nconst S_ATTRIB_VALUE_CLOSED = 41; // <a foo=\"bar\"\nconst S_ATTRIB_VALUE_UNQUOTED = 42; // <a foo=bar\nconst S_CLOSE_TAG = 43; // </a\nconst S_CLOSE_TAG_SAW_WHITE = 44; // </a >\nconst TAB = 9;\nconst NL = 0xA;\nconst CR = 0xD;\nconst SPACE = 0x20;\nconst BANG = 0x21;\nconst DQUOTE = 0x22;\nconst AMP = 0x26;\nconst SQUOTE = 0x27;\nconst MINUS = 0x2D;\nconst FORWARD_SLASH = 0x2F;\nconst SEMICOLON = 0x3B;\nconst LESS = 0x3C;\nconst EQUAL = 0x3D;\nconst GREATER = 0x3E;\nconst QUESTION = 0x3F;\nconst OPEN_BRACKET = 0x5B;\nconst CLOSE_BRACKET = 0x5D;\nconst NEL = 0x85;\nconst LS = 0x2028; // Line Separator\nconst isQuote = (c) => c === DQUOTE || c === SQUOTE;\nconst QUOTES = [DQUOTE, SQUOTE];\nconst DOCTYPE_TERMINATOR = [...QUOTES, OPEN_BRACKET, GREATER];\nconst DTD_TERMINATOR = [...QUOTES, LESS, CLOSE_BRACKET];\nconst XML_DECL_NAME_TERMINATOR = [EQUAL, QUESTION, ...S_LIST];\nconst ATTRIB_VALUE_UNQUOTED_TERMINATOR = [...S_LIST, GREATER, AMP, LESS];\nfunction nsPairCheck(parser, prefix, uri) {\n switch (prefix) {\n case \"xml\":\n if (uri !== XML_NAMESPACE) {\n parser.fail(`xml prefix must be bound to ${XML_NAMESPACE}.`);\n }\n break;\n case \"xmlns\":\n if (uri !== XMLNS_NAMESPACE) {\n parser.fail(`xmlns prefix must be bound to ${XMLNS_NAMESPACE}.`);\n }\n break;\n default:\n }\n switch (uri) {\n case XMLNS_NAMESPACE:\n parser.fail(prefix === \"\" ?\n `the default namespace may not be set to ${uri}.` :\n `may not assign a prefix (even \"xmlns\") to the URI \\\n${XMLNS_NAMESPACE}.`);\n break;\n case XML_NAMESPACE:\n switch (prefix) {\n case \"xml\":\n // Assinging the XML namespace to \"xml\" is fine.\n break;\n case \"\":\n parser.fail(`the default namespace may not be set to ${uri}.`);\n break;\n default:\n parser.fail(\"may not assign the xml namespace to another prefix.\");\n }\n break;\n default:\n }\n}\nfunction nsMappingCheck(parser, mapping) {\n for (const local of Object.keys(mapping)) {\n nsPairCheck(parser, local, mapping[local]);\n }\n}\nconst isNCName = (name) => NC_NAME_RE.test(name);\nconst isName = (name) => NAME_RE.test(name);\nconst FORBIDDEN_START = 0;\nconst FORBIDDEN_BRACKET = 1;\nconst FORBIDDEN_BRACKET_BRACKET = 2;\n/**\n * The list of supported events.\n */\nexports.EVENTS = [\n \"xmldecl\",\n \"text\",\n \"processinginstruction\",\n \"doctype\",\n \"comment\",\n \"opentagstart\",\n \"attribute\",\n \"opentag\",\n \"closetag\",\n \"cdata\",\n \"error\",\n \"end\",\n \"ready\",\n];\nconst EVENT_NAME_TO_HANDLER_NAME = {\n xmldecl: \"xmldeclHandler\",\n text: \"textHandler\",\n processinginstruction: \"piHandler\",\n doctype: \"doctypeHandler\",\n comment: \"commentHandler\",\n opentagstart: \"openTagStartHandler\",\n attribute: \"attributeHandler\",\n opentag: \"openTagHandler\",\n closetag: \"closeTagHandler\",\n cdata: \"cdataHandler\",\n error: \"errorHandler\",\n end: \"endHandler\",\n ready: \"readyHandler\",\n};\n// eslint-disable-next-line @typescript-eslint/ban-types\nclass SaxesParser {\n /**\n * @param opt The parser options.\n */\n constructor(opt) {\n this.opt = opt !== null && opt !== void 0 ? opt : {};\n this.fragmentOpt = !!this.opt.fragment;\n const xmlnsOpt = this.xmlnsOpt = !!this.opt.xmlns;\n this.trackPosition = this.opt.position !== false;\n this.fileName = this.opt.fileName;\n if (xmlnsOpt) {\n // This is the function we use to perform name checks on PIs and entities.\n // When namespaces are used, colons are not allowed in PI target names or\n // entity names. So the check depends on whether namespaces are used. See:\n //\n // https://www.w3.org/XML/xml-names-19990114-errata.html\n // NE08\n //\n this.nameStartCheck = isNCNameStartChar;\n this.nameCheck = isNCNameChar;\n this.isName = isNCName;\n // eslint-disable-next-line @typescript-eslint/unbound-method\n this.processAttribs = this.processAttribsNS;\n // eslint-disable-next-line @typescript-eslint/unbound-method\n this.pushAttrib = this.pushAttribNS;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment\n this.ns = Object.assign({ __proto__: null }, rootNS);\n const additional = this.opt.additionalNamespaces;\n if (additional != null) {\n nsMappingCheck(this, additional);\n Object.assign(this.ns, additional);\n }\n }\n else {\n this.nameStartCheck = isNameStartChar;\n this.nameCheck = isNameChar;\n this.isName = isName;\n // eslint-disable-next-line @typescript-eslint/unbound-method\n this.processAttribs = this.processAttribsPlain;\n // eslint-disable-next-line @typescript-eslint/unbound-method\n this.pushAttrib = this.pushAttribPlain;\n }\n //\n // The order of the members in this table needs to correspond to the state\n // numbers given to the states that correspond to the methods being recorded\n // here.\n //\n this.stateTable = [\n /* eslint-disable @typescript-eslint/unbound-method */\n this.sBegin,\n this.sBeginWhitespace,\n this.sDoctype,\n this.sDoctypeQuote,\n this.sDTD,\n this.sDTDQuoted,\n this.sDTDOpenWaka,\n this.sDTDOpenWakaBang,\n this.sDTDComment,\n this.sDTDCommentEnding,\n this.sDTDCommentEnded,\n this.sDTDPI,\n this.sDTDPIEnding,\n this.sText,\n this.sEntity,\n this.sOpenWaka,\n this.sOpenWakaBang,\n this.sComment,\n this.sCommentEnding,\n this.sCommentEnded,\n this.sCData,\n this.sCDataEnding,\n this.sCDataEnding2,\n this.sPIFirstChar,\n this.sPIRest,\n this.sPIBody,\n this.sPIEnding,\n this.sXMLDeclNameStart,\n this.sXMLDeclName,\n this.sXMLDeclEq,\n this.sXMLDeclValueStart,\n this.sXMLDeclValue,\n this.sXMLDeclSeparator,\n this.sXMLDeclEnding,\n this.sOpenTag,\n this.sOpenTagSlash,\n this.sAttrib,\n this.sAttribName,\n this.sAttribNameSawWhite,\n this.sAttribValue,\n this.sAttribValueQuoted,\n this.sAttribValueClosed,\n this.sAttribValueUnquoted,\n this.sCloseTag,\n this.sCloseTagSawWhite,\n /* eslint-enable @typescript-eslint/unbound-method */\n ];\n this._init();\n }\n /**\n * Indicates whether or not the parser is closed. If ``true``, wait for\n * the ``ready`` event to write again.\n */\n get closed() {\n return this._closed;\n }\n _init() {\n var _a;\n this.openWakaBang = \"\";\n this.text = \"\";\n this.name = \"\";\n this.piTarget = \"\";\n this.entity = \"\";\n this.q = null;\n this.tags = [];\n this.tag = null;\n this.topNS = null;\n this.chunk = \"\";\n this.chunkPosition = 0;\n this.i = 0;\n this.prevI = 0;\n this.carriedFromPrevious = undefined;\n this.forbiddenState = FORBIDDEN_START;\n this.attribList = [];\n // The logic is organized so as to minimize the need to check\n // this.opt.fragment while parsing.\n const { fragmentOpt } = this;\n this.state = fragmentOpt ? S_TEXT : S_BEGIN;\n // We want these to be all true if we are dealing with a fragment.\n this.reportedTextBeforeRoot = this.reportedTextAfterRoot = this.closedRoot =\n this.sawRoot = fragmentOpt;\n // An XML declaration is intially possible only when parsing whole\n // documents.\n this.xmlDeclPossible = !fragmentOpt;\n this.xmlDeclExpects = [\"version\"];\n this.entityReturnState = undefined;\n let { defaultXMLVersion } = this.opt;\n if (defaultXMLVersion === undefined) {\n if (this.opt.forceXMLVersion === true) {\n throw new Error(\"forceXMLVersion set but defaultXMLVersion is not set\");\n }\n defaultXMLVersion = \"1.0\";\n }\n this.setXMLVersion(defaultXMLVersion);\n this.positionAtNewLine = 0;\n this.doctype = false;\n this._closed = false;\n this.xmlDecl = {\n version: undefined,\n encoding: undefined,\n standalone: undefined,\n };\n this.line = 1;\n this.column = 0;\n this.ENTITIES = Object.create(XML_ENTITIES);\n (_a = this.readyHandler) === null || _a === void 0 ? void 0 : _a.call(this);\n }\n /**\n * The stream position the parser is currently looking at. This field is\n * zero-based.\n *\n * This field is not based on counting Unicode characters but is to be\n * interpreted as a plain index into a JavaScript string.\n */\n get position() {\n return this.chunkPosition + this.i;\n }\n /**\n * The column number of the next character to be read by the parser. *\n * This field is zero-based. (The first column in a line is 0.)\n *\n * This field reports the index at which the next character would be in the\n * line if the line were represented as a JavaScript string. Note that this\n * *can* be different to a count based on the number of *Unicode characters*\n * due to how JavaScript handles astral plane characters.\n *\n * See [[column]] for a number that corresponds to a count of Unicode\n * characters.\n */\n get columnIndex() {\n return this.position - this.positionAtNewLine;\n }\n /**\n * Set an event listener on an event. The parser supports one handler per\n * event type. If you try to set an event handler over an existing handler,\n * the old handler is silently overwritten.\n *\n * @param name The event to listen to.\n *\n * @param handler The handler to set.\n */\n on(name, handler) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access\n this[EVENT_NAME_TO_HANDLER_NAME[name]] = handler;\n }\n /**\n * Unset an event handler.\n *\n * @parma name The event to stop listening to.\n */\n off(name) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access\n this[EVENT_NAME_TO_HANDLER_NAME[name]] = undefined;\n }\n /**\n * Make an error object. The error object will have a message that contains\n * the ``fileName`` option passed at the creation of the parser. If position\n * tracking was turned on, it will also have line and column number\n * information.\n *\n * @param message The message describing the error to report.\n *\n * @returns An error object with a properly formatted message.\n */\n makeError(message) {\n var _a;\n let msg = (_a = this.fileName) !== null && _a !== void 0 ? _a : \"\";\n if (this.trackPosition) {\n if (msg.length > 0) {\n msg += \":\";\n }\n msg += `${this.line}:${this.column}`;\n }\n if (msg.length > 0) {\n msg += \": \";\n }\n return new Error(msg + message);\n }\n /**\n * Report a parsing error. This method is made public so that client code may\n * check for issues that are outside the scope of this project and can report\n * errors.\n *\n * @param message The error to report.\n *\n * @returns this\n */\n fail(message) {\n const err = this.makeError(message);\n const handler = this.errorHandler;\n if (handler === undefined) {\n throw err;\n }\n else {\n handler(err);\n }\n return this;\n }\n /**\n * Write a XML data to the parser.\n *\n * @param chunk The XML data to write.\n *\n * @returns this\n */\n // We do need object for the type here. Yes, it often causes problems\n // but not in this case.\n write(chunk) {\n if (this.closed) {\n return this.fail(\"cannot write after close; assign an onready handler.\");\n }\n let end = false;\n if (chunk === null) {\n // We cannot return immediately because carriedFromPrevious may need\n // processing.\n end = true;\n chunk = \"\";\n }\n else if (typeof chunk === \"object\") {\n chunk = chunk.toString();\n }\n // We checked if performing a pre-decomposition of the string into an array\n // of single complete characters (``Array.from(chunk)``) would be faster\n // than the current repeated calls to ``charCodeAt``. As of August 2018, it\n // isn't. (There may be Node-specific code that would perform faster than\n // ``Array.from`` but don't want to be dependent on Node.)\n if (this.carriedFromPrevious !== undefined) {\n // The previous chunk had char we must carry over.\n chunk = `${this.carriedFromPrevious}${chunk}`;\n this.carriedFromPrevious = undefined;\n }\n let limit = chunk.length;\n const lastCode = chunk.charCodeAt(limit - 1);\n if (!end &&\n // A trailing CR or surrogate must be carried over to the next\n // chunk.\n (lastCode === CR || (lastCode >= 0xD800 && lastCode <= 0xDBFF))) {\n // The chunk ends with a character that must be carried over. We cannot\n // know how to handle it until we get the next chunk or the end of the\n // stream. So save it for later.\n this.carriedFromPrevious = chunk[limit - 1];\n limit--;\n chunk = chunk.slice(0, limit);\n }\n const { stateTable } = this;\n this.chunk = chunk;\n this.i = 0;\n while (this.i < limit) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument\n stateTable[this.state].call(this);\n }\n this.chunkPosition += limit;\n return end ? this.end() : this;\n }\n /**\n * Close the current stream. Perform final well-formedness checks and reset\n * the parser tstate.\n *\n * @returns this\n */\n close() {\n return this.write(null);\n }\n /**\n * Get a single code point out of the current chunk. This updates the current\n * position if we do position tracking.\n *\n * This is the algorithm to use for XML 1.0.\n *\n * @returns The character read.\n */\n getCode10() {\n const { chunk, i } = this;\n this.prevI = i;\n // Yes, we do this instead of doing this.i++. Doing it this way, we do not\n // read this.i again, which is a bit faster.\n this.i = i + 1;\n if (i >= chunk.length) {\n return EOC;\n }\n // Using charCodeAt and handling the surrogates ourselves is faster\n // than using codePointAt.\n const code = chunk.charCodeAt(i);\n this.column++;\n if (code < 0xD800) {\n if (code >= SPACE || code === TAB) {\n return code;\n }\n switch (code) {\n case NL:\n this.line++;\n this.column = 0;\n this.positionAtNewLine = this.position;\n return NL;\n case CR:\n // We may get NaN if we read past the end of the chunk, which is fine.\n if (chunk.charCodeAt(i + 1) === NL) {\n // A \\r\\n sequence is converted to \\n so we have to skip over the\n // next character. We already know it has a size of 1 so ++ is fine\n // here.\n this.i = i + 2;\n }\n // Otherwise, a \\r is just converted to \\n, so we don't have to skip\n // ahead.\n // In either case, \\r becomes \\n.\n this.line++;\n this.column = 0;\n this.positionAtNewLine = this.position;\n return NL_LIKE;\n default:\n // If we get here, then code < SPACE and it is not NL CR or TAB.\n this.fail(\"disallowed character.\");\n return code;\n }\n }\n if (code > 0xDBFF) {\n // This is a specialized version of isChar10 that takes into account\n // that in this context code > 0xDBFF and code <= 0xFFFF. So it does not\n // test cases that don't need testing.\n if (!(code >= 0xE000 && code <= 0xFFFD)) {\n this.fail(\"disallowed character.\");\n }\n return code;\n }\n const final = 0x10000 + ((code - 0xD800) * 0x400) +\n (chunk.charCodeAt(i + 1) - 0xDC00);\n this.i = i + 2;\n // This is a specialized version of isChar10 that takes into account that in\n // this context necessarily final >= 0x10000.\n if (final > 0x10FFFF) {\n this.fail(\"disallowed character.\");\n }\n return final;\n }\n /**\n * Get a single code point out of the current chunk. This updates the current\n * position if we do position tracking.\n *\n * This is the algorithm to use for XML 1.1.\n *\n * @returns {number} The character read.\n */\n getCode11() {\n const { chunk, i } = this;\n this.prevI = i;\n // Yes, we do this instead of doing this.i++. Doing it this way, we do not\n // read this.i again, which is a bit faster.\n this.i = i + 1;\n if (i >= chunk.length) {\n return EOC;\n }\n // Using charCodeAt and handling the surrogates ourselves is faster\n // than using codePointAt.\n const code = chunk.charCodeAt(i);\n this.column++;\n if (code < 0xD800) {\n if ((code > 0x1F && code < 0x7F) || (code > 0x9F && code !== LS) ||\n code === TAB) {\n return code;\n }\n switch (code) {\n case NL: // 0xA\n this.line++;\n this.column = 0;\n this.positionAtNewLine = this.position;\n return NL;\n case CR: { // 0xD\n // We may get NaN if we read past the end of the chunk, which is\n // fine.\n const next = chunk.charCodeAt(i + 1);\n if (next === NL || next === NEL) {\n // A CR NL or CR NEL sequence is converted to NL so we have to skip\n // over the next character. We already know it has a size of 1.\n this.i = i + 2;\n }\n // Otherwise, a CR is just converted to NL, no skip.\n }\n /* yes, fall through */\n case NEL: // 0x85\n case LS: // Ox2028\n this.line++;\n this.column = 0;\n this.positionAtNewLine = this.position;\n return NL_LIKE;\n default:\n this.fail(\"disallowed character.\");\n return code;\n }\n }\n if (code > 0xDBFF) {\n // This is a specialized version of isCharAndNotRestricted that takes into\n // account that in this context code > 0xDBFF and code <= 0xFFFF. So it\n // does not test cases that don't need testing.\n if (!(code >= 0xE000 && code <= 0xFFFD)) {\n this.fail(\"disallowed character.\");\n }\n return code;\n }\n const final = 0x10000 + ((code - 0xD800) * 0x400) +\n (chunk.charCodeAt(i + 1) - 0xDC00);\n this.i = i + 2;\n // This is a specialized version of isCharAndNotRestricted that takes into\n // account that in this context necessarily final >= 0x10000.\n if (final > 0x10FFFF) {\n this.fail(\"disallowed character.\");\n }\n return final;\n }\n /**\n * Like ``getCode`` but with the return value normalized so that ``NL`` is\n * returned for ``NL_LIKE``.\n */\n getCodeNorm() {\n const c = this.getCode();\n return c === NL_LIKE ? NL : c;\n }\n unget() {\n this.i = this.prevI;\n this.column--;\n }\n /**\n * Capture characters into a buffer until encountering one of a set of\n * characters.\n *\n * @param chars An array of codepoints. Encountering a character in the array\n * ends the capture. (``chars`` may safely contain ``NL``.)\n *\n * @return The character code that made the capture end, or ``EOC`` if we hit\n * the end of the chunk. The return value cannot be NL_LIKE: NL is returned\n * instead.\n */\n captureTo(chars) {\n let { i: start } = this;\n const { chunk } = this;\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const c = this.getCode();\n const isNLLike = c === NL_LIKE;\n const final = isNLLike ? NL : c;\n if (final === EOC || chars.includes(final)) {\n this.text += chunk.slice(start, this.prevI);\n return final;\n }\n if (isNLLike) {\n this.text += `${chunk.slice(start, this.prevI)}\\n`;\n start = this.i;\n }\n }\n }\n /**\n * Capture characters into a buffer until encountering a character.\n *\n * @param char The codepoint that ends the capture. **NOTE ``char`` MAY NOT\n * CONTAIN ``NL``.** Passing ``NL`` will result in buggy behavior.\n *\n * @return ``true`` if we ran into the character. Otherwise, we ran into the\n * end of the current chunk.\n */\n captureToChar(char) {\n let { i: start } = this;\n const { chunk } = this;\n // eslint-disable-next-line no-constant-condition\n while (true) {\n let c = this.getCode();\n switch (c) {\n case NL_LIKE:\n this.text += `${chunk.slice(start, this.prevI)}\\n`;\n start = this.i;\n c = NL;\n break;\n case EOC:\n this.text += chunk.slice(start);\n return false;\n default:\n }\n if (c === char) {\n this.text += chunk.slice(start, this.prevI);\n return true;\n }\n }\n }\n /**\n * Capture characters that satisfy ``isNameChar`` into the ``name`` field of\n * this parser.\n *\n * @return The character code that made the test fail, or ``EOC`` if we hit\n * the end of the chunk. The return value cannot be NL_LIKE: NL is returned\n * instead.\n */\n captureNameChars() {\n const { chunk, i: start } = this;\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const c = this.getCode();\n if (c === EOC) {\n this.name += chunk.slice(start);\n return EOC;\n }\n // NL is not a name char so we don't have to test specifically for it.\n if (!isNameChar(c)) {\n this.name += chunk.slice(start, this.prevI);\n return c === NL_LIKE ? NL : c;\n }\n }\n }\n /**\n * Skip white spaces.\n *\n * @return The character that ended the skip, or ``EOC`` if we hit\n * the end of the chunk. The return value cannot be NL_LIKE: NL is returned\n * instead.\n */\n skipSpaces() {\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const c = this.getCodeNorm();\n if (c === EOC || !isS(c)) {\n return c;\n }\n }\n }\n setXMLVersion(version) {\n this.currentXMLVersion = version;\n /* eslint-disable @typescript-eslint/unbound-method */\n if (version === \"1.0\") {\n this.isChar = isChar10;\n this.getCode = this.getCode10;\n }\n else {\n this.isChar = isChar11;\n this.getCode = this.getCode11;\n }\n /* eslint-enable @typescript-eslint/unbound-method */\n }\n // STATE ENGINE METHODS\n // This needs to be a state separate from S_BEGIN_WHITESPACE because we want\n // to be sure never to come back to this state later.\n sBegin() {\n // We are essentially peeking at the first character of the chunk. Since\n // S_BEGIN can be in effect only when we start working on the first chunk,\n // the index at which we must look is necessarily 0. Note also that the\n // following test does not depend on decoding surrogates.\n // If the initial character is 0xFEFF, ignore it.\n if (this.chunk.charCodeAt(0) === 0xFEFF) {\n this.i++;\n this.column++;\n }\n this.state = S_BEGIN_WHITESPACE;\n }\n sBeginWhitespace() {\n // We need to know whether we've encountered spaces or not because as soon\n // as we run into a space, an XML declaration is no longer possible. Rather\n // than slow down skipSpaces even in places where we don't care whether it\n // skipped anything or not, we check whether prevI is equal to the value of\n // i from before we skip spaces.\n const iBefore = this.i;\n const c = this.skipSpaces();\n if (this.prevI !== iBefore) {\n this.xmlDeclPossible = false;\n }\n switch (c) {\n case LESS:\n this.state = S_OPEN_WAKA;\n // We could naively call closeText but in this state, it is not normal\n // to have text be filled with any data.\n if (this.text.length !== 0) {\n throw new Error(\"no-empty text at start\");\n }\n break;\n case EOC:\n break;\n default:\n this.unget();\n this.state = S_TEXT;\n this.xmlDeclPossible = false;\n }\n }\n sDoctype() {\n var _a;\n const c = this.captureTo(DOCTYPE_TERMINATOR);\n switch (c) {\n case GREATER: {\n (_a = this.doctypeHandler) === null || _a === void 0 ? void 0 : _a.call(this, this.text);\n this.text = \"\";\n this.state = S_TEXT;\n this.doctype = true; // just remember that we saw it.\n break;\n }\n case EOC:\n break;\n default:\n this.text += String.fromCodePoint(c);\n if (c === OPEN_BRACKET) {\n this.state = S_DTD;\n }\n else if (isQuote(c)) {\n this.state = S_DOCTYPE_QUOTE;\n this.q = c;\n }\n }\n }\n sDoctypeQuote() {\n const q = this.q;\n if (this.captureToChar(q)) {\n this.text += String.fromCodePoint(q);\n this.q = null;\n this.state = S_DOCTYPE;\n }\n }\n sDTD() {\n const c = this.captureTo(DTD_TERMINATOR);\n if (c === EOC) {\n return;\n }\n this.text += String.fromCodePoint(c);\n if (c === CLOSE_BRACKET) {\n this.state = S_DOCTYPE;\n }\n else if (c === LESS) {\n this.state = S_DTD_OPEN_WAKA;\n }\n else if (isQuote(c)) {\n this.state = S_DTD_QUOTED;\n this.q = c;\n }\n }\n sDTDQuoted() {\n const q = this.q;\n if (this.captureToChar(q)) {\n this.text += String.fromCodePoint(q);\n this.state = S_DTD;\n this.q = null;\n }\n }\n sDTDOpenWaka() {\n const c = this.getCodeNorm();\n this.text += String.fromCodePoint(c);\n switch (c) {\n case BANG:\n this.state = S_DTD_OPEN_WAKA_BANG;\n this.openWakaBang = \"\";\n break;\n case QUESTION:\n this.state = S_DTD_PI;\n break;\n default:\n this.state = S_DTD;\n }\n }\n sDTDOpenWakaBang() {\n const char = String.fromCodePoint(this.getCodeNorm());\n const owb = this.openWakaBang += char;\n this.text += char;\n if (owb !== \"-\") {\n this.state = owb === \"--\" ? S_DTD_COMMENT : S_DTD;\n this.openWakaBang = \"\";\n }\n }\n sDTDComment() {\n if (this.captureToChar(MINUS)) {\n this.text += \"-\";\n this.state = S_DTD_COMMENT_ENDING;\n }\n }\n sDTDCommentEnding() {\n const c = this.getCodeNorm();\n this.text += String.fromCodePoint(c);\n this.state = c === MINUS ? S_DTD_COMMENT_ENDED : S_DTD_COMMENT;\n }\n sDTDCommentEnded() {\n const c = this.getCodeNorm();\n this.text += String.fromCodePoint(c);\n if (c === GREATER) {\n this.state = S_DTD;\n }\n else {\n this.fail(\"malformed comment.\");\n // <!-- blah -- bloo --> will be recorded as\n // a comment of \" blah -- bloo \"\n this.state = S_DTD_COMMENT;\n }\n }\n sDTDPI() {\n if (this.captureToChar(QUESTION)) {\n this.text += \"?\";\n this.state = S_DTD_PI_ENDING;\n }\n }\n sDTDPIEnding() {\n const c = this.getCodeNorm();\n this.text += String.fromCodePoint(c);\n if (c === GREATER) {\n this.state = S_DTD;\n }\n }\n sText() {\n //\n // We did try a version of saxes where the S_TEXT state was split in two\n // states: one for text inside the root element, and one for text\n // outside. This was avoiding having to test this.tags.length to decide\n // what implementation to actually use.\n //\n // Peformance testing on gigabyte-size files did not show any advantage to\n // using the two states solution instead of the current one. Conversely, it\n // made the code a bit more complicated elsewhere. For instance, a comment\n // can appear before the root element so when a comment ended it was\n // necessary to determine whether to return to the S_TEXT state or to the\n // new text-outside-root state.\n //\n if (this.tags.length !== 0) {\n this.handleTextInRoot();\n }\n else {\n this.handleTextOutsideRoot();\n }\n }\n sEntity() {\n // This is essentially a specialized version of captureToChar(SEMICOLON...)\n let { i: start } = this;\n const { chunk } = this;\n // eslint-disable-next-line no-labels, no-restricted-syntax\n loop: \n // eslint-disable-next-line no-constant-condition\n while (true) {\n switch (this.getCode()) {\n case NL_LIKE:\n this.entity += `${chunk.slice(start, this.prevI)}\\n`;\n start = this.i;\n break;\n case SEMICOLON: {\n const { entityReturnState } = this;\n const entity = this.entity + chunk.slice(start, this.prevI);\n this.state = entityReturnState;\n let parsed;\n if (entity === \"\") {\n this.fail(\"empty entity name.\");\n parsed = \"&;\";\n }\n else {\n parsed = this.parseEntity(entity);\n this.entity = \"\";\n }\n if (entityReturnState !== S_TEXT || this.textHandler !== undefined) {\n this.text += parsed;\n }\n // eslint-disable-next-line no-labels\n break loop;\n }\n case EOC:\n this.entity += chunk.slice(start);\n // eslint-disable-next-line no-labels\n break loop;\n default:\n }\n }\n }\n sOpenWaka() {\n // Reminder: a state handler is called with at least one character\n // available in the current chunk. So the first call to get code inside of\n // a state handler cannot return ``EOC``. That's why we don't test\n // for it.\n const c = this.getCode();\n // either a /, ?, !, or text is coming next.\n if (isNameStartChar(c)) {\n this.state = S_OPEN_TAG;\n this.unget();\n this.xmlDeclPossible = false;\n }\n else {\n switch (c) {\n case FORWARD_SLASH:\n this.state = S_CLOSE_TAG;\n this.xmlDeclPossible = false;\n break;\n case BANG:\n this.state = S_OPEN_WAKA_BANG;\n this.openWakaBang = \"\";\n this.xmlDeclPossible = false;\n break;\n case QUESTION:\n this.state = S_PI_FIRST_CHAR;\n break;\n default:\n this.fail(\"disallowed character in tag name\");\n this.state = S_TEXT;\n this.xmlDeclPossible = false;\n }\n }\n }\n sOpenWakaBang() {\n this.openWakaBang += String.fromCodePoint(this.getCodeNorm());\n switch (this.openWakaBang) {\n case \"[CDATA[\":\n if (!this.sawRoot && !this.reportedTextBeforeRoot) {\n this.fail(\"text data outside of root node.\");\n this.reportedTextBeforeRoot = true;\n }\n if (this.closedRoot && !this.reportedTextAfterRoot) {\n this.fail(\"text data outside of root node.\");\n this.reportedTextAfterRoot = true;\n }\n this.state = S_CDATA;\n this.openWakaBang = \"\";\n break;\n case \"--\":\n this.state = S_COMMENT;\n this.openWakaBang = \"\";\n break;\n case \"DOCTYPE\":\n this.state = S_DOCTYPE;\n if (this.doctype || this.sawRoot) {\n this.fail(\"inappropriately located doctype declaration.\");\n }\n this.openWakaBang = \"\";\n break;\n default:\n // 7 happens to be the maximum length of the string that can possibly\n // match one of the cases above.\n if (this.openWakaBang.length >= 7) {\n this.fail(\"incorrect syntax.\");\n }\n }\n }\n sComment() {\n if (this.captureToChar(MINUS)) {\n this.state = S_COMMENT_ENDING;\n }\n }\n sCommentEnding() {\n var _a;\n const c = this.getCodeNorm();\n if (c === MINUS) {\n this.state = S_COMMENT_ENDED;\n (_a = this.commentHandler) === null || _a === void 0 ? void 0 : _a.call(this, this.text);\n this.text = \"\";\n }\n else {\n this.text += `-${String.fromCodePoint(c)}`;\n this.state = S_COMMENT;\n }\n }\n sCommentEnded() {\n const c = this.getCodeNorm();\n if (c !== GREATER) {\n this.fail(\"malformed comment.\");\n // <!-- blah -- bloo --> will be recorded as\n // a comment of \" blah -- bloo \"\n this.text += `--${String.fromCodePoint(c)}`;\n this.state = S_COMMENT;\n }\n else {\n this.state = S_TEXT;\n }\n }\n sCData() {\n if (this.captureToChar(CLOSE_BRACKET)) {\n this.state = S_CDATA_ENDING;\n }\n }\n sCDataEnding() {\n const c = this.getCodeNorm();\n if (c === CLOSE_BRACKET) {\n this.state = S_CDATA_ENDING_2;\n }\n else {\n this.text += `]${String.fromCodePoint(c)}`;\n this.state = S_CDATA;\n }\n }\n sCDataEnding2() {\n var _a;\n const c = this.getCodeNorm();\n switch (c) {\n case GREATER: {\n (_a = this.cdataHandler) === null || _a === void 0 ? void 0 : _a.call(this, this.text);\n this.text = \"\";\n this.state = S_TEXT;\n break;\n }\n case CLOSE_BRACKET:\n this.text += \"]\";\n break;\n default:\n this.text += `]]${String.fromCodePoint(c)}`;\n this.state = S_CDATA;\n }\n }\n // We need this separate state to check the first character fo the pi target\n // with this.nameStartCheck which allows less characters than this.nameCheck.\n sPIFirstChar() {\n const c = this.getCodeNorm();\n // This is first because in the case where the file is well-formed this is\n // the branch taken. We optimize for well-formedness.\n if (this.nameStartCheck(c)) {\n this.piTarget += String.fromCodePoint(c);\n this.state = S_PI_REST;\n }\n else if (c === QUESTION || isS(c)) {\n this.fail(\"processing instruction without a target.\");\n this.state = c === QUESTION ? S_PI_ENDING : S_PI_BODY;\n }\n else {\n this.fail(\"disallowed character in processing instruction name.\");\n this.piTarget += String.fromCodePoint(c);\n this.state = S_PI_REST;\n }\n }\n sPIRest() {\n // Capture characters into a piTarget while ``this.nameCheck`` run on the\n // character read returns true.\n const { chunk, i: start } = this;\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const c = this.getCodeNorm();\n if (c === EOC) {\n this.piTarget += chunk.slice(start);\n return;\n }\n // NL cannot satisfy this.nameCheck so we don't have to test specifically\n // for it.\n if (!this.nameCheck(c)) {\n this.piTarget += chunk.slice(start, this.prevI);\n const isQuestion = c === QUESTION;\n if (isQuestion || isS(c)) {\n if (this.piTarget === \"xml\") {\n if (!this.xmlDeclPossible) {\n this.fail(\"an XML declaration must be at the start of the document.\");\n }\n this.state = isQuestion ? S_XML_DECL_ENDING : S_XML_DECL_NAME_START;\n }\n else {\n this.state = isQuestion ? S_PI_ENDING : S_PI_BODY;\n }\n }\n else {\n this.fail(\"disallowed character in processing instruction name.\");\n this.piTarget += String.fromCodePoint(c);\n }\n break;\n }\n }\n }\n sPIBody() {\n if (this.text.length === 0) {\n const c = this.getCodeNorm();\n if (c === QUESTION) {\n this.state = S_PI_ENDING;\n }\n else if (!isS(c)) {\n this.text = String.fromCodePoint(c);\n }\n }\n // The question mark character is not valid inside any of the XML\n // declaration name/value pairs.\n else if (this.captureToChar(QUESTION)) {\n this.state = S_PI_ENDING;\n }\n }\n sPIEnding() {\n var _a;\n const c = this.getCodeNorm();\n if (c === GREATER) {\n const { piTarget } = this;\n if (piTarget.toLowerCase() === \"xml\") {\n this.fail(\"the XML declaration must appear at the start of the document.\");\n }\n (_a = this.piHandler) === null || _a === void 0 ? void 0 : _a.call(this, {\n target: piTarget,\n body: this.text,\n });\n this.piTarget = this.text = \"\";\n this.state = S_TEXT;\n }\n else if (c === QUESTION) {\n // We ran into ?? as part of a processing instruction. We initially took\n // the first ? as a sign that the PI was ending, but it is not. So we have\n // to add it to the body but we take the new ? as a sign that the PI is\n // ending.\n this.text += \"?\";\n }\n else {\n this.text += `?${String.fromCodePoint(c)}`;\n this.state = S_PI_BODY;\n }\n this.xmlDeclPossible = false;\n }\n sXMLDeclNameStart() {\n const c = this.skipSpaces();\n // The question mark character is not valid inside any of the XML\n // declaration name/value pairs.\n if (c === QUESTION) {\n // It is valid to go to S_XML_DECL_ENDING from this state.\n this.state = S_XML_DECL_ENDING;\n return;\n }\n if (c !== EOC) {\n this.state = S_XML_DECL_NAME;\n this.name = String.fromCodePoint(c);\n }\n }\n sXMLDeclName() {\n const c = this.captureTo(XML_DECL_NAME_TERMINATOR);\n // The question mark character is not valid inside any of the XML\n // declaration name/value pairs.\n if (c === QUESTION) {\n this.state = S_XML_DECL_ENDING;\n this.name += this.text;\n this.text = \"\";\n this.fail(\"XML declaration is incomplete.\");\n return;\n }\n if (!(isS(c) || c === EQUAL)) {\n return;\n }\n this.name += this.text;\n this.text = \"\";\n if (!this.xmlDeclExpects.includes(this.name)) {\n switch (this.name.length) {\n case 0:\n this.fail(\"did not expect any more name/value pairs.\");\n break;\n case 1:\n this.fail(`expected the name ${this.xmlDeclExpects[0]}.`);\n break;\n default:\n this.fail(`expected one of ${this.xmlDeclExpects.join(\", \")}`);\n }\n }\n this.state = c === EQUAL ? S_XML_DECL_VALUE_START : S_XML_DECL_EQ;\n }\n sXMLDeclEq() {\n const c = this.getCodeNorm();\n // The question mark character is not valid inside any of the XML\n // declaration name/value pairs.\n if (c === QUESTION) {\n this.state = S_XML_DECL_ENDING;\n this.fail(\"XML declaration is incomplete.\");\n return;\n }\n if (isS(c)) {\n return;\n }\n if (c !== EQUAL) {\n this.fail(\"value required.\");\n }\n this.state = S_XML_DECL_VALUE_START;\n }\n sXMLDeclValueStart() {\n const c = this.getCodeNorm();\n // The question mark character is not valid inside any of the XML\n // declaration name/value pairs.\n if (c === QUESTION) {\n this.state = S_XML_DECL_ENDING;\n this.fail(\"XML declaration is incomplete.\");\n return;\n }\n if (isS(c)) {\n return;\n }\n if (!isQuote(c)) {\n this.fail(\"value must be quoted.\");\n this.q = SPACE;\n }\n else {\n this.q = c;\n }\n this.state = S_XML_DECL_VALUE;\n }\n sXMLDeclValue() {\n const c = this.captureTo([this.q, QUESTION]);\n // The question mark character is not valid inside any of the XML\n // declaration name/value pairs.\n if (c === QUESTION) {\n this.state = S_XML_DECL_ENDING;\n this.text = \"\";\n this.fail(\"XML declaration is incomplete.\");\n return;\n }\n if (c === EOC) {\n return;\n }\n const value = this.text;\n this.text = \"\";\n switch (this.name) {\n case \"version\": {\n this.xmlDeclExpects = [\"encoding\", \"standalone\"];\n const version = value;\n this.xmlDecl.version = version;\n // This is the test specified by XML 1.0 but it is fine for XML 1.1.\n if (!/^1\\.[0-9]+$/.test(version)) {\n this.fail(\"version number must match /^1\\\\.[0-9]+$/.\");\n }\n // When forceXMLVersion is set, the XML declaration is ignored.\n else if (!this.opt.forceXMLVersion) {\n this.setXMLVersion(version);\n }\n break;\n }\n case \"encoding\":\n if (!/^[A-Za-z][A-Za-z0-9._-]*$/.test(value)) {\n this.fail(\"encoding value must match \\\n/^[A-Za-z0-9][A-Za-z0-9._-]*$/.\");\n }\n this.xmlDeclExpects = [\"standalone\"];\n this.xmlDecl.encoding = value;\n break;\n case \"standalone\":\n if (value !== \"yes\" && value !== \"no\") {\n this.fail(\"standalone value must match \\\"yes\\\" or \\\"no\\\".\");\n }\n this.xmlDeclExpects = [];\n this.xmlDecl.standalone = value;\n break;\n default:\n // We don't need to raise an error here since we've already raised one\n // when checking what name was expected.\n }\n this.name = \"\";\n this.state = S_XML_DECL_SEPARATOR;\n }\n sXMLDeclSeparator() {\n const c = this.getCodeNorm();\n // The question mark character is not valid inside any of the XML\n // declaration name/value pairs.\n if (c === QUESTION) {\n // It is valid to go to S_XML_DECL_ENDING from this state.\n this.state = S_XML_DECL_ENDING;\n return;\n }\n if (!isS(c)) {\n this.fail(\"whitespace required.\");\n this.unget();\n }\n this.state = S_XML_DECL_NAME_START;\n }\n sXMLDeclEnding() {\n var _a;\n const c = this.getCodeNorm();\n if (c === GREATER) {\n if (this.piTarget !== \"xml\") {\n this.fail(\"processing instructions are not allowed before root.\");\n }\n else if (this.name !== \"version\" &&\n this.xmlDeclExpects.includes(\"version\")) {\n this.fail(\"XML declaration must contain a version.\");\n }\n (_a = this.xmldeclHandler) === null || _a === void 0 ? void 0 : _a.call(this, this.xmlDecl);\n this.name = \"\";\n this.piTarget = this.text = \"\";\n this.state = S_TEXT;\n }\n else {\n // We got here because the previous character was a ?, but the question\n // mark character is not valid inside any of the XML declaration\n // name/value pairs.\n this.fail(\"The character ? is disallowed anywhere in XML declarations.\");\n }\n this.xmlDeclPossible = false;\n }\n sOpenTag() {\n var _a;\n const c = this.captureNameChars();\n if (c === EOC) {\n return;\n }\n const tag = this.tag = {\n name: this.name,\n attributes: Object.create(null),\n };\n this.name = \"\";\n if (this.xmlnsOpt) {\n this.topNS = tag.ns = Object.create(null);\n }\n (_a = this.openTagStartHandler) === null || _a === void 0 ? void 0 : _a.call(this, tag);\n this.sawRoot = true;\n if (!this.fragmentOpt && this.closedRoot) {\n this.fail(\"documents may contain only one root.\");\n }\n switch (c) {\n case GREATER:\n this.openTag();\n break;\n case FORWARD_SLASH:\n this.state = S_OPEN_TAG_SLASH;\n break;\n default:\n if (!isS(c)) {\n this.fail(\"disallowed character in tag name.\");\n }\n this.state = S_ATTRIB;\n }\n }\n sOpenTagSlash() {\n if (this.getCode() === GREATER) {\n this.openSelfClosingTag();\n }\n else {\n this.fail(\"forward-slash in opening tag not followed by >.\");\n this.state = S_ATTRIB;\n }\n }\n sAttrib() {\n const c = this.skipSpaces();\n if (c === EOC) {\n return;\n }\n if (isNameStartChar(c)) {\n this.unget();\n this.state = S_ATTRIB_NAME;\n }\n else if (c === GREATER) {\n this.openTag();\n }\n else if (c === FORWARD_SLASH) {\n this.state = S_OPEN_TAG_SLASH;\n }\n else {\n this.fail(\"disallowed character in attribute name.\");\n }\n }\n sAttribName() {\n const c = this.captureNameChars();\n if (c === EQUAL) {\n this.state = S_ATTRIB_VALUE;\n }\n else if (isS(c)) {\n this.state = S_ATTRIB_NAME_SAW_WHITE;\n }\n else if (c === GREATER) {\n this.fail(\"attribute without value.\");\n this.pushAttrib(this.name, this.name);\n this.name = this.text = \"\";\n this.openTag();\n }\n else if (c !== EOC) {\n this.fail(\"disallowed character in attribute name.\");\n }\n }\n sAttribNameSawWhite() {\n const c = this.skipSpaces();\n switch (c) {\n case EOC:\n return;\n case EQUAL:\n this.state = S_ATTRIB_VALUE;\n break;\n default:\n this.fail(\"attribute without value.\");\n // Should we do this???\n // this.tag.attributes[this.name] = \"\";\n this.text = \"\";\n this.name = \"\";\n if (c === GREATER) {\n this.openTag();\n }\n else if (isNameStartChar(c)) {\n this.unget();\n this.state = S_ATTRIB_NAME;\n }\n else {\n this.fail(\"disallowed character in attribute name.\");\n this.state = S_ATTRIB;\n }\n }\n }\n sAttribValue() {\n const c = this.getCodeNorm();\n if (isQuote(c)) {\n this.q = c;\n this.state = S_ATTRIB_VALUE_QUOTED;\n }\n else if (!isS(c)) {\n this.fail(\"unquoted attribute value.\");\n this.state = S_ATTRIB_VALUE_UNQUOTED;\n this.unget();\n }\n }\n sAttribValueQuoted() {\n // We deliberately do not use captureTo here. The specialized code we use\n // here is faster than using captureTo.\n const { q, chunk } = this;\n let { i: start } = this;\n // eslint-disable-next-line no-constant-condition\n while (true) {\n switch (this.getCode()) {\n case q:\n this.pushAttrib(this.name, this.text + chunk.slice(start, this.prevI));\n this.name = this.text = \"\";\n this.q = null;\n this.state = S_ATTRIB_VALUE_CLOSED;\n return;\n case AMP:\n this.text += chunk.slice(start, this.prevI);\n this.state = S_ENTITY;\n this.entityReturnState = S_ATTRIB_VALUE_QUOTED;\n return;\n case NL:\n case NL_LIKE:\n case TAB:\n this.text += `${chunk.slice(start, this.prevI)} `;\n start = this.i;\n break;\n case LESS:\n this.text += chunk.slice(start, this.prevI);\n this.fail(\"disallowed character.\");\n return;\n case EOC:\n this.text += chunk.slice(start);\n return;\n default:\n }\n }\n }\n sAttribValueClosed() {\n const c = this.getCodeNorm();\n if (isS(c)) {\n this.state = S_ATTRIB;\n }\n else if (c === GREATER) {\n this.openTag();\n }\n else if (c === FORWARD_SLASH) {\n this.state = S_OPEN_TAG_SLASH;\n }\n else if (isNameStartChar(c)) {\n this.fail(\"no whitespace between attributes.\");\n this.unget();\n this.state = S_ATTRIB_NAME;\n }\n else {\n this.fail(\"disallowed character in attribute name.\");\n }\n }\n sAttribValueUnquoted() {\n // We don't do anything regarding EOL or space handling for unquoted\n // attributes. We already have failed by the time we get here, and the\n // contract that saxes upholds states that upon failure, it is not safe to\n // rely on the data passed to event handlers (other than\n // ``onerror``). Passing \"bad\" data is not a problem.\n const c = this.captureTo(ATTRIB_VALUE_UNQUOTED_TERMINATOR);\n switch (c) {\n case AMP:\n this.state = S_ENTITY;\n this.entityReturnState = S_ATTRIB_VALUE_UNQUOTED;\n break;\n case LESS:\n this.fail(\"disallowed character.\");\n break;\n case EOC:\n break;\n default:\n if (this.text.includes(\"]]>\")) {\n this.fail(\"the string \\\"]]>\\\" is disallowed in char data.\");\n }\n this.pushAttrib(this.name, this.text);\n this.name = this.text = \"\";\n if (c === GREATER) {\n this.openTag();\n }\n else {\n this.state = S_ATTRIB;\n }\n }\n }\n sCloseTag() {\n const c = this.captureNameChars();\n if (c === GREATER) {\n this.closeTag();\n }\n else if (isS(c)) {\n this.state = S_CLOSE_TAG_SAW_WHITE;\n }\n else if (c !== EOC) {\n this.fail(\"disallowed character in closing tag.\");\n }\n }\n sCloseTagSawWhite() {\n switch (this.skipSpaces()) {\n case GREATER:\n this.closeTag();\n break;\n case EOC:\n break;\n default:\n this.fail(\"disallowed character in closing tag.\");\n }\n }\n // END OF STATE ENGINE METHODS\n handleTextInRoot() {\n // This is essentially a specialized version of captureTo which is optimized\n // for performing the ]]> check. A previous version of this code, checked\n // ``this.text`` for the presence of ]]>. It simplified the code but was\n // very costly when character data contained a lot of entities to be parsed.\n //\n // Since we are using a specialized loop, we also keep track of the presence\n // of ]]> in text data. The sequence ]]> is forbidden to appear as-is.\n //\n let { i: start, forbiddenState } = this;\n const { chunk, textHandler: handler } = this;\n // eslint-disable-next-line no-labels, no-restricted-syntax\n scanLoop: \n // eslint-disable-next-line no-constant-condition\n while (true) {\n switch (this.getCode()) {\n case LESS: {\n this.state = S_OPEN_WAKA;\n if (handler !== undefined) {\n const { text } = this;\n const slice = chunk.slice(start, this.prevI);\n if (text.length !== 0) {\n handler(text + slice);\n this.text = \"\";\n }\n else if (slice.length !== 0) {\n handler(slice);\n }\n }\n forbiddenState = FORBIDDEN_START;\n // eslint-disable-next-line no-labels\n break scanLoop;\n }\n case AMP:\n this.state = S_ENTITY;\n this.entityReturnState = S_TEXT;\n if (handler !== undefined) {\n this.text += chunk.slice(start, this.prevI);\n }\n forbiddenState = FORBIDDEN_START;\n // eslint-disable-next-line no-labels\n break scanLoop;\n case CLOSE_BRACKET:\n switch (forbiddenState) {\n case FORBIDDEN_START:\n forbiddenState = FORBIDDEN_BRACKET;\n break;\n case FORBIDDEN_BRACKET:\n forbiddenState = FORBIDDEN_BRACKET_BRACKET;\n break;\n case FORBIDDEN_BRACKET_BRACKET:\n break;\n default:\n throw new Error(\"impossible state\");\n }\n break;\n case GREATER:\n if (forbiddenState === FORBIDDEN_BRACKET_BRACKET) {\n this.fail(\"the string \\\"]]>\\\" is disallowed in char data.\");\n }\n forbiddenState = FORBIDDEN_START;\n break;\n case NL_LIKE:\n if (handler !== undefined) {\n this.text += `${chunk.slice(start, this.prevI)}\\n`;\n }\n start = this.i;\n forbiddenState = FORBIDDEN_START;\n break;\n case EOC:\n if (handler !== undefined) {\n this.text += chunk.slice(start);\n }\n // eslint-disable-next-line no-labels\n break scanLoop;\n default:\n forbiddenState = FORBIDDEN_START;\n }\n }\n this.forbiddenState = forbiddenState;\n }\n handleTextOutsideRoot() {\n // This is essentially a specialized version of captureTo which is optimized\n // for a specialized task. We keep track of the presence of non-space\n // characters in the text since these are errors when appearing outside the\n // document root element.\n let { i: start } = this;\n const { chunk, textHandler: handler } = this;\n let nonSpace = false;\n // eslint-disable-next-line no-labels, no-restricted-syntax\n outRootLoop: \n // eslint-disable-next-line no-constant-condition\n while (true) {\n const code = this.getCode();\n switch (code) {\n case LESS: {\n this.state = S_OPEN_WAKA;\n if (handler !== undefined) {\n const { text } = this;\n const slice = chunk.slice(start, this.prevI);\n if (text.length !== 0) {\n handler(text + slice);\n this.text = \"\";\n }\n else if (slice.length !== 0) {\n handler(slice);\n }\n }\n // eslint-disable-next-line no-labels\n break outRootLoop;\n }\n case AMP:\n this.state = S_ENTITY;\n this.entityReturnState = S_TEXT;\n if (handler !== undefined) {\n this.text += chunk.slice(start, this.prevI);\n }\n nonSpace = true;\n // eslint-disable-next-line no-labels\n break outRootLoop;\n case NL_LIKE:\n if (handler !== undefined) {\n this.text += `${chunk.slice(start, this.prevI)}\\n`;\n }\n start = this.i;\n break;\n case EOC:\n if (handler !== undefined) {\n this.text += chunk.slice(start);\n }\n // eslint-disable-next-line no-labels\n break outRootLoop;\n default:\n if (!isS(code)) {\n nonSpace = true;\n }\n }\n }\n if (!nonSpace) {\n return;\n }\n // We use the reportedTextBeforeRoot and reportedTextAfterRoot flags\n // to avoid reporting errors for every single character that is out of\n // place.\n if (!this.sawRoot && !this.reportedTextBeforeRoot) {\n this.fail(\"text data outside of root node.\");\n this.reportedTextBeforeRoot = true;\n }\n if (this.closedRoot && !this.reportedTextAfterRoot) {\n this.fail(\"text data outside of root node.\");\n this.reportedTextAfterRoot = true;\n }\n }\n pushAttribNS(name, value) {\n var _a;\n const { prefix, local } = this.qname(name);\n const attr = { name, prefix, local, value };\n this.attribList.push(attr);\n (_a = this.attributeHandler) === null || _a === void 0 ? void 0 : _a.call(this, attr);\n if (prefix === \"xmlns\") {\n const trimmed = value.trim();\n if (this.currentXMLVersion === \"1.0\" && trimmed === \"\") {\n this.fail(\"invalid attempt to undefine prefix in XML 1.0\");\n }\n this.topNS[local] = trimmed;\n nsPairCheck(this, local, trimmed);\n }\n else if (name === \"xmlns\") {\n const trimmed = value.trim();\n this.topNS[\"\"] = trimmed;\n nsPairCheck(this, \"\", trimmed);\n }\n }\n pushAttribPlain(name, value) {\n var _a;\n const attr = { name, value };\n this.attribList.push(attr);\n (_a = this.attributeHandler) === null || _a === void 0 ? void 0 : _a.call(this, attr);\n }\n /**\n * End parsing. This performs final well-formedness checks and resets the\n * parser to a clean state.\n *\n * @returns this\n */\n end() {\n var _a, _b;\n if (!this.sawRoot) {\n this.fail(\"document must contain a root element.\");\n }\n const { tags } = this;\n while (tags.length > 0) {\n const tag = tags.pop();\n this.fail(`unclosed tag: ${tag.name}`);\n }\n if ((this.state !== S_BEGIN) && (this.state !== S_TEXT)) {\n this.fail(\"unexpected end.\");\n }\n const { text } = this;\n if (text.length !== 0) {\n (_a = this.textHandler) === null || _a === void 0 ? void 0 : _a.call(this, text);\n this.text = \"\";\n }\n this._closed = true;\n (_b = this.endHandler) === null || _b === void 0 ? void 0 : _b.call(this);\n this._init();\n return this;\n }\n /**\n * Resolve a namespace prefix.\n *\n * @param prefix The prefix to resolve.\n *\n * @returns The namespace URI or ``undefined`` if the prefix is not defined.\n */\n resolve(prefix) {\n var _a, _b;\n let uri = this.topNS[prefix];\n if (uri !== undefined) {\n return uri;\n }\n const { tags } = this;\n for (let index = tags.length - 1; index >= 0; index--) {\n uri = tags[index].ns[prefix];\n if (uri !== undefined) {\n return uri;\n }\n }\n uri = this.ns[prefix];\n if (uri !== undefined) {\n return uri;\n }\n return (_b = (_a = this.opt).resolvePrefix) === null || _b === void 0 ? void 0 : _b.call(_a, prefix);\n }\n /**\n * Parse a qname into its prefix and local name parts.\n *\n * @param name The name to parse\n *\n * @returns\n */\n qname(name) {\n // This is faster than using name.split(\":\").\n const colon = name.indexOf(\":\");\n if (colon === -1) {\n return { prefix: \"\", local: name };\n }\n const local = name.slice(colon + 1);\n const prefix = name.slice(0, colon);\n if (prefix === \"\" || local === \"\" || local.includes(\":\")) {\n this.fail(`malformed name: ${name}.`);\n }\n return { prefix, local };\n }\n processAttribsNS() {\n var _a;\n const { attribList } = this;\n const tag = this.tag;\n {\n // add namespace info to tag\n const { prefix, local } = this.qname(tag.name);\n tag.prefix = prefix;\n tag.local = local;\n const uri = tag.uri = (_a = this.resolve(prefix)) !== null && _a !== void 0 ? _a : \"\";\n if (prefix !== \"\") {\n if (prefix === \"xmlns\") {\n this.fail(\"tags may not have \\\"xmlns\\\" as prefix.\");\n }\n if (uri === \"\") {\n this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`);\n tag.uri = prefix;\n }\n }\n }\n if (attribList.length === 0) {\n return;\n }\n const { attributes } = tag;\n const seen = new Set();\n // Note: do not apply default ns to attributes:\n // http://www.w3.org/TR/REC-xml-names/#defaulting\n for (const attr of attribList) {\n const { name, prefix, local } = attr;\n let uri;\n let eqname;\n if (prefix === \"\") {\n uri = name === \"xmlns\" ? XMLNS_NAMESPACE : \"\";\n eqname = name;\n }\n else {\n uri = this.resolve(prefix);\n // if there's any attributes with an undefined namespace,\n // then fail on them now.\n if (uri === undefined) {\n this.fail(`unbound namespace prefix: ${JSON.stringify(prefix)}.`);\n uri = prefix;\n }\n eqname = `{${uri}}${local}`;\n }\n if (seen.has(eqname)) {\n this.fail(`duplicate attribute: ${eqname}.`);\n }\n seen.add(eqname);\n attr.uri = uri;\n attributes[name] = attr;\n }\n this.attribList = [];\n }\n processAttribsPlain() {\n const { attribList } = this;\n // eslint-disable-next-line prefer-destructuring\n const attributes = this.tag.attributes;\n for (const { name, value } of attribList) {\n if (attributes[name] !== undefined) {\n this.fail(`duplicate attribute: ${name}.`);\n }\n attributes[name] = value;\n }\n this.attribList = [];\n }\n /**\n * Handle a complete open tag. This parser code calls this once it has seen\n * the whole tag. This method checks for well-formeness and then emits\n * ``onopentag``.\n */\n openTag() {\n var _a;\n this.processAttribs();\n const { tags } = this;\n const tag = this.tag;\n tag.isSelfClosing = false;\n // There cannot be any pending text here due to the onopentagstart that was\n // necessarily emitted before we get here. So we do not check text.\n (_a = this.openTagHandler) === null || _a === void 0 ? void 0 : _a.call(this, tag);\n tags.push(tag);\n this.state = S_TEXT;\n this.name = \"\";\n }\n /**\n * Handle a complete self-closing tag. This parser code calls this once it has\n * seen the whole tag. This method checks for well-formeness and then emits\n * ``onopentag`` and ``onclosetag``.\n */\n openSelfClosingTag() {\n var _a, _b, _c;\n this.processAttribs();\n const { tags } = this;\n const tag = this.tag;\n tag.isSelfClosing = true;\n // There cannot be any pending text here due to the onopentagstart that was\n // necessarily emitted before we get here. So we do not check text.\n (_a = this.openTagHandler) === null || _a === void 0 ? void 0 : _a.call(this, tag);\n (_b = this.closeTagHandler) === null || _b === void 0 ? void 0 : _b.call(this, tag);\n const top = this.tag = (_c = tags[tags.length - 1]) !== null && _c !== void 0 ? _c : null;\n if (top === null) {\n this.closedRoot = true;\n }\n this.state = S_TEXT;\n this.name = \"\";\n }\n /**\n * Handle a complete close tag. This parser code calls this once it has seen\n * the whole tag. This method checks for well-formeness and then emits\n * ``onclosetag``.\n */\n closeTag() {\n const { tags, name } = this;\n // Our state after this will be S_TEXT, no matter what, and we can clear\n // tagName now.\n this.state = S_TEXT;\n this.name = \"\";\n if (name === \"\") {\n this.fail(\"weird empty close tag.\");\n this.text += \"</>\";\n return;\n }\n const handler = this.closeTagHandler;\n let l = tags.length;\n while (l-- > 0) {\n const tag = this.tag = tags.pop();\n this.topNS = tag.ns;\n handler === null || handler === void 0 ? void 0 : handler(tag);\n if (tag.name === name) {\n break;\n }\n this.fail(\"unexpected close tag.\");\n }\n if (l === 0) {\n this.closedRoot = true;\n }\n else if (l < 0) {\n this.fail(`unmatched closing tag: ${name}.`);\n this.text += `</${name}>`;\n }\n }\n /**\n * Resolves an entity. Makes any necessary well-formedness checks.\n *\n * @param entity The entity to resolve.\n *\n * @returns The parsed entity.\n */\n parseEntity(entity) {\n // startsWith would be significantly slower for this test.\n if (entity[0] !== \"#\") {\n const defined = this.ENTITIES[entity];\n if (defined !== undefined) {\n return defined;\n }\n this.fail(this.isName(entity) ? \"undefined entity.\" :\n \"disallowed character in entity name.\");\n return `&${entity};`;\n }\n let num = NaN;\n if (entity[1] === \"x\" && /^#x[0-9a-f]+$/i.test(entity)) {\n num = parseInt(entity.slice(2), 16);\n }\n else if (/^#[0-9]+$/.test(entity)) {\n num = parseInt(entity.slice(1), 10);\n }\n // The character reference is required to match the CHAR production.\n if (!this.isChar(num)) {\n this.fail(\"malformed character entity.\");\n return `&${entity};`;\n }\n return String.fromCodePoint(num);\n }\n}\nexports.SaxesParser = SaxesParser;\n//# sourceMappingURL=saxes.js.map","interface MailboxItem<T> {\n value: T;\n next: MailboxItem<T> | null;\n}\n\nexport class Mailbox<T> {\n private _active: boolean = false;\n private _current: MailboxItem<T> | null = null;\n private _last: MailboxItem<T> | null = null;\n\n constructor(private _process: (ev: T) => void) {}\n\n public start() {\n this._active = true;\n this.flush();\n }\n\n public clear(): void {\n // we can't set _current to null because we might be currently processing\n // and enqueue following clear shouldn't start processing the enqueued item immediately\n if (this._current) {\n this._current.next = null;\n this._last = this._current;\n }\n }\n\n public enqueue(event: T): void {\n const enqueued = {\n value: event,\n next: null\n };\n\n if (this._current) {\n this._last!.next = enqueued;\n this._last = enqueued;\n return;\n }\n\n this._current = enqueued;\n this._last = enqueued;\n\n if (this._active) {\n this.flush();\n }\n }\n\n private flush() {\n while (this._current) {\n // atm the given _process is responsible for implementing proper try/catch handling\n // we assume here that this won't throw in a way that can affect this mailbox\n const consumed = this._current;\n this._process(consumed.value);\n this._current = consumed.next;\n }\n this._last = null;\n }\n}\n","export const STATE_DELIMITER = '.';\nexport const TARGETLESS_KEY = '';\nexport const NULL_EVENT = '';\nexport const STATE_IDENTIFIER = '#';\nexport const WILDCARD = '*';\nexport const XSTATE_INIT = '@xstate.init';\nexport const XSTATE_START = '@xstate.start';\nexport const XSTATE_SPAWN = '@xstate.spawn';\nexport const XSTATE_STOP = '@xstate.stop';\nexport const XSTATE_TERMINATE = '@xstate.terminate';\nexport const XSTATE_TIMER = 'xstate.timer';\n\nexport const XSTATE_LOGIC_EFFECT_RESOLVE = 'xstate.logic.effect.resolve';\nexport const XSTATE_LOGIC_EFFECT_REJECT = 'xstate.logic.effect.reject';\nexport const XSTATE_LOGIC_EFFECT_START = 'xstate.logic.effect.start';\n","import { XSTATE_INIT } from './constants.ts';\nimport {\n ActorTimeoutEvent,\n AfterEvent,\n DoneActorEvent,\n DoneStateEvent,\n ErrorActorEvent,\n ErrorPlatformEvent,\n TimeoutEvent\n} from './types.ts';\n\n/**\n * Returns an event that represents an implicit event that is sent after the\n * specified `delay`.\n *\n * @param delayRef The delay in milliseconds\n * @param id The state node ID where this event is handled\n */\nexport function createAfterEvent(\n delayRef: number | string,\n id: string\n): AfterEvent {\n return { type: 'xstate.after', delay: delayRef, stateId: id };\n}\n\nexport function createAfterEventId(delayRef: number | string, id: string) {\n return `xstate.after.${delayRef}.${id}`;\n}\n\n/**\n * Returns an event that represents an implicit state-level timeout. Fired when\n * a state's `timeout` duration elapses without the state being exited.\n *\n * @param id The state node ID where this timeout is configured\n */\nexport function createTimeoutEvent(id: string): TimeoutEvent {\n return { type: 'xstate.timeout', stateId: id };\n}\n\nexport function createTimeoutEventId(id: string) {\n return `xstate.timeout.${id}`;\n}\n\n/**\n * Returns an event that represents an implicit invoke-level timeout. Fired when\n * an invoked actor has not completed within its `timeout` duration.\n *\n * @param invokeId The invoked actor's ID\n */\nexport function createInvokeTimeoutEvent(\n invokeId: string,\n sessionId?: string\n): ActorTimeoutEvent {\n return {\n type: 'xstate.timeout.actor',\n actorId: invokeId,\n sessionId\n };\n}\n\nexport function createInvokeTimeoutEventId(invokeId: string) {\n return `xstate.timeout.actor.${invokeId}`;\n}\n\n/**\n * Returns an event that represents that a final state node has been reached in\n * the parent state node.\n *\n * @param id The final state node's parent state node `id`\n * @param output The data to pass into the event\n */\nexport function createDoneStateEvent(\n id: string,\n output?: unknown\n): DoneStateEvent {\n return {\n type: 'xstate.done.state',\n stateId: id,\n output\n };\n}\n\n/**\n * Returns an event that represents that an invoked service has terminated.\n *\n * An invoked service is terminated when it has reached a top-level final state\n * node, but not when it is canceled.\n *\n * @param invokeId The invoked service ID\n * @param output The data to pass into the event\n * @param sessionId The unique session ID of the completed actor\n */\nexport function createDoneActorEvent(\n invokeId: string,\n output: unknown,\n sessionId: string\n): DoneActorEvent {\n return {\n type: 'xstate.done.actor',\n output,\n actorId: invokeId,\n sessionId\n };\n}\n\nexport function createErrorActorEvent(\n id: string,\n error: unknown,\n sessionId: string\n): ErrorActorEvent {\n return {\n type: 'xstate.error.actor',\n error,\n actorId: id,\n sessionId\n };\n}\n\nexport function createErrorPlatformEvent(\n kind: string,\n error?: unknown\n): ErrorPlatformEvent {\n return { type: `xstate.error.${kind}`, error };\n}\n\nexport function createInitEvent(input: unknown) {\n return { type: XSTATE_INIT, input } as const;\n}\n","/**\n * This function makes sure that unhandled errors are thrown in a separate\n * macrotask. It allows those errors to be detected by global error handlers and\n * reported to bug tracking services without interrupting our own stack of\n * execution.\n *\n * @param err Error to be thrown\n */\nexport function reportUnhandledError(err: unknown) {\n setTimeout(() => {\n throw err;\n });\n}\n","export const symbolObservable: typeof Symbol.observable = (() =>\n (typeof Symbol === 'function' && Symbol.observable) ||\n '@@observable')() as any;\n","import isDevelopment from '#is-development';\nimport {\n type ActorTermination,\n AnyActor,\n AnyActorScope,\n EventObject\n} from './types';\n\nexport function assertSendToEvent(event: EventObject): void {\n if (typeof event === 'string') {\n throw new Error(\n isDevelopment\n ? // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n `Only event objects may be used with sendTo; use sendTo({ type: \"${event}\" }) instead`\n : `Only event objects may be used with sendTo`\n );\n }\n}\n\nexport const builtInActions = {\n // Actor refs are created while resolving the next snapshot. Starting is a\n // separate deferred effect so the returned list remains execution-complete.\n ['@xstate.spawn']: (actor: AnyActor) => {\n return actor.system.spawnActor(actor._parent, actor);\n },\n ['@xstate.start']: (actor: AnyActor) => {\n return actor.system.startActor(actor);\n },\n ['@xstate.raise']: (\n actorScope: AnyActorScope,\n _event: EventObject,\n options: { id?: string; delay?: number }\n ) => {\n return actorScope.system.scheduleTimer(\n actorScope.self,\n options.id!,\n options?.delay ?? 0\n );\n },\n ['@xstate.sendTo']: (\n actorScope: AnyActorScope,\n actor: AnyActor,\n event: EventObject,\n options: { id?: string; delay?: number }\n ) => {\n assertSendToEvent(event);\n if (options?.delay !== undefined) {\n return actorScope.system.scheduleTimer(\n actorScope.self,\n options.id!,\n options?.delay ?? 0\n );\n } else {\n return actorScope.system._relay(actorScope.self, actor, event);\n }\n },\n ['@xstate.cancel']: (actorScope: AnyActorScope, sendId: string) => {\n return actorScope.system.cancelTimer(actorScope.self, sendId);\n },\n ['@xstate.stop']: (actorScope: AnyActorScope, actor: AnyActor) => {\n return actorScope.system.stopActor(actor);\n },\n ['@xstate.terminate']: (actor: AnyActor, termination: ActorTermination) => {\n return actor.system.terminateActor(actor, termination);\n }\n};\n","import type { AnyActorLogic } from './types.ts';\n\nconst sourceKeyCaches = new WeakMap<object, Map<AnyActorLogic, string>>();\n\n/** @internal */\nexport function resolveRegisteredActorSource(\n actors: Record<string, AnyActorLogic>,\n logic: AnyActorLogic\n): string | undefined {\n let cache = sourceKeyCaches.get(actors);\n if (!cache) {\n cache = new Map();\n for (const key of Object.keys(actors)) {\n const registeredLogic = actors[key];\n // Several source keys may intentionally share one implementation. The\n // first key is its canonical persistence identity when spawning by the\n // raw logic value, which cannot retain which alias was used to access it.\n if (!cache.has(registeredLogic)) {\n cache.set(registeredLogic, key);\n }\n }\n sourceKeyCaches.set(actors, cache);\n }\n\n return cache.get(logic);\n}\n","import { XSTATE_STOP } from '../constants.ts';\nimport type { AnyActorSystem } from '../system.ts';\nimport type {\n AnyActor,\n EventObject,\n Snapshot,\n Subscription\n} from '../types.ts';\n\nconst subscriptions = /* #__PURE__ */ new WeakMap<AnyActor, Subscription>();\n\n/**\n * Internal factory for actor logic that attaches to another actor on start\n * (`enq.listen()` / `enq.subscribeTo()`) and detaches when stopped.\n */\nexport function createAttachedLogic(\n attach: (\n input: any,\n scope: { self: AnyActor; system: AnyActorSystem }\n ) => Subscription | undefined,\n /**\n * Names the logic so its generated actor ids get their own prefix, out of\n * the id space that user sources allocate from.\n */\n id?: string\n): any {\n const initialTransition = (input: unknown, _: unknown) =>\n [\n {\n status: 'active',\n output: undefined,\n error: undefined,\n input\n },\n []\n ] as const;\n\n return {\n id,\n start: (state: any, { self, system }: any) => {\n // Don't attach if the target doesn't exist or is stopped.\n const target = state.input.actor;\n if (!target || target.getSnapshot().status === 'stopped') {\n return;\n }\n const subscription = attach(state.input, { self, system });\n if (!subscription) {\n return;\n }\n\n // Attached actors are not registered as children (their `input` holds\n // non-serializable function mappers), so a parent stop does not cascade\n // to them. Subscribe to the parent and tear down when it stops/errors,\n // so the subscription never relays to a stopped parent or leaks the\n // source subscription.\n let parentSubscription: Subscription | undefined;\n let torndown = false;\n const teardown = () => {\n if (torndown) {\n return;\n }\n torndown = true;\n subscription.unsubscribe();\n parentSubscription?.unsubscribe();\n };\n\n const parent: AnyActor | undefined = self._parent;\n if (parent) {\n parentSubscription = parent.subscribe({\n complete: teardown,\n error: teardown\n });\n }\n\n subscriptions.set(self, { unsubscribe: teardown });\n },\n transition: (state: any, event: EventObject, { self }: any) => {\n if (event.type === XSTATE_STOP) {\n subscriptions.get(self)?.unsubscribe();\n subscriptions.delete(self);\n return [\n {\n ...state,\n status: 'stopped',\n error: undefined\n },\n []\n ];\n }\n return [state, []];\n },\n initialTransition,\n getInitialSnapshot: (actorScope: unknown, input: unknown) =>\n initialTransition(input, actorScope)[0],\n getPersistedSnapshot: (snapshot: Snapshot<unknown>) => snapshot,\n restoreSnapshot: (snapshot: Snapshot<unknown>) => snapshot\n };\n}\n\n/**\n * Relays a mapped event to the attached actor's parent, unless the attached\n * actor has been stopped (the mapper is not called in that case).\n */\nexport function relayMappedToParent(\n self: AnyActor,\n system: AnyActorSystem,\n getEvent: () => EventObject\n): void {\n if (self.getSnapshot().status === 'stopped' || !self._parent) {\n return;\n }\n system._relay(self, self._parent, getEvent());\n}\n","import { AnyActorSystem } from '../system.ts';\nimport { matchesEventDescriptor } from '../utils.ts';\nimport {\n ActorLogic,\n ActorRefFromLogic,\n AnyActor,\n EventObject,\n Snapshot\n} from '../types';\nimport { createAttachedLogic, relayMappedToParent } from './attached.ts';\n\nexport type ListenerSnapshot = Snapshot<undefined> & {\n input: ListenerInput<any, any>;\n};\n\nexport interface ListenerInput<\n TEmitted extends EventObject,\n TMappedEvent extends EventObject\n> {\n actor: AnyActor;\n eventType: string;\n mapper: (event: TEmitted) => TMappedEvent;\n}\n\nexport type ListenerActorLogic<\n TEmitted extends EventObject = EventObject,\n TMappedEvent extends EventObject = EventObject\n> = ActorLogic<\n ListenerSnapshot,\n EventObject,\n ListenerInput<TEmitted, TMappedEvent>,\n AnyActorSystem,\n EventObject\n>;\n\nexport type ListenerActorRef<\n TEmitted extends EventObject = EventObject,\n TMappedEvent extends EventObject = EventObject\n> = ActorRefFromLogic<ListenerActorLogic<TEmitted, TMappedEvent>>;\n\n/**\n * Creates actor logic for listening to emitted events from another actor. Used\n * internally by `enq.listen()`.\n */\nexport function createListenerLogic<\n TEmitted extends EventObject = EventObject,\n TMappedEvent extends EventObject = EventObject\n>(): ListenerActorLogic<TEmitted, TMappedEvent> {\n return createAttachedLogic(\n (\n { actor, eventType, mapper }: ListenerInput<TEmitted, TMappedEvent>,\n { self, system }\n ) => {\n // Determine the subscription type:\n // - For exact matches or '*', subscribe directly\n // - For partial wildcards ('data.*'), subscribe to '*' and filter\n const isPartialWildcard = eventType !== '*' && eventType.endsWith('.*');\n\n return actor.on(isPartialWildcard ? '*' : eventType, (emittedEvent) => {\n if (\n isPartialWildcard &&\n !matchesEventDescriptor(emittedEvent.type, eventType)\n ) {\n return;\n }\n relayMappedToParent(self, system, () =>\n mapper(emittedEvent as TEmitted)\n );\n });\n },\n 'xstate.listener'\n );\n}\n\n// Singleton logic instance\nexport const listenerLogic = /* #__PURE__ */ createListenerLogic();\n","import { AnyActorSystem } from '../system.ts';\nimport {\n ActorLogic,\n ActorRefFromLogic,\n AnyActorRef,\n EventObject,\n Snapshot\n} from '../types';\nimport { createAttachedLogic, relayMappedToParent } from './attached.ts';\n\nexport type SubscriptionSnapshot = Snapshot<undefined> & {\n input: SubscriptionInput<any, any, any, any>;\n};\n\nexport interface SubscriptionMappers<\n TSnapshot extends Snapshot<unknown>,\n TOutput,\n TMappedEvent extends EventObject\n> {\n snapshot?: (snapshot: TSnapshot) => TMappedEvent;\n done?: (output: TOutput) => TMappedEvent;\n error?: (error: unknown) => TMappedEvent;\n}\n\nexport interface SubscriptionInput<\n TSnapshot extends Snapshot<unknown>,\n TOutput,\n TMappedEvent extends EventObject,\n TMappers extends SubscriptionMappers<TSnapshot, TOutput, TMappedEvent>\n> {\n actor: AnyActorRef;\n mappers: TMappers;\n}\n\nexport type SubscriptionActorLogic<\n TSnapshot extends Snapshot<unknown> = Snapshot<unknown>,\n TOutput = unknown,\n TMappedEvent extends EventObject = EventObject\n> = ActorLogic<\n SubscriptionSnapshot,\n EventObject,\n SubscriptionInput<\n TSnapshot,\n TOutput,\n TMappedEvent,\n SubscriptionMappers<TSnapshot, TOutput, TMappedEvent>\n >,\n AnyActorSystem,\n EventObject\n>;\n\nexport type SubscriptionActorRef<\n TSnapshot extends Snapshot<unknown> = Snapshot<unknown>,\n TOutput = unknown,\n TMappedEvent extends EventObject = EventObject\n> = ActorRefFromLogic<SubscriptionActorLogic<TSnapshot, TOutput, TMappedEvent>>;\n\n/**\n * Creates actor logic for subscribing to lifecycle events (done/error/snapshot)\n * from another actor. Used internally by `enq.subscribeTo()`.\n */\nexport function createSubscriptionLogic<\n TSnapshot extends Snapshot<unknown> = Snapshot<unknown>,\n TOutput = unknown,\n TMappedEvent extends EventObject = EventObject\n>(): SubscriptionActorLogic<TSnapshot, TOutput, TMappedEvent> {\n return createAttachedLogic(({ actor, mappers }, { self, system }) => {\n const { done, error, snapshot: onSnapshot } = mappers;\n\n return actor.subscribe({\n next: (snapshot: TSnapshot) => {\n if (snapshot.status === 'done' && done) {\n relayMappedToParent(self, system, () =>\n done(snapshot.output as TOutput)\n );\n } else if (snapshot.status === 'error' && error) {\n relayMappedToParent(self, system, () => error(snapshot.error));\n } else if (snapshot.status === 'active' && onSnapshot) {\n relayMappedToParent(self, system, () => onSnapshot(snapshot));\n }\n },\n error: (err: unknown) => {\n if (error) {\n relayMappedToParent(self, system, () => error(err));\n }\n },\n complete: () => {\n // Actor completed without output (stopped); no action needed\n }\n });\n }, 'xstate.subscription');\n}\n\n// Singleton logic instance\nexport const subscriptionLogic = /* #__PURE__ */ createSubscriptionLogic();\n","import type { AnyActor, AnyActorScope } from './types.ts';\n\n/** Marks the internal lazy scope without imposing structure on custom runtimes. @internal */\nexport const lazyActorScope = Symbol();\n\ntype InternalActorScope = AnyActorScope & {\n _parent?: AnyActor;\n [lazyActorScope]?: true;\n};\n\n/** Whether actor capabilities are represented by a lazy pure-transition scope. @internal */\nexport function isLazyActorScope(actorScope: AnyActorScope): boolean {\n return !!(actorScope as InternalActorScope)[lazyActorScope];\n}\n\n/** Reads parent metadata without otherwise touching actor capabilities. @internal */\nexport function getActorScopeParent(\n actorScope: AnyActorScope\n): AnyActor | undefined {\n return isLazyActorScope(actorScope)\n ? (actorScope as InternalActorScope)._parent\n : actorScope.self._parent;\n}\n\n/** Adds only `self`, preserving callback surfaces that expose no other capabilities. @internal */\nexport function withActorSelf<T extends object>(\n args: T,\n actorScope: AnyActorScope\n): T & Pick<AnyActorScope, 'self'> {\n if (!isLazyActorScope(actorScope)) {\n return Object.assign(args, { self: actorScope.self });\n }\n Object.defineProperty(args, 'self', {\n enumerable: true,\n get: () => actorScope.self\n });\n return args as T & Pick<AnyActorScope, 'self'>;\n}\n\n/** Adds the actor reference and parent without exposing the system. @internal */\nexport function withActorSelfAndParent<T extends object>(\n args: T,\n actorScope: AnyActorScope\n): T & Pick<AnyActorScope, 'self'> & { parent: AnyActor | undefined } {\n if (!isLazyActorScope(actorScope)) {\n const self = actorScope.self;\n return Object.assign(args, { self, parent: self._parent });\n }\n Object.defineProperties(args, {\n self: { enumerable: true, get: () => actorScope.self },\n parent: { enumerable: true, get: () => getActorScopeParent(actorScope) }\n });\n return args as T &\n Pick<AnyActorScope, 'self'> & { parent: AnyActor | undefined };\n}\n\n/** Adds actor capabilities without reading them until the callback does. @internal */\nexport function withActorScope<T extends object>(\n args: T,\n actorScope: AnyActorScope\n): T &\n Pick<AnyActorScope, 'self' | 'system'> & {\n parent: AnyActor | undefined;\n } {\n if (!isLazyActorScope(actorScope)) {\n const actorArgs = args as T &\n Pick<AnyActorScope, 'self' | 'system'> & {\n parent: AnyActor | undefined;\n };\n const self = actorScope.self;\n actorArgs.self = self;\n actorArgs.system = actorScope.system;\n actorArgs.parent = self._parent;\n return actorArgs;\n }\n Object.defineProperties(args, {\n self: { enumerable: true, get: () => actorScope.self },\n system: { enumerable: true, get: () => actorScope.system },\n parent: { enumerable: true, get: () => getActorScopeParent(actorScope) }\n });\n return args as T &\n Pick<AnyActorScope, 'self' | 'system'> & {\n parent: AnyActor | undefined;\n };\n}\n","import isDevelopment from '#is-development';\nimport { assertSendToEvent, builtInActions } from './actions.ts';\nimport { resolveRegisteredActorSource } from './actorSource.ts';\nimport { listenerLogic, type ListenerInput } from './actors/listener.ts';\nimport {\n subscriptionLogic,\n type SubscriptionInput,\n type SubscriptionMappers\n} from './actors/subscription.ts';\nimport { XSTATE_SPAWN, XSTATE_START, XSTATE_TERMINATE } from './constants.ts';\nimport { createErrorPlatformEvent } from './eventUtils.ts';\nimport {\n getActorIdPrefix,\n parseGeneratedActorId,\n type ActorSystemRuntime,\n type DeadLetterDetail,\n type EventRejectionReason\n} from './system.ts';\nimport { isLazyActorScope, withActorScope } from './actorScope.ts';\nimport { getEventOutput } from './utils.ts';\nimport type {\n Action,\n ActorTermination,\n AnyAction,\n AnyActor,\n AnyActorLogic,\n AnyActorScope,\n AnyEventObject,\n AnyMachineSnapshot,\n CancelExecutableActionObject,\n CustomExecutableActionObject,\n EmitExecutableActionObject,\n EnqueueObject,\n EventObject,\n ExecutableActionObject,\n MachineContext,\n RaiseExecutableActionObject,\n DeadLetterExecutableActionObject,\n SendToExecutableActionObject,\n Snapshot,\n SpecialExecutableAction,\n SpawnExecutableActionObject,\n StartExecutableActionObject,\n StopExecutableActionObject,\n TerminateExecutableActionObject\n} from './types.ts';\n\ntype TransitionActionRecord = {\n action: (...args: any[]) => any;\n args: any[];\n childUpdate?:\n | {\n type: 'add';\n actor: AnyActor;\n id: string;\n counters?: Record<string, number>;\n }\n | { type: 'remove'; actor: AnyActor };\n};\n\ntype EffectRuntime = Partial<ActorSystemRuntime>;\n\nfunction execCustomEffect(\n this: CustomExecutableActionObject\n): void | PromiseLike<void> | undefined {\n return this.action?.(...this.args);\n}\n\nfunction execEmitEffect(\n this: EmitExecutableActionObject,\n runtime: EffectRuntime = this.source.system\n): void | PromiseLike<void> {\n return runtime.emitEvent!(this.source, this.event);\n}\n\n/** @internal Creates an emitted-event effect. */\nexport function createEmitEffect(\n actorScope: AnyActorScope,\n event: EventObject\n): EmitExecutableActionObject {\n return {\n kind: 'emit',\n exec: execEmitEffect,\n type: event.type,\n source: actorScope.self,\n event,\n params: undefined,\n args: []\n };\n}\n\nfunction execDeadLetterEffect(\n this: DeadLetterExecutableActionObject,\n runtime: EffectRuntime = this.target.system\n): void | PromiseLike<void> {\n return runtime.deadLetter!(\n this.source,\n this.target,\n this.event,\n this.reason,\n this.detail\n );\n}\n\n/** @internal Creates a dead-letter effect for a boundary-rejected event. */\nexport function createDeadLetterEffect(\n actorScope: AnyActorScope,\n source: AnyActor | undefined,\n event: AnyEventObject,\n reason: EventRejectionReason,\n detail?: DeadLetterDetail\n): DeadLetterExecutableActionObject {\n return {\n kind: 'builtin',\n type: '@xstate.deadLetter',\n exec: execDeadLetterEffect,\n source,\n target: actorScope.self,\n event,\n reason,\n detail,\n params: undefined,\n args: []\n };\n}\n\n/** @internal Creates a directly executable user effect. */\nexport function createCustomEffect(\n type: string,\n action: (runtime?: EffectRuntime) => void | PromiseLike<void> | undefined,\n params?: unknown\n): CustomExecutableActionObject {\n return {\n kind: 'action',\n exec: action,\n type,\n action: action as () => void | PromiseLike<void>,\n params,\n args: []\n };\n}\n\nfunction execSpawnEffect(\n this: SpawnExecutableActionObject,\n runtime: EffectRuntime = this.actor.system\n): void | PromiseLike<void> {\n return runtime.spawnActor!(this.source, this.actor);\n}\n\nfunction execStartEffect(\n this: StartExecutableActionObject,\n runtime: EffectRuntime = this.actor.system\n): void | PromiseLike<void> {\n return runtime.startActor!(this.actor);\n}\n\nfunction execStopEffect(\n this: StopExecutableActionObject,\n runtime: EffectRuntime = this.source.system\n): void | PromiseLike<void> {\n return runtime.stopActor!(this.actor);\n}\n\nfunction execTerminateEffect(\n this: TerminateExecutableActionObject,\n runtime: EffectRuntime = this.actor.system\n): void | PromiseLike<void> {\n const termination: ActorTermination =\n this.status === 'done'\n ? { status: 'done', output: this.output, error: undefined }\n : { status: 'error', output: undefined, error: this.error };\n return runtime.terminateActor!(this.actor, termination);\n}\n\nfunction execRaiseEffect(\n this: RaiseExecutableActionObject,\n runtime: EffectRuntime = this.source.system\n): void | PromiseLike<void> {\n return runtime.scheduleTimer!(this.source, this.id!, this.delay ?? 0);\n}\n\nfunction execSendToEffect(\n this: SendToExecutableActionObject,\n runtime: EffectRuntime = this.source.system\n): void | PromiseLike<void> {\n assertSendToEvent(this.event);\n if (this.delay !== undefined) {\n return runtime.scheduleTimer!(this.source, this.id!, this.delay);\n }\n return runtime.sendEvent!(this.source, this.target, this.event);\n}\n\nfunction execCancelEffect(\n this: CancelExecutableActionObject,\n runtime: EffectRuntime = this.source.system\n): void | PromiseLike<void> {\n return runtime.cancelTimer!(this.source, this.id);\n}\n\nfunction updateLogicalTimers(\n snapshot: AnyMachineSnapshot,\n effect: ExecutableActionObject,\n actorScope: AnyActorScope\n): AnyMachineSnapshot {\n if (!isBuiltInExecutableAction(effect)) {\n return snapshot;\n }\n\n if (effect.type === '@xstate.cancel') {\n if (!snapshot.timers?.[effect.id]) {\n return snapshot;\n }\n const timers = { ...snapshot.timers };\n delete timers[effect.id];\n return { ...snapshot, timers };\n }\n\n if (\n (effect.type !== '@xstate.raise' && effect.type !== '@xstate.sendTo') ||\n effect.delay === undefined\n ) {\n return snapshot;\n }\n\n let nextTimerId = snapshot._nextTimerId ?? 0;\n const id = effect.id ?? `xstate.timer.auto.${nextTimerId++}`;\n effect.id = id;\n const target =\n effect.type === '@xstate.raise' || effect.target === actorScope.self\n ? 'self'\n : effect.target;\n\n return {\n ...snapshot,\n timers: {\n ...snapshot.timers,\n [id]: {\n id,\n delay: effect.delay,\n type: effect.type,\n event: effect.event,\n target\n }\n },\n _nextTimerId: nextTimerId\n };\n}\n\nexport function mergeContextPatch(\n context: MachineContext,\n patch: MachineContext\n): MachineContext {\n return { ...context, ...patch };\n}\n\nfunction pushBuiltInAction(actions: any[], action: any, ...args: any[]) {\n const actionRecord: TransitionActionRecord = { action, args };\n actions.push(actionRecord as AnyAction);\n return actionRecord;\n}\n\n/** @internal Max-merges generated-id counter records, copy-on-write. */\nexport function mergeActorIdCounters(\n current: Record<string, number> | undefined,\n update: Record<string, number>\n): Record<string, number> {\n const merged = { ...current };\n for (const key of Object.keys(update)) {\n merged[key] = Math.max(merged[key] ?? 0, update[key]);\n }\n return merged;\n}\n\nfunction applyChildUpdate(\n snapshot: AnyMachineSnapshot,\n update: NonNullable<TransitionActionRecord['childUpdate']>,\n actorScope: AnyActorScope\n): AnyMachineSnapshot {\n if (update.type === 'add') {\n return {\n ...snapshot,\n children: { ...snapshot.children, [update.id]: update.actor },\n ...(update.counters && {\n _nextActorIds: mergeActorIdCounters(\n snapshot._nextActorIds,\n update.counters\n )\n })\n };\n }\n\n const children = { ...snapshot.children };\n let owned = update.actor._parent === actorScope.self;\n for (const key of Object.keys(children)) {\n if (children[key] === update.actor) {\n owned = true;\n delete children[key];\n }\n }\n if (!owned) {\n throw new Error(\n isDevelopment\n ? `Cannot stop child actor ${update.actor.id} of ${actorScope.self.id} because it is not a child`\n : `Cannot stop non-child actor ${update.actor.id}`\n );\n }\n actorScope.system._unregister(update.actor);\n return { ...snapshot, children };\n}\n\nfunction getTransitionActionRecord(\n action: AnyAction\n): TransitionActionRecord | undefined {\n if (\n typeof action === 'object' &&\n action !== null &&\n 'action' in action &&\n typeof action.action === 'function'\n ) {\n return action as TransitionActionRecord;\n }\n return undefined;\n}\n\nfunction pushSpawnedChild(\n actions: any[],\n actor: AnyActor,\n id: string,\n counters?: Record<string, number>\n) {\n const action = pushBuiltInAction(\n actions,\n builtInActions['@xstate.spawn'],\n actor\n );\n action.childUpdate = { type: 'add', actor, id, counters };\n}\n\n/**\n * Spawn-allocation state shared by every enqueue object of one transition, so\n * generated ids stay unique and resolvable across action functions and\n * microsteps of the same event.\n */\ninterface SpawnAllocation {\n counters: Map<string, number>;\n /** Explicit child ids claimed by spawns/invokes of this transition. */\n explicitIds: Set<string>;\n /** Ids of children stopped by this transition, freeing them for reuse. */\n stoppedIds: Set<string>;\n}\n\nconst spawnAllocations = new WeakMap<object, SpawnAllocation>();\n\nconst createSpawnAllocation = (): SpawnAllocation => ({\n counters: new Map(),\n explicitIds: new Set(),\n stoppedIds: new Set()\n});\n\n/**\n * Starts a fresh spawn-allocation transaction for one logical transition.\n * Called at every transition boundary so pure replays from the same snapshot\n * allocate identical ids.\n *\n * @internal\n */\nexport function beginSpawnAllocation(actorScope: AnyActorScope): void {\n spawnAllocations.set(actorScope, createSpawnAllocation());\n}\n\n// Read the raw snapshot: getSnapshot() throws while the actor initializes,\n// and entry actions run before any snapshot exists.\nfunction getWorkingSnapshotOf(actorScope: AnyActorScope):\n | {\n _nextActorIds?: Record<string, number>;\n children?: Record<string, AnyActor | undefined>;\n }\n | undefined {\n return (\n actorScope.self as {\n _snapshot?: {\n _nextActorIds?: Record<string, number>;\n children?: Record<string, AnyActor | undefined>;\n };\n }\n )._snapshot;\n}\n\nfunction getRegisteredActors(\n actorScope: AnyActorScope\n): Record<string, AnyActorLogic> | undefined {\n return (\n actorScope.self as {\n logic?: { sources?: { actors?: Record<string, AnyActorLogic> } };\n }\n ).logic?.sources?.actors;\n}\n\nfunction resolveTransitionSpawnSource(\n actorScope: AnyActorScope,\n source: string | AnyActorLogic\n): { logic: AnyActorLogic; src: string | undefined } {\n const registeredActors = getRegisteredActors(actorScope);\n if (typeof source === 'string') {\n const logic = registeredActors?.[source];\n if (!logic) {\n throw new Error(`Actor source '${source}' is not provided`);\n }\n return { logic, src: source };\n }\n if (!registeredActors) {\n return { logic: source, src: undefined };\n }\n return {\n logic: source,\n src: resolveRegisteredActorSource(registeredActors, source)\n };\n}\n\n/**\n * Internal helper actors (listeners, subscriptions) number their ids from\n * system-level counters under `xstate.`-prefixed names; snapshot-owned\n * children number from per-snapshot counters. The two spaces only stay\n * collision-free because their prefixes are disjoint, so user sources must\n * not enter the reserved namespace.\n */\nfunction assertUnreservedPrefix(prefix: string): void {\n if (isDevelopment && prefix.startsWith('xstate.')) {\n throw new Error(\n `Child actor ids with the \"xstate.\" prefix are reserved for internal actors; rename the \"${prefix}\" source or logic id.`\n );\n }\n}\n\n/**\n * The next free index for a prefix. The parent snapshot's persisted counter\n * is always a floor, so a freed id is never handed out again — not even when\n * an explicit id reserved a lower one earlier in the transition.\n */\nfunction nextChildIndex(\n actorScope: AnyActorScope,\n allocation: SpawnAllocation,\n prefix: string\n): number {\n return Math.max(\n allocation.counters.get(prefix) ?? 0,\n getWorkingSnapshotOf(actorScope)?._nextActorIds?.[prefix] ?? 0\n );\n}\n\n/**\n * Allocates the next generated child id for the transition's allocation\n * transaction, seeded from the parent snapshot's own persisted counters. This\n * is the single allocator for snapshot-owned children (`enq.spawn` and\n * context-factory spawns); a correct allocation cannot collide.\n *\n * @internal\n */\nexport function allocateChildId(\n actorScope: AnyActorScope,\n src: string | AnyActorLogic,\n localAllocation?: SpawnAllocation\n): { id: string; counters: Record<string, number> } {\n if (isDevelopment && !spawnAllocations.get(actorScope)) {\n console.warn(\n 'A child id was generated outside a spawn-allocation transaction; ids may repeat across enqueue objects. Transition entry points must call beginSpawnAllocation().'\n );\n }\n const allocation =\n spawnAllocations.get(actorScope) ??\n localAllocation ??\n createSpawnAllocation();\n const prefix = getActorIdPrefix(src);\n assertUnreservedPrefix(prefix);\n const next = nextChildIndex(actorScope, allocation, prefix);\n allocation.counters.set(prefix, next + 1);\n return { id: `${prefix}:${next}`, counters: { [prefix]: next + 1 } };\n}\n\n/**\n * Requires an explicit child id to be unoccupied before a spawn or invoke\n * claims it: an address must name at most one live actor. An id is occupied\n * when a child of this parent already holds it and this transition has not\n * stopped that child, or when an earlier spawn of this transition claimed it.\n *\n * @internal\n */\nexport function assertChildIdFree(\n actorScope: AnyActorScope,\n id: string,\n localAllocation?: SpawnAllocation\n): void {\n const allocation =\n spawnAllocations.get(actorScope) ??\n localAllocation ??\n createSpawnAllocation();\n const existing = getWorkingSnapshotOf(actorScope)?.children?.[id] as\n | AnyActor\n | undefined;\n // A terminated child no longer occupies its id: it relayed its completion\n // and is removed from `children` right after the transition handling it,\n // so the supervisor pattern — respawn under the same name while handling\n // the child's done/error event — must not conflict with the outgoing\n // entry. Remote handles never expose a terminal status locally; the\n // completion event that removes one is the owning runtime's business.\n const occupied =\n existing !== undefined &&\n !allocation.stoppedIds.has(id) &&\n existing.getSnapshot().status === 'active';\n if (allocation.explicitIds.has(id) || occupied) {\n throw new Error(\n isDevelopment\n ? `Cannot spawn child actor with id '${id}': the id is already in use by another child of '${actorScope.self.id}'. Stop the existing child before reusing its id.`\n : `Child actor id '${id}' is already in use`\n );\n }\n allocation.explicitIds.add(id);\n}\n\n/**\n * Records that this transition stopped a child, freeing its id for a later\n * spawn or invoke of the same transition (the invoke restart pattern).\n *\n * @internal\n */\nfunction recordStoppedChild(actorScope: AnyActorScope, actor: AnyActor): void {\n const allocation = spawnAllocations.get(actorScope);\n if (allocation) {\n allocation.stoppedIds.add(actor.id);\n allocation.explicitIds.delete(actor.id);\n }\n}\n\n/**\n * Reserves an explicit generated-shaped id (`worker:5`) in the transaction\n * and the parent snapshot, so live runs and pure replays allocate the same\n * later ids even after this child is removed.\n *\n * @internal\n */\nexport function reserveChildId(\n actorScope: AnyActorScope,\n id: string,\n localAllocation?: SpawnAllocation\n): Record<string, number> | undefined {\n const generated = parseGeneratedActorId(id);\n if (!generated) {\n return undefined;\n }\n assertUnreservedPrefix(generated.prefix);\n const allocation =\n spawnAllocations.get(actorScope) ??\n localAllocation ??\n createSpawnAllocation();\n // The requested id is used as asked, but numbering continues from the\n // highest reservation: an explicit low id never rewinds the counter.\n const next = Math.max(\n nextChildIndex(actorScope, allocation, generated.prefix),\n generated.index + 1\n );\n allocation.counters.set(generated.prefix, next);\n return { [generated.prefix]: next };\n}\n\n/**\n * The counters allocated so far in the transition's transaction, for\n * committing into a snapshot built outside `applyChildUpdate` (the\n * pre-initial snapshot with context-factory spawns).\n *\n * @internal\n */\nexport function takeSpawnAllocationCounters(\n actorScope: AnyActorScope\n): Record<string, number> | undefined {\n const counters = spawnAllocations.get(actorScope)?.counters;\n if (!counters?.size) {\n return undefined;\n }\n return Object.fromEntries(counters);\n}\n\nexport function createTransitionEnqueue(\n actorScope: AnyActorScope,\n actions: any[],\n internalEvents: EventObject[],\n actorSubscriptions = false,\n createActors = true\n) {\n // Paths that never begin a transaction keep a per-enqueue scope.\n const localAllocation =\n spawnAllocations.get(actorScope) ?? createSpawnAllocation();\n const props: Partial<EnqueueObject<any, any>> = {\n cancel: (id: string) => {\n pushBuiltInAction(\n actions,\n builtInActions['@xstate.cancel'],\n actorScope,\n id\n );\n },\n emit: (emittedEvent) => {\n actions.push(emittedEvent);\n },\n log: (...args) => {\n pushBuiltInAction(actions, actorScope.logger, ...args);\n },\n raise: (raisedEvent, options) => {\n if (typeof raisedEvent === 'string') {\n throw new Error(\n isDevelopment\n ? `Only event objects may be used with raise; use raise({ type: \"${raisedEvent}\" }) instead`\n : `Only event objects may be used with raise`\n );\n }\n if (options?.delay !== undefined) {\n pushBuiltInAction(\n actions,\n builtInActions['@xstate.raise'],\n actorScope,\n raisedEvent,\n options\n );\n } else {\n internalEvents.push(raisedEvent);\n }\n },\n spawn: (source: string | AnyActorLogic, options: any) => {\n const { logic, src } = resolveTransitionSpawnSource(actorScope, source);\n if (!createActors) {\n // TODO: replace this speculative placeholder with a typed inert actor ref.\n return {\n id: options?.id ?? options?.registryKey ?? src ?? (logic as any).id\n } as AnyActor;\n }\n // Generated ids allocate from the parent snapshot's own counters\n // through the transition's allocation transaction; explicit\n // generated-shaped ids reserve their numbering the same way.\n let id = options?.id;\n let counters: Record<string, number> | undefined;\n if (id === undefined) {\n ({ id, counters } = allocateChildId(\n actorScope,\n src ?? logic,\n localAllocation\n ));\n } else {\n assertChildIdFree(actorScope, id, localAllocation);\n counters = reserveChildId(actorScope, id, localAllocation);\n }\n const actor = actorScope.system.createActorRef(logic, {\n ...options,\n ...(src !== undefined && { src }),\n id,\n parent: actorScope.self\n });\n pushSpawnedChild(actions, actor, id, counters);\n return actor;\n },\n sendTo: (actor, event, options) => {\n if (!actor) {\n internalEvents.push(\n createErrorPlatformEvent('communication', {\n message: 'Unable to send event to an undefined actor',\n event\n })\n );\n return;\n }\n pushBuiltInAction(\n actions,\n builtInActions['@xstate.sendTo'],\n actorScope,\n actor,\n event,\n options\n );\n },\n stop: (actor) => {\n if (actor) {\n // enq.stop accepts the consumer ActorRef contract; refs handed to\n // machine code are always full actor instances at runtime.\n const actorInstance = actor as AnyActor;\n const action = pushBuiltInAction(\n actions,\n builtInActions['@xstate.stop'],\n actorScope,\n actorInstance\n );\n action.childUpdate = { type: 'remove', actor: actorInstance };\n recordStoppedChild(actorScope, actorInstance);\n }\n }\n };\n\n if (actorSubscriptions) {\n Object.assign(props, {\n listen: (actor: any, eventType: string, mapper: any) => {\n if (!createActors) {\n return { id: undefined } as unknown as AnyActor;\n }\n const input: ListenerInput<any, any> = {\n actor,\n eventType,\n mapper\n };\n const listenerActor = actorScope.system.createActorRef(listenerLogic, {\n input,\n parent: actorScope.self\n });\n pushBuiltInAction(\n actions,\n builtInActions['@xstate.spawn'],\n listenerActor\n );\n return listenerActor;\n },\n subscribeTo: (actor: any, mappers: any) => {\n if (!createActors) {\n return { id: undefined } as unknown as AnyActor;\n }\n const normalizedMappers: SubscriptionMappers<any, any, any> =\n typeof mappers === 'function' ? { snapshot: mappers } : mappers;\n\n const input: SubscriptionInput<any, any, any, any> = {\n actor,\n mappers: normalizedMappers\n };\n const subscriptionActor = actorScope.system.createActorRef(\n subscriptionLogic,\n {\n input,\n parent: actorScope.self\n }\n );\n pushBuiltInAction(\n actions,\n builtInActions['@xstate.spawn'],\n subscriptionActor\n );\n return subscriptionActor;\n }\n });\n }\n\n return createEnqueueObject(props, (action, ...args) => {\n pushBuiltInAction(actions, action, ...args);\n });\n}\n\nfunction getBuiltInActionFields(\n action: (...args: any[]) => void,\n args: unknown[]\n): Partial<SpecialExecutableAction> | undefined {\n switch (action) {\n case builtInActions['@xstate.spawn']: {\n const [actor] = args as Parameters<\n (typeof builtInActions)['@xstate.spawn']\n >;\n return {\n type: '@xstate.spawn',\n kind: 'builtin',\n exec: execSpawnEffect,\n source: actor._parent,\n actor,\n id: actor.id,\n logic: (actor as any).logic,\n src: actor.src,\n input: (actor as any).options?.input\n };\n }\n case builtInActions['@xstate.raise']: {\n const [, event, options] = args as Parameters<\n (typeof builtInActions)['@xstate.raise']\n >;\n return {\n type: '@xstate.raise',\n kind: 'builtin',\n exec: execRaiseEffect,\n source: (\n args as Parameters<(typeof builtInActions)['@xstate.raise']>\n )[0].self,\n event,\n id: options?.id,\n delay: options?.delay\n };\n }\n case builtInActions['@xstate.sendTo']: {\n const [, target, event, options] = args as Parameters<\n (typeof builtInActions)['@xstate.sendTo']\n >;\n return {\n type: '@xstate.sendTo',\n kind: 'builtin',\n exec: execSendToEffect,\n source: (\n args as Parameters<(typeof builtInActions)['@xstate.sendTo']>\n )[0].self,\n target,\n event,\n id: options?.id,\n delay: options?.delay\n };\n }\n case builtInActions['@xstate.cancel']: {\n const [, id] = args as Parameters<\n (typeof builtInActions)['@xstate.cancel']\n >;\n return {\n type: '@xstate.cancel',\n kind: 'builtin',\n exec: execCancelEffect,\n source: (\n args as Parameters<(typeof builtInActions)['@xstate.cancel']>\n )[0].self,\n id\n };\n }\n case builtInActions['@xstate.stop']: {\n const [, actor] = args as Parameters<\n (typeof builtInActions)['@xstate.stop']\n >;\n return {\n type: '@xstate.stop',\n kind: 'builtin',\n exec: execStopEffect,\n source: (args as Parameters<(typeof builtInActions)['@xstate.stop']>)[0]\n .self,\n actor,\n id: actor.id\n };\n }\n default:\n return undefined;\n }\n}\n\nfunction createStartEffect(actor: AnyActor): StartExecutableActionObject {\n const args: Parameters<(typeof builtInActions)['@xstate.start']> = [actor];\n return {\n kind: 'builtin',\n exec: execStartEffect,\n type: XSTATE_START,\n source: actor._parent,\n params: undefined,\n args,\n actor,\n id: actor.id\n };\n}\n\nexport function createSpawnEffect(\n actor: AnyActor\n): SpawnExecutableActionObject {\n const args: Parameters<(typeof builtInActions)['@xstate.spawn']> = [actor];\n return {\n kind: 'builtin',\n exec: execSpawnEffect,\n type: XSTATE_SPAWN,\n source: actor._parent,\n params: undefined,\n args,\n actor,\n id: actor.id,\n logic: (actor as any).logic,\n src: actor.src,\n input: (actor as any).options?.input\n };\n}\n\n/** @internal Creates an immediate actor-to-actor delivery effect. */\nexport function createSendToEffect(\n actorScope: AnyActorScope,\n target: AnyActor,\n event: EventObject\n): SendToExecutableActionObject {\n const args: Parameters<(typeof builtInActions)['@xstate.sendTo']> = [\n actorScope,\n target,\n event,\n {}\n ];\n return {\n kind: 'builtin',\n exec: execSendToEffect,\n type: '@xstate.sendTo',\n source: actorScope.self,\n target,\n event,\n id: undefined,\n delay: undefined,\n params: undefined,\n args\n };\n}\n\n/** @internal Creates the terminal lifecycle effect for an actor. */\nexport function createTerminationEffect(\n actorScope: AnyActorScope,\n snapshot: Snapshot<unknown>\n): TerminateExecutableActionObject {\n if (snapshot.status !== 'done' && snapshot.status !== 'error') {\n throw new Error('Cannot terminate an active or stopped actor');\n }\n const termination: ActorTermination =\n snapshot.status === 'done'\n ? { status: 'done', output: snapshot.output, error: undefined }\n : { status: 'error', output: undefined, error: snapshot.error };\n const args: Parameters<(typeof builtInActions)['@xstate.terminate']> = [\n actorScope.self,\n termination\n ];\n return {\n kind: 'builtin',\n exec: execTerminateEffect,\n type: XSTATE_TERMINATE,\n source: actorScope.self,\n actor: actorScope.self,\n id: actorScope.self.id,\n ...termination,\n params: undefined,\n args\n };\n}\n\n/**\n * Ensures that a newly terminal snapshot has exactly one ordered actor\n * termination effect.\n *\n * @internal\n */\nexport function finalizeTransitionResult<\n TSnapshot extends Snapshot<unknown>,\n TEffect\n>(\n actorScope: AnyActorScope,\n previousSnapshot: TSnapshot | undefined,\n [nextSnapshot, effects]: [TSnapshot, TEffect[]]\n): [TSnapshot, Array<TEffect | TerminateExecutableActionObject>] {\n const becameTerminal =\n nextSnapshot.status === 'done' || nextSnapshot.status === 'error';\n const wasTerminal =\n previousSnapshot?.status === 'done' || previousSnapshot?.status === 'error';\n const hasTerminationEffect = effects.some(\n (effect) =>\n typeof effect === 'object' &&\n effect !== null &&\n 'type' in effect &&\n effect.type === XSTATE_TERMINATE\n );\n\n return becameTerminal && !wasTerminal && !hasTerminationEffect\n ? [\n nextSnapshot,\n [...effects, createTerminationEffect(actorScope, nextSnapshot)]\n ]\n : [nextSnapshot, effects];\n}\n\n/**\n * Attached (listener/subscription) starts are ordered before child starts so\n * that a listener/subscription captures events emitted synchronously as its\n * target actor starts.\n */\nexport function deriveDeferredStarts(\n effects: ReadonlyArray<ExecutableActionObject>\n): StartExecutableActionObject[] {\n const attachedStarts: StartExecutableActionObject[] = [];\n const childStarts: StartExecutableActionObject[] = [];\n\n for (const effect of effects) {\n if (!isBuiltInExecutableAction(effect) || effect.type !== XSTATE_SPAWN) {\n continue;\n }\n const { actor, logic } = effect;\n const start = createStartEffect(actor);\n if (logic === listenerLogic || logic === subscriptionLogic) {\n attachedStarts.push(start);\n } else {\n childStarts.push(start);\n }\n }\n\n return [...attachedStarts, ...childStarts];\n}\n\nexport function isBuiltInExecutableAction(\n action: ExecutableActionObject\n): action is SpecialExecutableAction {\n return action.kind === 'builtin';\n}\n\n/** Executes transition effects sequentially, awaiting each runtime operation. */\nexport async function executeEffects(\n effects: readonly ExecutableActionObject[],\n runtime?: Partial<ActorSystemRuntime>\n): Promise<void> {\n for (const effect of effects) {\n await effect.exec(runtime);\n }\n}\n\nexport function resolveActionsWithContext(\n currentSnapshot: AnyMachineSnapshot,\n event: AnyEventObject,\n actorScope: AnyActorScope,\n actions: AnyAction[]\n): [AnyMachineSnapshot, ExecutableActionObject[]] {\n let intermediateSnapshot = currentSnapshot;\n const executableActions: ExecutableActionObject[] = [];\n\n for (const action of actions) {\n const actionArgs = isLazyActorScope(actorScope)\n ? withActorScope(\n {\n context: intermediateSnapshot.context,\n event,\n output: getEventOutput(event),\n children: intermediateSnapshot.children,\n actions: currentSnapshot.machine.sources.actions,\n actors: currentSnapshot.machine.sources.actors\n },\n actorScope\n )\n : {\n context: intermediateSnapshot.context,\n event,\n output: getEventOutput(event),\n self: actorScope.self,\n system: actorScope.system,\n parent: actorScope.self._parent,\n children: intermediateSnapshot.children,\n actions: currentSnapshot.machine.sources.actions,\n actors: currentSnapshot.machine.sources.actors\n };\n\n const isInline = typeof action === 'function';\n const actionRecord = getTransitionActionRecord(action);\n\n const resolvedAction = isInline\n ? action\n : actionRecord\n ? actionRecord.action.bind(null, ...actionRecord.args)\n : false;\n\n let actionParams = undefined;\n\n if (typeof action === 'object' && action !== null) {\n const {\n type: _,\n childUpdate: _childUpdate,\n ...emittedEventParams\n } = action as any;\n actionParams = emittedEventParams;\n }\n\n if (actionRecord?.childUpdate) {\n intermediateSnapshot = applyChildUpdate(\n intermediateSnapshot,\n actionRecord.childUpdate,\n actorScope\n );\n }\n\n if (resolvedAction && '_special' in resolvedAction) {\n executableActions.push({\n kind: 'action',\n exec: execCustomEffect,\n type:\n typeof action === 'object'\n ? 'action' in action && typeof action.action === 'function'\n ? (action.action.name ?? '(anonymous)')\n : ((action as any).type ?? '(anonymous)')\n : action.name || '(anonymous)',\n params: actionParams,\n args: [],\n action: undefined\n });\n\n const specialAction = resolvedAction as unknown as Action<\n any,\n any,\n any,\n any,\n any,\n any,\n any\n >;\n\n const res = specialAction(actionArgs as any, emptyEnqueueObject);\n\n if (res && ('context' in res || 'children' in res)) {\n // Special-action patches never change `nodes`, so a shallow clone is\n // equivalent to `cloneMachineSnapshot` — and keeps this module (and\n // non-machine logic like `createFSM`) independent of State.ts.\n intermediateSnapshot = {\n ...intermediateSnapshot,\n ...(res.context !== undefined\n ? {\n context: mergeContextPatch(\n intermediateSnapshot.context,\n res.context\n )\n }\n : {}),\n ...('children' in res ? { children: res.children } : {})\n };\n }\n continue;\n }\n\n if (!resolvedAction || !('resolve' in resolvedAction)) {\n const builtInFields =\n typeof action === 'object' &&\n action !== null &&\n 'action' in action &&\n typeof action.action === 'function'\n ? getBuiltInActionFields(action.action, action.args)\n : undefined;\n const isEmittedEvent =\n typeof action === 'object' && action !== null && !actionRecord;\n\n const executableAction = {\n kind: builtInFields\n ? ('builtin' as const)\n : isEmittedEvent\n ? ('emit' as const)\n : ('action' as const),\n type:\n typeof action === 'object'\n ? 'action' in action && typeof action.action === 'function'\n ? (action.action.name ?? '(anonymous)')\n : (action as AnyEventObject).type\n : action.name || '(anonymous)',\n params: builtInFields ? undefined : actionParams,\n args:\n typeof action === 'object' && 'action' in action ? action.args : [],\n ...(builtInFields\n ? {}\n : isEmittedEvent\n ? { source: actorScope.self, event: action }\n : {\n action: actionRecord?.action ?? (isInline ? action : undefined)\n }),\n ...(!builtInFields\n ? { exec: isEmittedEvent ? execEmitEffect : execCustomEffect }\n : {}),\n ...builtInFields\n };\n\n const typedExecutableAction = executableAction as ExecutableActionObject;\n intermediateSnapshot = updateLogicalTimers(\n intermediateSnapshot,\n typedExecutableAction,\n actorScope\n );\n executableActions.push(typedExecutableAction);\n continue;\n }\n }\n\n return [intermediateSnapshot, executableActions];\n}\n\nexport function createEnqueueObject(\n props: Partial<EnqueueObject<any, any>>,\n action: <T extends (...args: any[]) => any>(\n fn: T,\n ...args: Parameters<T>\n ) => void\n): EnqueueObject<any, any> {\n const enqueueFn = (\n fn: (...args: any[]) => any,\n ...args: Parameters<typeof fn>\n ) => {\n action(fn, ...args);\n };\n\n Object.assign(enqueueFn, {\n cancel: noop,\n emit: noop,\n log: noop,\n raise: noop,\n spawn: emptyActor,\n sendTo: noop,\n stop: noop,\n listen: emptyActor,\n subscribeTo: emptyActor,\n ...props\n });\n\n return enqueueFn as any;\n}\n\nconst noop = () => {};\nconst emptyActor = () => ({}) as any;\n\nconst emptyEnqueueObject = createEnqueueObject({}, noop);\n","export function parseDurationToMilliseconds(\n duration: string\n): number | undefined {\n const normalizedDuration = duration.trim();\n\n const millisecondsMatch = normalizedDuration.match(/^(\\d+)ms$/i);\n if (millisecondsMatch) {\n return parseInt(millisecondsMatch[1], 10);\n }\n\n const secondsMatch = normalizedDuration.match(/^(\\d*)(\\.?)(\\d*)s$/i);\n if (secondsMatch) {\n const wholePart = secondsMatch[1] ? parseInt(secondsMatch[1], 10) : 0;\n const hasDecimal = !!secondsMatch[2];\n const fracPart = secondsMatch[3]\n ? parseInt(secondsMatch[3].padEnd(3, '0').slice(0, 3), 10)\n : 0;\n\n return wholePart * 1000 + (hasDecimal ? fracPart : 0);\n }\n\n const iso8601DurationMatch = normalizedDuration.match(\n /^P(?:(?<weeks>\\d+(?:[.,]\\d+)?)W)?(?:(?<days>\\d+(?:[.,]\\d+)?)D)?(?:T(?:(?<hours>\\d+(?:[.,]\\d+)?)H)?(?:(?<minutes>\\d+(?:[.,]\\d+)?)M)?(?:(?<seconds>\\d+(?:[.,]\\d+)?)S)?)?$/i\n );\n\n if (!iso8601DurationMatch?.groups) {\n return undefined;\n }\n\n const { weeks, days, hours, minutes, seconds } = iso8601DurationMatch.groups;\n if (!weeks && !days && !hours && !minutes && !seconds) {\n return undefined;\n }\n\n const toNumber = (value: string | undefined) =>\n value ? Number(value.replace(',', '.')) : 0;\n\n return (\n toNumber(weeks) * 7 * 24 * 60 * 60 * 1000 +\n toNumber(days) * 24 * 60 * 60 * 1000 +\n toNumber(hours) * 60 * 60 * 1000 +\n toNumber(minutes) * 60 * 1000 +\n toNumber(seconds) * 1000\n );\n}\n\nexport function parseDelayToMilliseconds(\n delay: string | number | undefined\n): number | undefined {\n if (delay === undefined) {\n return undefined;\n }\n\n if (typeof delay === 'number') {\n return delay;\n }\n\n return parseDurationToMilliseconds(delay);\n}\n","import { hasAmbientInspector } from './inspectionAmbient.ts';\nimport type { AnyActor, Snapshot } from './types.ts';\n\n/** Snapshot-scoped actor identity and system view. @internal */\nexport interface SnapshotActorRef {\n actor: AnyActor;\n systemState: SnapshotSystemState;\n}\n\ninterface SnapshotSystemState {\n root?: AnyActor;\n children?: Map<string, AnyActor>;\n keyedActors: Map<PropertyKey, AnyActor | undefined>;\n snapshot: AnyActor['system']['_snapshot'];\n sourceSystem: AnyActor['system'];\n sourceVersion: number;\n}\n\nconst snapshotActorRefs = new WeakMap<object, SnapshotActorRef>();\nconst lazySnapshotActorRefs = new WeakMap<object, () => SnapshotActorRef>();\nconst emptyKeyedActors = new Map<PropertyKey, AnyActor | undefined>();\n\nfunction copyRegisteredActors(\n system: AnyActor['system'],\n state?: SnapshotSystemState\n): Map<string, AnyActor> {\n if (state) {\n const children = new Map<string, AnyActor>(state.children);\n if (state.root?.sessionId) {\n children.set(state.root.sessionId, state.root);\n }\n return children;\n }\n return new Map(system.children);\n}\n\nfunction captureRegisteredActors(system: AnyActor['system']): {\n root?: AnyActor;\n children?: Map<string, AnyActor>;\n} {\n const root = system._getRootActor?.();\n const peekedChildren = system._peekChildren?.();\n if (!root && !peekedChildren) {\n if (system._getRootActor && system._peekChildren) {\n return {};\n }\n const children = new Map<string, AnyActor>(system.children);\n return children.size ? { children } : {};\n }\n if (!peekedChildren?.size) {\n return root ? { root } : {};\n }\n return { children: new Map<string, AnyActor>(system.children) };\n}\n\nfunction getKeyedActors(\n system: AnyActor['system']\n): Map<PropertyKey, AnyActor | undefined> {\n const peek = system._peekKeyedActors;\n if (peek) {\n return peek.call(system) ?? emptyKeyedActors;\n }\n return system.keyedActors;\n}\n\n/** Marks topology or persisted runtime state as changed. @internal */\nexport function markSystemSnapshotDirty(system: AnyActor['system']): void {\n system._snapshotVersion++;\n}\n\nfunction getSystemSnapshotVersion(system: AnyActor['system']): number {\n return system._snapshotVersion;\n}\n\nfunction getSnapshotChildren(\n snapshot: Snapshot<unknown>\n): Record<string, AnyActor | undefined> {\n return 'children' in snapshot && snapshot.children\n ? (snapshot.children as Record<string, AnyActor | undefined>)\n : {};\n}\n\n/**\n * Creates the isolated receptionist/id view used by a pure branch. Scheduling,\n * relaying and clocks remain delegated to the snapshot's execution system.\n *\n * @internal\n */\nexport function createSnapshotSystem(\n baseSystem: AnyActor['system'],\n children: Record<string, AnyActor | undefined>,\n baseState?: SnapshotSystemState\n): AnyActor['system'] {\n const forwardInspection = hasAmbientInspector();\n const registeredActors = copyRegisteredActors(baseSystem, baseState);\n const keyedActors = new Map<PropertyKey, AnyActor | undefined>(\n baseState?.keyedActors ?? getKeyedActors(baseSystem)\n );\n const reverseKeyedActors = new WeakMap<AnyActor, PropertyKey>();\n const system: AnyActor['system'] = Object.assign(Object.create(baseSystem), {\n children: registeredActors,\n keyedActors,\n reverseKeyedActors,\n _snapshot: { ...(baseState?.snapshot ?? baseSystem._snapshot) },\n _snapshotVersion: baseState?.sourceVersion ?? baseSystem._snapshotVersion,\n _register: (sessionId: string, actor: AnyActor) => {\n registeredActors.set(sessionId, actor);\n markSystemSnapshotDirty(system);\n return sessionId;\n },\n _unregister: (actor: AnyActor) => {\n if (actor.sessionId) {\n registeredActors.delete(actor.sessionId);\n }\n const registryKey = reverseKeyedActors.get(actor);\n if (registryKey !== undefined && keyedActors.get(registryKey) === actor) {\n keyedActors.delete(registryKey);\n }\n reverseKeyedActors.delete(actor);\n markSystemSnapshotDirty(system);\n },\n _set: (registryKey: PropertyKey, actor: AnyActor) => {\n const existing = keyedActors.get(registryKey);\n if (existing && existing !== actor) {\n throw new Error(\n `Actor with registry key '${String(registryKey)}' already exists.`\n );\n }\n keyedActors.set(registryKey, actor);\n reverseKeyedActors.set(actor, registryKey);\n markSystemSnapshotDirty(system);\n },\n get: (registryKey: PropertyKey) => keyedActors.get(registryKey),\n getAll: () => Object.fromEntries(keyedActors),\n // Pure transition resolution must not leak topology inspection events\n // into a live runtime system — planning branches stay silent. The one\n // exception is a durable execution's own transitions (marked by the\n // ambient inspector at creation time): there the pure path IS the\n // execution, so inspection forwards to the base system's observers.\n _hasInspectionObservers: forwardInspection\n ? () => baseSystem._hasInspectionObservers?.() ?? false\n : () => false,\n _sendInspectionEvent: forwardInspection\n ? (event: Parameters<AnyActor['system']['_sendInspectionEvent']>[0]) =>\n baseSystem._sendInspectionEvent(event)\n : () => {}\n });\n\n for (const [registryKey, actor] of keyedActors) {\n if (!actor) {\n continue;\n }\n reverseKeyedActors.set(actor, registryKey);\n }\n for (const actor of Object.values(children)) {\n if (!actor) {\n continue;\n }\n if (actor.sessionId) {\n registeredActors.set(actor.sessionId, actor);\n }\n const registryKey = actor.registryKey;\n if (registryKey) {\n keyedActors.set(registryKey, actor);\n reverseKeyedActors.set(actor, registryKey);\n }\n }\n\n return system;\n}\n\n/** Returns the actor identity associated with a transition snapshot. @internal */\nexport function getSnapshotActorRef(\n snapshot: Snapshot<unknown>\n): SnapshotActorRef | undefined {\n const existing = snapshotActorRefs.get(snapshot);\n if (existing) {\n return existing;\n }\n const create = lazySnapshotActorRefs.get(snapshot);\n if (!create) {\n return undefined;\n }\n const created = create();\n snapshotActorRefs.set(snapshot, created);\n lazySnapshotActorRefs.delete(snapshot);\n return created;\n}\n\n/** Reads an already materialized snapshot association without creating one. @internal */\nexport function peekSnapshotActorRef(\n snapshot: Snapshot<unknown>\n): SnapshotActorRef | undefined {\n return snapshotActorRefs.get(snapshot);\n}\n\n/** Returns the existing identity provider without resolving it. @internal */\nexport function getSnapshotActorRefProvider(\n snapshot: Snapshot<unknown>\n): (() => SnapshotActorRef) | undefined {\n const existing = snapshotActorRefs.get(snapshot);\n return existing ? () => existing : lazySnapshotActorRefs.get(snapshot);\n}\n\n/** Defers actor/system identity allocation until a snapshot capability is used. @internal */\nexport function setLazySnapshotActorRef(\n snapshot: Snapshot<unknown>,\n create: () => SnapshotActorRef\n): void {\n snapshotActorRefs.delete(snapshot);\n lazySnapshotActorRefs.set(snapshot, create);\n}\n\n/**\n * Copies an internal actor association without rebuilding its system view.\n *\n * @internal\n */\nexport function copySnapshotActorRef(\n source: Snapshot<unknown>,\n target: Snapshot<unknown>\n): boolean {\n const ref = snapshotActorRefs.get(source);\n if (ref) {\n snapshotActorRefs.set(target, ref);\n return true;\n }\n const create = lazySnapshotActorRefs.get(source);\n if (create) {\n lazySnapshotActorRefs.set(target, create);\n return true;\n }\n return false;\n}\n\n/** Refreshes the only topology change made by an otherwise idle root start. */\nexport function refreshSnapshotActorRefRoot(\n snapshot: Snapshot<unknown>,\n actor: AnyActor,\n system: AnyActor['system']\n): boolean {\n const ref = snapshotActorRefs.get(snapshot);\n const sourceVersion = getSystemSnapshotVersion(system);\n if (\n ref?.actor !== actor ||\n ref.systemState.sourceSystem !== system ||\n ref.systemState.sourceVersion + 1 !== sourceVersion ||\n system._getRootActor?.() !== actor ||\n system._peekChildren?.()\n ) {\n return false;\n }\n ref.systemState.root = actor;\n ref.systemState.sourceVersion = sourceVersion;\n return true;\n}\n\n/**\n * Associates a transition snapshot with an actor and an immutable system view.\n * The internal association is excluded from enumeration and persistence.\n *\n * @internal\n */\nexport function setSnapshotActorRef(\n snapshot: Snapshot<unknown>,\n actor: AnyActor,\n baseSystem: AnyActor['system'] = actor.system,\n previousSnapshot?: Snapshot<unknown>\n): void {\n lazySnapshotActorRefs.delete(snapshot);\n const sourceVersion = getSystemSnapshotVersion(baseSystem);\n const previousRef = previousSnapshot\n ? getSnapshotActorRef(previousSnapshot)\n : undefined;\n const reusableRef =\n previousRef?.actor === actor ? previousRef : getSnapshotActorRef(snapshot);\n\n if (\n reusableRef?.actor === actor &&\n reusableRef.systemState.sourceSystem === baseSystem &&\n reusableRef.systemState.sourceVersion === sourceVersion\n ) {\n snapshotActorRefs.set(snapshot, reusableRef);\n return;\n }\n\n const capturedActors = captureRegisteredActors(baseSystem);\n let children = capturedActors.children;\n const baseKeyedActors = getKeyedActors(baseSystem);\n let keyedActors = baseKeyedActors.size\n ? new Map(baseKeyedActors)\n : emptyKeyedActors;\n for (const child of Object.values(getSnapshotChildren(snapshot))) {\n if (!child) {\n continue;\n }\n if (child.sessionId) {\n (children ??= new Map()).set(child.sessionId, child);\n }\n const registryKey = child.registryKey;\n if (registryKey) {\n if (keyedActors === emptyKeyedActors) {\n keyedActors = new Map();\n }\n keyedActors.set(registryKey, child);\n }\n }\n snapshotActorRefs.set(snapshot, {\n actor,\n systemState: {\n ...capturedActors,\n children,\n keyedActors,\n snapshot: { ...baseSystem._snapshot },\n sourceSystem: baseSystem,\n sourceVersion\n }\n } satisfies SnapshotActorRef);\n}\n","import { createActor } from './createActor.ts';\nimport { isMachineSnapshot } from './State.ts';\nimport {\n createSnapshotSystem,\n getSnapshotActorRef,\n getSnapshotActorRefProvider,\n peekSnapshotActorRef,\n setLazySnapshotActorRef,\n setSnapshotActorRef,\n type SnapshotActorRef\n} from './snapshotActorRef.ts';\nimport {\n ActorScope,\n AnyActor,\n AnyActorLogic,\n AnyActorScope,\n EmittedFrom,\n EventFromLogic,\n InputFrom,\n Snapshot,\n SnapshotFrom\n} from './types.ts';\nimport { lazyActorScope } from './actorScope.ts';\n\n/** @internal */\nexport function setInertActorScopeSnapshot<T>(\n actorScope: AnyActorScope,\n snapshot: T,\n attachActorRef = true\n): T {\n const lazyState = getLazyInertActorState(actorScope);\n if (lazyState) {\n lazyState.snapshot = snapshot;\n if (lazyState.materialized) {\n (lazyState.materialized.self as any)._snapshot = snapshot;\n }\n } else {\n (actorScope.self as any)._snapshot = snapshot;\n }\n if (attachActorRef && snapshot && typeof snapshot === 'object') {\n setSnapshotActorRef(snapshot as any, actorScope.self);\n }\n return snapshot;\n}\n\n/** @internal */\nexport function isInertActorScope(actorScope: AnyActorScope): boolean {\n return (\n !!getLazyInertActorState(actorScope) ||\n !!(actorScope.self as any).options?._inert\n );\n}\n\n/** @internal */\nexport function attachSnapshotActorRef<TSnapshot>(\n actorScope: AnyActorScope,\n snapshot: TSnapshot\n): TSnapshot {\n setInertActorScopeSnapshot(actorScope, snapshot, false);\n const lazyState = getLazyInertActorState(actorScope);\n snapshotActorScopes.set(snapshot as object, actorScope);\n const create = () => {\n setSnapshotActorRef(\n snapshot as Snapshot<unknown>,\n actorScope.self,\n actorScope.system\n );\n return getSnapshotActorRef(snapshot as Snapshot<unknown>)!;\n };\n if (lazyState) {\n if (lazyState.materialized) {\n lazyState.identityProvider = create;\n } else {\n lazyState.identityProvider ??= create;\n }\n }\n setLazySnapshotActorRef(snapshot as Snapshot<unknown>, create);\n return snapshot;\n}\n\ntype LazyInertActorState = {\n snapshot: unknown;\n materialized?: AnyActorScope;\n sourceRef?: () => SnapshotActorRef;\n sourceChildren: Record<string, AnyActor | undefined>;\n identityProvider?: () => SnapshotActorRef;\n parent?: AnyActor;\n parentKnown: boolean;\n materialize: () => AnyActorScope;\n};\n\nconst lazyInertActorState = Symbol();\ntype LazyInertActorScope = AnyActorScope & {\n [lazyInertActorState]?: LazyInertActorState;\n};\nconst snapshotActorScopes = new WeakMap<object, AnyActorScope>();\nlet inertActorMaterializationObserver: (() => void) | undefined;\n\nfunction getLazyInertActorState(\n actorScope: AnyActorScope\n): LazyInertActorState | undefined {\n return (actorScope as LazyInertActorScope)[lazyInertActorState];\n}\n\nfunction materializeInertActorScope(actorScope: AnyActorScope): AnyActorScope {\n return getLazyInertActorState(actorScope)!.materialize();\n}\n\nconst lazyInertActorScopePrototype = {\n [lazyActorScope]: true,\n get _parent() {\n const actorScope = this as AnyActorScope;\n const state = getLazyInertActorState(actorScope)!;\n return state.parentKnown\n ? state.parent\n : materializeInertActorScope(actorScope).self._parent;\n },\n get self() {\n return materializeInertActorScope(this as AnyActorScope).self;\n },\n get defer() {\n return materializeInertActorScope(this as AnyActorScope).defer;\n },\n get id() {\n return materializeInertActorScope(this as AnyActorScope).id;\n },\n get logger() {\n return materializeInertActorScope(this as AnyActorScope).logger;\n },\n get sessionId() {\n return materializeInertActorScope(this as AnyActorScope).sessionId;\n },\n get stopChild() {\n return materializeInertActorScope(this as AnyActorScope).stopChild;\n },\n get system() {\n return materializeInertActorScope(this as AnyActorScope).system;\n },\n get emit() {\n return materializeInertActorScope(this as AnyActorScope).emit;\n },\n get actionExecutor() {\n return materializeInertActorScope(this as AnyActorScope).actionExecutor;\n }\n};\n\n/** Test-only allocation instrumentation. @internal */\nexport function setInertActorMaterializationObserver(\n observer: (() => void) | undefined\n): void {\n inertActorMaterializationObserver = observer;\n}\n\nfunction createMaterializedInertActorScope<T extends AnyActorLogic>(\n actorLogic: T,\n sourceRef: (() => SnapshotActorRef) | undefined,\n sourceChildren: Record<string, AnyActor | undefined>,\n currentSnapshot: SnapshotFrom<T> | undefined,\n sourceSelf?: AnyActor\n): AnyActorScope {\n inertActorMaterializationObserver?.();\n const snapshotRef = sourceRef?.();\n const previousSelf = sourceSelf ?? snapshotRef?.actor;\n const baseSystem = previousSelf?.system;\n const system =\n previousSelf && baseSystem\n ? createSnapshotSystem(\n baseSystem,\n sourceChildren,\n sourceSelf ? undefined : snapshotRef?.systemState\n )\n : undefined;\n const self = createActor(\n actorLogic as AnyActorLogic,\n {\n _inert: true,\n ...(previousSelf\n ? {\n id: previousSelf.id,\n _sessionId: previousSelf.sessionId\n }\n : {}),\n ...(system ? { _systemRef: { current: system } } : {})\n } as any\n );\n if (previousSelf?._parent) {\n self._parent = previousSelf._parent;\n // `address` memoizes on first read assuming `_parent` is final; nothing\n // reads it between construction and this assignment, but drop any memo so\n // a future construction-time read cannot pin a root-shaped address.\n (self as unknown as { _address?: string })._address = undefined;\n }\n if (currentSnapshot) {\n (self as any)._snapshot = currentSnapshot;\n }\n\n // Reuse the branch actor's scope while keeping planning transactional.\n return Object.create((self as any)._actorScope, {\n defer: { value: () => {} },\n stopChild: { value: (child: AnyActor) => (child as any)._stop() },\n actionExecutor: { value: () => {} }\n });\n}\n\n/** @internal */\nexport function createInertActorScope<T extends AnyActorLogic>(\n actorLogic: T,\n snapshot?: SnapshotFrom<T>,\n sourceSelf?: AnyActor,\n sourceActorScope?: AnyActorScope\n): AnyActorScope {\n const sourceScope =\n sourceActorScope ??\n (snapshot && typeof snapshot === 'object'\n ? snapshotActorScopes.get(snapshot as object)\n : undefined);\n const sourceState = sourceScope\n ? getLazyInertActorState(sourceScope)\n : undefined;\n const eagerSourceRef =\n snapshot && typeof snapshot === 'object'\n ? peekSnapshotActorRef(snapshot as Snapshot<unknown>)\n : undefined;\n const sourceRef =\n sourceState?.identityProvider ??\n (snapshot && typeof snapshot === 'object'\n ? getSnapshotActorRefProvider(snapshot as Snapshot<unknown>)\n : undefined);\n const state = {\n snapshot,\n sourceRef,\n sourceChildren: isMachineSnapshot(snapshot)\n ? (snapshot as any).children\n : {},\n identityProvider: sourceState?.identityProvider ?? sourceRef,\n parent:\n sourceSelf?._parent ??\n sourceState?.parent ??\n eagerSourceRef?.actor._parent,\n parentKnown:\n !!sourceSelf ||\n !!sourceState?.parentKnown ||\n !!eagerSourceRef ||\n !snapshot\n } as LazyInertActorState;\n state.materialize = () =>\n (state.materialized ??= createMaterializedInertActorScope(\n actorLogic,\n state.sourceRef,\n state.sourceChildren,\n state.snapshot as SnapshotFrom<T>,\n sourceSelf\n ));\n if (!state.identityProvider && !snapshot) {\n const identitySnapshot = {} as Snapshot<unknown>;\n const identitySourceRef = state.sourceRef;\n const identitySourceChildren = state.sourceChildren;\n let identityScope: AnyActorScope | undefined;\n let identityRef: SnapshotActorRef | undefined;\n const getIdentityScope = () =>\n (identityScope ??= createMaterializedInertActorScope(\n actorLogic,\n identitySourceRef,\n identitySourceChildren,\n undefined,\n sourceSelf\n ));\n state.materialize = () => {\n const scope = getIdentityScope();\n if (state.snapshot !== undefined) {\n (scope.self as any)._snapshot = state.snapshot;\n }\n return (state.materialized = scope);\n };\n state.identityProvider = () => {\n if (identityRef) {\n return identityRef;\n }\n const scope = getIdentityScope();\n setSnapshotActorRef(identitySnapshot, scope.self, scope.system);\n return (identityRef = getSnapshotActorRef(identitySnapshot)!);\n };\n }\n const actorScope = Object.create(lazyInertActorScopePrototype) as ActorScope<\n SnapshotFrom<T>,\n EventFromLogic<T>,\n any,\n EmittedFrom<T>\n >;\n (actorScope as LazyInertActorScope)[lazyInertActorState] = state;\n return actorScope;\n}\n\n/** @deprecated Use `initialTransition(…)` instead. */\nexport function getInitialSnapshot<T extends AnyActorLogic>(\n actorLogic: T,\n ...[input]: undefined extends InputFrom<T>\n ? [input?: InputFrom<T>]\n : [input: InputFrom<T>]\n): SnapshotFrom<T> {\n const actorScope = createInertActorScope(actorLogic);\n return actorLogic.initialTransition(input, actorScope)[0];\n}\n\n/**\n * Determines the next snapshot for the given `actorLogic` based on the given\n * `snapshot` and `event`.\n *\n * If the `snapshot` is `undefined`, the initial snapshot of the `actorLogic` is\n * used.\n *\n * @deprecated Use `transition(…)` instead.\n * @example\n *\n * ```ts\n * import { getNextSnapshot } from 'xstate';\n * import { trafficLightMachine } from './trafficLightMachine.ts';\n *\n * const nextSnapshot = getNextSnapshot(\n * trafficLightMachine, // actor logic\n * undefined, // snapshot (or initial state if undefined)\n * { type: 'TIMER' }\n * ); // event object\n *\n * console.log(nextSnapshot.value);\n * // => 'yellow'\n *\n * const nextSnapshot2 = getNextSnapshot(\n * trafficLightMachine, // actor logic\n * nextSnapshot, // snapshot\n * { type: 'TIMER' }\n * ); // event object\n *\n * console.log(nextSnapshot2.value);\n * // =>'red'\n * ```\n */\nexport function getNextSnapshot<T extends AnyActorLogic>(\n actorLogic: T,\n snapshot: SnapshotFrom<T>,\n event: EventFromLogic<T>\n): SnapshotFrom<T> {\n const actorScope = createInertActorScope(actorLogic, snapshot);\n const transitionResult = actorLogic.transition(snapshot, event, actorScope);\n const nextSnapshot = Array.isArray(transitionResult)\n ? transitionResult[0]\n : transitionResult;\n setInertActorScopeSnapshot(actorScope, nextSnapshot, false);\n return nextSnapshot === snapshot\n ? nextSnapshot\n : attachSnapshotActorRef(actorScope, nextSnapshot);\n}\n","import isDevelopment from '#is-development';\nimport { MachineSnapshot, cloneMachineSnapshot } from './State.ts';\nimport type { StateNode } from './StateNode.ts';\nimport {\n createAfterEvent,\n createAfterEventId,\n createDoneStateEvent,\n createInvokeTimeoutEvent,\n createInvokeTimeoutEventId,\n createTimeoutEvent,\n createTimeoutEventId\n} from './eventUtils.ts';\nimport {\n XSTATE_INIT,\n STATE_DELIMITER,\n STATE_IDENTIFIER,\n XSTATE_STOP,\n XSTATE_TIMER\n} from './constants.ts';\nimport {\n getEventOutput,\n isErrorEvent,\n matchesEvent,\n matchesEventDescriptor\n} from './utils.ts';\nimport {\n AnyEventObject,\n AnyMachineSnapshot,\n AnyStateMachine,\n AnyStateNode,\n AnyTransitionDefinition,\n DelayedTransitionDefinition,\n EventObject,\n ExecutableActionObject,\n HistoryValue,\n MachineContext,\n StateValue,\n TransitionDefinition,\n AnyAction,\n AnyTransitionConfig,\n AnyActor,\n AnyActorScope,\n DoneStateEvent\n} from './types.ts';\nimport {\n resolveOutput,\n normalizeTarget,\n toArray,\n toStatePath,\n resolveReferencedActor,\n toTransitionConfigArray\n} from './utils.ts';\nimport { builtInActions } from './actions.ts';\nimport {\n assertChildIdFree,\n createEnqueueObject,\n createTerminationEffect,\n createTransitionEnqueue,\n createSendToEffect,\n deriveDeferredStarts,\n mergeContextPatch,\n resolveActionsWithContext\n} from './transitionActions.ts';\nimport { parseDurationToMilliseconds } from './delay.ts';\nimport { transitionEffectSignal, transitionEffectTargets } from './system.ts';\nimport { isInertActorScope } from './getNextSnapshot.ts';\nimport {\n getActorScopeParent,\n isLazyActorScope,\n withActorSelfAndParent,\n withActorScope\n} from './actorScope.ts';\n\ntype AnyStateNodeIterable = Iterable<AnyStateNode>;\n\nfunction getConfiguredDelayValue(\n delay: number | string,\n delaySource: Record<string, any>\n) {\n if (typeof delay !== 'string') {\n return delay;\n }\n\n const referencedDelay = delaySource[delay];\n if (referencedDelay !== undefined) {\n return referencedDelay;\n }\n\n return parseDurationToMilliseconds(delay) ?? delay;\n}\n\nfunction resolveDelay(\n delay: number | string | ((args: any) => number),\n delaySource: Record<string, any>,\n args: {\n context: MachineContext;\n event: EventObject;\n stateNode: AnyStateNode;\n input?: Record<string, unknown>;\n }\n) {\n if (typeof delay === 'function') {\n return delay(args);\n }\n\n const configuredDelay = getConfiguredDelayValue(delay, delaySource);\n if (typeof configuredDelay === 'function') {\n return configuredDelay(args);\n }\n\n return configuredDelay;\n}\n\nfunction getStateInput(snapshot: AnyMachineSnapshot, stateNodeId: string) {\n return snapshot._stateInputs?.[stateNodeId];\n}\n\nexport function isAtomicStateNode(stateNode: AnyStateNode) {\n return (\n stateNode.type === 'atomic' ||\n stateNode.type === 'final' ||\n stateNode.type === 'choice'\n );\n}\n\nfunction getChildren(stateNode: AnyStateNode): Array<AnyStateNode> {\n return Object.values(stateNode.states).filter((sn) => sn.type !== 'history');\n}\n\nexport function getProperAncestors(\n stateNode: AnyStateNode,\n toStateNode: AnyStateNode | undefined\n): Array<typeof stateNode> {\n const ancestors: Array<typeof stateNode> = [];\n\n if (toStateNode === stateNode) {\n return ancestors;\n }\n\n // add all ancestors\n let m = stateNode.parent;\n while (m && m !== toStateNode) {\n ancestors.push(m);\n m = m.parent;\n }\n\n return ancestors;\n}\n\nexport function getAllStateNodes(\n stateNodes: Iterable<AnyStateNode>\n): Set<AnyStateNode> {\n const nodeSet = new Set(stateNodes);\n const activeParentSet = new Set<AnyStateNode>();\n for (const stateNode of nodeSet) {\n if (stateNode.parent) {\n activeParentSet.add(stateNode.parent);\n }\n }\n\n // add descendants\n for (const s of nodeSet) {\n // if previously active, add existing child nodes\n if (s.type === 'compound' && !activeParentSet.has(s)) {\n for (const sn of getInitialStateNodes(s)) {\n nodeSet.add(sn);\n }\n continue;\n }\n\n if (s.type === 'parallel') {\n for (const child of getChildren(s)) {\n if (!nodeSet.has(child)) {\n const initialStates = getInitialStateNodes(child);\n for (const initialStateNode of initialStates) {\n nodeSet.add(initialStateNode);\n }\n }\n }\n }\n }\n\n // add all ancestors\n // Stop walking up as soon as we hit a node already in the set: its own\n // ancestor chain is guaranteed to be added when it is visited by this loop\n // (Set iteration visits elements added during iteration), so shared ancestor\n // chains are never re-walked once per descendant.\n for (const s of nodeSet) {\n let m = s.parent;\n\n while (m && !nodeSet.has(m)) {\n nodeSet.add(m);\n m = m.parent;\n }\n }\n\n return nodeSet;\n}\n\nexport function getStateValue(\n rootNode: AnyStateNode,\n stateNodes: AnyStateNodeIterable\n): StateValue {\n const config = getAllStateNodes(stateNodes);\n const adjList = new Map<AnyStateNode, Array<AnyStateNode>>();\n\n for (const s of config) {\n if (!adjList.has(s)) {\n adjList.set(s, []);\n }\n\n if (!s.parent) {\n continue;\n }\n\n if (!adjList.has(s.parent)) {\n adjList.set(s.parent, []);\n }\n\n adjList.get(s.parent)!.push(s);\n }\n\n const getValueFromAdj = (baseNode: AnyStateNode): StateValue => {\n const childStateNodes = adjList.get(baseNode);\n\n if (!childStateNodes) {\n return {}; // todo: fix?\n }\n\n if (baseNode.type === 'compound') {\n const childStateNode = childStateNodes[0];\n if (!childStateNode) {\n return {};\n }\n if (isAtomicStateNode(childStateNode)) {\n return childStateNode.key;\n }\n }\n\n const stateValue: StateValue = {};\n for (const childStateNode of childStateNodes) {\n stateValue[childStateNode.key] = getValueFromAdj(childStateNode);\n }\n\n return stateValue;\n };\n\n return getValueFromAdj(rootNode);\n}\n\nexport function isInFinalState(\n stateNodeSet: Set<AnyStateNode>,\n stateNode: AnyStateNode\n): boolean {\n if (stateNode.type === 'compound') {\n return getChildren(stateNode).some(\n (s) => s.type === 'final' && stateNodeSet.has(s)\n );\n }\n if (stateNode.type === 'parallel') {\n return getChildren(stateNode).every((sn) =>\n isInFinalState(stateNodeSet, sn)\n );\n }\n\n return stateNode.type === 'final';\n}\n\nexport const isStateId = (str: string) => str[0] === STATE_IDENTIFIER;\n\nfunction getLegacyEventType(event: EventObject): string | undefined {\n switch (event.type) {\n case 'xstate.done.actor':\n case 'xstate.error.actor':\n return `${event.type}.${(event as any).actorId}`;\n case 'xstate.snapshot.actor':\n return `xstate.snapshot.${(event as any).actorId}`;\n case 'xstate.done.state':\n return `xstate.done.state.${(event as any).stateId}`;\n case 'xstate.after':\n return `xstate.after.${(event as any).delay}.${(event as any).stateId}`;\n case 'xstate.timeout':\n return `xstate.timeout.${(event as any).stateId}`;\n case 'xstate.timeout.actor':\n return `xstate.timeout.actor.${(event as any).actorId}`;\n default:\n return undefined;\n }\n}\n\nfunction getEventTypeAliases(event: EventObject): string[] {\n const legacyType = getLegacyEventType(event);\n return legacyType ? [event.type, legacyType] : [event.type];\n}\n\nexport function getEventDescriptorKey(event: EventObject): string {\n const legacyType = getLegacyEventType(event);\n return legacyType ? `${event.type}|${legacyType}` : event.type;\n}\n\nexport function matchesActorSession(\n event: EventObject,\n snapshot: AnyMachineSnapshot,\n actorId: string\n): boolean {\n const child = snapshot.children[actorId];\n if (!child || !('sessionId' in event)) {\n return true;\n }\n // One rule: a ref that knows its incarnation compares it; a remote handle\n // without a host-supplied token (sessionId undefined) defers to the\n // runtime that owns the child.\n return (\n child.sessionId === undefined ||\n child.sessionId === (event as { sessionId?: string }).sessionId\n );\n}\n\nfunction normalizeLegacyInternalEvent(\n event: EventObject,\n machine: AnyStateMachine\n): EventObject {\n if (\n event.type === 'xstate.done.actor' ||\n event.type === 'xstate.error.actor' ||\n event.type === 'xstate.snapshot.actor' ||\n event.type === 'xstate.done.state' ||\n event.type === 'xstate.after' ||\n event.type === 'xstate.timeout' ||\n event.type === 'xstate.timeout.actor'\n ) {\n return event;\n }\n\n const normalizeWithId = (\n prefix: string,\n type: string,\n idKey: 'actorId' | 'stateId'\n ) =>\n event.type.startsWith(prefix)\n ? {\n ...event,\n type,\n [idKey]: (event as any)[idKey] ?? event.type.slice(prefix.length)\n }\n : undefined;\n\n const normalized =\n normalizeWithId('xstate.done.actor.', 'xstate.done.actor', 'actorId') ??\n normalizeWithId('xstate.error.actor.', 'xstate.error.actor', 'actorId') ??\n normalizeWithId('xstate.snapshot.', 'xstate.snapshot.actor', 'actorId') ??\n normalizeWithId('xstate.done.state.', 'xstate.done.state', 'stateId') ??\n normalizeWithId(\n 'xstate.timeout.actor.',\n 'xstate.timeout.actor',\n 'actorId'\n ) ??\n normalizeWithId('xstate.timeout.', 'xstate.timeout', 'stateId');\n\n if (normalized) {\n return normalized;\n }\n\n const afterPrefix = 'xstate.after.';\n if (!event.type.startsWith(afterPrefix)) {\n return event;\n }\n\n const stateId = [...machine.idMap.keys()]\n .sort((a, b) => b.length - a.length)\n .find((id) => event.type.endsWith(`.${id}`));\n if (!stateId) {\n return event;\n }\n const delayText = event.type.slice(afterPrefix.length, -stateId.length - 1);\n return {\n ...event,\n type: 'xstate.after',\n delay: Number.isNaN(+delayText) ? delayText : +delayText,\n stateId\n } as AnyEventObject;\n}\n\nexport function getCandidates<TEvent extends EventObject>(\n stateNode: StateNode<any, TEvent>,\n event: TEvent\n): Array<TransitionDefinition<any, TEvent>> {\n const eventTypes = getEventTypeAliases(event);\n const exactMatches = eventTypes.flatMap(\n (eventType) => stateNode.transitions.get(eventType) ?? []\n );\n const wildcardCandidates = [...stateNode.transitions.keys()]\n .filter(\n (eventDescriptor) =>\n !eventTypes.includes(eventDescriptor) &&\n eventTypes.some((eventType) =>\n matchesEventDescriptor(eventType, eventDescriptor)\n )\n )\n .sort((a, b) => b.length - a.length)\n .flatMap((key) => stateNode.transitions.get(key)!);\n\n return exactMatches.length\n ? [...exactMatches, ...wildcardCandidates]\n : wildcardCandidates;\n}\n\nfunction scheduleDelayedEvent(\n stateNode: AnyStateNode,\n timerId: string,\n resolveEvent: (args: any) => AnyEventObject,\n resolveScheduledDelay: (x: {\n context: MachineContext;\n event: EventObject;\n delays: Record<string, any>;\n input?: Record<string, unknown>;\n }) => any\n) {\n const oldEntry = stateNode.entry;\n stateNode.entry = (x: any, enq: any) => {\n enq.raise(resolveEvent(x) as any, {\n id: timerId,\n delay: resolveScheduledDelay(x)\n });\n return typeof oldEntry === 'function' ? oldEntry(x, enq) : undefined;\n };\n const oldExit = stateNode.exit;\n stateNode.exit = (_: any, enq: any) => {\n enq.cancel(timerId);\n return typeof oldExit === 'function' ? oldExit(_, enq) : undefined;\n };\n}\n\n/** All delayed transitions from the config. */\nexport function getDelayedTransitions(\n stateNode: AnyStateNode\n): Array<DelayedTransitionDefinition<MachineContext, EventObject>> {\n const afterConfig = stateNode.config.after;\n const timeoutConfig = (stateNode.config as any).timeout;\n const onTimeoutConfig = (stateNode.config as any).onTimeout;\n const invokeDefs = stateNode.invoke.filter(\n (invokeDef) => invokeDef.timeout !== undefined\n );\n\n if (!afterConfig && timeoutConfig === undefined && invokeDefs.length === 0) {\n return [];\n }\n\n if (isDevelopment && timeoutConfig !== undefined && !onTimeoutConfig) {\n throw new Error(\n `State \"${stateNode.id}\" has \\`timeout\\` but no \\`onTimeout\\` transition.`\n );\n }\n\n if (isDevelopment) {\n for (const invokeDef of invokeDefs) {\n if (!invokeDef.onTimeout) {\n throw new Error(\n `Invoke on state \"${stateNode.id}\" has \\`timeout\\` but no \\`onTimeout\\` transition.`\n );\n }\n }\n }\n\n // Every delayed transition — `after`, state-level `timeout`/`onTimeout`, and\n // invoke-level `timeout`/`onTimeout` — has the same shape: an event raised on\n // entry (and cancelled on exit) plus a transition that catches it. They\n // differ only in the event raised, the transition(s) caught, and whether the\n // delay resolves against the machine's `delays` map (invoke timeouts do not).\n //\n // `xstate.timeout` is a dedicated event category so a state-level `timeout`\n // cannot collide with an explicit `after` entry on the same state. Invoke\n // timeouts are scheduled on the enclosing state; completion transitions\n // cancel the timer separately, so it clears even when the parent stays active.\n const sources: Array<{\n event: AnyEventObject;\n timerId: string;\n resolveEvent?: (args: any) => AnyEventObject;\n eventMatcher?: (\n event: EventObject,\n snapshot: AnyMachineSnapshot\n ) => boolean;\n delay: any;\n transitions: unknown;\n fromDelaysMap: boolean;\n }> = [];\n\n if (afterConfig) {\n for (const key of Object.keys(afterConfig)) {\n const delay = Number.isNaN(+key) ? key : +key;\n sources.push({\n event: createAfterEvent(delay, stateNode.id),\n timerId: createAfterEventId(delay, stateNode.id),\n delay,\n transitions: afterConfig[key],\n fromDelaysMap: true\n });\n }\n }\n\n if (timeoutConfig !== undefined && onTimeoutConfig) {\n sources.push({\n event: createTimeoutEvent(stateNode.id),\n timerId: createTimeoutEventId(stateNode.id),\n delay: timeoutConfig,\n transitions: onTimeoutConfig,\n fromDelaysMap: true\n });\n }\n\n for (const invokeDef of invokeDefs) {\n sources.push({\n event: createInvokeTimeoutEvent(invokeDef.id),\n timerId: createInvokeTimeoutEventId(invokeDef.id),\n resolveEvent: ({ children }: any) =>\n createInvokeTimeoutEvent(\n invokeDef.id,\n children[invokeDef.id]?.sessionId\n ),\n eventMatcher: (event, snapshot) =>\n matchesActorSession(event, snapshot, invokeDef.id),\n delay: invokeDef.timeout!,\n transitions: invokeDef.onTimeout,\n fromDelaysMap: false\n });\n }\n\n // `delay` here is the raw config value, retained only as metadata on the\n // transition definition — the live delay is resolved at runtime in the\n // scheduled entry action, so no eager resolution is needed.\n const delayedTransitions: Array<\n AnyTransitionConfig & {\n event: string;\n delay: any;\n _eventMatcher?: (\n event: EventObject,\n snapshot: AnyMachineSnapshot\n ) => boolean;\n }\n > = [];\n\n for (const {\n event,\n timerId,\n resolveEvent,\n eventMatcher,\n delay,\n transitions,\n fromDelaysMap\n } of sources) {\n scheduleDelayedEvent(\n stateNode,\n timerId,\n resolveEvent ?? (() => event),\n (x) =>\n resolveDelay(delay, fromDelaysMap ? x.delays : {}, {\n context: x.context,\n event: x.event,\n stateNode,\n input: x.input\n })\n );\n const { type: eventType, ...eventPattern } = event;\n for (const transition of toTransitionConfigArray(transitions as any)) {\n delayedTransitions.push({\n ...transition,\n matches: {\n ...transition.matches,\n ...Object.fromEntries(\n Object.entries(eventPattern).filter(\n ([, value]) => value !== undefined\n )\n )\n },\n event: eventType,\n delay,\n _eventMatcher: eventMatcher\n });\n }\n }\n\n return delayedTransitions.map((delayedTransition) => ({\n ...formatTransition(\n stateNode,\n delayedTransition.event,\n delayedTransition as AnyTransitionConfig\n ),\n delay: delayedTransition.delay\n }));\n}\n\nexport function formatTransition(\n stateNode: AnyStateNode,\n descriptor: string,\n transitionConfig: AnyTransitionConfig\n): AnyTransitionDefinition {\n const normalizedTarget = normalizeTarget(transitionConfig.target);\n const reenter = transitionConfig.reenter ?? false;\n const target = resolveTarget(stateNode, normalizedTarget);\n assertLegalTargetSet(stateNode, target);\n\n const transition = {\n ...transitionConfig,\n target,\n source: stateNode,\n reenter,\n eventType: descriptor,\n toJSON: () => ({\n ...transition,\n source: `#${stateNode.id}`,\n target: target ? target.map((t) => `#${t.id}`) : undefined\n })\n };\n\n return transition;\n}\n\nfunction isStateNodeDescendantOf(\n stateNode: AnyStateNode,\n ancestor: AnyStateNode\n): boolean {\n for (let current = stateNode.parent; current; current = current.parent) {\n if (current === ancestor) {\n return true;\n }\n }\n return false;\n}\n\nfunction getLeastCommonStateNodeAncestor(\n left: AnyStateNode,\n right: AnyStateNode\n): AnyStateNode | undefined {\n const leftAncestors = new Set<AnyStateNode>();\n for (\n let current: AnyStateNode | undefined = left;\n current;\n current = current.parent\n ) {\n leftAncestors.add(current);\n }\n for (\n let current: AnyStateNode | undefined = right;\n current;\n current = current.parent\n ) {\n if (leftAncestors.has(current)) {\n return current;\n }\n }\n return undefined;\n}\n\nfunction assertLegalTargetSet(\n source: AnyStateNode,\n targets: readonly AnyStateNode[] | undefined\n): void {\n if (!targets || targets.length < 2) {\n return;\n }\n for (let leftIndex = 0; leftIndex < targets.length; leftIndex++) {\n for (\n let rightIndex = leftIndex + 1;\n rightIndex < targets.length;\n rightIndex++\n ) {\n const left = targets[leftIndex];\n const right = targets[rightIndex];\n const commonAncestor = getLeastCommonStateNodeAncestor(left, right);\n if (\n left === right ||\n isStateNodeDescendantOf(left, right) ||\n isStateNodeDescendantOf(right, left) ||\n commonAncestor?.type !== 'parallel'\n ) {\n throw new Error(\n isDevelopment\n ? `Invalid transition definition for state node '${source.id}': target set is not a legal SCXML configuration.`\n : `Invalid target set for '${source.id}'`\n );\n }\n }\n }\n}\n\n/**\n * Collects route transitions from all descendants with explicit IDs. Called\n * once on the root node to avoid O(N²) repeated traversals.\n */\nexport function formatRouteTransitions(rootStateNode: AnyStateNode): void {\n const routeTransitions: AnyTransitionDefinition[] = [];\n const collectRoutes = (states: Record<string, AnyStateNode>) => {\n Object.values(states).forEach((sn) => {\n if (sn.config.route && sn.config.id) {\n const routeId = sn.config.id;\n const routeConfig = sn.config.route;\n const routeMatches = ({ event }: { event: any }) =>\n event.to === `#${routeId}`;\n\n if (typeof routeConfig === 'function') {\n // Transition-style route: the function is the guard and resolver.\n // Returning undefined/false blocks the route; returning true or a\n // config object allows it.\n routeTransitions.push(\n formatTransition(rootStateNode, 'xstate.route', {\n guard: routeMatches,\n to: (args: any) => {\n const result = routeConfig(args);\n if (!result) {\n return undefined;\n }\n return {\n ...(result === true ? {} : result),\n target: `#${routeId}`\n };\n }\n } as AnyTransitionConfig)\n );\n if (sn.states) {\n collectRoutes(sn.states);\n }\n return;\n }\n\n const { guard: _guard, ...routeOptions } = routeConfig as any;\n const transition: AnyTransitionConfig = {\n ...routeOptions,\n guard: routeMatches,\n target: `#${routeId}`\n };\n\n routeTransitions.push(\n formatTransition(rootStateNode, 'xstate.route', transition)\n );\n }\n if (sn.states) {\n collectRoutes(sn.states);\n }\n });\n };\n collectRoutes(rootStateNode.states);\n if (routeTransitions.length > 0) {\n rootStateNode.transitions.set('xstate.route', routeTransitions as any);\n }\n}\n\nfunction resolveTarget(\n stateNode: AnyStateNode,\n targets: ReadonlyArray<string | AnyStateNode> | undefined\n): ReadonlyArray<AnyStateNode> | undefined {\n if (targets === undefined) {\n // an undefined target signals that the state node should not transition from that state when receiving that event\n return undefined;\n }\n return targets.map((target) => {\n if (typeof target !== 'string') {\n return target;\n }\n if (isStateId(target)) {\n return stateNode.machine.getStateNodeById(target);\n }\n\n const isInternalTarget = target[0] === STATE_DELIMITER;\n // If internal target is defined on machine,\n // do not include machine key on target\n if (isInternalTarget && !stateNode.parent) {\n return getStateNodeByPath(stateNode, target.slice(1));\n }\n const resolvedTarget = isInternalTarget ? stateNode.key + target : target;\n if (stateNode.parent) {\n try {\n const targetStateNode = getStateNodeByPath(\n stateNode.parent,\n resolvedTarget\n );\n return targetStateNode;\n } catch (err: any) {\n throw new Error(\n isDevelopment\n ? `Invalid transition definition for state node '${stateNode.id}':\\n${err.message}`\n : `Invalid transition for '${stateNode.id}': ${err.message}`\n );\n }\n } else {\n throw new Error(\n isDevelopment\n ? `Invalid target: \"${target}\" is not a valid target from the root node. Did you mean \".${target}\"?`\n : `Invalid target: \"${target}\"`\n );\n }\n });\n}\n\nfunction resolveHistoryDefaultTransition(\n stateNode: AnyStateNode & { type: 'history' }\n): AnyTransitionDefinition {\n const normalizedTarget = normalizeTarget(stateNode.config.target);\n if (!normalizedTarget) {\n if (stateNode.parent!.type === 'parallel') {\n return {\n target: [stateNode.parent!],\n source: stateNode,\n reenter: false,\n eventType: '' as any\n };\n }\n return stateNode.parent!.initial as AnyTransitionDefinition;\n }\n const target = normalizedTarget.map((t) =>\n typeof t === 'string' ? getStateNodeByPath(stateNode.parent!, t) : t\n );\n assertLegalTargetSet(stateNode, target);\n return {\n target,\n source: stateNode,\n reenter: false,\n eventType: '' as any,\n to: (stateNode.config as any)._historyDefaultTransition\n };\n}\n\nfunction isHistoryNode(\n stateNode: AnyStateNode\n): stateNode is AnyStateNode & { type: 'history' } {\n return stateNode.type === 'history';\n}\n\nfunction getInitialStateNodes(stateNode: AnyStateNode) {\n const set = new Set<AnyStateNode>();\n\n function iter(descStateNode: AnyStateNode): void {\n if (set.has(descStateNode)) {\n return;\n }\n set.add(descStateNode);\n if (descStateNode.type === 'compound') {\n for (const target of descStateNode.initial.target ?? []) {\n iter(target);\n }\n } else if (descStateNode.type === 'parallel') {\n for (const child of getChildren(descStateNode)) {\n iter(child);\n }\n }\n }\n\n iter(stateNode);\n for (const initialState of set) {\n for (const ancestor of getProperAncestors(initialState, stateNode)) {\n set.add(ancestor);\n }\n }\n\n return set;\n}\n\n/** Returns the child state node from its relative `stateKey`, or throws. */\nfunction getStateNode(stateNode: AnyStateNode, stateKey: string): AnyStateNode {\n if (isStateId(stateKey)) {\n return stateNode.machine.getStateNodeById(stateKey);\n }\n const result = stateNode.states?.[stateKey];\n if (!result) {\n throw new Error(\n isDevelopment && !stateNode.states\n ? `Unable to retrieve child state '${stateKey}' from '${stateNode.id}'; no child states exist.`\n : `Child state '${stateKey}' does not exist on '${stateNode.id}'`\n );\n }\n return result;\n}\n\n/**\n * Returns the relative state node from the given `statePath`, or throws.\n *\n * @param statePath The string or string array relative path to the state node.\n */\nexport function getStateNodeByPath(\n stateNode: AnyStateNode,\n statePath: string | string[]\n): AnyStateNode {\n if (typeof statePath === 'string' && isStateId(statePath)) {\n try {\n return stateNode.machine.getStateNodeById(statePath);\n } catch {\n // try individual paths\n // throw e;\n }\n }\n const arrayStatePath = toStatePath(statePath).slice();\n let currentStateNode: AnyStateNode = stateNode;\n while (arrayStatePath.length) {\n const key = arrayStatePath.shift()!;\n if (!key.length) {\n break;\n }\n currentStateNode = getStateNode(currentStateNode, key);\n }\n return currentStateNode;\n}\n\n/**\n * Returns the state nodes represented by the current state value.\n *\n * @param stateValue The state value or State instance\n */\nexport function getStateNodes(\n stateNode: AnyStateNode,\n stateValue: StateValue\n): Array<AnyStateNode> {\n if (typeof stateValue === 'string') {\n const childStateNode = stateNode.states[stateValue];\n if (!childStateNode) {\n throw new Error(\n `State '${stateValue}' does not exist on '${stateNode.id}'`\n );\n }\n return [stateNode, childStateNode];\n }\n\n const childStateKeys = Object.keys(stateValue);\n const childStateNodes = new Array<AnyStateNode>(childStateKeys.length);\n const allStateNodes: Array<AnyStateNode> = [\n stateNode.machine.root,\n stateNode\n ];\n\n for (let i = 0; i < childStateKeys.length; i++) {\n const subStateNode = getStateNode(stateNode, childStateKeys[i]);\n childStateNodes[i] = subStateNode;\n allStateNodes.push(subStateNode);\n }\n\n for (let i = 0; i < childStateKeys.length; i++) {\n allStateNodes.push(\n ...getStateNodes(childStateNodes[i], stateValue[childStateKeys[i]]!)\n );\n }\n\n return allStateNodes;\n}\n\nexport type TransitionSelectionResult = {\n enabled: boolean;\n result: unknown;\n reusable: boolean;\n};\n\nexport type TransitionSelectionResults = Map<\n AnyTransitionDefinition,\n TransitionSelectionResult\n>;\n\nexport function transitionNode<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(\n stateNode: AnyStateNode,\n stateValue: StateValue,\n snapshot: MachineSnapshot<\n TContext,\n TEvent,\n any,\n any,\n any,\n any,\n any,\n any // TStateSchema\n >,\n event: TEvent,\n actorScope: AnyActorScope,\n selectionResults?: TransitionSelectionResults\n): Array<TransitionDefinition<TContext, TEvent>> | undefined {\n // leaf node\n if (typeof stateValue === 'string') {\n const childStateNode = getStateNode(stateNode, stateValue);\n const next = childStateNode.next(\n snapshot,\n event,\n actorScope,\n selectionResults\n );\n\n if (!next || !next.length) {\n return stateNode.next(snapshot, event, actorScope, selectionResults);\n }\n\n return next;\n }\n\n const subStateKeys = Object.keys(stateValue);\n const subStateKey = subStateKeys[0];\n\n if (subStateKeys.length === 1) {\n const childStateNode = getStateNode(stateNode, subStateKey);\n const next = transitionNode(\n childStateNode,\n stateValue[subStateKey]!,\n snapshot,\n event,\n actorScope,\n selectionResults\n );\n\n if (!next || !next.length) {\n return stateNode.next(snapshot, event, actorScope, selectionResults);\n }\n\n return next;\n }\n\n const allInnerTransitions: Array<TransitionDefinition<TContext, TEvent>> = [];\n\n for (const subStateKey of subStateKeys) {\n const subStateValue = stateValue[subStateKey];\n\n if (!subStateValue) {\n continue;\n }\n\n const subStateNode = getStateNode(stateNode, subStateKey);\n const innerTransitions = transitionNode(\n subStateNode,\n subStateValue,\n snapshot,\n event,\n actorScope,\n selectionResults\n );\n if (innerTransitions) {\n allInnerTransitions.push(...innerTransitions);\n }\n }\n\n if (!allInnerTransitions.length) {\n return stateNode.next(snapshot, event, actorScope, selectionResults);\n }\n\n return allInnerTransitions;\n}\n\nfunction isDescendant(\n childStateNode: AnyStateNode,\n parentStateNode: AnyStateNode\n): boolean {\n let marker = childStateNode;\n while (marker.parent && marker.parent !== parentStateNode) {\n marker = marker.parent;\n }\n\n return marker.parent === parentStateNode;\n}\n\nfunction hasDescendantState(\n stateNodes: Set<AnyStateNode>,\n parentStateNode: AnyStateNode\n): boolean {\n for (const stateNode of stateNodes) {\n if (isDescendant(stateNode, parentStateNode)) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction hasIntersection<T>(s1: Iterable<T>, s2: Iterable<T>): boolean {\n const s1Size =\n s1 instanceof Set ? s1.size : Array.isArray(s1) ? s1.length : undefined;\n const s2Size =\n s2 instanceof Set ? s2.size : Array.isArray(s2) ? s2.length : undefined;\n\n if (s1Size !== undefined && s2Size !== undefined && s2Size < s1Size) {\n [s1, s2] = [s2, s1];\n }\n\n const set1 = s1 instanceof Set ? s1 : new Set(s1);\n for (const item of s2) {\n if (set1.has(item)) {\n return true;\n }\n }\n return false;\n}\n\nfunction removeConflictingTransitions(\n enabledTransitions: Array<AnyTransitionDefinition>,\n stateNodeSet: Set<AnyStateNode>,\n snapshot: AnyMachineSnapshot,\n resolveTransition: TransitionResultResolver\n): Array<AnyTransitionDefinition> {\n const filteredTransitions = new Set<AnyTransitionDefinition>();\n const exitSets = new Map<AnyTransitionDefinition, Array<AnyStateNode>>();\n\n const getExitSet = (transition: AnyTransitionDefinition) => {\n let exitSet = exitSets.get(transition);\n if (!exitSet) {\n exitSet = computeExitSet(\n [transition],\n stateNodeSet,\n snapshot,\n resolveTransition\n );\n exitSets.set(transition, exitSet);\n }\n\n return exitSet;\n };\n\n for (const t1 of enabledTransitions) {\n let t1Preempted = false;\n const transitionsToRemove = new Set<AnyTransitionDefinition>();\n for (const t2 of filteredTransitions) {\n if (hasIntersection(getExitSet(t1), getExitSet(t2))) {\n if (isDescendant(t1.source, t2.source)) {\n transitionsToRemove.add(t2);\n } else if (t2.source.type === 'final' && t1.source.type !== 'final') {\n // A transition sourced in a final state yields to a conflicting\n // transition from a live state, so a done region doesn't keep\n // consuming events its siblings can still handle.\n transitionsToRemove.add(t2);\n } else {\n t1Preempted = true;\n break;\n }\n }\n }\n if (!t1Preempted) {\n for (const t3 of transitionsToRemove) {\n filteredTransitions.delete(t3);\n }\n filteredTransitions.add(t1);\n }\n }\n\n return Array.from(filteredTransitions);\n}\n\ntype ResolvableTransition = Parameters<typeof getTransitionResult>[0];\ntype TransitionResultResolver = (\n transition: ResolvableTransition\n) => ReturnType<typeof getTransitionResult>;\n\nfunction createTransitionResultResolver(\n snapshot: AnyMachineSnapshot,\n event: AnyEventObject,\n actorScope: AnyActorScope,\n resolveActions: boolean,\n selectionResults?: TransitionSelectionResults\n): TransitionResultResolver {\n let cache:\n | Map<ResolvableTransition, ReturnType<typeof getTransitionResult>>\n | undefined;\n return (transition) => {\n if (!transition.to) {\n return getTransitionResult(transition, snapshot, event, actorScope, {\n resolveActions,\n selectionResult: selectionResults?.get(\n transition as AnyTransitionDefinition\n )\n });\n }\n let result = cache?.get(transition);\n if (!result) {\n result = getTransitionResult(transition, snapshot, event, actorScope, {\n resolveActions,\n selectionResult: selectionResults?.get(\n transition as AnyTransitionDefinition\n )\n });\n (cache ??= new Map()).set(transition, result);\n }\n return result;\n };\n}\n\nfunction getEffectiveTargetStates(\n transition: Pick<AnyTransitionDefinition, 'target' | 'source'>,\n snapshot: AnyMachineSnapshot,\n resolveTransition: TransitionResultResolver\n): Array<AnyStateNode> {\n const historyValue = snapshot.historyValue;\n const { targets } = resolveTransition(transition);\n if (!targets) {\n return [];\n }\n\n const targetSet = new Set<AnyStateNode>();\n\n for (const targetNode of targets) {\n if (isHistoryNode(targetNode)) {\n if (historyValue[targetNode.id]) {\n for (const node of historyValue[targetNode.id]) {\n targetSet.add(node);\n }\n } else {\n for (const node of getEffectiveTargetStates(\n resolveHistoryDefaultTransition(targetNode),\n snapshot,\n resolveTransition\n )) {\n targetSet.add(node);\n }\n }\n } else {\n targetSet.add(targetNode);\n }\n }\n\n return [...targetSet];\n}\n\n/**\n * Narrows a parallel domain to the single child region that contains every\n * effective target, so that a transition confined to one region does not exit\n * (and reset) its sibling regions.\n */\nfunction narrowParallelDomain(\n domain: AnyStateNode,\n targetStates: Array<AnyStateNode>\n): AnyStateNode {\n let narrowed = domain;\n while (narrowed.type === 'parallel') {\n const region = getChildren(narrowed).find((child) =>\n targetStates.every(\n (target) => target === child || isDescendant(target, child)\n )\n );\n if (!region) {\n break;\n }\n narrowed = region;\n }\n return narrowed;\n}\n\nfunction getTransitionDomain(\n transition: AnyTransitionDefinition,\n snapshot: AnyMachineSnapshot,\n resolveTransition: TransitionResultResolver\n): AnyStateNode | undefined {\n const targetStates = getEffectiveTargetStates(\n transition,\n snapshot,\n resolveTransition\n );\n\n const { targets, reenter } = resolveTransition(transition);\n\n if (transition._transitionDomain) {\n if (\n transition._transitionDomain === 'internal' &&\n transition.source.type === 'compound' &&\n targetStates.every((target) => isDescendant(target, transition.source))\n ) {\n return transition.source;\n }\n\n const [head, ...tail] = targetStates.concat(transition.source);\n for (const ancestor of getProperAncestors(head, undefined)) {\n if (\n ancestor.type === 'compound' &&\n tail.every((stateNode) => isDescendant(stateNode, ancestor))\n ) {\n return ancestor;\n }\n }\n\n return;\n }\n\n // A history target that restores the source itself must exit and reenter\n // the source (SCXML domain = the source's ancestor), unlike a plain\n // non-reentering self-target: the enter set restores the stored\n // configuration from outside the source, so the exit set must match or the\n // source's invoked actors are re-created without being stopped.\n const restoresSourceViaHistory =\n targets?.some(isHistoryNode) &&\n targetStates.some((target) => target === transition.source);\n\n if (\n !restoresSourceViaHistory &&\n targetStates.every(\n (target) =>\n target === transition.source || isDescendant(target, transition.source)\n )\n ) {\n // Targets are contained within the source. A reentering transition\n // exits and reenters the source itself; otherwise the domain narrows\n // past parallel nodes so sibling regions are left untouched.\n return reenter\n ? transition.source\n : narrowParallelDomain(transition.source, targetStates);\n }\n\n const [head, ...tail] = targetStates.concat(transition.source);\n // Find the least common ancestor (LCA) of the source and effective targets.\n for (const ancestor of getProperAncestors(head, undefined)) {\n if (tail.every((sn) => isDescendant(sn, ancestor))) {\n // A cross-region transition (source in one parallel region, targets in\n // another) only exits the region containing its targets; the source\n // region and other sibling regions stay put unless it reenters.\n return reenter ? ancestor : narrowParallelDomain(ancestor, targetStates);\n }\n }\n\n // at this point we know that it's a root transition since LCA couldn't be found\n if (reenter) {\n return;\n }\n\n return narrowParallelDomain(transition.source.machine.root, targetStates);\n}\n\nfunction computeExitSet(\n transitions: Array<AnyTransitionDefinition>,\n stateNodeSet: Set<AnyStateNode>,\n snapshot: AnyMachineSnapshot,\n resolveTransition: TransitionResultResolver\n): Array<AnyStateNode> {\n const statesToExit = new Set<AnyStateNode>();\n for (const transition of transitions) {\n const { targets, reenter } = resolveTransition(transition);\n\n if (targets?.length) {\n const domain = getTransitionDomain(\n transition,\n snapshot,\n resolveTransition\n );\n\n if (reenter && transition.source === domain) {\n statesToExit.add(domain);\n }\n\n for (const stateNode of stateNodeSet) {\n if (isDescendant(stateNode, domain!)) {\n statesToExit.add(stateNode);\n }\n }\n }\n }\n\n return [...statesToExit];\n}\n\ntype Microstep = readonly [AnyMachineSnapshot, ExecutableActionObject[]];\n\nexport function initialMicrostep(\n root: AnyStateNode,\n preInitialState: AnyMachineSnapshot,\n actorScope: AnyActorScope,\n initEvent: AnyEventObject,\n internalQueue: AnyEventObject[]\n): Microstep {\n const initialStateNodes = [...getInitialStateNodes(root)];\n const statesForDefaultEntry = new Set<AnyStateNode>();\n const collectDefaultEntryStates = (stateNode: AnyStateNode): void => {\n if (stateNode.type === 'compound') {\n statesForDefaultEntry.add(stateNode);\n for (const target of stateNode.initial.target ?? []) {\n collectDefaultEntryStates(target);\n }\n } else if (stateNode.type === 'parallel') {\n for (const child of getChildren(stateNode)) {\n collectDefaultEntryStates(child);\n }\n }\n };\n collectDefaultEntryStates(root);\n return microstep(\n [\n {\n target: initialStateNodes.filter(\n (stateNode) =>\n !initialStateNodes.some(\n (other) => other !== stateNode && isDescendant(other, stateNode)\n )\n ),\n source: root,\n reenter: true,\n eventType: null as any,\n toJSON: null as any,\n _statesForDefaultEntry: [...statesForDefaultEntry]\n } as AnyTransitionDefinition\n ],\n preInitialState,\n actorScope,\n initEvent,\n true,\n internalQueue\n );\n}\n\n/** https://www.w3.org/TR/scxml/#microstepProcedure */\nfunction microstep(\n transitions: Array<AnyTransitionDefinition>,\n currentSnapshot: AnyMachineSnapshot,\n actorScope: AnyActorScope,\n event: AnyEventObject,\n isInitial: boolean,\n internalQueue: Array<AnyEventObject>,\n selectionResults?: TransitionSelectionResults\n): Microstep {\n const executableActions: ExecutableActionObject[] = [];\n\n if (!transitions.length) {\n return [currentSnapshot, executableActions];\n }\n\n {\n const mutStateNodeSet = new Set(currentSnapshot.nodes as StateNode[]);\n let historyValue = currentSnapshot.historyValue;\n const originalContext = currentSnapshot.context;\n\n const filteredTransitions =\n transitions.length === 1\n ? transitions\n : removeConflictingTransitions(\n transitions,\n mutStateNodeSet,\n currentSnapshot,\n createTransitionResultResolver(\n currentSnapshot,\n event,\n actorScope,\n false,\n selectionResults\n )\n );\n const getCurrentTransitionResult = createTransitionResultResolver(\n currentSnapshot,\n event,\n actorScope,\n true,\n selectionResults\n );\n const changesState = filteredTransitions.some((transition) => {\n const { targets, reenter } = getCurrentTransitionResult(transition);\n return !!targets?.length || !!reenter;\n });\n const getStateActionsAndContext = (\n transitionFn: any,\n context: MachineContext,\n children: AnyMachineSnapshot['children'],\n input: Record<string, unknown> | undefined\n ): [\n actions: any[],\n context: MachineContext | undefined,\n internalEvents: EventObject[] | undefined\n ] => {\n if (transitionFn.length === 2) {\n // enqueue action; retrieve\n const actions: any[] = [];\n const internalEvents: EventObject[] = [];\n let updatedContext: MachineContext | undefined;\n\n const enqueue = createTransitionEnqueue(\n actorScope,\n actions,\n internalEvents,\n true\n );\n\n const args = isLazyActorScope(actorScope)\n ? withActorScope(\n {\n context,\n event,\n children,\n actions: currentSnapshot.machine.sources.actions,\n actors: currentSnapshot.machine.sources.actors,\n guards: currentSnapshot.machine.sources.guards,\n delays: currentSnapshot.machine.sources.delays,\n input\n },\n actorScope\n )\n : {\n context,\n event,\n parent: actorScope.self._parent,\n self: actorScope.self,\n children,\n system: actorScope.system,\n actions: currentSnapshot.machine.sources.actions,\n actors: currentSnapshot.machine.sources.actors,\n guards: currentSnapshot.machine.sources.guards,\n delays: currentSnapshot.machine.sources.delays,\n input\n };\n const res = transitionFn(args, enqueue);\n\n if (res?.context !== undefined) {\n updatedContext = mergeContextPatch(context, res.context);\n }\n\n return [actions, updatedContext, internalEvents];\n }\n\n // For 1-argument actions, wrap them to include input\n // Preserve _special flag if present (for entry/exit actions)\n const wrappedAction = Object.assign(\n (args: any, enqueue: any) =>\n transitionFn(\n isLazyActorScope(actorScope)\n ? withActorScope(\n {\n context: args.context,\n event: args.event,\n output: args.output,\n children: args.children,\n actions: args.actions,\n actors: args.actors,\n input\n },\n actorScope\n )\n : { ...args, input },\n enqueue\n ),\n '_special' in transitionFn ? { _special: true } : {}\n );\n return [[wrappedAction], undefined, undefined];\n };\n\n let nextState = currentSnapshot;\n const getInvokeStopActions = (\n stateNode: AnyStateNode,\n children: AnyMachineSnapshot['children']\n ): AnyAction[] => {\n const actions: AnyAction[] = [];\n const enqueue = createTransitionEnqueue(actorScope, actions, []);\n for (const invokeDef of stateNode.invoke) {\n const child = children[invokeDef.id];\n if (child) {\n enqueue.stop(child);\n }\n }\n return actions;\n };\n const exitStates = () => {\n const statesToExit = computeExitSet(\n filteredTransitions,\n mutStateNodeSet,\n currentSnapshot,\n getCurrentTransitionResult\n );\n\n statesToExit.sort((a, b) => b.order - a.order);\n\n let changedHistory: HistoryValue | undefined;\n const currentStateNodes = [...mutStateNodeSet];\n\n // From SCXML algorithm: https://www.w3.org/TR/scxml/#exitStates\n for (const exitStateNode of statesToExit) {\n for (const historyNode of Object.values(exitStateNode.states)) {\n if (historyNode.type !== 'history') {\n continue;\n }\n\n const predicate =\n historyNode.history === 'deep'\n ? (sn: AnyStateNode) =>\n isAtomicStateNode(sn) && isDescendant(sn, exitStateNode)\n : (sn: AnyStateNode) => sn.parent === exitStateNode;\n\n changedHistory ??= { ...historyValue };\n changedHistory[historyNode.id] = currentStateNodes.filter(predicate);\n }\n }\n\n for (const exitStateNode of statesToExit) {\n const stateInput = getStateInput(currentSnapshot, exitStateNode.id);\n\n const [exitActions, nextContext, internalEvents] = exitStateNode.exit\n ? getStateActionsAndContext(\n exitStateNode.exit,\n nextState.context,\n currentSnapshot.children,\n stateInput\n )\n : [[], undefined, undefined];\n if (internalEvents?.length) {\n internalQueue.push(...internalEvents);\n }\n if (nextContext) {\n nextState = cloneMachineSnapshot(nextState, {\n context: nextContext\n });\n }\n const [resolvedState, resolvedActions] = resolveActionsWithContext(\n nextState,\n event,\n actorScope,\n exitActions\n );\n nextState = resolvedState;\n executableActions.push(...resolvedActions);\n\n const invokeStopActions = getInvokeStopActions(\n exitStateNode,\n nextState.children\n );\n if (invokeStopActions.length) {\n const [stoppedState, stopEffects] = resolveActionsWithContext(\n nextState,\n event,\n actorScope,\n invokeStopActions\n );\n nextState = stoppedState;\n executableActions.push(...stopEffects);\n }\n\n mutStateNodeSet.delete(exitStateNode);\n }\n\n historyValue = changedHistory || historyValue;\n };\n\n // Exit states\n if (!isInitial && changesState) {\n exitStates();\n }\n\n let context = nextState.context;\n const transitionActions: AnyAction[] = [];\n const internalEvents: EventObject[] = [];\n\n for (const t of filteredTransitions) {\n if (t.actions) {\n transitionActions.push(...toArray(t.actions));\n }\n const res = getCurrentTransitionResult(t);\n if (res.context !== undefined) {\n context = mergeContextPatch(context, res.context);\n }\n if (res.actions) {\n transitionActions.push(...res.actions);\n }\n if (res.internalEvents) {\n internalEvents.push(...res.internalEvents);\n }\n }\n\n if (internalEvents.length) {\n internalQueue.push(...internalEvents);\n }\n\n const enterStates = () => {\n const getMachineOutput = (rootCompletionNode: AnyStateNode) => {\n const rootNode = nextState.machine.root;\n\n let completionOutput: unknown;\n if (\n rootCompletionNode.output !== undefined &&\n rootCompletionNode.parent\n ) {\n const rootDoneEvent = internalQueue.find(\n (e) =>\n e.type === 'xstate.done.state' &&\n (e as DoneStateEvent).stateId === rootNode.id\n ) as DoneStateEvent | undefined;\n completionOutput =\n rootDoneEvent && rootCompletionNode.parent === rootNode\n ? rootDoneEvent.output\n : resolveOutput(\n rootCompletionNode.output,\n nextState.context,\n event,\n actorScope.self,\n stateInputMap[rootCompletionNode.id]\n );\n } else if (rootCompletionNode.type === 'parallel') {\n const parallelDoneEvent = internalQueue.find(\n (e) =>\n e.type === 'xstate.done.state' &&\n (e as DoneStateEvent).stateId === rootCompletionNode.id\n ) as DoneStateEvent | undefined;\n completionOutput = parallelDoneEvent?.output;\n }\n\n if (rootNode.output === undefined) {\n return rootCompletionNode.parent === rootNode\n ? completionOutput\n : undefined;\n }\n\n return resolveOutput(\n rootNode.output,\n nextState.context,\n createDoneStateEvent(rootCompletionNode.id, completionOutput),\n actorScope.self\n );\n };\n\n const statesToEnter = new Set<AnyStateNode>();\n // those are states that were directly targeted or indirectly targeted by the explicit target\n // in other words, those are states for which initial actions should be executed\n // when we target `#deep_child` initial actions of its ancestors shouldn't be executed\n const statesForDefaultEntry = new Set<AnyStateNode>();\n const historyDefaultsByParent = new Map<\n AnyStateNode,\n AnyTransitionDefinition[]\n >();\n const addAncestorStatesToEnter = (\n ancestors: AnyStateNode[],\n reentrancyDomain: AnyStateNode | undefined\n ) => {\n for (const anc of ancestors) {\n if (!reentrancyDomain || isDescendant(anc, reentrancyDomain)) {\n statesToEnter.add(anc);\n }\n if (anc.type === 'parallel') {\n for (const child of getChildren(anc)) {\n if (!hasDescendantState(statesToEnter, child)) {\n statesToEnter.add(child);\n addDescendantStatesToEnter(child);\n }\n }\n }\n }\n };\n\n const addDescendantStatesToEnter = (stateNode: AnyStateNode) => {\n if (isHistoryNode(stateNode)) {\n if (historyValue[stateNode.id]) {\n const historyStateNodes = historyValue[stateNode.id];\n for (const s of historyStateNodes) {\n statesToEnter.add(s);\n addDescendantStatesToEnter(s);\n }\n for (const s of historyStateNodes) {\n addAncestorStatesToEnter(\n getProperAncestors(s, stateNode.parent),\n undefined\n );\n }\n } else {\n const historyDefaultTransition =\n resolveHistoryDefaultTransition(stateNode);\n const historyParent = stateNode.parent!;\n statesForDefaultEntry.add(historyParent);\n const defaults = historyDefaultsByParent.get(historyParent) ?? [];\n defaults.push(historyDefaultTransition);\n historyDefaultsByParent.set(historyParent, defaults);\n const { targets } = getCurrentTransitionResult(\n historyDefaultTransition\n );\n for (const s of targets ?? []) {\n statesToEnter.add(s);\n\n if (historyDefaultTransition === stateNode.parent?.initial) {\n statesForDefaultEntry.add(stateNode.parent);\n }\n\n addDescendantStatesToEnter(s);\n }\n\n for (const s of targets ?? []) {\n addAncestorStatesToEnter(\n getProperAncestors(s, stateNode.parent),\n undefined\n );\n }\n }\n return;\n }\n\n if (stateNode.type === 'compound') {\n const initialStates =\n getCurrentTransitionResult(stateNode.initial).targets ?? [];\n\n for (const initialState of initialStates) {\n if (!isHistoryNode(initialState)) {\n statesToEnter.add(initialState);\n }\n }\n statesForDefaultEntry.add(stateNode);\n for (const initialState of initialStates) {\n addDescendantStatesToEnter(initialState);\n }\n for (const initialState of initialStates) {\n addAncestorStatesToEnter(\n getProperAncestors(initialState, stateNode),\n undefined\n );\n }\n return;\n }\n\n if (stateNode.type === 'parallel') {\n for (const child of getChildren(stateNode)) {\n if (!hasDescendantState(statesToEnter, child)) {\n statesToEnter.add(child);\n statesForDefaultEntry.add(child);\n addDescendantStatesToEnter(child);\n }\n }\n }\n };\n\n for (const transition of filteredTransitions) {\n const domain = getTransitionDomain(\n transition,\n currentSnapshot,\n getCurrentTransitionResult\n );\n\n const { targets, reenter } = getCurrentTransitionResult(transition);\n\n for (const targetNode of targets ?? []) {\n if (\n !isHistoryNode(targetNode) &&\n (transition.source !== targetNode ||\n transition.source !== domain ||\n reenter)\n ) {\n statesToEnter.add(targetNode);\n statesForDefaultEntry.add(targetNode);\n }\n addDescendantStatesToEnter(targetNode);\n }\n const targetStates = getEffectiveTargetStates(\n transition,\n currentSnapshot,\n getCurrentTransitionResult\n );\n for (const s of targetStates) {\n const ancestors = getProperAncestors(s, domain);\n if (domain?.type === 'parallel') {\n ancestors.push(domain);\n }\n addAncestorStatesToEnter(\n ancestors,\n !transition.source.parent && reenter ? undefined : domain\n );\n }\n if (reenter && domain === transition.source) {\n // A reentering transition whose domain is its own source exits and\n // reenters the source, so the source must be entered explicitly —\n // it has no ancestor inside the domain to add it.\n statesToEnter.add(transition.source);\n }\n }\n\n if (isInitial) {\n for (const stateNode of (filteredTransitions[0] as any)\n ._statesForDefaultEntry ?? [currentSnapshot.machine.root]) {\n statesForDefaultEntry.add(stateNode);\n }\n }\n\n const stateInputMap: Record<string, Record<string, unknown>> = {\n ...currentSnapshot._stateInputs\n };\n let stateInputsChanged = false;\n for (const transition of filteredTransitions) {\n const { targets, input } = getCurrentTransitionResult(transition);\n if (input && targets) {\n for (const targetNode of targets) {\n stateInputMap[targetNode.id] = input;\n stateInputsChanged = true;\n }\n }\n }\n\n const completedNodes = new Set<AnyStateNode>();\n const children = { ...nextState.children };\n for (const stateNodeToEnter of [...statesToEnter].sort(\n (a, b) => a.order - b.order\n )) {\n mutStateNodeSet.add(stateNodeToEnter);\n const actions: AnyAction[] = [];\n\n let invoked = false;\n for (const invokeDef of stateNodeToEnter.invoke) {\n invoked = true;\n\n let src = invokeDef.logic;\n if (typeof src === 'function') {\n src = src({\n actors: currentSnapshot.machine.sources.actors,\n context: nextState.context,\n event,\n self: actorScope.self\n });\n }\n\n const logic =\n typeof src === 'string'\n ? resolveReferencedActor(currentSnapshot.machine, src)\n : src;\n\n if (!logic) {\n throw new Error(\n isDevelopment\n ? `Actor logic '${typeof src === 'string' ? src : 'inline'}' not implemented in machine '${currentSnapshot.machine.id}'`\n : `Actor logic '${typeof src === 'string' ? src : 'inline'}' not implemented`\n );\n }\n\n const input =\n typeof invokeDef.input === 'function'\n ? invokeDef.input({\n self: actorScope.self,\n context: nextState.context,\n event,\n input: stateInputMap[stateNodeToEnter.id],\n output: getEventOutput(event)\n })\n : invokeDef.input;\n\n assertChildIdFree(actorScope, invokeDef.id);\n const actor = actorScope.system.createActorRef(logic, {\n ...invokeDef,\n input,\n parent: actorScope.self,\n syncSnapshot: !!invokeDef.onSnapshot\n });\n\n actions.push({\n action: builtInActions['@xstate.spawn'],\n args: [actor]\n });\n\n if (invokeDef.id) {\n children[invokeDef.id] = actor;\n }\n }\n\n if (invoked) {\n nextState = cloneMachineSnapshot(nextState, { children });\n }\n let context = nextState.context;\n let contextChangedByEntry = false;\n\n const stateInput = stateInputMap[stateNodeToEnter.id];\n\n if (stateNodeToEnter.entry) {\n const [resultActions, nextContext, nextInternalEvents] =\n getStateActionsAndContext(\n stateNodeToEnter.entry,\n context,\n children,\n stateInput\n );\n actions.push(...resultActions);\n if (nextInternalEvents?.length) {\n internalQueue.push(...nextInternalEvents);\n }\n if (nextContext) {\n context = nextContext;\n contextChangedByEntry = true;\n }\n }\n\n if (contextChangedByEntry) {\n nextState.context = context;\n }\n\n if (statesForDefaultEntry.has(stateNodeToEnter)) {\n const defaultTransitions = [\n stateNodeToEnter.initial,\n ...(historyDefaultsByParent.get(stateNodeToEnter) ?? [])\n ].filter(Boolean);\n for (const defaultTransition of defaultTransitions) {\n const {\n actions: initialActions,\n context: initialContext,\n input: initialInput,\n internalEvents: initialInternalEvents\n } = getTransitionResult(\n defaultTransition,\n nextState,\n event,\n actorScope\n );\n if (initialActions) {\n actions.push(...initialActions);\n }\n if (initialInternalEvents?.length) {\n internalQueue.push(...initialInternalEvents);\n }\n if (initialContext !== undefined) {\n nextState.context = mergeContextPatch(\n nextState.context,\n initialContext\n );\n }\n if (initialInput && defaultTransition.target) {\n for (const targetNode of defaultTransition.target) {\n stateInputMap[targetNode.id] = initialInput;\n stateInputsChanged = true;\n }\n }\n }\n }\n\n const [resolvedState, resolvedActions] = resolveActionsWithContext(\n nextState,\n event,\n actorScope,\n actions\n );\n nextState = resolvedState;\n actions.length = 0;\n executableActions.push(...resolvedActions);\n\n if (stateNodeToEnter.type !== 'final') {\n continue;\n }\n\n const parent = stateNodeToEnter.parent;\n let ancestorMarker =\n parent?.type === 'parallel' ? parent : parent?.parent;\n let rootCompletionNode = ancestorMarker || stateNodeToEnter;\n\n if (parent?.type === 'compound') {\n internalQueue.push(\n createDoneStateEvent(\n parent.id,\n stateNodeToEnter.output !== undefined\n ? resolveOutput(\n stateNodeToEnter.output,\n nextState.context,\n event,\n actorScope.self,\n stateInput\n )\n : undefined\n )\n );\n }\n\n while (\n ancestorMarker?.type === 'parallel' &&\n !completedNodes.has(ancestorMarker) &&\n isInFinalState(mutStateNodeSet, ancestorMarker)\n ) {\n completedNodes.add(ancestorMarker);\n const regionOutput: Record<string, unknown> = {};\n for (const region of getChildren(ancestorMarker)) {\n if (region.type === 'final') {\n regionOutput[region.key] =\n region.output !== undefined\n ? resolveOutput(\n region.output,\n nextState.context,\n event,\n actorScope.self,\n stateInputMap[region.id]\n )\n : undefined;\n continue;\n }\n\n if (region.type === 'parallel') {\n const regionDoneEvent = internalQueue.find(\n (e) =>\n e.type === 'xstate.done.state' &&\n (e as DoneStateEvent).stateId === region.id\n ) as DoneStateEvent | undefined;\n regionOutput[region.key] = regionDoneEvent?.output;\n continue;\n }\n\n const finalChild = getChildren(region).find(\n (s) => s.type === 'final' && mutStateNodeSet.has(s)\n );\n regionOutput[region.key] =\n finalChild?.output !== undefined\n ? resolveOutput(\n finalChild.output,\n nextState.context,\n event,\n actorScope.self,\n stateInputMap[finalChild.id]\n )\n : undefined;\n }\n internalQueue.push(\n createDoneStateEvent(ancestorMarker.id, regionOutput)\n );\n rootCompletionNode = ancestorMarker;\n ancestorMarker = ancestorMarker.parent;\n }\n if (ancestorMarker) {\n continue;\n }\n\n nextState = cloneMachineSnapshot(nextState, {\n status: 'done',\n output: getMachineOutput(rootCompletionNode)\n });\n }\n\n if (stateInputsChanged) {\n nextState = cloneMachineSnapshot(nextState, {\n _stateInputs: stateInputMap\n });\n }\n };\n\n // Execute transition content\n const [resolvedTransitionState, transitionExecutableActions] =\n resolveActionsWithContext(\n nextState,\n event,\n actorScope,\n transitionActions\n );\n nextState = resolvedTransitionState;\n executableActions.push(...transitionExecutableActions);\n if (context && context !== currentSnapshot.context) {\n nextState = cloneMachineSnapshot(nextState, { context });\n }\n\n // Enter states\n if (isInitial || changesState) {\n enterStates();\n }\n\n const nextStateNodes = [...mutStateNodeSet];\n\n if (nextState.status === 'done') {\n const allExitActions: AnyAction[] = [];\n const nextStateNodesToExit = nextStateNodes.sort(\n (a, b) => b.order - a.order\n );\n\n nextStateNodesToExit.forEach((stateNode) => {\n if (stateNode.exit) {\n const stateInput = getStateInput(nextState, stateNode.id);\n const [exitActions, , nextInternalEvents] = getStateActionsAndContext(\n stateNode.exit,\n nextState.context,\n nextState.children,\n stateInput\n );\n allExitActions.push(...exitActions);\n if (nextInternalEvents?.length) {\n internalQueue.push(...nextInternalEvents);\n }\n }\n });\n\n const [resolvedState, resolvedActions] = resolveActionsWithContext(\n nextState,\n event,\n actorScope,\n allExitActions\n );\n nextState = resolvedState;\n executableActions.push(...resolvedActions);\n\n const [stoppedState, stopEffects] = stopChildren(\n nextState,\n event,\n actorScope\n );\n nextState = stoppedState;\n executableActions.push(...stopEffects);\n\n const [withoutTimers, cancelEffects] = cancelTimers(\n nextState,\n event,\n actorScope\n );\n nextState = withoutTimers;\n executableActions.push(...cancelEffects);\n }\n\n if (\n historyValue === currentSnapshot.historyValue &&\n currentSnapshot.nodes.length === mutStateNodeSet.size &&\n currentSnapshot.nodes.every((node) =>\n mutStateNodeSet.has(node as StateNode)\n )\n ) {\n // If context was changed (e.g. by entry actions during self-transition),\n // clone to ensure reference inequality for eventless transition re-evaluation\n if (nextState.context !== originalContext) {\n return [\n nextState === currentSnapshot\n ? cloneMachineSnapshot(nextState)\n : nextState,\n executableActions\n ];\n }\n return [nextState, executableActions];\n }\n\n return [\n cloneMachineSnapshot(nextState, {\n _nodes: nextStateNodes,\n historyValue\n }),\n executableActions\n ];\n }\n}\n\n/**\n * Gets the transition result for a given transition without executing the\n * transition.\n */\nexport function getTransitionResult(\n transition: Pick<AnyTransitionDefinition, 'target' | 'to' | 'source'> & {\n reenter?: AnyTransitionDefinition['reenter'];\n input?: AnyTransitionDefinition['input'];\n context?: AnyTransitionDefinition['context'];\n },\n snapshot: AnyMachineSnapshot,\n event: AnyEventObject,\n actorScope: AnyActorScope,\n options?: {\n resolveActions?: boolean;\n selectionResult?: TransitionSelectionResult;\n }\n): {\n targets: Readonly<AnyStateNode[]> | undefined;\n context: MachineContext | undefined;\n actions: AnyAction[] | undefined;\n reenter?: boolean;\n internalEvents: EventObject[] | undefined;\n input: Record<string, unknown> | undefined;\n} {\n let transitionArgs: any;\n const getTransitionArgs = () =>\n (transitionArgs ??= isLazyActorScope(actorScope)\n ? withActorScope(\n {\n context: snapshot.context,\n event,\n output: getEventOutput(event),\n value: snapshot.value,\n children: snapshot.children,\n actions: snapshot.machine.sources.actions,\n actors: snapshot.machine.sources.actors,\n guards: snapshot.machine.sources.guards,\n delays: snapshot.machine.sources.delays,\n input: getStateInput(snapshot, transition.source.id)\n },\n actorScope\n )\n : {\n context: snapshot.context,\n event,\n output: getEventOutput(event),\n value: snapshot.value,\n children: snapshot.children,\n system: actorScope.system,\n parent: actorScope.self._parent,\n self: actorScope.self,\n actions: snapshot.machine.sources.actions,\n actors: snapshot.machine.sources.actors,\n guards: snapshot.machine.sources.guards,\n delays: snapshot.machine.sources.delays,\n input: getStateInput(snapshot, transition.source.id)\n });\n\n if (transition.to) {\n const actions: AnyAction[] = [];\n const internalEvents: EventObject[] = [];\n const res = options?.selectionResult?.reusable\n ? options.selectionResult.result\n : transition.to(\n getTransitionArgs(),\n createTransitionEnqueue(\n actorScope,\n actions,\n internalEvents,\n true,\n options?.resolveActions ?? true\n )\n );\n\n const targets = res?.target\n ? resolveTarget(transition.source, toArray(res.target) as string[])\n : undefined;\n\n const resolvedInput =\n res?.input ??\n (typeof transition.input === 'function'\n ? transition.input({\n context: snapshot.context,\n event,\n output: getEventOutput(event)\n })\n : transition.input);\n\n return {\n targets: targets,\n context: res?.context,\n reenter: res?.reenter,\n actions,\n internalEvents,\n input: resolvedInput\n };\n }\n\n // Resolve input for regular transitions\n const resolvedInput =\n typeof transition.input === 'function'\n ? transition.input({\n context: snapshot.context,\n event,\n output: getEventOutput(event)\n })\n : transition.input;\n const resolvedContext =\n typeof transition.context === 'function'\n ? transition.context(getTransitionArgs())\n : transition.context;\n\n return {\n targets: transition.target as AnyStateNode[] | undefined,\n context: resolvedContext,\n reenter: transition.reenter,\n actions: undefined,\n internalEvents: undefined,\n input: resolvedInput\n };\n}\n\nexport function macrostep(\n snapshot: AnyMachineSnapshot,\n event: EventObject,\n actorScope: AnyActorScope,\n internalQueue: AnyEventObject[],\n initialMicrosteps: Microstep[] = []\n): {\n snapshot: typeof snapshot;\n microsteps: Microstep[];\n} {\n let nextSnapshot = snapshot;\n const microsteps: Microstep[] = initialMicrosteps.slice();\n\n function removeTerminatedChild(terminalEvent: EventObject) {\n if (\n terminalEvent.type !== 'xstate.done.actor' &&\n terminalEvent.type !== 'xstate.error.actor'\n ) {\n return;\n }\n\n const { actorId, sessionId } = terminalEvent as AnyEventObject & {\n actorId?: string;\n sessionId?: string;\n };\n if (!actorId) {\n return;\n }\n const child = nextSnapshot.children[actorId];\n if (!child) {\n return;\n }\n // The same staleness rule matchesActorSession applies to transition\n // selection: a completion from a different incarnation must not remove\n // the still-running child either.\n if (child.sessionId !== undefined && child.sessionId !== sessionId) {\n return;\n }\n\n const children = { ...nextSnapshot.children };\n delete children[actorId];\n actorScope.system._unregister(child);\n nextSnapshot = cloneMachineSnapshot(nextSnapshot, { children });\n\n if (microsteps.length) {\n const [, lastEffects] = microsteps.at(-1)!;\n microsteps[microsteps.length - 1] = [nextSnapshot, lastEffects];\n } else {\n microsteps.push([nextSnapshot, []]);\n }\n }\n\n function completeMacrostep() {\n const effects = microsteps.flatMap(([, actions]) => actions);\n const starts = deriveDeferredStarts(effects);\n const shouldTerminate =\n (snapshot.status === 'active' || initialMicrosteps.length > 0) &&\n (nextSnapshot.status === 'done' || nextSnapshot.status === 'error');\n\n if (starts.length || shouldTerminate) {\n const terminalEffects = shouldTerminate\n ? [...starts, createTerminationEffect(actorScope, nextSnapshot)]\n : starts;\n if (microsteps.length) {\n const [lastSnapshot, lastEffects] = microsteps.at(-1)!;\n microsteps[microsteps.length - 1] = [\n lastSnapshot,\n [...lastEffects, ...terminalEffects]\n ];\n } else {\n microsteps.push([nextSnapshot, terminalEffects]);\n }\n }\n\n return { snapshot: nextSnapshot, microsteps };\n }\n\n function addMicrostep(\n step: Microstep,\n transitions: AnyTransitionDefinition[]\n ) {\n // collect microsteps; surfaced on the enclosing '@xstate.transition' event\n // via its `microsteps[]` facet (there is no standalone microstep event)\n if (\n !isInertActorScope(actorScope) &&\n (event.type === XSTATE_INIT ||\n (actorScope.system._hasInspectionObservers?.() ?? true))\n ) {\n const collectedMicrosteps =\n ((actorScope.self as any)._collectedMicrosteps as any[]) || [];\n collectedMicrosteps.push(...transitions);\n (actorScope.self as any)._collectedMicrosteps = collectedMicrosteps;\n }\n microsteps.push(step);\n }\n\n // Handle stop event\n if (event.type === XSTATE_STOP) {\n const [stoppedChildrenSnapshot, stopEffects] = stopChildren(\n nextSnapshot,\n event,\n actorScope\n );\n const [withoutTimers, cancelEffects] = cancelTimers(\n stoppedChildrenSnapshot,\n event,\n actorScope\n );\n nextSnapshot = cloneMachineSnapshot(withoutTimers, {\n status: 'stopped'\n });\n addMicrostep([nextSnapshot, [...stopEffects, ...cancelEffects]], []);\n return completeMacrostep();\n }\n\n let nextEvent = normalizeLegacyInternalEvent(event, snapshot.machine);\n\n if (event.type === XSTATE_TIMER) {\n const timer = nextSnapshot.timers[(event as any).id];\n if (!timer) {\n return completeMacrostep();\n }\n\n const timers = { ...nextSnapshot.timers };\n delete timers[timer.id];\n nextSnapshot = cloneMachineSnapshot(nextSnapshot, { timers });\n if (timer.type === '@xstate.raise') {\n internalQueue.push(timer.event);\n addMicrostep([nextSnapshot, []], []);\n } else {\n const target = timer.target === 'self' ? actorScope.self : timer.target;\n addMicrostep(\n [nextSnapshot, [createSendToEffect(actorScope, target, timer.event)]],\n []\n );\n }\n }\n\n // Assume the state is at rest (no raised events)\n // Determine the next state based on the next microstep\n if (nextEvent.type !== XSTATE_INIT && nextEvent.type !== XSTATE_TIMER) {\n const currentEvent = nextEvent;\n const isErr = isErrorEvent(currentEvent);\n const selectionResults: TransitionSelectionResults = new Map();\n\n const transitions = nextSnapshot.machine.getTransitionData(\n nextSnapshot as any,\n currentEvent,\n actorScope,\n selectionResults\n );\n\n if (isErr && !transitions.length) {\n if (\n currentEvent.type === 'xstate.error.actor' &&\n !matchesActorSession(\n currentEvent,\n nextSnapshot,\n (currentEvent as AnyEventObject).actorId\n )\n ) {\n return completeMacrostep();\n }\n // TODO: we should likely only allow transitions selected by very explicit descriptors\n // `*` shouldn't be matched, likely `xstate.error.*` shouldn't be either\n // similarly `xstate.error.actor.*` and `xstate.error.actor.todo.*` have to be considered too\n nextSnapshot = cloneMachineSnapshot<typeof snapshot>(snapshot, {\n status: 'error',\n error: currentEvent.error\n });\n addMicrostep([nextSnapshot, []], []);\n removeTerminatedChild(currentEvent);\n return completeMacrostep();\n }\n const step = microstep(\n transitions,\n snapshot,\n actorScope,\n nextEvent,\n false, // isInitial\n internalQueue,\n selectionResults\n );\n nextSnapshot = step[0];\n addMicrostep(step, transitions);\n removeTerminatedChild(currentEvent);\n }\n\n if (\n !internalQueue.length &&\n snapshot.machine._hasEventlessTransitions === false\n ) {\n return completeMacrostep();\n }\n\n let shouldSelectEventlessTransitions = true;\n const maxIterations = snapshot.machine.options?.maxIterations ?? Infinity;\n let iterationCount = 0;\n\n let microstepCount = 0;\n while (nextSnapshot.status === 'active') {\n microstepCount++;\n if (microstepCount > 1000) {\n throw new Error('Microstep count exceeded 1000');\n }\n iterationCount++;\n if (iterationCount > maxIterations) {\n throw new Error(\n isDevelopment\n ? `Infinite loop detected: the machine has processed more than ${maxIterations} microsteps without reaching a stable state. This usually happens when there's a cycle of transitions (e.g., eventless transitions or raised events causing state A -> B -> C -> A).`\n : `Infinite loop detected (>${maxIterations} microsteps)`\n );\n }\n\n let selectionResults: TransitionSelectionResults | undefined;\n let enabledTransitions: AnyTransitionDefinition[] =\n shouldSelectEventlessTransitions\n ? selectEventlessTransitions(nextSnapshot, nextEvent, actorScope)\n : [];\n\n // eventless transitions should always be selected after selecting *regular* transitions\n // by assigning `undefined` to `previousState` we ensure that `shouldSelectEventlessTransitions` gets always computed to true in such a case\n const previousState = enabledTransitions.length ? nextSnapshot : undefined;\n\n if (!enabledTransitions.length) {\n if (!internalQueue.length) {\n break;\n }\n nextEvent = internalQueue.shift()!;\n selectionResults = new Map();\n enabledTransitions = nextSnapshot.machine.getTransitionData(\n nextSnapshot as any,\n nextEvent,\n actorScope,\n selectionResults\n );\n }\n\n const step = microstep(\n enabledTransitions,\n nextSnapshot,\n actorScope,\n nextEvent,\n false,\n internalQueue,\n selectionResults\n );\n nextSnapshot = step[0];\n shouldSelectEventlessTransitions = nextSnapshot !== previousState;\n addMicrostep(step, enabledTransitions);\n removeTerminatedChild(nextEvent);\n }\n\n return completeMacrostep();\n}\n\n/**\n * Resolves a partial state value with its full representation in the state\n * node's machine.\n *\n * @param stateValue The partial state value to resolve.\n */\nexport function resolveStateValue(\n rootNode: AnyStateNode,\n stateValue: StateValue\n): StateValue {\n const allStateNodes = getAllStateNodes(getStateNodes(rootNode, stateValue));\n return getStateValue(rootNode, allStateNodes);\n}\n\nexport function hasEffect(\n transition: AnyTransitionDefinition,\n context: MachineContext,\n event: EventObject,\n snapshot: AnyMachineSnapshot,\n actorScope: AnyActorScope\n): boolean {\n if (transition.to) {\n return evaluateTransitionFunction(\n transition.to,\n context,\n event,\n snapshot,\n actorScope,\n snapshot.machine.sources,\n transition.source.id\n ).enabled;\n }\n\n return false;\n}\n\nconst triggerTransitionEffect = () => {\n throw transitionEffectSignal;\n};\nlet transitionEffectEnqueue: ReturnType<typeof createEnqueueObject> | undefined;\nfunction getTransitionEffectEnqueue() {\n return (transitionEffectEnqueue ??= createEnqueueObject(\n {\n emit: triggerTransitionEffect,\n cancel: triggerTransitionEffect,\n log: triggerTransitionEffect,\n raise: triggerTransitionEffect,\n spawn: triggerTransitionEffect,\n sendTo: triggerTransitionEffect,\n stop: triggerTransitionEffect,\n listen: triggerTransitionEffect,\n subscribeTo: triggerTransitionEffect\n },\n triggerTransitionEffect\n ));\n}\n\nfunction evaluateTransitionFunction(\n transitionTo: NonNullable<AnyTransitionDefinition['to']>,\n context: MachineContext,\n event: EventObject,\n snapshot: AnyMachineSnapshot,\n actorScope: AnyActorScope,\n sources: AnyMachineSnapshot['machine']['sources'],\n sourceId: string\n): TransitionSelectionResult {\n let res;\n const parent = getActorScopeParent(actorScope);\n if (parent) {\n transitionEffectTargets.push(parent);\n }\n\n try {\n res = transitionTo(\n withActorScope(\n {\n context,\n event,\n output: getEventOutput(event),\n value: snapshot.value,\n children: snapshot.children,\n actions: sources.actions,\n actors: sources.actors,\n guards: sources.guards,\n delays: sources.delays,\n input: getStateInput(snapshot, sourceId)\n },\n actorScope\n ),\n getTransitionEffectEnqueue()\n );\n } catch (err) {\n if (err === transitionEffectSignal) {\n return { enabled: true, result: undefined, reusable: false };\n }\n throw err;\n } finally {\n if (parent) {\n transitionEffectTargets.pop();\n }\n }\n\n return { enabled: res !== undefined, result: res, reusable: true };\n}\n\nfunction stopChildren(\n snapshot: AnyMachineSnapshot,\n event: AnyEventObject,\n actorScope: AnyActorScope\n): [AnyMachineSnapshot, ExecutableActionObject[]] {\n let children: AnyActor[];\n if (\n !snapshot.children ||\n (children = Object.values(snapshot.children).filter(Boolean) as AnyActor[])\n .length === 0\n ) {\n return [snapshot, []];\n }\n const actions: AnyAction[] = [];\n const enqueue = createTransitionEnqueue(actorScope, actions, []);\n for (const child of children) {\n enqueue.stop(child);\n }\n return resolveActionsWithContext(snapshot, event, actorScope, actions);\n}\n\nfunction cancelTimers(\n snapshot: AnyMachineSnapshot,\n event: AnyEventObject,\n actorScope: AnyActorScope\n): [AnyMachineSnapshot, ExecutableActionObject[]] {\n const timerIds = Object.keys(snapshot.timers);\n if (!timerIds.length) {\n return [snapshot, []];\n }\n const actions: AnyAction[] = [];\n const enqueue = createTransitionEnqueue(actorScope, actions, []);\n for (const id of timerIds) {\n enqueue.cancel(id);\n }\n return resolveActionsWithContext(snapshot, event, actorScope, actions);\n}\n\nfunction selectEventlessTransitions(\n snapshot: AnyMachineSnapshot,\n event: AnyEventObject,\n actorScope: AnyActorScope\n) {\n const enabledTransitionSet: Set<AnyTransitionDefinition> = new Set();\n const atomicStates = snapshot.nodes.filter(isAtomicStateNode);\n\n for (const atomicStateNode of atomicStates) {\n loop: for (\n let stateNode: AnyStateNode | undefined = atomicStateNode;\n stateNode;\n stateNode = stateNode.parent\n ) {\n if (!stateNode.always) {\n continue;\n }\n for (const transition of stateNode.always) {\n if (\n evaluateCandidate(transition, event, snapshot, stateNode, actorScope)\n ) {\n enabledTransitionSet.add(transition);\n break loop;\n }\n }\n }\n }\n\n return removeConflictingTransitions(\n Array.from(enabledTransitionSet),\n new Set(snapshot.nodes),\n snapshot,\n createTransitionResultResolver(snapshot, event, actorScope, false)\n );\n}\n\nexport function evaluateCandidate(\n candidate: AnyTransitionDefinition,\n event: EventObject,\n snapshot: AnyMachineSnapshot,\n stateNode: AnyStateNode,\n actorScope: AnyActorScope,\n selectionResults?: TransitionSelectionResults\n): boolean {\n if (candidate.matches && !matchesEvent(event, candidate.matches)) {\n return false;\n }\n\n if (candidate._eventMatcher && !candidate._eventMatcher(event, snapshot)) {\n return false;\n }\n\n if (candidate.guard) {\n const guardArgs = withActorSelfAndParent(\n {\n context: snapshot.context,\n event,\n output: getEventOutput(event),\n children: snapshot.children,\n actions: stateNode.machine.sources.actions,\n actors: stateNode.machine.sources.actors,\n guards: stateNode.machine.sources.guards,\n delays: stateNode.machine.sources.delays,\n _snapshot: snapshot\n },\n actorScope\n );\n if (!(candidate.guard as (args: typeof guardArgs) => boolean)(guardArgs)) {\n return false;\n }\n }\n\n if (candidate.to) {\n const evaluation = evaluateTransitionFunction(\n candidate.to,\n snapshot.context,\n event,\n snapshot,\n actorScope,\n stateNode.machine.sources,\n candidate.source.id\n );\n selectionResults?.set(candidate, evaluation);\n return evaluation.enabled;\n }\n\n return true;\n}\n","import isDevelopment from '#is-development';\nimport { isMachineSnapshot } from './State.ts';\nimport type { StateNode } from './StateNode.ts';\nimport { TARGETLESS_KEY, WILDCARD } from './constants.ts';\nimport { isStateId } from './stateUtils.ts';\nimport type {\n AnyActor,\n AnyEventObject,\n AnyMachineSnapshot,\n AnyStateMachine,\n AnyTransitionConfig,\n AnyTransitionConfigFunction,\n ErrorEvent,\n EventObject,\n InvokeConfig,\n MachineContext,\n Mapper,\n NonReducibleUnknown,\n Observer,\n OutputArg,\n SingleOrArray,\n StateLike,\n StateValue,\n TransitionConfigTarget\n} from './types.ts';\n\nexport function matchesState(\n parentStateId: StateValue,\n childStateId: StateValue\n): boolean {\n const parentStateValue = toStateValue(parentStateId);\n const childStateValue = toStateValue(childStateId);\n\n if (typeof childStateValue === 'string') {\n if (typeof parentStateValue === 'string') {\n return childStateValue === parentStateValue;\n }\n\n // Parent more specific than child\n return false;\n }\n\n if (typeof parentStateValue === 'string') {\n return parentStateValue in childStateValue;\n }\n\n return Object.keys(parentStateValue).every((key) => {\n if (!(key in childStateValue)) {\n return false;\n }\n\n return matchesState(parentStateValue[key]!, childStateValue[key]!);\n });\n}\n\nexport function checkStateIn(\n snapshot: AnyMachineSnapshot,\n stateValue: StateValue\n) {\n if (typeof stateValue === 'string' && isStateId(stateValue)) {\n const target = snapshot.machine.getStateNodeById(stateValue);\n return snapshot.nodes.some((sn) => sn === target);\n }\n\n return snapshot.matches(stateValue);\n}\n\nexport function toStatePath(stateId: string | string[]): string[] {\n if (isArray(stateId)) {\n return stateId;\n }\n\n const result: string[] = [];\n let segment = '';\n\n for (let i = 0; i < stateId.length; i++) {\n const char = stateId.charCodeAt(i);\n switch (char) {\n // \\\n case 92:\n // consume the next character\n segment += stateId[i + 1];\n // and skip over it\n i++;\n continue;\n // .\n case 46:\n result.push(segment);\n segment = '';\n continue;\n }\n segment += stateId[i];\n }\n\n result.push(segment);\n\n return result;\n}\n\nfunction toStateValue(stateValue: StateLike<any> | StateValue): StateValue {\n if (isMachineSnapshot(stateValue)) {\n return stateValue.value;\n }\n\n if (typeof stateValue !== 'string') {\n return stateValue as StateValue;\n }\n\n const statePath = toStatePath(stateValue);\n\n return pathToStateValue(statePath);\n}\n\nexport function pathToStateValue(statePath: string[]): StateValue {\n if (statePath.length === 1) {\n return statePath[0];\n }\n\n const value: StateValue = {};\n let marker = value;\n\n for (let i = 0; i < statePath.length - 1; i++) {\n if (i === statePath.length - 2) {\n marker[statePath[i]] = statePath[i + 1];\n } else {\n const previous = marker;\n marker = {};\n previous[statePath[i]] = marker;\n }\n }\n\n return value;\n}\n\nexport function mapValues<P, O extends Record<string, unknown>>(\n collection: O,\n iteratee: (item: O[keyof O], key: keyof O, collection: O, i: number) => P\n): { [key in keyof O]: P };\nexport function mapValues(\n collection: Record<string, unknown>,\n iteratee: (\n item: unknown,\n key: string,\n collection: Record<string, unknown>,\n i: number\n ) => unknown\n) {\n const result: Record<string, unknown> = {};\n\n const collectionKeys = Object.keys(collection);\n for (let i = 0; i < collectionKeys.length; i++) {\n const key = collectionKeys[i];\n result[key] = iteratee(collection[key], key, collection, i);\n }\n\n return result;\n}\n\nfunction toArrayStrict<T>(value: readonly T[] | T): readonly T[] {\n if (isArray(value)) {\n return value;\n }\n return [value];\n}\n\nexport function toArray<T>(value: readonly T[] | T | undefined): readonly T[] {\n if (value === undefined) {\n return [];\n }\n return toArrayStrict(value);\n}\n\nexport function resolveOutput<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject\n>(\n mapper:\n | Mapper<TContext, TExpressionEvent, unknown, EventObject>\n | NonReducibleUnknown,\n context: TContext,\n event: TExpressionEvent,\n self: AnyActor,\n input?: Record<string, unknown>\n): unknown {\n if (typeof mapper === 'function') {\n const outputMapper = mapper as Mapper<\n TContext,\n TExpressionEvent,\n unknown,\n EventObject\n >;\n const args = {\n context,\n event,\n output: getEventOutput(event),\n self,\n input\n } as unknown as Parameters<typeof outputMapper>[0];\n\n return outputMapper(args);\n }\n\n if (\n isDevelopment &&\n !!mapper &&\n typeof mapper === 'object' &&\n Object.values(mapper).some((val) => typeof val === 'function')\n ) {\n console.warn(\n `Dynamically mapping values to individual properties is deprecated. Use a single function that returns the mapped object instead.\\nFound object containing properties whose values are possibly mapping functions: ${Object.entries(\n mapper\n )\n .filter(([, value]) => typeof value === 'function')\n .map(\n ([key, value]) =>\n `\\n - ${key}: ${(value as () => any)\n .toString()\n .replace(/\\n\\s*/g, '')}`\n )\n .join('')}`\n );\n }\n\n return mapper;\n}\n\nexport function getEventOutput<TEvent extends EventObject>(\n event: TEvent\n): OutputArg<TEvent>['output'] {\n if (isDoneEvent(event)) {\n const doneEvent = event as unknown as EventObject & { output: unknown };\n return doneEvent.output as OutputArg<TEvent>['output'];\n }\n\n return undefined as OutputArg<TEvent>['output'];\n}\n\nfunction isDoneEvent(event: EventObject): boolean {\n return (\n event.type === 'xstate.done.actor' || event.type === 'xstate.done.state'\n );\n}\n\nfunction isArray(value: any): value is readonly any[] {\n return Array.isArray(value);\n}\n\nexport function isErrorEvent(event: AnyEventObject): event is ErrorEvent {\n return event.type.startsWith('xstate.error.');\n}\n\nexport function toTransitionConfigArray(\n configLike: SingleOrArray<\n AnyTransitionConfig | TransitionConfigTarget | AnyTransitionConfigFunction\n >\n): Array<AnyTransitionConfig> {\n return toArrayStrict(configLike).map((transitionLike) => {\n if (\n typeof transitionLike === 'undefined' ||\n typeof transitionLike === 'string'\n ) {\n return { target: transitionLike };\n }\n\n if (typeof transitionLike === 'function') {\n return { to: transitionLike };\n }\n\n return transitionLike;\n });\n}\n\nexport function normalizeTarget<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(\n target: SingleOrArray<string | StateNode<TContext, TEvent>> | undefined\n): ReadonlyArray<string | StateNode<TContext, TEvent>> | undefined {\n if (target === undefined || target === TARGETLESS_KEY) {\n return undefined;\n }\n return toArray(target);\n}\n\nexport function toObserver<T>(\n nextHandler?: Observer<T> | ((value: T) => void),\n errorHandler?: (error: any) => void,\n completionHandler?: () => void\n): Observer<T> {\n const isObserver = typeof nextHandler === 'object';\n const self = isObserver ? nextHandler : undefined;\n\n return {\n next: (isObserver ? nextHandler.next : nextHandler)?.bind(self),\n error: (isObserver ? nextHandler.error : errorHandler)?.bind(self),\n complete: (isObserver ? nextHandler.complete : completionHandler)?.bind(\n self\n )\n };\n}\n\nexport function createInvokeId(stateNodeId: string, index: number): string {\n return `${index}.${stateNodeId}`;\n}\n\nexport function resolveReferencedActor(machine: AnyStateMachine, src: string) {\n const match = src.match(/^xstate\\.invoke\\.(\\d+)\\.(.*)/)!;\n if (!match) {\n return machine.sources.actors[src];\n }\n const [, indexStr, nodeId] = match;\n const node = machine.getStateNodeById(nodeId);\n const invokeConfig = node.config.invoke!;\n const configSrc = (\n Array.isArray(invokeConfig)\n ? invokeConfig[indexStr as any]\n : (invokeConfig as InvokeConfig<\n any,\n any,\n any,\n any,\n any,\n any,\n any, // TEmitted\n any // TMeta\n >)\n ).src;\n // A referenced actor may itself be registered by name.\n return typeof configSrc === 'string'\n ? machine.sources.actors[configSrc]\n : configSrc;\n}\n\nexport function getAllOwnEventDescriptors(snapshot: AnyMachineSnapshot) {\n return [...new Set([...snapshot.nodes.flatMap((sn) => sn.ownEvents)])];\n}\n\n/** @internal Events synthesized from active transition descriptors. */\nexport function getAllOwnEvents(snapshot: AnyMachineSnapshot) {\n const events = snapshot.nodes.flatMap((stateNode) =>\n [...stateNode.transitions.values()].flatMap((transitions) =>\n transitions.map((transition) => {\n const event: AnyEventObject = {\n type: transition.eventType,\n ...transition.matches\n };\n if (\n 'actorId' in event &&\n (event.type === 'xstate.done.actor' ||\n event.type === 'xstate.error.actor' ||\n event.type === 'xstate.snapshot.actor' ||\n event.type === 'xstate.timeout.actor')\n ) {\n event.sessionId = snapshot.children[event.actorId]?.sessionId;\n }\n return event;\n })\n )\n );\n return events.filter(\n (event, index) =>\n events.findIndex((candidate) => {\n const keys = Object.keys(event);\n return (\n keys.length === Object.keys(candidate).length &&\n keys.every((key) => Object.is(event[key], candidate[key]))\n );\n }) === index\n );\n}\n\nexport function matchesEvent(\n event: EventObject,\n pattern: Record<string, unknown>\n): boolean {\n return Object.entries(pattern).every(([key, value]) =>\n Object.is((event as AnyEventObject)[key], value)\n );\n}\n\n/**\n * Checks if an event type matches an event descriptor, supporting wildcards.\n * Event descriptors can be:\n *\n * - Exact matches: \"event.type\"\n * - Wildcard: \"*\"\n * - Partial matches: \"event.*\"\n *\n * @param eventType - The actual event type string\n * @param descriptor - The event descriptor to match against\n * @returns True if the event type matches the descriptor\n */\nexport function matchesEventDescriptor(\n eventType: string,\n descriptor: string\n): boolean {\n if (descriptor === eventType) {\n return true;\n }\n\n if (descriptor === WILDCARD) {\n return true;\n }\n\n if (!descriptor.endsWith('.*')) {\n return false;\n }\n\n if (isDevelopment && /.*\\*.+/.test(descriptor)) {\n console.warn(\n `Wildcards can only be the last token of an event descriptor (e.g., \"event.*\") or the entire event descriptor (\"*\"). Check the \"${descriptor}\" event.`\n );\n }\n\n const partialEventTokens = descriptor.split('.');\n const eventTokens = eventType.split('.');\n\n for (\n let tokenIndex = 0;\n tokenIndex < partialEventTokens.length;\n tokenIndex++\n ) {\n const partialEventToken = partialEventTokens[tokenIndex];\n const eventToken = eventTokens[tokenIndex];\n\n if (partialEventToken === '*') {\n const isLastToken = tokenIndex === partialEventTokens.length - 1;\n\n if (isDevelopment && !isLastToken) {\n console.warn(\n `Infix wildcards in transition events are not allowed. Check the \"${descriptor}\" transition.`\n );\n }\n\n return isLastToken;\n }\n\n if (partialEventToken !== eventToken) {\n return false;\n }\n }\n\n return true;\n}\n","import { ACTOR_REF_TYPE } from './createActor.ts';\nimport type { AnyActorSystem } from './system.ts';\nimport type {\n AnyActor,\n AnyEventObject,\n Snapshot,\n Subscription\n} from './types.ts';\n\nconst emptySubscription: Subscription = { unsubscribe() {} };\n\nconst restoreHint =\n 'or restore this snapshot with embedded children on the runtime that owns them.';\n\n/** @internal */\nexport function isRemoteActorRef(actorRef: AnyActor): boolean {\n return (actorRef as { _remote?: boolean })._remote === true;\n}\n\n/**\n * The lifecycle-only snapshot a remote handle exposes. `active` is accurate\n * by construction: a completion removes the child from its parent's\n * `children`, so a handle only exists while the child is presumed active,\n * and the terminal result arrives as a completion event instead of a\n * snapshot. Full snapshots are a co-location capability.\n */\nconst remoteSnapshot: Snapshot<undefined> = Object.freeze({\n status: 'active' as const,\n output: undefined,\n error: undefined\n});\n\n/**\n * Creates a location-transparent handle to an actor whose state lives with\n * another runtime. The handle is constructed from identity alone — no lookup\n * — and every send routes through the system's runtime; its state is not\n * synchronously readable.\n *\n * The surface is deliberately minimal: it covers every member the runtime\n * reaches for a restored child (send/_send, lifecycle via start/_stop and\n * system.stopActor, persistence, subscribe/on as inert subscriptions).\n * Members that only make sense for a co-located actor (public stop(),\n * select(), trigger) throw a descriptive error rather than being absent, so\n * calling one reports what went wrong instead of a bare TypeError. Observable\n * interop and _processingStatus are omitted entirely.\n *\n * @internal\n */\nexport function createRemoteActorRef(\n system: AnyActorSystem,\n options: {\n id: string;\n address: string;\n src: string;\n parent: AnyActor | undefined;\n registryKey?: string;\n syncSnapshot?: boolean;\n incarnation?: string;\n }\n): AnyActor {\n const handle = {\n _remote: true as const,\n // Self-reference so context persistence recognizes the handle as an\n // actor reference instead of recursing into it.\n ref: undefined as unknown as AnyActor,\n id: options.id,\n address: options.address,\n src: options.src,\n registryKey: options.registryKey,\n // The host-supplied incarnation token, when present: the owner's\n // sessionId for this child, letting this side drop stale completions and\n // journaled sends name the intended incarnation. Without one the handle\n // does not know the child's incarnation and the owning runtime is the\n // authority on staleness.\n sessionId: options.incarnation as string,\n system,\n _parent: options.parent,\n // Round-trips through persistence verbatim (undefined stays undefined,\n // so re-persisting is byte-stable); a remote handle cannot act on it\n // locally.\n _syncSnapshot: options.syncSnapshot,\n send(event: AnyEventObject) {\n void system.sendEvent(undefined, ref, event);\n },\n _send(event: AnyEventObject) {\n throw new Error(\n `Remote actor '${options.address}' has no local mailbox to receive \"${event.type}\". Its state lives with another runtime; install a runtime that can reach it (via \\`createDurable\\`'s adapter runtime operations, or \\`system.runtime\\`) before sending, ${restoreHint}`\n );\n },\n getSnapshot(): Snapshot<undefined> {\n return remoteSnapshot;\n },\n getPersistedSnapshot(): never {\n throw new Error(\n `Cannot persist remote actor '${options.address}' from here: its state lives with the runtime that owns it. Persist it there, ${restoreHint}`\n );\n },\n start() {},\n _stop() {},\n stop() {\n throw new Error(\n `Cannot stop remote actor '${options.address}' directly: stopping is a co-located operation. Stop it through the system runtime that owns it (\\`system.stopActor(ref)\\`), ${restoreHint}`\n );\n },\n select() {\n throw new Error(\n `Cannot select from remote actor '${options.address}': its snapshot is not synchronously readable because its state lives with another runtime. Read it on the runtime that owns it, ${restoreHint}`\n );\n },\n get trigger(): never {\n throw new Error(\n `Remote actor '${options.address}' has no \\`trigger\\` shorthand: it requires a co-located actor. Use \\`send(...)\\`, which routes through the system runtime.`\n );\n },\n // Observation is a co-location capability: a remote handle never emits,\n // so subscriptions are inert rather than errors — generic observers may\n // attach to any ref.\n subscribe(): Subscription {\n return emptySubscription;\n },\n on(): Subscription {\n return emptySubscription;\n },\n _isRunning() {\n return false;\n },\n // The same shape Actor.toJSON produces, so serialized snapshots carry\n // one actor-reference marker whether a child is co-located or remote.\n toJSON() {\n return {\n xstate$type: ACTOR_REF_TYPE,\n id: options.id,\n address: options.address,\n src: options.src\n };\n }\n };\n const ref = handle as unknown as AnyActor;\n handle.ref = ref;\n return ref;\n}\n","import isDevelopment from '#is-development';\nimport { ACTOR_REF_TYPE } from './createActor.ts';\nimport { getStateValue } from './stateUtils.ts';\nimport type {\n AnyMachineSnapshot,\n AnyStateMachine,\n AnyActor,\n EventObject,\n HistoryValue,\n MachineContext,\n StateConfig,\n StateValue,\n StateValueMap,\n AnyActorRef,\n Snapshot,\n MetaObject,\n StateSchema,\n StateId,\n StateIdInputs,\n StateContextFromStateValue,\n SnapshotStatus,\n PersistedHistoryValue,\n AnyStateNode,\n LogicalTimer\n} from './types.ts';\nimport { matchesState } from './utils.ts';\nimport {\n copySnapshotActorRef,\n getSnapshotActorRef,\n setSnapshotActorRef\n} from './snapshotActorRef.ts';\nimport { isRemoteActorRef } from './remoteActorRef.ts';\n\nconst emptySnapshotRecord = Object.freeze({});\n\nfunction compactSnapshotRecord<T extends object>(value: T | undefined): T {\n if (value === emptySnapshotRecord) {\n return value;\n }\n return value && Object.keys(value).length\n ? value\n : (emptySnapshotRecord as T);\n}\n\nexport function isMachineSnapshot(value: unknown): value is AnyMachineSnapshot {\n return (\n !!value &&\n typeof value === 'object' &&\n 'machine' in value &&\n 'value' in value\n );\n}\n\ntype Values<T> = T[keyof T];\n\ntype MatchingObjectStateValue<\n TStateValue extends Record<string, unknown>,\n TTestStateValue extends Record<string, unknown>\n> =\n false extends Values<{\n [K in keyof TTestStateValue]: K extends keyof TStateValue\n ? NonNullable<TStateValue[K]> extends StateValue\n ? NonNullable<TTestStateValue[K]> extends StateValue\n ? [\n MatchingStateValue<\n NonNullable<TStateValue[K]>,\n NonNullable<TTestStateValue[K]>\n >\n ] extends [never]\n ? false\n : true\n : false\n : false\n : false;\n }>\n ? never\n : {\n [K in keyof TStateValue]: K extends keyof TTestStateValue\n ? MatchingStateValue<\n NonNullable<TStateValue[K]>,\n NonNullable<TTestStateValue[K]>\n >\n : TStateValue[K];\n };\n\ntype MatchingStateValue<\n TStateValue extends StateValue,\n TTestStateValue extends StateValue\n> = StateValue extends TTestStateValue\n ? TStateValue\n : string extends TTestStateValue\n ? TStateValue\n : TStateValue extends unknown\n ? TTestStateValue extends string\n ? TStateValue extends string\n ? TTestStateValue extends TStateValue\n ? TTestStateValue\n : Extract<TStateValue, TTestStateValue>\n : TStateValue extends Record<string, unknown>\n ? TStateValue & Record<TTestStateValue, StateValue | undefined>\n : never\n : TTestStateValue extends Record<string, unknown>\n ? TStateValue extends Record<string, unknown>\n ? MatchingObjectStateValue<TStateValue, TTestStateValue>\n : never\n : never\n : never;\n\ninterface MachineSnapshotBase<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TStateValue extends StateValue,\n TTag extends string,\n _TOutput,\n TMeta extends MetaObject,\n TStateSchema extends StateSchema = StateSchema\n> {\n /** The state machine that produced this state snapshot. */\n machine: AnyStateMachine;\n /** The tags of the active state nodes that represent the current state value. */\n tags: Set<string>;\n /**\n * The current state value.\n *\n * This represents the active state nodes in the state machine.\n *\n * - For atomic state nodes, it is a string.\n * - For compound parent state nodes, it is an object where:\n *\n * - The key is the parent state node's key\n * - The value is the current state value of the active child state node(s)\n *\n * @example\n *\n * ```ts\n * // single-level state node\n * snapshot.value; // => 'yellow'\n *\n * // nested state nodes\n * snapshot.value; // => { red: 'wait' }\n * ```\n */\n value: TStateValue;\n /** The current status of this snapshot. */\n status: SnapshotStatus;\n error: unknown;\n context: TContext;\n\n historyValue: Readonly<HistoryValue>;\n /** The enabled state nodes representative of the state value. */\n nodes: Array<AnyStateNode>;\n /** An object mapping actor names to spawned/invoked actors. */\n children: TChildren;\n /** Pending logical timers owned by this machine snapshot. */\n timers: Readonly<Record<string, LogicalTimer>>;\n /** @internal */\n _stateInputs: Record<string, Record<string, unknown>>;\n /** @internal */\n _nextTimerId: number;\n /** @internal */\n _nextActorIds?: Record<string, number>;\n /**\n * Whether the current state value is a subset of the given partial state\n * value.\n *\n * @param partialStateValue\n */\n matches<const TTestStateValue extends string>(\n partialStateValue: TTestStateValue,\n ...args: string extends TTestStateValue ? [never] : []\n ): this is MachineSnapshot<\n StateContextFromStateValue<TStateSchema, TContext, TTestStateValue>,\n TEvent,\n TChildren,\n MatchingStateValue<TStateValue, TTestStateValue>,\n TTag,\n _TOutput,\n TMeta,\n TStateSchema\n >;\n matches<const TTestStateValue extends StateValueMap>(\n partialStateValue: TTestStateValue,\n ...args: string extends keyof TTestStateValue ? [never] : []\n ): this is MachineSnapshot<\n StateContextFromStateValue<TStateSchema, TContext, TTestStateValue>,\n TEvent,\n TChildren,\n MatchingStateValue<TStateValue, TTestStateValue>,\n TTag,\n _TOutput,\n TMeta,\n TStateSchema\n >;\n matches(partialStateValue: StateValue): boolean;\n\n /**\n * Whether the current state nodes has a state node with the specified `tag`.\n *\n * @param tag\n */\n hasTag: (tag: TTag) => boolean;\n\n /**\n * Determines whether sending the `event` will cause a non-forbidden\n * transition to be selected, even if the transitions have no actions nor\n * change the state value.\n *\n * @param event The event to test\n * @returns Whether the event will cause a transition\n */\n can: (event: TEvent) => boolean;\n\n getMeta: () => Record<\n StateId<TStateSchema> & string,\n TMeta | undefined // States might not have meta defined\n >;\n\n /**\n * Returns the inputs for the current active state nodes, keyed by state node\n * id.\n */\n getInputs: () => StateIdInputs<TStateSchema>;\n\n toJSON: () => unknown;\n}\n\ninterface ActiveMachineSnapshot<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TStateValue extends StateValue,\n TTag extends string,\n TOutput,\n TMeta extends MetaObject,\n TStateSchema extends StateSchema\n> extends MachineSnapshotBase<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TStateSchema\n> {\n status: 'active';\n output: undefined;\n error: undefined;\n}\n\ninterface DoneMachineSnapshot<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TStateValue extends StateValue,\n TTag extends string,\n TOutput,\n TMeta extends MetaObject,\n TStateSchema extends StateSchema\n> extends MachineSnapshotBase<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TStateSchema\n> {\n status: 'done';\n output: TOutput;\n error: undefined;\n}\n\ninterface ErrorMachineSnapshot<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TStateValue extends StateValue,\n TTag extends string,\n TOutput,\n TMeta extends MetaObject,\n TStateSchema extends StateSchema\n> extends MachineSnapshotBase<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TStateSchema\n> {\n status: 'error';\n output: undefined;\n error: unknown;\n}\n\ninterface StoppedMachineSnapshot<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TStateValue extends StateValue,\n TTag extends string,\n TOutput,\n TMeta extends MetaObject,\n TStateSchema extends StateSchema\n> extends MachineSnapshotBase<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TStateSchema\n> {\n status: 'stopped';\n output: undefined;\n error: undefined;\n}\n\nexport type MachineSnapshot<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TStateValue extends StateValue,\n TTag extends string,\n TOutput,\n TMeta extends MetaObject,\n TStateSchema extends StateSchema\n> =\n | ActiveMachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TStateSchema\n >\n | DoneMachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TStateSchema\n >\n | ErrorMachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TStateSchema\n >\n | StoppedMachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TStateSchema\n >;\n\nconst machineSnapshotMatches = function matches(\n this: AnyMachineSnapshot,\n testValue: StateValue\n) {\n return matchesState(testValue, this.value);\n};\n\nconst machineSnapshotHasTag = function hasTag(\n this: AnyMachineSnapshot,\n tag: string\n) {\n return this.tags.has(tag);\n};\n\nconst machineSnapshotCan = function can(\n this: AnyMachineSnapshot,\n event: EventObject\n) {\n if (isDevelopment && !this.machine) {\n console.warn(\n `state.can(...) used outside of a machine-created State object; this will always return false.`\n );\n }\n\n // The dry-run logic lives on the machine so that non-machine bundles\n // (e.g. `createFSM`) don't pay for the transition-resolution machinery.\n return this.machine?._canTransition(this, event) ?? false;\n};\n\nconst machineSnapshotToJSON = function toJSON(this: AnyMachineSnapshot) {\n const {\n nodes,\n _stateInputs,\n tags,\n machine,\n getMeta,\n getInputs,\n toJSON,\n can,\n hasTag,\n matches,\n ...jsonValues\n } = this;\n return { ...jsonValues, tags: Array.from(tags) };\n};\n\nconst machineSnapshotGetMeta = function getMeta(this: AnyMachineSnapshot) {\n const meta: Record<string, any> = {};\n for (const stateNode of this.nodes) {\n if (stateNode.meta !== undefined) {\n meta[stateNode.id] = stateNode.meta;\n }\n }\n return meta;\n};\n\nconst machineSnapshotGetInputs = function getInputs<\n TStateSchema extends StateSchema\n>(\n this: AnyMachineSnapshot & {\n _stateInputs: StateIdInputs<TStateSchema>;\n }\n): StateIdInputs<TStateSchema> {\n return this._stateInputs;\n};\n\nfunction collectTags(stateNodes: Array<AnyStateNode>): Set<string> {\n const tags = new Set<string>();\n for (const stateNode of stateNodes) {\n for (const tag of stateNode.tags) {\n tags.add(tag);\n }\n }\n return tags;\n}\n\nexport function createMachineSnapshot<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TStateValue extends StateValue,\n TTag extends string,\n TMeta extends MetaObject,\n TStateSchema extends StateSchema\n>(\n config: StateConfig<TContext, TEvent>,\n machine: AnyStateMachine,\n actorRef?: AnyActor\n): MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n undefined,\n TMeta,\n TStateSchema\n> {\n const snapshot = {\n status: config.status as never,\n output: config.output,\n error: config.error,\n machine,\n context: config.context,\n nodes: config._nodes,\n value: (config.value ??\n getStateValue(machine.root, config._nodes)) as never,\n tags: collectTags(config._nodes),\n children: compactSnapshotRecord(config.children) as TChildren,\n timers: compactSnapshotRecord(config.timers),\n historyValue: compactSnapshotRecord(config.historyValue),\n _stateInputs: compactSnapshotRecord(config._stateInputs),\n _nextTimerId: config._nextTimerId ?? 0,\n _nextActorIds: config._nextActorIds,\n matches: machineSnapshotMatches as never,\n hasTag: machineSnapshotHasTag,\n can: machineSnapshotCan,\n getMeta: machineSnapshotGetMeta,\n getInputs: machineSnapshotGetInputs,\n toJSON: machineSnapshotToJSON\n };\n if (actorRef) {\n setSnapshotActorRef(snapshot, actorRef);\n }\n return snapshot;\n}\n\nexport function cloneMachineSnapshot<TState extends AnyMachineSnapshot>(\n snapshot: TState,\n config: Partial<StateConfig<any, any>> = {}\n): TState {\n const configWithSnapshot = {\n ...snapshot,\n ...config\n } as StateConfig<any, any>;\n\n if ((config._nodes ?? snapshot.nodes) === snapshot.nodes) {\n const clonedSnapshot = {\n status: configWithSnapshot.status as never,\n output: configWithSnapshot.output,\n error: configWithSnapshot.error,\n machine: snapshot.machine,\n context: configWithSnapshot.context,\n nodes: snapshot.nodes,\n value: snapshot.value,\n tags: snapshot.tags,\n children: compactSnapshotRecord(configWithSnapshot.children),\n timers: compactSnapshotRecord(configWithSnapshot.timers),\n historyValue: compactSnapshotRecord(configWithSnapshot.historyValue),\n _stateInputs: compactSnapshotRecord(configWithSnapshot._stateInputs),\n _nextTimerId: configWithSnapshot._nextTimerId ?? 0,\n _nextActorIds: configWithSnapshot._nextActorIds,\n matches: machineSnapshotMatches as never,\n hasTag: machineSnapshotHasTag,\n can: machineSnapshotCan,\n getMeta: machineSnapshotGetMeta,\n getInputs: machineSnapshotGetInputs,\n toJSON: machineSnapshotToJSON\n } as unknown as TState;\n copySnapshotActorRef(snapshot, clonedSnapshot);\n return clonedSnapshot;\n }\n\n const clonedSnapshot = createMachineSnapshot(\n {\n ...configWithSnapshot,\n value: undefined\n },\n snapshot.machine\n ) as unknown as TState;\n copySnapshotActorRef(snapshot, clonedSnapshot);\n return clonedSnapshot;\n}\n\nfunction serializeHistoryValue(\n historyValue: HistoryValue\n): PersistedHistoryValue {\n const result: PersistedHistoryValue = {};\n\n for (const key in historyValue) {\n const value = historyValue[key];\n if (Array.isArray(value)) {\n result[key] = value.map((item) => ({ id: item.id }));\n }\n }\n\n return result;\n}\n\nexport function getPersistedSnapshot<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TStateValue extends StateValue,\n TTag extends string,\n TOutput,\n TMeta extends MetaObject\n>(\n snapshot: MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n any // state schema\n >,\n options?: unknown\n): Snapshot<unknown> {\n const {\n nodes,\n _stateInputs,\n tags,\n machine,\n children,\n timers,\n context,\n can,\n hasTag,\n matches,\n getMeta,\n getInputs,\n toJSON,\n ...jsonValues\n } = snapshot;\n\n const childrenJson: Record<string, unknown> = {};\n const timersJson: Record<string, unknown> = {};\n\n const embedChildren =\n (options as { embedChildren?: boolean } | undefined)?.embedChildren !==\n false;\n for (const id in children) {\n const child = children[id] as any;\n if (\n typeof child.src !== 'string' &&\n (!options || !('__unsafeAllowInlineActors' in (options as object)))\n ) {\n throw new Error('An inline child actor cannot be persisted.');\n }\n // Children are referenced by their logical address. Embedding the child\n // state is the co-locating runtime's whole-tree checkpoint capability;\n // remote handles never embed — their state lives with another runtime.\n const embed = embedChildren && !isRemoteActorRef(child);\n if (!embed && typeof child.src !== 'string') {\n // Fail where it is actionable: a by-address reference without a\n // registered source key could be persisted but never restored.\n throw new Error(\n `Unable to persist child '${id}' by address: it requires a registered source key.`\n );\n }\n childrenJson[id as keyof typeof childrenJson] = {\n address: child.address,\n // The explicit marker disambiguates a by-address reference from a child\n // whose own persisted snapshot happens to be undefined.\n ...(embed\n ? { snapshot: child.getPersistedSnapshot(options) }\n : {\n remote: true,\n // A remote handle's sessionId IS the host-supplied incarnation\n // token, round-tripped verbatim. A local child persisted by\n // address never stamps its own sessionId: that value is this\n // incarnation's, not a durable identity, and it would make\n // persisted snapshots nondeterministic across replays.\n incarnation: isRemoteActorRef(child) ? child.sessionId : undefined\n }),\n src: child.src,\n registryKey: child.registryKey,\n syncSnapshot: child._syncSnapshot\n };\n }\n\n const snapshotActor = getSnapshotActorRef(snapshot)?.actor;\n // Only the wall clock is stamped into persisted timers: a custom clock's\n // readings (a simulated clock, a monotonic counter) are meaningless in any\n // other process, and restoring them under the wall clock would fire every\n // pending delay instantly. Pure-transition snapshots have no local\n // schedule and persist no timestamp.\n const scheduledTimers = snapshotActor?.system?._clock?.now\n ? undefined\n : snapshotActor?.system?._snapshot?._scheduledTimers;\n for (const id in timers) {\n const timer = timers[id];\n let event = timer.event;\n if (event.type === 'xstate.timeout.actor') {\n event = { ...event };\n delete (event as EventObject & { sessionId?: string }).sessionId;\n }\n let target: string | { type: 'parent' };\n if (timer.target === 'self') {\n target = 'self';\n } else {\n const childId = Object.entries(children).find(\n ([, child]) => child === timer.target\n )?.[0];\n if (childId) {\n target = childId;\n } else if (\n timer.target === getSnapshotActorRef(snapshot)?.actor._parent\n ) {\n target = { type: 'parent' };\n } else {\n throw new Error(\n `Unable to persist timer '${id}': target actor '${timer.target.id}' is no longer addressable from this snapshot.`\n );\n }\n }\n // A live runtime knows when the timer is due; persist the wall-clock\n // start (dueAt - declared delay) so restore can honor the absolute\n // deadline. Derived from dueAt, not the scheduling moment, so repeated\n // persist/restore cycles keep the same deadline. Without a live schedule\n // (a restored-but-never-started actor, a pure-transition snapshot) the\n // timer's carried-in start — which only a wall-clock actor ever stamped —\n // passes through, so re-persisting cannot push the deadline back.\n const scheduled = scheduledTimers?.[`${snapshotActor!.sessionId}.${id}`];\n const startedAt = scheduled\n ? scheduled.dueAt - timer.delay\n : timer.startedAt;\n timersJson[id] = {\n id: timer.id,\n delay: timer.delay,\n type: timer.type,\n event,\n target,\n ...(startedAt !== undefined && { startedAt })\n };\n }\n\n const persisted: Record<string, unknown> = {\n ...jsonValues,\n context: persistContext(context) as any,\n children: childrenJson,\n timers: timersJson,\n historyValue: serializeHistoryValue(jsonValues.historyValue)\n };\n\n if (_stateInputs && Object.keys(_stateInputs).length > 0) {\n persisted.stateInputs = _stateInputs;\n }\n\n if (machine.version !== undefined) {\n persisted.machine = {\n id: machine.id,\n version: machine.version\n };\n persisted.version = machine.version;\n }\n\n return persisted as Snapshot<unknown>;\n}\n\nfunction persistContext(contextPart: Record<string, unknown>) {\n let copy: typeof contextPart | undefined;\n for (const key in contextPart) {\n const value = contextPart[key];\n if (value && typeof value === 'object') {\n if ('sessionId' in value && 'send' in value && 'ref' in value) {\n copy ??= Array.isArray(contextPart)\n ? (contextPart.slice() as typeof contextPart)\n : { ...contextPart };\n copy[key] = {\n xstate$type: ACTOR_REF_TYPE,\n id: (value as any as AnyActor).id\n };\n } else {\n const result = persistContext(value as typeof contextPart);\n if (result !== value) {\n copy ??= Array.isArray(contextPart)\n ? (contextPart.slice() as typeof contextPart)\n : { ...contextPart };\n copy[key] = result;\n }\n }\n }\n }\n return copy ?? contextPart;\n}\n","import {\n XSTATE_LOGIC_EFFECT_REJECT,\n XSTATE_LOGIC_EFFECT_RESOLVE,\n XSTATE_LOGIC_EFFECT_START\n} from './constants.ts';\nimport type { ActorTermination, AnyActor, AnyEventObject } from './types.ts';\n\ntype StepEffects = Record<\n string,\n | { status: 'active' }\n | { status: 'done'; output: unknown }\n | { status: 'error'; error: unknown }\n>;\n\nfunction getStepEffect(actor: AnyActor, key: string) {\n return (actor.getSnapshot() as { effects?: StepEffects }).effects?.[key];\n}\n\nfunction waitForStep<TStepOutput>(\n actor: AnyActor,\n key: string\n): Promise<TStepOutput> {\n return new Promise((resolve, reject) => {\n const subscription = actor.subscribe((snapshot) => {\n const effect = (snapshot as { effects?: StepEffects }).effects?.[key];\n if (effect?.status === 'done') {\n subscription.unsubscribe();\n resolve(effect.output as TStepOutput);\n } else if (effect?.status === 'error') {\n subscription.unsubscribe();\n reject(effect.error as Error);\n }\n });\n });\n}\n\n/**\n * Runs one keyed step of an async actor with the built-in journal: the\n * result is memoized in the actor's own snapshot (`effects[key]`), so a\n * restored actor skips completed steps when its logic function re-runs.\n * Custom runtimes that implement `runStep` use this for the default local\n * behavior, the same way `deliverEvent` exposes local delivery.\n *\n * @experimental\n */\nexport async function runStep<TStepOutput>(\n actor: AnyActor,\n key: string,\n exec: () => TStepOutput | PromiseLike<TStepOutput>,\n sendSelf: (event: AnyEventObject) => void = (event) =>\n void actor.system.sendEvent(actor, actor, event)\n): Promise<TStepOutput> {\n const effect = getStepEffect(actor, key);\n if (effect?.status === 'done') {\n return effect.output as TStepOutput;\n }\n if (effect?.status === 'error') {\n throw effect.error;\n }\n if (effect?.status === 'active') {\n return waitForStep(actor, key);\n }\n\n sendSelf({ type: XSTATE_LOGIC_EFFECT_START, key });\n try {\n const output = await exec();\n sendSelf({ type: XSTATE_LOGIC_EFFECT_RESOLVE, key, output });\n return output;\n } catch (error) {\n sendSelf({ type: XSTATE_LOGIC_EFFECT_REJECT, key, error });\n throw error;\n }\n}\n\n/**\n * Delivers an event directly to a target actor, bypassing any installed host\n * runtime. Custom runtimes use this for the default local delivery behavior\n * inside their own `sendEvent` implementations.\n *\n * @experimental\n */\nexport function deliverEvent(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n): void {\n if (rejectUndeliverableEvent(source, target, event)) {\n return;\n }\n const runtimeTarget = target as AnyActor & {\n _lastSourceRef?: AnyActor;\n _send(event: AnyEventObject): void;\n };\n\n runtimeTarget._lastSourceRef = source;\n runtimeTarget._send(event);\n}\n\n/**\n * Returns the boundary error preventing this delivery, if any: an internal\n * event type cannot cross an actor boundary from an external sender.\n */\nfunction getEventBoundaryError(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n): Error | undefined {\n const runtimeTarget = target as AnyActor & {\n logic?: { isInternalEventType?: (eventType: string) => boolean };\n };\n\n if (\n source !== target &&\n runtimeTarget.logic?.isInternalEventType?.(event.type)\n ) {\n return new Error(\n `Internal event \"${event.type}\" cannot be sent to actor \"${target.id}\" from outside.`\n );\n }\n return undefined;\n}\n\n/**\n * Rejects an event that must not cross the delivery boundary — an internal\n * event type sent from outside its owning actor — by reporting it as a dead\n * letter. Returns `true` when the event was rejected and must not be\n * delivered. Host runtimes must call this before taking ownership of\n * delivery.\n */\nexport function rejectUndeliverableEvent(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n): boolean {\n const error = getEventBoundaryError(source, target, event);\n if (error) {\n void target.system.deadLetter(source, target, event, 'internalEvent', {\n error\n });\n return true;\n }\n return false;\n}\n\n/**\n * Publishes an actor's terminal result, notifying its parent and observers.\n * Custom runtimes use this for the default local behavior inside their own\n * `terminateActor` implementations.\n *\n * @experimental\n */\nexport function terminateActor(\n actor: AnyActor,\n termination: ActorTermination\n): void {\n (\n actor as AnyActor & { _terminate(termination: ActorTermination): void }\n )._terminate(termination);\n}\n\n/**\n * Stops an actor without producing a completion result. Custom runtimes use\n * this for the default local behavior inside their own `stopActor`\n * implementations.\n *\n * @experimental\n */\nexport function stopActor(actor: AnyActor): void {\n (actor as AnyActor & { _stop(): void })._stop();\n}\n","import isDevelopment from '#is-development';\nimport type { InspectionEvent, SentRecord } from './inspection.ts';\nimport type { StandardSchemaV1 } from './schema.types.ts';\nimport {\n AnyEventObject,\n ActorTermination,\n ActorSystemInfo,\n AnyActor,\n Observer,\n HomomorphicOmit,\n EventObject,\n Subscription,\n AnyActorLogic,\n ActorOptions\n} from './types.ts';\nimport { XSTATE_TIMER } from './constants.ts';\nimport { toObserver } from './utils.ts';\nimport { getAmbientInspector } from './inspectionAmbient.ts';\nimport { markSystemSnapshotDirty } from './snapshotActorRef.ts';\nimport {\n rejectUndeliverableEvent,\n deliverEvent,\n stopActor as stopActorLocally,\n terminateActor as terminateActorLocally,\n runStep\n} from './runtimeHelpers.ts';\n\ninterface ScheduledTimer {\n id: string;\n scheduledAt: number;\n dueAt: number;\n delay: number;\n source: AnyActor;\n}\n\nexport interface Clock {\n /** Returns the clock's current time in milliseconds. */\n now?(): number;\n setTimeout(fn: (...args: any[]) => void, timeout: number): any;\n clearTimeout(id: any): void;\n}\n\ninterface Scheduler {\n schedule(source: AnyActor, id: string, delay: number): void;\n cancel(source: AnyActor, id: string): void;\n cancelAll(actor: AnyActor): void;\n}\n\nlet systemIdPrefix: string | undefined;\nlet nextSystemId = 0;\n\n/** @internal */\nexport const transitionEffectSignal = new Error('Transition effect');\n/** @internal */\nexport const transitionEffectTargets: AnyActor[] = [];\n\nfunction createSystemIdPrefix(): string {\n let crypto: Crypto | undefined;\n try {\n crypto = globalThis.crypto;\n } catch {\n // Use the process-local fallback below.\n }\n\n if (crypto?.getRandomValues) {\n try {\n const values = new Uint32Array(4);\n crypto.getRandomValues(values);\n return Array.from(values, (value) =>\n value.toString(36).padStart(7, '0')\n ).join('');\n } catch {\n // Try randomUUID next.\n }\n }\n\n if (crypto?.randomUUID) {\n try {\n return crypto.randomUUID().replaceAll('-', '');\n } catch {\n // Use the process-local fallback below.\n }\n }\n\n return `xstate-${Date.now().toString(36)}-${Math.random()\n .toString(36)\n .slice(2)}`;\n}\n\nfunction createSystemId(): string {\n systemIdPrefix ??= createSystemIdPrefix();\n return `${systemIdPrefix}:${(nextSystemId++).toString(36)}`;\n}\n\n/**\n * The identity a durable execution pins on every system its transitions\n * create. Shared across all transitions (and replays) of one execution, so\n * session ids become a deterministic function of actor-creation order:\n * `<executionId>:0`, `<executionId>:1`, … A replayed execution re-creates\n * the same session ids, so journaled completion events (which carry the\n * producing incarnation's `sessionId`) still match the children the replay\n * re-creates.\n */\nexport interface ExecutionIdentity {\n systemId: string;\n nextSessionId: number;\n}\n\nlet ambientExecutionIdentity: ExecutionIdentity | undefined;\n\n/** @internal Runs `fn` with systems it creates pinned to `identity`. */\nexport function withExecutionIdentity<T>(\n identity: ExecutionIdentity | undefined,\n fn: () => T\n): T {\n if (!identity) {\n return fn();\n }\n const previous = ambientExecutionIdentity;\n ambientExecutionIdentity = identity;\n try {\n return fn();\n } finally {\n ambientExecutionIdentity = previous;\n }\n}\n\nexport {\n hasAmbientInspector,\n withSystemInspector\n} from './inspectionAmbient.ts';\n\n/**\n * Derives the deterministic id prefix for a generated actor id from its actor\n * source: the registered source key when the source is a string, the logic's\n * own `id` otherwise, with `x` as the last-resort prefix.\n *\n * @internal\n */\nexport function getActorIdPrefix(\n src: string | AnyActorLogic | undefined\n): string {\n if (typeof src === 'string') {\n return src;\n }\n const logicId = (src as { id?: unknown } | undefined)?.id;\n // Anonymous machines get the placeholder id '(machine)'; only named logic\n // earns a named id prefix.\n return typeof logicId === 'string' &&\n logicId.length &&\n logicId !== '(machine)'\n ? logicId\n : 'x';\n}\n\n/**\n * Encodes one actor id as an address segment. `/` separates segments, so it\n * is percent-encoded, and the escape character `%` is escaped first so the\n * encoding stays injective: the ids 'a/b' and 'a%2Fb' must not produce the\n * same address.\n *\n * @internal\n */\nexport function encodeAddressSegment(id: string): string {\n return id.includes('/') || id.includes('%')\n ? id.replaceAll('%', '%25').replaceAll('/', '%2F')\n : id;\n}\n\n/**\n * Parses a generated-shaped actor id (`prefix:<n>`). This single definition is\n * the determinism contract for id reservation: live allocation, replay, and\n * restore must all agree on what counts as generated-shaped. Deliberately\n * broader than ids a generated allocation could produce — over-reserving\n * skips numbers, which is harmless, while under-reserving could collide.\n *\n * @internal\n */\nexport function parseGeneratedActorId(\n id: string\n): { prefix: string; index: number } | undefined {\n const separator = id.lastIndexOf(':');\n if (separator <= 0 || separator === id.length - 1) {\n return undefined;\n }\n const index = Number(id.slice(separator + 1));\n return Number.isSafeInteger(index) && index >= 0\n ? { prefix: id.slice(0, separator), index }\n : undefined;\n}\n\n/**\n * The id (and address root segment) of the first parentless actor of a logic:\n * the logic's own name, or `x:0` for anonymous logic.\n *\n * @internal\n */\nexport function getRootActorId(\n src: string | AnyActorLogic | undefined\n): string {\n const prefix = getActorIdPrefix(src);\n return prefix === 'x' ? 'x:0' : prefix;\n}\n\nfunction getActorIdCounterKey(\n parent: AnyActor | undefined,\n prefix: string\n): string {\n return `${parent ? parent.address : ''}|${prefix}`;\n}\n\nfunction bumpActorIdCounter(\n system: AnyActorSystem,\n counterKey: string,\n next: number\n): void {\n const counters = system._snapshot._nextActorIds;\n if ((counters[counterKey] ?? 0) >= next) {\n return;\n }\n // Copy-on-write: snapshot systems share this record by shallow `_snapshot`\n // copies, so branches must not observe each other's allocations.\n system._snapshot._nextActorIds = { ...counters, [counterKey]: next };\n markSystemSnapshotDirty(system);\n}\n\n/** @internal */\nexport function resolveActorId(\n system: AnyActorSystem,\n requestedId: string | undefined,\n options?: {\n parent?: AnyActor;\n src?: string | AnyActorLogic;\n }\n): string {\n if (requestedId !== undefined) {\n const generated = parseGeneratedActorId(requestedId);\n if (generated) {\n bumpActorIdCounter(\n system,\n getActorIdCounterKey(options?.parent, generated.prefix),\n generated.index + 1\n );\n } else if (!options?.parent) {\n // Reserve a restored root's bare name so a later parentless actor of\n // the same logic in this system numbers past it.\n bumpActorIdCounter(\n system,\n getActorIdCounterKey(undefined, requestedId),\n 1\n );\n }\n return requestedId;\n }\n\n const prefix = getActorIdPrefix(options?.src);\n const counterKey = getActorIdCounterKey(options?.parent, prefix);\n const counter = system._snapshot._nextActorIds[counterKey] ?? 0;\n bumpActorIdCounter(system, counterKey, counter + 1);\n // The first parentless actor of a logic gets the logic's own name; later\n // parentless actors of the same logic in a shared system get numbered so\n // addresses stay unique.\n return !options?.parent && prefix !== 'x' && counter === 0\n ? prefix\n : `${prefix}:${counter}`;\n}\n\n/** @internal */\nexport function bookSessionId(system: AnyActorSystem): string {\n return `${system._identity.systemId}:${system._identity.nextSessionId++}`;\n}\n\n/**\n * Runtime operations used to execute effects.\n *\n * XState calculates pure transitions; a runtime executes their effects. The\n * built-in local runtime is one implementation at the same level as any\n * other: install a different one via `system.runtime` (for durable hosts,\n * through `createDurable`'s adapter runtime operations).\n */\n/**\n * Why an event was not delivered: `'invalidEvent'` (payload failed its\n * declared schema), `'internalEvent'` (an internal event type sent from\n * outside its owning actor) or `'stopped'` (the target actor already\n * stopped). Hosts may report additional reasons.\n */\nexport type EventRejectionReason =\n | 'invalidEvent'\n | 'internalEvent'\n | 'stopped'\n | (string & {});\n\n/** Extra detail attached to a dead letter. */\nexport interface DeadLetterDetail {\n /** Standard Schema issues for `invalidEvent` rejections. */\n issues?: readonly StandardSchemaV1.Issue[];\n /** The underlying error describing the rejection. */\n error?: Error;\n}\n\n/**\n * Describes an event that was rejected at the delivery boundary instead of\n * being delivered to its target actor (a dead letter).\n */\nexport interface EventRejection extends DeadLetterDetail {\n /** The event that was rejected. */\n event: AnyEventObject;\n /** The actor the event was addressed to. */\n targetRef: AnyActor | undefined;\n /** The `id` of the target actor. */\n targetId: string | undefined;\n /** The actor that sent the event, or `undefined` for an external send. */\n sourceRef: AnyActor | undefined;\n /** Whether the event came from outside the system or from another actor. */\n eventOrigin: 'external' | 'actor';\n reason: EventRejectionReason;\n}\n\nexport interface ActorSystemRuntime {\n /** Publishes a newly created actor to the runtime. */\n spawnActor(\n source: AnyActor | undefined,\n actor: AnyActor\n ): void | PromiseLike<void>;\n /** Starts an actor. */\n startActor(actor: AnyActor): void | PromiseLike<void>;\n /** Stops an actor without producing a completion result. */\n stopActor(actor: AnyActor): void | PromiseLike<void>;\n /** Completes or errors an actor and publishes its terminal result. */\n terminateActor(\n actor: AnyActor,\n termination: ActorTermination\n ): void | PromiseLike<void>;\n /** Delivers an event between actors. */\n sendEvent(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n ): void | PromiseLike<void>;\n /** Publishes an emitted event. */\n emitEvent(source: AnyActor, event: EventObject): void | PromiseLike<void>;\n /** Schedules a logical timer. */\n scheduleTimer(\n source: AnyActor,\n id: string,\n delay: number\n ): void | PromiseLike<void>;\n /** Cancels one logical timer. */\n cancelTimer(source: AnyActor, id: string): void | PromiseLike<void>;\n /**\n * Runs an async actor's entire body as one durable unit. The actor is the\n * natural journal entry: its identity — `address`, string `src` key and\n * serializable `input` — crosses any boundary, so a host can wrap `exec`\n * in its own step primitive, or ignore `exec` entirely and re-run the\n * registered logic on a remote executor from `(src, input)` alone. The\n * default runs the body in this process, unjournaled.\n *\n * Like `runStep`, this is an orchestration frame: it may span external\n * events and must never be serialized behind other runtime operations.\n */\n runLogic(\n actor: AnyActor,\n exec: () => PromiseLike<unknown>\n ): PromiseLike<unknown>;\n /**\n * Runs one keyed step of an async actor (`enq.step`). The default journals\n * the result in the actor's own snapshot; a durable host implements this\n * to journal steps in its own journal instead — memoized results replay\n * without re-running `exec`.\n *\n * Unlike other runtime operations, a step is an orchestration frame that\n * may itself await runtime operations, so implementations must not\n * serialize it behind them.\n */\n runStep(\n actor: AnyActor,\n key: string,\n exec: () => unknown | PromiseLike<unknown>\n ): unknown | PromiseLike<unknown>;\n /**\n * Reports an undeliverable event. Delivery stays at-most-once — this is\n * observability, not retry: the default logs in development, emits an\n * inspection event and calls the root actor's `onRejectedEvent` hook.\n * `detail` carries validation issues and the underlying error for events\n * rejected at the delivery boundary.\n */\n deadLetter(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject,\n reason: EventRejectionReason,\n detail?: DeadLetterDetail\n ): void | PromiseLike<void>;\n /** Cancels all logical timers owned by an actor. */\n cancelAllTimers(source: AnyActor): void | PromiseLike<void>;\n}\n\n/** @internal Every operation of `ActorSystemRuntime`, for runtime wrappers. */\nexport const RUNTIME_OPERATIONS = [\n 'spawnActor',\n 'startActor',\n 'stopActor',\n 'terminateActor',\n 'emitEvent',\n 'scheduleTimer',\n 'cancelTimer',\n 'cancelAllTimers',\n 'deadLetter'\n // `runLogic`, `runStep` and `sendEvent` are deliberately absent: durable\n // executions wire them separately, since logic bodies and steps await\n // other runtime operations and root-addressed sends are captured per\n // batch.\n] as const satisfies readonly (keyof ActorSystemRuntime)[];\n\ntype ScheduledTimerId = string & { __scheduledTimerId: never };\n\nconst emptyScheduledTimers = Object.freeze(\n {}\n) as ActorSystem<any>['_snapshot']['_scheduledTimers'];\n\nfunction createScheduledTimerId(actor: AnyActor, id: string): ScheduledTimerId {\n return `${actor.sessionId}.${id}` as ScheduledTimerId;\n}\n\nexport interface ActorSystem<\n T extends ActorSystemInfo\n> extends ActorSystemRuntime {\n /** @internal Allocates an actor reference during snapshot calculation. */\n createActorRef(\n logic: AnyActorLogic,\n options: ActorOptions<AnyActorLogic>\n ): AnyActor;\n /** @internal */\n children: Map<string, AnyActor>;\n /** @internal Avoids materializing the registered-actor map. */\n _getRootActor?: () => AnyActor | undefined;\n /** @internal Avoids materializing the registered-actor map. */\n _peekChildren?: () => Map<string, AnyActor> | undefined;\n /** @internal */\n reverseKeyedActors: WeakMap<AnyActor, keyof T['actors']>;\n /** @internal */\n keyedActors: Map<keyof T['actors'], AnyActor | undefined>;\n /** @internal */\n _peekKeyedActors?: () =>\n | Map<keyof T['actors'], AnyActor | undefined>\n | undefined;\n /** @internal */\n _register: (sessionId: string, actor: AnyActor) => string;\n /** @internal */\n _unregister: (actor: AnyActor) => void;\n /** @internal */\n _set: <K extends keyof T['actors']>(key: K, actor: AnyActor) => void;\n get: <K extends keyof T['actors']>(key: K) => T['actors'][K] | undefined;\n getAll: () => Partial<T['actors']>;\n\n inspect: (\n observer:\n | Observer<InspectionEvent>\n | ((inspectionEvent: InspectionEvent) => void)\n ) => Subscription;\n /** @internal Avoids collecting inspection-only transition metadata. */\n _hasInspectionObservers?: () => boolean;\n /** @internal */\n _sendInspectionEvent: (\n event: HomomorphicOmit<InspectionEvent, 'rootId'>\n ) => void;\n /** @internal */\n _relay: (\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n ) => void | PromiseLike<void>;\n scheduler: Scheduler;\n getSnapshot: () => {\n _scheduledTimers: Record<string, ScheduledTimer>;\n };\n /**\n * Runtime identity shared by every snapshot view of this actor system.\n *\n * @internal\n */\n _identity: {\n systemId: string;\n nextSessionId: number;\n };\n /** @internal */\n _snapshot: {\n _scheduledTimers: Record<ScheduledTimerId, ScheduledTimer>;\n /** Deterministic generated-id counters keyed by `${parentAddress}|${srcPrefix}`. */\n _nextActorIds: Record<string, number>;\n };\n /** @internal */\n _snapshotVersion: number;\n start: () => void;\n _clock: Clock;\n _logger: (...args: any[]) => void;\n /**\n * The runtime executing this system's effects. When unset, the built-in\n * local in-memory runtime runs them; `createActor(machine).start()` is just\n * that built-in runtime. A host runtime installed here applies to every\n * actor in the system — snapshot-scoped views and children created later\n * included — and may implement any subset of operations, with the rest\n * keeping the built-in behavior.\n *\n * An operation that returns a promise owns its own failure handling: the\n * paths that hand work to a runtime do not await it. `createDurable`\n * tracks its adapter's operations and fails `executeEffects` when one\n * rejects.\n *\n * Durable hosts should provide this through `createDurable`'s\n * adapter runtime operations rather than assigning it directly.\n */\n runtime?: Partial<ActorSystemRuntime>;\n}\n\nexport type AnyActorSystem = ActorSystem<any>;\n\n// These optional lazy fields intentionally have no emitted initializers.\n// oxlint-disable-next-line typescript/no-unsafe-declaration-merging\ninterface RuntimeSystem<T extends ActorSystemInfo> {\n runtime?: Partial<ActorSystemRuntime>;\n _children?: Map<string, AnyActor>;\n _keyedActors?: Map<keyof T['actors'], AnyActor | undefined>;\n _reverseKeyedActors?: WeakMap<AnyActor, keyof T['actors']>;\n _inspectionObservers?: Set<Observer<InspectionEvent>>;\n _timerMap?: { [id: ScheduledTimerId]: number };\n _onRejectedEvent?: (rejection: EventRejection) => void;\n}\n\nclass RuntimeSystem<T extends ActorSystemInfo> implements ActorSystem<T> {\n public _identity = ambientExecutionIdentity ?? {\n systemId: createSystemId(),\n nextSessionId: 0\n };\n public _snapshot: ActorSystem<T>['_snapshot'];\n public _snapshotVersion = 0;\n public scheduler: Scheduler = this;\n public _clock: Clock;\n public _logger: (...args: any[]) => void;\n public createActorRef: ActorSystem<T>['createActorRef'];\n\n public get children(): Map<string, AnyActor> {\n const children = (this._children ??= new Map());\n if (this._getRootActor()) {\n children.set(this._rootActor.sessionId, this._rootActor);\n }\n return children;\n }\n\n public set children(children: Map<string, AnyActor>) {\n this._children = children;\n }\n\n public _getRootActor(): AnyActor | undefined {\n return this._rootActor._isRunning() ? this._rootActor : undefined;\n }\n\n public _peekChildren(): Map<string, AnyActor> | undefined {\n return this._children;\n }\n\n public get keyedActors(): Map<keyof T['actors'], AnyActor | undefined> {\n return (this._keyedActors ??= new Map());\n }\n\n public set keyedActors(actors: Map<keyof T['actors'], AnyActor | undefined>) {\n this._keyedActors = actors;\n }\n\n public get reverseKeyedActors(): WeakMap<AnyActor, keyof T['actors']> {\n return (this._reverseKeyedActors ??= new WeakMap());\n }\n\n public set reverseKeyedActors(actors: WeakMap<AnyActor, keyof T['actors']>) {\n this._reverseKeyedActors = actors;\n }\n\n /** @internal Avoids materializing the receptionist for empty systems. */\n public _peekKeyedActors():\n | Map<keyof T['actors'], AnyActor | undefined>\n | undefined {\n return this._keyedActors;\n }\n\n constructor(\n private _rootActor: AnyActor,\n options: {\n clock: Clock;\n logger: (...args: any[]) => void;\n snapshot?: unknown;\n createActorRef: ActorSystem<T>['createActorRef'];\n onRejectedEvent?: (rejection: EventRejection) => void;\n }\n ) {\n this._onRejectedEvent = options.onRejectedEvent;\n const restoredSnapshot =\n typeof options.snapshot === 'object' && options.snapshot !== null\n ? (options.snapshot as {\n scheduler?: Record<ScheduledTimerId, ScheduledTimer>;\n })\n : undefined;\n this._clock = options.clock;\n this._logger = options.logger;\n this.createActorRef = options.createActorRef;\n const ambientInspector = getAmbientInspector();\n if (ambientInspector) {\n this.inspect(ambientInspector);\n }\n this._snapshot = {\n _scheduledTimers: restoredSnapshot?.scheduler ?? emptyScheduledTimers,\n // System-level counters are process-local backstops; per-actor\n // counters persist on each machine snapshot, and restored explicit ids\n // reserve their numbering here via `resolveActorId`.\n _nextActorIds: {}\n };\n }\n\n // Records a send on the *sender's* transition for the `sent[]` inspection\n // facet. Captures the send when it is initiated (including delayed sends that\n // may never deliver), keyed to the source actor's in-flight transition.\n private _recordSent(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject,\n delay?: number,\n id?: string\n ): void {\n if (!this._inspectionObservers?.size || !source) {\n return;\n }\n const inspectionSource = source as AnyActor & {\n _collectedSent?: SentRecord[];\n };\n const collected = (inspectionSource._collectedSent ??= []);\n collected.push({\n targetRef: target,\n targetId: target.id,\n event,\n delay,\n id\n });\n }\n\n public schedule(source: AnyActor, id: string, delay: number): void {\n const existingId = createScheduledTimerId(source, id);\n if (this._timerMap?.[existingId] !== undefined) {\n this.cancel(source, id);\n }\n\n const timer = source.getSnapshot()?.timers?.[id];\n if (timer) {\n const target = timer.target === 'self' ? source : timer.target;\n this._recordSent(source, target, timer.event, delay, id);\n }\n\n const scheduledAt = this._clock.now?.() ?? Date.now();\n const scheduledTimer: ScheduledTimer = {\n source,\n delay,\n id,\n scheduledAt,\n dueAt: scheduledAt + delay\n };\n const scheduledTimerId = createScheduledTimerId(source, id);\n if (this._snapshot._scheduledTimers === emptyScheduledTimers) {\n this._snapshot._scheduledTimers = {};\n }\n this._snapshot._scheduledTimers[scheduledTimerId] = scheduledTimer;\n markSystemSnapshotDirty(this);\n\n const timeout = this._clock.setTimeout(() => {\n if (this._timerMap) {\n delete this._timerMap[scheduledTimerId];\n }\n delete this._snapshot._scheduledTimers[scheduledTimerId];\n markSystemSnapshotDirty(this);\n\n this._deliver(source, source, { type: XSTATE_TIMER, id });\n }, delay);\n\n (this._timerMap ??= {})[scheduledTimerId] = timeout;\n }\n\n public cancel(source: AnyActor, id: string): void {\n const scheduledTimerId = createScheduledTimerId(source, id);\n const timeout = this._timerMap?.[scheduledTimerId];\n\n if (this._timerMap) {\n delete this._timerMap[scheduledTimerId];\n }\n if (this._snapshot._scheduledTimers !== emptyScheduledTimers) {\n delete this._snapshot._scheduledTimers[scheduledTimerId];\n }\n markSystemSnapshotDirty(this);\n\n if (timeout !== undefined) {\n this._clock.clearTimeout(timeout);\n }\n }\n\n public cancelAll(actor: AnyActor): void {\n for (const scheduledTimerId in this._snapshot._scheduledTimers) {\n const scheduledTimer =\n this._snapshot._scheduledTimers[scheduledTimerId as ScheduledTimerId];\n if (scheduledTimer.source === actor) {\n this.cancel(actor, scheduledTimer.id);\n }\n }\n }\n\n // Delivers an event to the target actor. Used by both `_relay` (which also\n // records the send) and the scheduler's timer (which already recorded it).\n private _deliver(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n ): void {\n deliverEvent(source, target, event);\n }\n\n public _register(sessionId: string, actor: AnyActor): string {\n if (actor === this._rootActor) {\n this._children?.set(sessionId, actor);\n } else {\n (this._children ??= new Map()).set(sessionId, actor);\n }\n markSystemSnapshotDirty(this);\n return sessionId;\n }\n\n public _unregister(actor: AnyActor): void {\n let changed: boolean;\n // Remote handles have no sessionId and are never in the session map;\n // their registry cleanup happens through the keyed-actor path below.\n if (actor === this._rootActor) {\n changed = this._getRootActor() !== undefined;\n changed =\n (actor.sessionId !== undefined &&\n (this._children?.delete(actor.sessionId) ?? false)) ||\n changed;\n } else {\n changed =\n actor.sessionId !== undefined &&\n (this._children?.delete(actor.sessionId) ?? false);\n }\n const registryKey = this._reverseKeyedActors?.get(actor);\n\n if (registryKey !== undefined) {\n if (this._keyedActors?.get(registryKey) === actor) {\n this._keyedActors.delete(registryKey);\n changed = true;\n }\n this._reverseKeyedActors?.delete(actor);\n }\n if (changed) {\n markSystemSnapshotDirty(this);\n }\n }\n\n public get<K extends keyof T['actors']>(\n registryKey: K\n ): T['actors'][K] | undefined {\n return this._keyedActors?.get(registryKey) as T['actors'][K] | undefined;\n }\n\n public getAll(): Partial<T['actors']> {\n return Object.fromEntries(this._keyedActors?.entries() ?? []) as Partial<\n T['actors']\n >;\n }\n\n public _set<K extends keyof T['actors']>(\n registryKey: K,\n actor: AnyActor\n ): void {\n const existing = this._keyedActors?.get(registryKey);\n if (existing && existing !== actor) {\n throw new Error(\n `Actor with registry key '${registryKey as string}' already exists.`\n );\n }\n\n (this._keyedActors ??= new Map()).set(registryKey, actor);\n (this._reverseKeyedActors ??= new WeakMap()).set(actor, registryKey);\n if (existing !== actor) {\n markSystemSnapshotDirty(this);\n }\n }\n\n public inspect(\n observerOrFn:\n | Observer<InspectionEvent>\n | ((inspectionEvent: InspectionEvent) => void)\n ): Subscription {\n const observer = toObserver(observerOrFn);\n (this._inspectionObservers ??= new Set()).add(observer);\n\n return {\n unsubscribe: () => {\n this._inspectionObservers?.delete(observer);\n }\n };\n }\n\n public _hasInspectionObservers(): boolean {\n return !!this._inspectionObservers?.size;\n }\n\n public _sendInspectionEvent(\n event: HomomorphicOmit<InspectionEvent, 'rootId'>\n ): void {\n if (!this._inspectionObservers?.size) {\n return;\n }\n const resolvedInspectionEvent: InspectionEvent = {\n ...event,\n rootId: this._rootActor.sessionId!\n };\n this._inspectionObservers.forEach((observer) =>\n observer.next?.(resolvedInspectionEvent)\n );\n }\n\n // Unlike the other operations, spawn has no local work: local actors\n // register with the system when they are constructed, so this only\n // notifies a host runtime.\n public spawnActor(\n source: AnyActor | undefined,\n actor: AnyActor\n ): void | PromiseLike<void> {\n return this.runtime?.spawnActor?.(source, actor);\n }\n\n public startActor(actor: AnyActor): void | PromiseLike<void> {\n const override = this.runtime?.startActor;\n if (override) {\n return override(actor);\n }\n actor.start();\n }\n\n public stopActor(actor: AnyActor): void | PromiseLike<void> {\n const override = this.runtime?.stopActor;\n if (override) {\n return override(actor);\n }\n stopActorLocally(actor);\n }\n\n public terminateActor(\n actor: AnyActor,\n termination: ActorTermination\n ): void | PromiseLike<void> {\n const override = this.runtime?.terminateActor;\n if (override) {\n return override(actor, termination);\n }\n terminateActorLocally(actor, termination);\n }\n\n public sendEvent(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n ): void | PromiseLike<void> {\n if (rejectUndeliverableEvent(source, target, event)) {\n return;\n }\n // Record for the inspection `sent[]` facet regardless of which runtime\n // delivers, so host runtimes keep inspection parity.\n this._recordSent(source, target, event);\n const override = this.runtime?.sendEvent;\n if (override) {\n return override(source, target, event);\n }\n this._deliver(source, target, event);\n }\n\n public emitEvent(\n source: AnyActor,\n event: EventObject\n ): void | PromiseLike<void> {\n const override = this.runtime?.emitEvent;\n if (override) {\n return override(source, event);\n }\n (source as AnyActor & { _emit(value: EventObject): void })._emit(event);\n }\n\n public deadLetter(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject,\n reason: EventRejectionReason,\n detail?: DeadLetterDetail\n ): void | PromiseLike<void> {\n this._sendInspectionEvent({\n type: '@xstate.deadletter',\n actorRef: target,\n sourceRef: source,\n event,\n reason,\n issues: detail?.issues,\n error: detail?.error\n });\n this._onRejectedEvent?.({\n event,\n targetRef: target,\n targetId: target.id,\n sourceRef: source,\n eventOrigin: source ? 'actor' : 'external',\n reason,\n issues: detail?.issues,\n error: detail?.error\n });\n const override = this.runtime?.deadLetter;\n if (override) {\n return override(source, target, event, reason, detail);\n }\n if (isDevelopment) {\n console.warn(\n `Event \"${event.type}\" to actor \"${target.id}\" was not delivered (${reason}).`\n );\n }\n }\n\n public runStep(\n actor: AnyActor,\n key: string,\n exec: () => unknown | PromiseLike<unknown>\n ): unknown | PromiseLike<unknown> {\n const override = this.runtime?.runStep;\n if (override) {\n return override(actor, key, exec);\n }\n return runStep(actor, key, exec);\n }\n\n public runLogic(\n actor: AnyActor,\n exec: () => PromiseLike<unknown>\n ): PromiseLike<unknown> {\n const override = this.runtime?.runLogic;\n if (override) {\n return override(actor, exec);\n }\n return exec();\n }\n\n public scheduleTimer(\n source: AnyActor,\n id: string,\n delay: number\n ): void | PromiseLike<void> {\n const override = this.runtime?.scheduleTimer;\n if (override) {\n // The local scheduler records delayed sends for inspection inside\n // `schedule`; keep that parity for host runtimes.\n const timer = source.getSnapshot()?.timers?.[id];\n if (timer) {\n const target = timer.target === 'self' ? source : timer.target;\n this._recordSent(source, target, timer.event, delay, id);\n }\n return override(source, id, delay);\n }\n this.schedule(source, id, delay);\n }\n\n public cancelTimer(source: AnyActor, id: string): void | PromiseLike<void> {\n const override = this.runtime?.cancelTimer;\n if (override) {\n return override(source, id);\n }\n this.cancel(source, id);\n }\n\n public cancelAllTimers(source: AnyActor): void | PromiseLike<void> {\n const override = this.runtime?.cancelAllTimers;\n if (override) {\n return override(source);\n }\n this.cancelAll(source);\n }\n\n public _relay(\n source: AnyActor | undefined,\n target: AnyActor,\n event: AnyEventObject\n ): void | PromiseLike<void> {\n if (\n transitionEffectTargets.length &&\n transitionEffectTargets.includes(target)\n ) {\n throw transitionEffectSignal;\n }\n // Returned so callers that can observe a host runtime's asynchronous\n // delivery do; the built-in runtime delivers synchronously.\n return this.sendEvent(source, target, event);\n }\n\n public getSnapshot(): {\n _scheduledTimers: Record<string, ScheduledTimer>;\n } {\n return {\n _scheduledTimers: { ...this._snapshot._scheduledTimers }\n };\n }\n\n public start(): void {\n const scheduledTimers = this._snapshot._scheduledTimers;\n let resetScheduledTimers = true;\n for (const scheduledId in scheduledTimers) {\n if (resetScheduledTimers) {\n this._snapshot._scheduledTimers = {};\n resetScheduledTimers = false;\n }\n const { source, dueAt, id } =\n scheduledTimers[scheduledId as ScheduledTimerId];\n this.scheduleTimer(\n source,\n id,\n Math.max(0, dueAt - (this._clock.now?.() ?? Date.now()))\n );\n }\n }\n}\n\nexport function createRuntimeSystem<T extends ActorSystemInfo>(\n rootActor: AnyActor,\n options: {\n clock: Clock;\n logger: (...args: any[]) => void;\n snapshot?: unknown;\n createActorRef: ActorSystem<T>['createActorRef'];\n onRejectedEvent?: (rejection: EventRejection) => void;\n }\n): ActorSystem<T> {\n return new RuntimeSystem(rootActor, options);\n}\n","import isDevelopment from '#is-development';\nimport type { ActionRecord, SentRecord } from './inspection.ts';\nimport { Mailbox } from './Mailbox.ts';\nimport { XSTATE_STOP } from './constants.ts';\nimport {\n createDoneActorEvent,\n createErrorActorEvent,\n createInitEvent\n} from './eventUtils.ts';\nimport { reportUnhandledError } from './reportUnhandledError.ts';\nimport { symbolObservable } from './symbolObservable.ts';\nimport {\n encodeAddressSegment,\n AnyActorSystem,\n bookSessionId,\n Clock,\n createRuntimeSystem,\n resolveActorId\n} from './system.ts';\n\n// those are needed to make JSDoc `@link` work properly\n// oxlint-disable no-unused-vars\nimport type {\n createObservableLogic,\n createEventObservableLogic\n} from './actors/observable.ts';\nimport type { createCallbackLogic } from './actors/callback.ts';\nimport type { createLogic } from './actors/logic.ts';\nimport type { createAsyncLogic } from './actors/promise.ts';\nimport type { createMachine } from './createMachine.ts';\n// oxlint-enable no-unused-vars\n\nlet executingCustomAction: boolean = false;\n\nimport type {\n ActorTermination,\n ActorScope,\n ActorTrigger,\n AnyActor,\n AnyActorLogic,\n EmittedFrom,\n EventFromLogic,\n SendableEventFromLogic,\n InputFrom,\n PersistedSnapshotFor,\n Snapshot,\n SnapshotFrom,\n AnyTransitionDefinition,\n ExecutableActionObject,\n Readable,\n ActorLogicTransitionResult\n} from './types.ts';\nimport {\n ActorOptions,\n ActorInstance,\n ActorRef,\n EventObject,\n InteropSubscribable,\n Observer,\n Subscription\n} from './types.ts';\nimport { toObserver } from './utils.ts';\nimport { finalizeTransitionResult } from './transitionActions.ts';\nimport {\n refreshSnapshotActorRefRoot,\n setSnapshotActorRef\n} from './snapshotActorRef.ts';\n\n/**\n * Marks a serialized object as an actor reference (`xstate$type` in JSON\n * output and persisted context).\n */\nexport const ACTOR_REF_TYPE = 'actorRef';\n\nconst emptyInspectionRecords = Object.freeze([]) as unknown as never[];\n\n// those values are currently used by @xstate/react directly so it's important to keep the assigned values in sync\nexport enum ProcessingStatus {\n NotStarted = 0,\n Running = 1,\n Stopped = 2\n}\n\nconst defaultOptions = Object.freeze({\n clock: {\n setTimeout: (fn, ms) => {\n return setTimeout(fn, ms);\n },\n clearTimeout: (id) => {\n return clearTimeout(id);\n }\n } as Clock,\n logger: console.log.bind(console)\n});\n\nfunction safeCall<T>(fn: ((arg: T) => void) | undefined, arg?: T) {\n try {\n fn?.(arg as T);\n } catch (err) {\n reportUnhandledError(err);\n }\n}\n\nfunction executeExecutableEffects(\n effects: readonly ExecutableActionObject[] | undefined,\n actorScope: ActorScope<any, any, any, any>\n): void {\n if (!effects?.length) {\n return;\n }\n\n for (const effect of effects) {\n actorScope.actionExecutor(effect);\n }\n}\n\nfunction createActorRef(\n logic: AnyActorLogic,\n options: ActorOptions<AnyActorLogic>\n): AnyActor {\n return new Actor(logic, options);\n}\n\n/**\n * An Actor is a running process that can receive events, send events and change\n * its behavior based on the events it receives, which can cause effects outside\n * of the actor. When you run a state machine, it becomes an actor.\n *\n * An `Actor` is the concrete runtime instance with lifecycle methods and\n * system-owned internals. It also satisfies the narrower `ActorRef` contract,\n * so consumer APIs should accept `ActorRef` when they only need to send events\n * or read snapshots.\n */\nexport class Actor<TLogic extends AnyActorLogic> implements ActorInstance<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>,\n EmittedFrom<TLogic>,\n SendableEventFromLogic<TLogic>\n> {\n /** The current internal state of the actor. */\n private _snapshot!: SnapshotFrom<TLogic>;\n /**\n * The clock that is responsible for setting and clearing timeouts, such as\n * delayed events and transitions.\n */\n public clock: Clock;\n public options: Readonly<ActorOptions<TLogic>>;\n\n /** The unique identifier for this actor relative to its parent. */\n public id: string;\n\n private _boundProcess?: (event: EventFromLogic<TLogic>) => void;\n private mailbox?: Mailbox<EventFromLogic<TLogic>>;\n private _mailboxStarted = false;\n\n private observers?: Set<Observer<SnapshotFrom<TLogic>>>;\n private eventListeners:\n | Map<string, Set<(emittedEvent: EmittedFrom<TLogic>) => void>>\n | undefined;\n private logger: (...args: any[]) => void;\n\n /** @internal */\n public _processingStatus: ProcessingStatus = ProcessingStatus.NotStarted;\n private _forceDeferredActions = false;\n\n // Actor Ref\n public _parent?: AnyActor;\n /** @internal */\n public _syncSnapshot?: boolean;\n public ref: ActorRef<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>,\n EmittedFrom<TLogic>,\n SendableEventFromLogic<TLogic>\n >;\n // TODO: add typings for system\n private _actorScope: ActorScope<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>,\n AnyActorSystem,\n EmittedFrom<TLogic>,\n SendableEventFromLogic<TLogic>\n >;\n\n /** @internal */\n public _lastSourceRef?: AnyActor;\n /** @internal */\n public _collectedMicrosteps: AnyTransitionDefinition[] | undefined;\n /** @internal Actions executed during the in-flight transition. */\n public _collectedActions: ActionRecord[] | undefined;\n /** @internal Events relayed to other actors during the in-flight transition. */\n public _collectedSent: SentRecord[] | undefined;\n private _initialEffects: ExecutableActionObject[] | undefined;\n public registryKey: string | undefined;\n\n /** The globally unique process ID for this invocation. */\n public sessionId: string;\n\n private _address?: string;\n /**\n * The deterministic logical address of this actor within its system: the\n * `/`-joined path of actor ids from the root. Stable across persistence and\n * restore, unlike `sessionId`, which identifies one incarnation.\n *\n * `/` separates segments, so an id containing one (a state name with a\n * slash reaches its invoked child's id) is percent-encoded to keep the\n * path unambiguous.\n */\n public get address(): string {\n // `id` and `_parent` never change after construction, so the whole chain\n // memoizes to O(1) amortized.\n return (this._address ??= this._parent\n ? `${this._parent.address}/${encodeAddressSegment(this.id)}`\n : encodeAddressSegment(this.id));\n }\n\n /** The system to which this actor belongs. */\n public system: AnyActorSystem;\n\n private _trigger?: ActorTrigger<SendableEventFromLogic<TLogic>>;\n\n public get trigger(): ActorTrigger<SendableEventFromLogic<TLogic>> {\n return (this._trigger ??= new Proxy({} as Actor<TLogic>['trigger'], {\n get: (_, eventType: string) => {\n return (payload?: Record<PropertyKey, unknown>) => {\n this.send({\n ...payload,\n type: eventType\n } as SendableEventFromLogic<TLogic>);\n };\n }\n }) as ActorTrigger<SendableEventFromLogic<TLogic>>);\n }\n\n private _boundSend?: ActorRef<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>,\n EmittedFrom<TLogic>,\n SendableEventFromLogic<TLogic>\n >['send'];\n\n public get send(): ActorRef<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>,\n EmittedFrom<TLogic>,\n SendableEventFromLogic<TLogic>\n >['send'] {\n return (this._boundSend ??= this._sendPublic.bind(this));\n }\n\n public src: string | AnyActorLogic;\n\n /**\n * Creates a new actor instance for the given logic with the provided options,\n * if any.\n *\n * @param logic The logic to create an actor from\n * @param options Actor options\n */\n constructor(\n public logic: TLogic,\n options?: ActorOptions<TLogic>\n ) {\n const resolvedOptions = (\n options ? { ...defaultOptions, ...options } : defaultOptions\n ) as ActorOptions<TLogic> & typeof defaultOptions;\n\n const { clock, logger, parent, syncSnapshot, id, registryKey, inspect } =\n resolvedOptions;\n\n this.system = parent\n ? parent.system\n : (resolvedOptions._systemRef?.current ??\n createRuntimeSystem(this, {\n clock,\n logger,\n snapshot: resolvedOptions.snapshot ?? resolvedOptions.state,\n createActorRef,\n onRejectedEvent: resolvedOptions.onRejectedEvent\n }));\n\n if (\n !parent &&\n resolvedOptions._systemRef &&\n !resolvedOptions._systemRef.current\n ) {\n resolvedOptions._systemRef.current = this.system;\n }\n\n if (inspect && !parent) {\n // Always inspect at the system-level\n this.system.inspect(toObserver(inspect));\n }\n\n this.sessionId = resolvedOptions._sessionId ?? bookSessionId(this.system);\n this.id = resolveActorId(this.system, id, {\n parent,\n src: resolvedOptions.src ?? logic\n });\n this.logger = options?.logger ?? this.system._logger;\n this.clock = options?.clock ?? this.system._clock;\n this._parent = parent;\n this._syncSnapshot = syncSnapshot;\n this.options = resolvedOptions as ActorOptions<TLogic> &\n typeof defaultOptions;\n this.src = resolvedOptions.src ?? logic;\n this.ref = this;\n this._actorScope = this as unknown as typeof this._actorScope;\n\n if (registryKey) {\n this.registryKey = registryKey;\n this.system._set(registryKey, this);\n }\n\n // prepare to collect initial microsteps during initialTransition\n this._collectedMicrosteps = undefined;\n const persistedState = options?.snapshot ?? options?.state;\n this._restored = persistedState !== undefined;\n try {\n if (persistedState) {\n this._setSnapshot(\n this.logic.restoreSnapshot\n ? this.logic.restoreSnapshot(persistedState, this._actorScope)\n : persistedState\n );\n } else if (options?._inert) {\n // Inert actors (createInertActorScope) only anchor a scope for pure\n // transition functions; computing an initial snapshot here would run\n // init-time side effects (context factories, entry) a second time.\n } else {\n const [snapshot, effects] = finalizeTransitionResult(\n this._actorScope,\n undefined,\n this.logic.initialTransition(this.options?.input, this._actorScope)\n );\n this._setSnapshot(snapshot);\n this._initialEffects = effects.length ? effects : undefined;\n }\n } catch (err) {\n // if we get here then it means that we assign a value to this._snapshot that is not of the correct type\n // we can't get the true `TSnapshot & { status: 'error'; }`, it's impossible\n // so right now this is a lie of sorts\n this._setSnapshot({\n status: 'error',\n output: undefined,\n error: err\n } as SnapshotFrom<TLogic>);\n // discard any functions deferred during the failed initial snapshot\n // computation so they can't run against an inconsistent actor\n if (this._deferred) {\n this._deferred.length = 0;\n }\n }\n\n if (\n registryKey &&\n (this._snapshot as Snapshot<unknown>).status !== 'active'\n ) {\n this.system._unregister(this);\n }\n\n // Announce actor topology: emitted once for every actor (root and every\n // spawned/invoked child) so the actor graph can be drawn before any\n // transitions occur. This is the only place actor identity is announced.\n if (this.system._hasInspectionObservers?.() ?? true) {\n this.system._sendInspectionEvent({\n type: '@xstate.actor',\n actorRef: this,\n parentRef: this._parent,\n id: this.id,\n src: this.src,\n snapshot: this._snapshot\n });\n }\n }\n\n // array of functions to defer\n private _deferred: Array<() => void> | undefined;\n\n private _restored = false;\n\n /** @internal */\n public _getLogger(): ActorScope<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>\n >['logger'] {\n return this.logger;\n }\n\n private get self(): Actor<TLogic> {\n return this;\n }\n\n private get defer(): (fn: () => void) => void {\n const defer = (fn: () => void) => this._defer(fn);\n Object.defineProperty(this, 'defer', { value: defer });\n return defer;\n }\n\n private get stopChild(): (child: AnyActor) => void {\n const stopChild = (child: AnyActor) => this._stopChild(child);\n Object.defineProperty(this, 'stopChild', { value: stopChild });\n return stopChild;\n }\n\n private get emit(): (event: EmittedFrom<TLogic>) => void | PromiseLike<void> {\n const emit = (event: EmittedFrom<TLogic>) =>\n this.system.emitEvent(this, event);\n Object.defineProperty(this, 'emit', { value: emit });\n return emit;\n }\n\n private get actionExecutor(): (action: ExecutableActionObject) => void {\n const actionExecutor = (action: ExecutableActionObject) =>\n this._executeAction(action);\n Object.defineProperty(this, 'actionExecutor', { value: actionExecutor });\n return actionExecutor;\n }\n\n /** @internal */\n public _isRunning(): boolean {\n return this._processingStatus === ProcessingStatus.Running;\n }\n\n /** @internal */\n public _defer(fn: () => void): void {\n (this._deferred ??= []).push(fn);\n }\n\n /** @internal */\n public _stopChild(child: AnyActor): void {\n if (child._parent !== this) {\n throw new Error(\n isDevelopment\n ? `Cannot stop child actor ${child.id} of ${this.id} because it is not a child`\n : `Cannot stop non-child actor ${child.id}`\n );\n }\n (child as Actor<AnyActorLogic>)._stop();\n }\n\n /** @internal */\n public _executeAction(action: ExecutableActionObject): void {\n const exec = () => {\n // Record every executed action for the '@xstate.transition' inspection\n // event's `actions[]` facet (replaces the v5 '@xstate.action' event).\n if (this.system._hasInspectionObservers?.() ?? true) {\n (this._collectedActions ??= []).push({\n type: action.type,\n params: action.params\n });\n }\n const saveExecutingCustomAction = executingCustomAction;\n try {\n executingCustomAction = true;\n void action.exec();\n } finally {\n executingCustomAction = saveExecutingCustomAction;\n }\n };\n if (\n this._processingStatus === ProcessingStatus.Running &&\n !this._forceDeferredActions\n ) {\n exec();\n } else {\n (this._deferred ??= []).push(exec);\n }\n }\n\n /** Associates each live snapshot with this actor for later pure transitions. */\n private _setSnapshot(snapshot: SnapshotFrom<TLogic>): void {\n const previousSnapshot = this._snapshot;\n this._snapshot = snapshot;\n setSnapshotActorRef(snapshot, this, this.system, previousSnapshot);\n }\n\n private _setErrorSnapshot(\n err: unknown,\n snapshot: SnapshotFrom<TLogic> = this._snapshot\n ) {\n this._setSnapshot({\n ...(snapshot as Snapshot<unknown>),\n status: 'error',\n error: err\n } as SnapshotFrom<TLogic>);\n }\n\n /** Recover via the logic's error event if possible; otherwise error out. */\n private _recoverOrError(\n err: unknown,\n snapshot?: SnapshotFrom<TLogic>\n ): boolean {\n if (this._tryHandleExecutionError(err, snapshot)) {\n return true;\n }\n this._setErrorSnapshot(err);\n this._error(err);\n return false;\n }\n\n private _tryHandleExecutionError(\n err: unknown,\n snapshot: SnapshotFrom<TLogic> = this._snapshot\n ): boolean {\n // Machine logic can recover from execution errors via `onError`\n // transitions; the logic decides (so the actor stays logic-agnostic).\n const errorEvent = this.logic.getExecutionErrorEvent?.(snapshot, err) as\n | EventFromLogic<TLogic>\n | undefined;\n if (!errorEvent) {\n return false;\n }\n\n try {\n const [nextSnapshot, effects] = finalizeTransitionResult(\n this._actorScope,\n snapshot,\n this.logic.transition(snapshot, errorEvent, this._actorScope)\n );\n this._setSnapshot(nextSnapshot);\n executeExecutableEffects(effects, this._actorScope);\n this.update(nextSnapshot, errorEvent);\n return true;\n } catch {\n return false;\n }\n }\n\n private _next(snapshot: SnapshotFrom<TLogic>) {\n for (const observer of this.observers ?? emptyInspectionRecords) {\n safeCall(observer.next, snapshot);\n }\n }\n\n private update(snapshot: SnapshotFrom<TLogic>, event: EventObject): void {\n // Update state\n this._setSnapshot(snapshot);\n\n // Execute deferred effects\n const deferred = this._deferred;\n for (let i = 0; i < (deferred?.length ?? 0); i++) {\n const deferredFn = deferred![i];\n try {\n deferredFn();\n } catch (err) {\n // this error can only be caught when executing *initial* actions\n // it's the only time when we call actions provided by the user through those deferreds\n // when the actor is already running we always execute them synchronously while transitioning\n // no \"builtin deferred\" should actually throw an error since they are either safe\n // or the control flow is passed through the mailbox and errors should be caught by the `_process` used by the mailbox\n deferred!.length = 0;\n if (this._tryHandleExecutionError(err, snapshot)) {\n return;\n }\n this._setErrorSnapshot(err, snapshot);\n this._error(err);\n break;\n }\n }\n if (deferred) {\n deferred.length = 0;\n }\n\n switch ((this._snapshot as Snapshot<unknown>).status) {\n case 'active':\n this._next(snapshot);\n break;\n case 'done':\n case 'error':\n // Terminal lifecycle is represented by the ordered\n // `@xstate.terminate` effect returned by the actor logic.\n break;\n }\n this._inspectTransition(this._snapshot, event);\n }\n\n /** @internal Emits the transition inspection event; used by the pure\n * `transition()` path for snapshots driven outside a live actor. */\n public _inspectTransition(\n snapshot: SnapshotFrom<TLogic>,\n event: EventObject\n ): void {\n if (this.system._hasInspectionObservers?.() ?? true) {\n this.system._sendInspectionEvent({\n type: '@xstate.transition',\n actorRef: this,\n event,\n sourceRef: this._lastSourceRef,\n targetRef: this,\n snapshot,\n microsteps: this._collectedMicrosteps ?? emptyInspectionRecords,\n actions: this._collectedActions ?? emptyInspectionRecords,\n sent: this._collectedSent ?? emptyInspectionRecords,\n eventType: event.type\n });\n }\n this._collectedMicrosteps = undefined;\n this._collectedActions = undefined;\n this._collectedSent = undefined;\n }\n\n private _flushInitialEffects(): boolean {\n if (!this._initialEffects?.length) {\n return true;\n }\n this._forceDeferredActions = true;\n try {\n executeExecutableEffects(this._initialEffects, this._actorScope);\n this._initialEffects = undefined;\n return true;\n } catch (err) {\n this._initialEffects = undefined;\n if (this._deferred) {\n this._deferred.length = 0;\n }\n this._recoverOrError(err);\n return (this._snapshot as Snapshot<unknown>).status === 'active';\n } finally {\n this._forceDeferredActions = false;\n }\n }\n\n /**\n * Subscribe an observer to an actor’s snapshot values.\n *\n * @remarks\n * The observer will receive the actor’s snapshot value when it is emitted.\n * The observer can be:\n *\n * - A plain function that receives the latest snapshot, or\n * - An observer object whose `.next(snapshot)` method receives the latest\n * snapshot\n *\n * @example\n *\n * ```ts\n * // Observer as a plain function\n * const subscription = actor.subscribe((snapshot) => {\n * console.log(snapshot);\n * });\n * ```\n *\n * @example\n *\n * ```ts\n * // Observer as an object\n * const subscription = actor.subscribe({\n * next(snapshot) {\n * console.log(snapshot);\n * },\n * error(err) {\n * // ...\n * },\n * complete() {\n * // ...\n * }\n * });\n * ```\n *\n * The return value of `actor.subscribe(observer)` is a subscription object\n * that has an `.unsubscribe()` method. You can call\n * `subscription.unsubscribe()` to unsubscribe the observer:\n *\n * @example\n *\n * ```ts\n * const subscription = actor.subscribe((snapshot) => {\n * // ...\n * });\n *\n * // Unsubscribe the observer\n * subscription.unsubscribe();\n * ```\n *\n * When the actor is stopped, all of its observers will automatically be\n * unsubscribed.\n *\n * @param observer - Either a plain function that receives the latest\n * snapshot, or an observer object whose `.next(snapshot)` method receives\n * the latest snapshot\n */\n public subscribe(observer: Observer<SnapshotFrom<TLogic>>): Subscription;\n public subscribe(\n nextListener?: (snapshot: SnapshotFrom<TLogic>) => void,\n errorListener?: (error: any) => void,\n completeListener?: () => void\n ): Subscription;\n public subscribe(\n nextListenerOrObserver?:\n | ((snapshot: SnapshotFrom<TLogic>) => void)\n | Observer<SnapshotFrom<TLogic>>,\n errorListener?: (error: any) => void,\n completeListener?: () => void\n ): Subscription {\n const observer = toObserver(\n nextListenerOrObserver,\n errorListener,\n completeListener\n );\n\n if (this._processingStatus !== ProcessingStatus.Stopped) {\n (this.observers ??= new Set()).add(observer);\n } else {\n switch ((this._snapshot as Snapshot<unknown>).status) {\n case 'done':\n safeCall(observer.complete);\n break;\n case 'error': {\n const err = (this._snapshot as Snapshot<unknown>).error;\n if (!observer.error) {\n reportUnhandledError(err);\n } else {\n safeCall(observer.error, err);\n }\n break;\n }\n }\n }\n\n return {\n unsubscribe: () => {\n this.observers?.delete(observer);\n }\n };\n }\n\n public on<TType extends EmittedFrom<TLogic>['type'] | '*'>(\n type: TType,\n handler: (\n emitted: EmittedFrom<TLogic> &\n (TType extends '*' ? unknown : { type: TType })\n ) => void\n ): Subscription {\n let listeners = this.eventListeners?.get(type);\n if (!listeners) {\n listeners = new Set();\n (this.eventListeners ??= new Map()).set(type, listeners);\n }\n listeners.add(handler as (emittedEvent: EmittedFrom<TLogic>) => void);\n\n return {\n unsubscribe: () => {\n listeners.delete(\n handler as (emittedEvent: EmittedFrom<TLogic>) => void\n );\n }\n };\n }\n\n public select<TSelected>(\n selector: (snapshot: SnapshotFrom<TLogic>) => TSelected,\n equalityFn: (a: TSelected, b: TSelected) => boolean = Object.is\n ): Readable<TSelected> {\n return {\n subscribe: (\n observerOrFn:\n | Observer<TSelected>\n | ((value: TSelected) => void)\n | undefined,\n errorListener?: (error: any) => void,\n completeListener?: () => void\n ) => {\n const observer = toObserver(\n observerOrFn,\n errorListener,\n completeListener\n );\n let selected = selector(this.getSnapshot());\n return this.subscribe({\n next: (snapshot) => {\n const next = selector(snapshot);\n if (!equalityFn(selected, next)) {\n selected = next;\n observer.next?.(next);\n }\n },\n error: observer.error,\n complete: observer.complete\n });\n },\n get: () => selector(this.getSnapshot())\n };\n }\n\n /** Starts the Actor from the initial state */\n public start(): this {\n if (this._processingStatus === ProcessingStatus.Running) {\n // Do not restart the service if it is already started\n return this;\n }\n\n if (this._processingStatus === ProcessingStatus.Stopped) {\n return this;\n }\n\n if (this._syncSnapshot) {\n this.subscribe({\n next: (snapshot: Snapshot<unknown>) => {\n if (snapshot.status === 'active') {\n this.system._relay(this, this._parent!, {\n type: 'xstate.snapshot.actor',\n actorId: this.id,\n sessionId: this.sessionId,\n snapshot\n });\n }\n },\n error: () => {}\n });\n }\n\n this.system._register(this.sessionId, this);\n if (this.registryKey) {\n this.system._set(this.registryKey, this);\n }\n this._processingStatus = ProcessingStatus.Running;\n\n this._lastSourceRef = this._parent;\n\n const status = (this._snapshot as Snapshot<unknown>).status;\n\n switch (status) {\n case 'done':\n // a state machine can be \"done\" upon initialization (it could reach a final state using initial microsteps)\n // we still need to complete observers, flush deferreds etc\n if (this._restored) {\n // Restoration does not replay the transition that originally\n // terminated the actor, and must not notify the parent again.\n this._next(this._snapshot);\n this._stopProcedure();\n this._complete();\n return this;\n }\n if (!this._flushInitialEffects()) {\n return this;\n }\n this.update(\n this._snapshot,\n createInitEvent(\n this.options.input\n ) as unknown as EventFromLogic<TLogic>\n );\n // TODO: rethink cleanup of observers, mailbox, etc\n return this;\n case 'error':\n this._error((this._snapshot as Snapshot<unknown>).error);\n return this;\n }\n\n if (!this._parent) {\n this.system.start();\n }\n\n if (!this._flushInitialEffects()) {\n return this;\n }\n\n if (this.logic.start) {\n try {\n this.logic.start(this._snapshot, this._actorScope, {\n restored: this._restored\n });\n } catch (err) {\n this._setErrorSnapshot(err);\n this._error(err);\n return this;\n }\n }\n\n if (\n !this._restored &&\n !this._deferred?.length &&\n !this.observers?.size &&\n !(this.system._hasInspectionObservers?.() ?? true)\n ) {\n // Starting changes the registered system view associated with the\n // snapshot, even when there is nothing to publish or execute.\n if (!refreshSnapshotActorRefRoot(this._snapshot, this, this.system)) {\n this._setSnapshot(this._snapshot);\n }\n this._collectedMicrosteps = undefined;\n this._collectedActions = undefined;\n this._collectedSent = undefined;\n } else {\n this.update(\n this._snapshot,\n createInitEvent(this.options.input) as unknown as EventFromLogic<TLogic>\n );\n }\n\n if (this._restored) {\n type RestoredTimer = { id: string; delay: number; startedAt?: number };\n const timers =\n (\n this._snapshot as unknown as {\n timers?: Record<string, RestoredTimer>;\n }\n ).timers ?? {};\n // startedAt is only persisted from — and only meaningful under — the\n // wall clock; a custom clock (a simulated clock, a monotonic counter)\n // restores every timer with its declared delay. The clamp bounds\n // remaining time by the declared delay in case the wall clock moved\n // backwards between persist and restore.\n const wallClock = !this.system._clock.now;\n const now = Date.now();\n for (const timer of Object.values(timers)) {\n // A timer persisted from a live runtime carries its wall-clock start;\n // honor the absolute deadline instead of restarting the full delay.\n // Without a start (a pure-transition snapshot, or an older snapshot)\n // the declared delay is all there is.\n const delay =\n wallClock && timer.startedAt !== undefined\n ? Math.min(\n timer.delay,\n Math.max(0, timer.startedAt + timer.delay - now)\n )\n : timer.delay;\n this.system.scheduleTimer(this, timer.id, delay);\n }\n this._restored = false;\n }\n\n this._mailboxStarted = true;\n this.mailbox?.start();\n\n return this;\n }\n\n private _process(event: EventFromLogic<TLogic>) {\n let nextState: ActorLogicTransitionResult<SnapshotFrom<TLogic>> | undefined;\n let caughtError;\n try {\n nextState = finalizeTransitionResult(\n this._actorScope,\n this._snapshot,\n this.logic.transition(this._snapshot, event, this._actorScope)\n );\n } catch (err) {\n // we wrap it in a box so we can rethrow it later even if falsy value gets caught here\n caughtError = { err };\n }\n\n if (caughtError) {\n this._collectedMicrosteps = undefined;\n this._collectedActions = undefined;\n this._collectedSent = undefined;\n if (!this._recoverOrError(caughtError.err)) {\n this._inspectTransition(this._snapshot, event);\n }\n return;\n }\n if (!nextState) {\n return;\n }\n\n let snapshot = this._snapshot;\n try {\n const [nextSnapshot, effects] = nextState;\n snapshot = nextSnapshot;\n this._setSnapshot(snapshot);\n executeExecutableEffects(effects, this._actorScope);\n this.update(snapshot, event);\n } catch (err) {\n if (!this._recoverOrError(err, snapshot)) {\n this._inspectTransition(this._snapshot, event);\n }\n return;\n }\n\n if (event.type === XSTATE_STOP) {\n this._stopProcedure();\n this._complete();\n }\n }\n\n /** @internal */\n public _emit(event: EmittedFrom<TLogic>): void {\n for (const listeners of [\n this.eventListeners?.get(event.type),\n this.eventListeners?.get('*')\n ]) {\n if (listeners) {\n for (const handler of listeners) {\n safeCall(handler, event);\n }\n }\n }\n }\n\n /** @internal */\n public _terminate(termination: ActorTermination): void {\n if (termination.status === 'done') {\n // The terminal snapshot is published before observer completion and the\n // parent notification, matching actor lifecycle order.\n this._next(this._snapshot);\n this._stopProcedure();\n this._complete();\n if (this._parent) {\n this.system._relay(\n this,\n this._parent,\n createDoneActorEvent(this.id, termination.output, this.sessionId)\n );\n }\n return;\n }\n if (termination.status === 'error') {\n this._error(termination.error);\n }\n }\n\n /** @internal */\n public _stop(): this {\n if (this._processingStatus === ProcessingStatus.Stopped) {\n return this;\n }\n this.mailbox?.clear();\n if (this._processingStatus === ProcessingStatus.NotStarted) {\n this._processingStatus = ProcessingStatus.Stopped;\n this.system._unregister(this);\n return this;\n }\n this._send({ type: XSTATE_STOP } as EventFromLogic<TLogic>);\n this.system._unregister(this);\n\n return this;\n }\n\n /** Stops the Actor and unsubscribe all listeners. */\n public stop(): this {\n if (this._parent) {\n throw new Error('A non-root actor cannot be stopped directly.');\n }\n return this._stop();\n }\n private _complete(): void {\n for (const observer of this.observers ?? emptyInspectionRecords) {\n safeCall(observer.complete);\n }\n this.observers?.clear();\n this.eventListeners?.clear();\n }\n\n private _error(err: unknown): void {\n this._stopProcedure();\n if (!this.observers?.size) {\n if (!this._parent) {\n reportUnhandledError(err);\n }\n } else {\n let reportError = false;\n\n for (const observer of this.observers) {\n const errorListener = observer.error;\n reportError ||= !errorListener;\n safeCall(errorListener, err);\n }\n this.observers.clear();\n if (reportError) {\n reportUnhandledError(err);\n }\n }\n this.eventListeners?.clear();\n\n if (this._parent) {\n this.system._relay(\n this,\n this._parent,\n createErrorActorEvent(this.id, err, this.sessionId)\n );\n }\n }\n // TODO: atm children don't belong entirely to the actor so\n // in a way - it's not even super aware of them\n // so we can't stop them from here but we really should!\n // right now, they are being stopped within the machine's transition\n // but that could throw and leave us with \"orphaned\" active actors\n private _stopProcedure(): void {\n if (this._processingStatus !== ProcessingStatus.Running) {\n // Actor already stopped; do nothing\n return;\n }\n\n // Cancel all delayed events\n this.system.cancelAllTimers(this);\n\n // TODO: mailbox.reset\n this.mailbox?.clear();\n this.mailbox = undefined;\n this._boundProcess = undefined;\n this._mailboxStarted = false;\n\n this._processingStatus = ProcessingStatus.Stopped;\n this.system._unregister(this);\n }\n\n /** @internal */\n public _send(event: EventFromLogic<TLogic>) {\n if (this._processingStatus === ProcessingStatus.Stopped) {\n this.system.deadLetter(\n this._lastSourceRef,\n this as AnyActor,\n event,\n 'stopped'\n );\n return;\n }\n\n let mailbox = this.mailbox;\n if (!mailbox) {\n this._boundProcess ??= this._process.bind(this);\n mailbox = this.mailbox = new Mailbox(this._boundProcess);\n if (this._mailboxStarted) {\n mailbox.start();\n }\n }\n mailbox.enqueue(event);\n }\n\n /**\n * Sends an event to the running Actor to trigger a transition.\n *\n * @param event The event to send\n */\n private _sendPublic(event: SendableEventFromLogic<TLogic>) {\n if (isDevelopment && typeof event === 'string') {\n throw new Error(\n `Only event objects may be sent to actors; use .send({ type: \"${event}\" }) instead`\n );\n }\n this.system._relay(undefined, this, event);\n }\n\n /**\n * Returns the actor's serializable logical identity: its `id`, `address`,\n * and registered source key (when the actor was created from one).\n */\n public toJSON() {\n return {\n xstate$type: ACTOR_REF_TYPE,\n id: this.id,\n address: this.address,\n src: typeof this.src === 'string' ? this.src : undefined\n };\n }\n\n /**\n * Obtain the internal state of the actor, which can be persisted.\n *\n * @remarks\n * The internal state can be persisted from any actor, not only machines.\n *\n * Note that the persisted state is not the same as the snapshot from\n * {@link Actor.getSnapshot}. Persisted state represents the internal state of\n * the actor, while snapshots represent the actor's last emitted value.\n *\n * Can be restored with {@link ActorOptions.state}\n * @see https://stately.ai/docs/persistence\n */\n public getPersistedSnapshot(options?: {\n /**\n * Whether persisted machine children embed their own persisted state\n * (the co-locating runtime's whole-tree checkpoint) or are referenced by\n * logical address only, leaving each child's state with the runtime that\n * owns it. Defaults to `true`.\n */\n embedChildren?: boolean;\n }): Snapshot<unknown> & PersistedSnapshotFor<TLogic>;\n public getPersistedSnapshot(\n options?: unknown\n ): Snapshot<unknown> & PersistedSnapshotFor<TLogic> {\n return this.logic.getPersistedSnapshot(\n this._snapshot,\n options\n ) as Snapshot<unknown> & PersistedSnapshotFor<TLogic>;\n }\n\n public [symbolObservable](): InteropSubscribable<SnapshotFrom<TLogic>> {\n return this;\n }\n\n /**\n * Read an actor’s snapshot synchronously.\n *\n * @remarks\n * The snapshot is the last value the actor published, not a query of its\n * private state: the actor emits a snapshot when it transitions, and this\n * returns that cached last emission. The read is coherent within one\n * synchronous transition turn because event processing runs to completion;\n * across asynchronous boundaries it may be stale, like any observed value.\n *\n * Only co-located actors publish full snapshots. A location-transparent\n * remote handle exposes lifecycle only ({ status, output?, error? }): while\n * the handle exists among its parent's children the child is presumed\n * `active`, and its terminal result arrives as a completion event.\n *\n * Note that some actors, such as callback actors generated with\n * `createCallbackLogic`, will not emit snapshots.\n * @see {@link Actor.subscribe} to subscribe to an actor’s snapshot values.\n * @see {@link Actor.getPersistedSnapshot} to persist the internal state of an actor (which is more than just a snapshot).\n */\n public getSnapshot(): SnapshotFrom<TLogic> {\n if (isDevelopment && !this._snapshot) {\n throw new Error(\n `Snapshot can't be read while the actor initializes itself`\n );\n }\n return this._snapshot;\n }\n}\n\nexport type RequiredActorOptionsKeys<TLogic extends AnyActorLogic> =\n undefined extends InputFrom<TLogic> ? never : 'input';\n\n/**\n * Creates a new actor instance for the given actor logic with the provided\n * options, if any.\n *\n * @remarks\n * When you create an actor from actor logic via `createActor(logic)`, you\n * implicitly create an actor system where the created actor is the root actor.\n * Any actors spawned from this root actor and its descendants are part of that\n * actor system.\n * @example\n *\n * ```ts\n * import { createActor } from 'xstate';\n * import { someActorLogic } from './someActorLogic.ts';\n *\n * // Creating the actor, which implicitly creates an actor system with itself as the root actor\n * const actor = createActor(someActorLogic);\n *\n * actor.subscribe((snapshot) => {\n * console.log(snapshot);\n * });\n *\n * // Actors must be started by calling `actor.start()`, which will also start the actor system.\n * actor.start();\n *\n * // Actors can receive events\n * actor.send({ type: 'someEvent' });\n *\n * // You can stop root actors by calling `actor.stop()`, which will also stop the actor system and all actors in that system.\n * actor.stop();\n * ```\n *\n * @param logic - The actor logic to create an actor from. For a state machine\n * actor logic creator, see {@link createMachine}. Other actor logic creators\n * include {@link createCallbackLogic}, {@link createEventObservableLogic},\n * {@link createObservableLogic}, {@link createLogic}, and\n * {@link createAsyncLogic}.\n * @param options - Actor options\n */\nexport function createActor<TLogic extends AnyActorLogic>(\n logic: TLogic,\n options?: ActorOptions<TLogic> & {\n [K in RequiredActorOptionsKeys<TLogic>]: unknown;\n }\n): Actor<TLogic> {\n return new Actor(logic, options);\n}\n","const cache = new WeakMap<any, any>();\n\nexport function memo<T>(object: any, key: string, fn: () => T): T {\n let memoizedData = cache.get(object);\n\n if (!memoizedData) {\n memoizedData = { [key]: fn() };\n cache.set(object, memoizedData);\n } else if (!(key in memoizedData)) {\n memoizedData[key] = fn();\n }\n\n return memoizedData[key];\n}\n","import isDevelopment from '#is-development';\nimport { NULL_EVENT, STATE_DELIMITER } from './constants.ts';\nimport type { SetupStateSchemas } from './schema.types.ts';\nimport { createInvokeTimeoutEventId } from './eventUtils.ts';\nimport { memo } from './memo.ts';\nimport {\n evaluateCandidate,\n formatTransition,\n getCandidates,\n getEventDescriptorKey,\n getDelayedTransitions,\n matchesActorSession,\n type TransitionSelectionResults\n} from './stateUtils.ts';\nimport type {\n DelayedTransitionDefinition,\n EventObject,\n InitialTransitionDefinition,\n MachineContext,\n Mapper,\n StateNodesConfig,\n TransitionDefinition,\n TransitionDefinitionMap,\n AnyStateMachine,\n AnyStateNodeConfig,\n NonReducibleUnknown,\n EventDescriptor,\n AnyActorScope,\n AnyStateNode,\n AnyEventObject,\n AnyAction,\n AnyTransitionConfig,\n AnyTransitionDefinition,\n AnyMachineSnapshot,\n AnyInvokeDefinition\n} from './types.ts';\nimport {\n createInvokeId,\n mapValues,\n toArray,\n toTransitionConfigArray\n} from './utils.ts';\n\nconst EMPTY_OBJECT = {};\nconst CHOICE_CONFIG_KEYS = [\n 'invoke',\n 'after',\n 'on',\n 'entry',\n 'exit',\n 'always',\n 'states',\n 'initial',\n 'onDone',\n 'timeout',\n 'onTimeout',\n 'history',\n 'target',\n 'output'\n] as const;\n\ninterface StateNodeOptions<\n TContext extends MachineContext,\n TEvent extends EventObject\n> {\n _key: string;\n _parent?: StateNode<TContext, TEvent>;\n _machine: AnyStateMachine;\n}\n\nexport class StateNode<\n TContext extends MachineContext = MachineContext,\n TEvent extends EventObject = EventObject\n> {\n /**\n * The relative key of the state node, which represents its location in the\n * overall state value.\n */\n public key: string;\n /** The unique ID of the state node. */\n public id: string;\n /**\n * The type of this state node:\n *\n * - `'atomic'` - no child state nodes\n * - `'compound'` - nested child state nodes (XOR)\n * - `'parallel'` - orthogonal nested child state nodes (AND)\n * - `'history'` - history state node\n * - `'choice'` - pure routing decision state node\n * - `'final'` - final state node\n */\n public type:\n | 'atomic'\n | 'compound'\n | 'parallel'\n | 'final'\n | 'history'\n | 'choice';\n /** The string path from the root machine node to this node. */\n public path: string[];\n /** The child state nodes. */\n public states: StateNodesConfig<any, any>;\n /**\n * The type of history on this state node. Can be:\n *\n * - `'shallow'` - recalls only top-level historical state value\n * - `'deep'` - recalls historical state value at all levels\n */\n public history: false | 'shallow' | 'deep';\n /** The action(s) to be executed upon entering the state node. */\n public entry: AnyAction | undefined;\n /** The action(s) to be executed upon exiting the state node. */\n public exit: AnyAction | undefined;\n /** The parent state node. */\n public parent?: StateNode<any, any>;\n /** The root machine node. */\n public machine: AnyStateMachine;\n /**\n * The meta data associated with this state node, which will be returned in\n * State instances.\n */\n public meta?: any;\n /**\n * The output data sent with the `xstate.done.state` event if this is a final\n * state node.\n */\n public output?:\n | Mapper<MachineContext, EventObject, unknown, EventObject>\n | NonReducibleUnknown;\n\n /**\n * The order this state node appears. Corresponds to the implicit document\n * order.\n */\n public order: number = -1;\n\n public description?: string;\n\n public schemas: SetupStateSchemas | undefined;\n\n public tags: string[] = [];\n public transitions!: Map<string, AnyTransitionDefinition[]>;\n public always?: Array<AnyTransitionDefinition>;\n public invoke: Array<AnyInvokeDefinition>;\n public on!: TransitionDefinitionMap<any, any>;\n public after!: Array<DelayedTransitionDefinition<any, any>>;\n public events!: Array<EventDescriptor<any>>;\n public ownEvents!: Array<EventDescriptor<any>>;\n private _candidateCache?: Map<string, AnyTransitionDefinition[]>;\n\n constructor(\n /** The raw config used to create the machine. */\n public config: AnyStateNodeConfig,\n options: StateNodeOptions<TContext, TEvent>\n ) {\n this.parent = options._parent;\n this.key = options._key;\n this.machine = options._machine;\n this.path = this.parent ? this.parent.path.concat(this.key) : [];\n const firstStateKey = this.config.states\n ? Object.keys(this.config.states)[0]\n : undefined;\n this.id =\n this.config.id || [this.machine.id, ...this.path].join(STATE_DELIMITER);\n this.type =\n this.config.type ||\n (firstStateKey !== undefined\n ? 'compound'\n : this.config.history\n ? 'history'\n : 'atomic');\n this.description = this.config.description;\n this.schemas = this.config.schemas;\n\n validateStateNodeConfig(this);\n\n this.order = this.machine.idMap.size;\n this.machine.idMap.set(this.id, this);\n\n this.states = (\n this.config.states\n ? mapValues(\n this.config.states,\n (stateConfig: AnyStateNodeConfig, key) => {\n const stateNode = new StateNode(stateConfig, {\n _parent: this,\n _key: key,\n _machine: this.machine\n });\n return stateNode;\n }\n )\n : EMPTY_OBJECT\n ) as StateNodesConfig<TContext, TEvent>;\n\n if (this.type === 'compound' && !this.config.initial) {\n throw new Error(\n isDevelopment\n ? `No initial state specified for compound state node \"#${\n this.id\n }\". Try adding { initial: \"${firstStateKey}\" } to the state config.`\n : `No initial state specified for compound state node \"#${this.id}\".`\n );\n }\n\n // History config\n this.history =\n this.config.history === true ? 'shallow' : this.config.history || false;\n\n this.entry = this.config.entry as AnyAction | undefined;\n this.exit = this.config.exit as AnyAction | undefined;\n\n if (this.entry) {\n // @ts-expect-error _special is an internal marker not on the Action type\n this.entry._special = true;\n }\n\n if (this.exit) {\n // @ts-expect-error _special is an internal marker not on the Action type\n this.exit._special = true;\n }\n\n this.meta = this.config.meta;\n this.output =\n this.type === 'final' || !this.parent ? this.config.output : undefined;\n this.tags = toArray(config.tags).slice();\n this.invoke = toArray(this.config.invoke).map((invokeConfig, i) => {\n const { src, registryKey } = invokeConfig;\n const invokeId = createInvokeId(this.id, i);\n const resolvedId = invokeConfig.id ?? invokeId;\n // Referenced (string) actors keep their logical name so persisted\n // snapshots reference `src: 'fetchUser'` rather than a positional id;\n // only inline logic gets the synthetic source name.\n const sourceName =\n typeof src === 'string' ? src : `xstate.invoke.${invokeId}`;\n\n return {\n ...invokeConfig,\n src: sourceName,\n logic: src,\n id: resolvedId,\n registryKey\n } as AnyInvokeDefinition;\n });\n }\n\n /** @internal */\n public _initialize() {\n this.after = getDelayedTransitions(this) as any;\n this.transitions = formatTransitions(this);\n if (this.type === 'choice') {\n this.always = formatChoiceTransitions(this);\n } else if (this.config.always) {\n this.always = mapTransitionConfigs(this.config.always, (transition) =>\n formatTransition(this, NULL_EVENT, transition)\n );\n }\n\n for (const key of Object.keys(this.states)) {\n this.states[key]._initialize();\n }\n\n this._refreshEventMetadata();\n }\n\n /** @internal */\n public _refreshEventMetadata() {\n const on = {} as TransitionDefinitionMap<TContext, TEvent>;\n const ownEvents: EventDescriptor<any>[] = [];\n for (const [descriptor, transitions] of this.transitions) {\n (on as any)[descriptor] = transitions.slice();\n if (\n transitions.some(\n (transition) =>\n transition.target || transition.reenter || transition.to\n )\n ) {\n ownEvents.push(descriptor);\n }\n }\n this.on = on;\n this.ownEvents = ownEvents;\n\n const events = new Set<EventDescriptor<any>>(ownEvents);\n for (const state of Object.values(this.states)) {\n for (const event of state.events) {\n events.add(event);\n }\n }\n this.events = Array.from(events);\n }\n\n public get initial(): InitialTransitionDefinition {\n return memo(this, 'initial', () =>\n formatInitialTransition(this, this.config.initial)\n );\n }\n\n /** @internal */\n public next(\n snapshot: AnyMachineSnapshot,\n event: AnyEventObject,\n actorScope: AnyActorScope,\n selectionResults?: TransitionSelectionResults\n ): Array<AnyTransitionDefinition> | undefined {\n const descriptorKey = getEventDescriptorKey(event);\n let candidates = this._candidateCache?.get(descriptorKey);\n if (!candidates) {\n candidates = getCandidates(this, event);\n (this._candidateCache ??= new Map()).set(descriptorKey, candidates);\n }\n\n for (const candidate of candidates) {\n const guardPassed = evaluateCandidate(\n candidate,\n event,\n snapshot,\n this,\n actorScope,\n selectionResults\n );\n\n if (guardPassed) {\n return [candidate];\n }\n }\n\n return undefined;\n }\n}\n\nfunction validateStateNodeConfig(stateNode: AnyStateNode) {\n const config = stateNode.config as any;\n\n if (\n stateNode.type === 'history' &&\n !(\n (typeof config.target === 'string' && config.target.trim().length > 0) ||\n (Array.isArray(config.target) &&\n config.target.length > 0 &&\n config.target.every(\n (target: unknown) =>\n typeof target === 'string' && target.trim().length > 0\n ))\n )\n ) {\n throw new Error(\n isDevelopment\n ? `History state \"${stateNode.id}\" must declare a non-empty \\`target\\`.`\n : `Missing history target on \"${stateNode.id}\"`\n );\n }\n\n if (stateNode.type !== 'choice') {\n if (isDevelopment && config.choice !== undefined) {\n throw new Error(\n `State \"${stateNode.id}\" has \\`choice\\`, but \\`choice\\` can only be used with \\`type: 'choice'\\`.`\n );\n }\n return;\n }\n\n if (typeof config.choice !== 'function') {\n throw new Error(\n isDevelopment\n ? `Choice state \"${stateNode.id}\" must declare a \\`choice\\` function.`\n : `Missing \\`choice\\` function on \"${stateNode.id}\"`\n );\n }\n\n if (isDevelopment) {\n for (const key of CHOICE_CONFIG_KEYS) {\n if (config[key] !== undefined) {\n throw new Error(\n `Choice state \"${stateNode.id}\" cannot declare \\`${key}\\`.`\n );\n }\n }\n }\n}\n\nfunction formatChoiceTransitions(\n stateNode: AnyStateNode\n): AnyTransitionDefinition[] {\n const choice = (stateNode.config as any).choice;\n const validateChoiceResult = (result: any): AnyTransitionConfig => {\n if (!result || result.target === undefined) {\n throw new Error(\n isDevelopment\n ? `Choice state \"${stateNode.id}\" must resolve to a target.`\n : `Choice \"${stateNode.id}\" has no target`\n );\n }\n if (isDevelopment) {\n for (const key of ['actions', 'to'] as const) {\n if (result[key] !== undefined) {\n throw new Error(\n `Choice state \"${stateNode.id}\" cannot declare \\`${key}\\` on a choice.`\n );\n }\n }\n }\n return result;\n };\n\n return [\n formatTransition(stateNode, NULL_EVENT, {\n to: (args: any) => validateChoiceResult(choice(args))\n } as AnyTransitionConfig)\n ];\n}\n\nfunction mapTransitionConfigs<T>(\n transitionsConfig: unknown,\n mapper: (transition: AnyTransitionConfig) => T\n): T[] {\n const transitionConfigs = toTransitionConfigArray(transitionsConfig as any);\n const transitions = new Array<T>(transitionConfigs.length);\n\n for (let i = 0; i < transitionConfigs.length; i++) {\n transitions[i] = mapper(transitionConfigs[i]);\n }\n\n return transitions;\n}\n\nfunction formatTransitions<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(\n stateNode: AnyStateNode\n): Map<string, TransitionDefinition<TContext, TEvent>[]> {\n const transitions = new Map<\n string,\n TransitionDefinition<TContext, AnyEventObject>[]\n >();\n const addTransitions = (\n descriptor: string,\n additions: AnyTransitionDefinition[]\n ) => {\n transitions.set(descriptor, [\n ...(transitions.get(descriptor) ?? []),\n ...additions\n ]);\n };\n if (stateNode.config.on) {\n for (const descriptor of Object.keys(stateNode.config.on)) {\n if (descriptor === NULL_EVENT) {\n throw new Error(\n isDevelopment\n ? 'Null events (\"\") cannot be specified as a transition key. Use `always: { ... }` instead.'\n : 'Null event transition key'\n );\n }\n const transitionsConfig = stateNode.config.on[descriptor];\n transitions.set(\n descriptor,\n mapTransitionConfigs(transitionsConfig, (transition) =>\n formatTransition(stateNode, descriptor, transition)\n )\n );\n }\n }\n if (stateNode.config.onDone) {\n const descriptor = 'xstate.done.state';\n addTransitions(\n descriptor,\n mapTransitionConfigs(stateNode.config.onDone, (transition) =>\n formatTransition(stateNode, descriptor, {\n ...transition,\n matches: { ...transition.matches, stateId: stateNode.id }\n })\n )\n );\n }\n if (stateNode.config.onError) {\n const descriptor = 'xstate.error.*';\n transitions.set(\n descriptor,\n mapTransitionConfigs(stateNode.config.onError, (transition) =>\n formatTransition(stateNode, descriptor, transition)\n )\n );\n }\n const createCancelInvokeTimeoutTransition = (\n descriptor: string,\n timeoutEventId: string,\n actorId: string\n ): AnyTransitionDefinition =>\n formatTransition(stateNode, descriptor, {\n matches: { actorId },\n _eventMatcher: (event: EventObject, snapshot: AnyMachineSnapshot) =>\n matchesActorSession(event, snapshot, actorId),\n to: (_args: any, enq: any) => {\n enq.cancel(timeoutEventId);\n return {};\n }\n } as AnyTransitionConfig);\n const formatInvokeCompletionTransition = (\n descriptor: string,\n transitionConfig: AnyTransitionConfig,\n timeoutEventId: string\n ): AnyTransitionDefinition => {\n const { target, to, reenter, ...rest } = transitionConfig;\n\n return formatTransition(stateNode, descriptor, {\n ...rest,\n reenter,\n to: (args: any, enq: any) => {\n if (to) {\n let didEnqueue = false;\n const trackingEnqueue = new Proxy(enq, {\n apply(target, thisArg, argArray) {\n didEnqueue = true;\n return Reflect.apply(target, thisArg, argArray);\n },\n get(target, prop, receiver) {\n const value = Reflect.get(target, prop, receiver);\n\n if (typeof value !== 'function') {\n return value;\n }\n\n return (...argArray: any[]) => {\n didEnqueue = true;\n return value.apply(target, argArray);\n };\n }\n });\n const result = to(args, trackingEnqueue);\n\n if (result !== undefined || didEnqueue) {\n enq.cancel(timeoutEventId);\n }\n\n return result;\n }\n\n enq.cancel(timeoutEventId);\n return {\n target,\n reenter\n };\n }\n } as AnyTransitionConfig);\n };\n for (const invokeDef of stateNode.invoke) {\n const withInvokeMatch = (transition: AnyTransitionConfig) => ({\n ...transition,\n matches: { ...transition.matches, actorId: invokeDef.id },\n _eventMatcher: (event: EventObject, snapshot: AnyMachineSnapshot) =>\n matchesActorSession(event, snapshot, invokeDef.id)\n });\n const invokeTimeoutEventId =\n invokeDef.timeout !== undefined\n ? createInvokeTimeoutEventId(invokeDef.id)\n : undefined;\n\n if (invokeDef.onDone) {\n const descriptor = 'xstate.done.actor';\n const invokeDoneTransitions = mapTransitionConfigs(\n invokeDef.onDone,\n (rawTransition) => {\n const transition = withInvokeMatch(rawTransition);\n return invokeTimeoutEventId\n ? formatInvokeCompletionTransition(\n descriptor,\n transition,\n invokeTimeoutEventId\n )\n : formatTransition(stateNode, descriptor, transition);\n }\n );\n\n if (invokeTimeoutEventId) {\n invokeDoneTransitions.push(\n createCancelInvokeTimeoutTransition(\n descriptor,\n invokeTimeoutEventId,\n invokeDef.id\n )\n );\n }\n\n addTransitions(descriptor, invokeDoneTransitions);\n } else if (invokeTimeoutEventId) {\n const descriptor = 'xstate.done.actor';\n addTransitions(descriptor, [\n createCancelInvokeTimeoutTransition(\n descriptor,\n invokeTimeoutEventId,\n invokeDef.id\n )\n ]);\n }\n if (invokeDef.onError) {\n const descriptor = 'xstate.error.actor';\n addTransitions(\n descriptor,\n mapTransitionConfigs(invokeDef.onError, (rawTransition) => {\n const transition = withInvokeMatch(rawTransition);\n return invokeTimeoutEventId\n ? formatInvokeCompletionTransition(\n descriptor,\n transition,\n invokeTimeoutEventId\n )\n : formatTransition(stateNode, descriptor, transition);\n })\n );\n }\n if (invokeDef.onSnapshot) {\n const descriptor = 'xstate.snapshot.actor';\n addTransitions(\n descriptor,\n mapTransitionConfigs(invokeDef.onSnapshot, (transition) =>\n formatTransition(stateNode, descriptor, withInvokeMatch(transition))\n )\n );\n }\n }\n for (const delayedTransition of stateNode.after) {\n let existing = transitions.get(delayedTransition.eventType);\n if (!existing) {\n existing = [];\n transitions.set(delayedTransition.eventType, existing);\n }\n existing.push(\n delayedTransition as TransitionDefinition<TContext, AnyEventObject>\n );\n }\n return transitions as Map<string, TransitionDefinition<TContext, any>[]>;\n}\n\nfunction formatInitialTransition(\n stateNode: AnyStateNode,\n _target:\n | string\n | { target: string | string[]; input?: any; to?: (...args: any[]) => any }\n | undefined\n): InitialTransitionDefinition {\n const targetString =\n typeof _target === 'object' && _target !== null ? _target.target : _target;\n const input =\n typeof _target === 'object' && _target !== null ? _target.input : undefined;\n const to =\n typeof _target === 'object' && _target !== null ? _target.to : undefined;\n const targetStrings = Array.isArray(targetString)\n ? targetString\n : targetString\n ? [targetString]\n : [];\n const resolvedTargets = targetStrings.map((target) =>\n target.startsWith('#')\n ? stateNode.machine.getStateNodeById(target.slice(1))\n : stateNode.states[target]\n );\n if (resolvedTargets.some((target) => !target)) {\n throw new Error(\n isDevelopment\n ? `Initial state node \"${targetStrings.find((_, index) => !resolvedTargets[index])}\" not found on parent state node #${stateNode.id}`\n : `Initial state not found on \"#${stateNode.id}\"`\n );\n }\n const transition: InitialTransitionDefinition = {\n source: stateNode,\n target: resolvedTargets.length\n ? (resolvedTargets as AnyStateNode[])\n : undefined,\n input,\n to\n };\n\n return transition;\n}\n","import type {\n ActorLogicValidator,\n ActorValidationRequest\n} from './validation.types.ts';\n\nexport function assertValid(\n validator: ActorLogicValidator,\n request: ActorValidationRequest\n): void {\n const error = validator.check(request);\n if (error) {\n throw error;\n }\n}\n","import isDevelopment from '#is-development';\nimport { ACTOR_REF_TYPE, createActor } from './createActor.ts';\nimport {\n createErrorPlatformEvent,\n createInitEvent,\n createInvokeTimeoutEvent\n} from './eventUtils.ts';\nimport { XSTATE_TIMER } from './constants.ts';\nimport { parseGeneratedActorId } from './system.ts';\nimport { createRemoteActorRef } from './remoteActorRef.ts';\n\nimport { createSpawner } from './spawn.ts';\nimport {\n attachSnapshotActorRef,\n createInertActorScope,\n isInertActorScope,\n setInertActorScopeSnapshot\n} from './getNextSnapshot.ts';\nimport { withActorSelf } from './actorScope.ts';\nimport {\n createMachineSnapshot,\n cloneMachineSnapshot,\n getPersistedSnapshot,\n MachineSnapshot\n} from './State.ts';\nimport { setSnapshotActorRef } from './snapshotActorRef.ts';\nimport { StateNode } from './StateNode.ts';\nimport {\n formatRouteTransitions,\n getAllStateNodes,\n getStateNodeByPath,\n getStateNodes,\n getTransitionResult,\n hasEffect,\n initialMicrostep,\n isInFinalState,\n isStateId,\n macrostep,\n resolveStateValue,\n transitionNode,\n type TransitionSelectionResults\n} from './stateUtils.ts';\nimport {\n beginSpawnAllocation,\n createDeadLetterEffect,\n createSpawnEffect,\n resolveActionsWithContext,\n mergeActorIdCounters,\n takeSpawnAllocationCounters\n} from './transitionActions.ts';\nimport { AnyActorSystem, type DeadLetterDetail } from './system.ts';\nimport type {\n ActorLogic,\n ActorLogicTransitionResult,\n ActorScope,\n AnyActor,\n AnyActorLogic,\n AnyActorRef,\n AnyActorScope,\n AnyEventObject,\n AnyMachineSnapshot,\n AnyTransitionDefinition,\n Equals,\n EventDescriptor,\n EmittedFrom,\n EventObject,\n EventFromLogic,\n ExecutableActionObject,\n ExecutableActionObjectFromLogic,\n HistoryValue,\n InputFrom,\n IsAny,\n LogicalTimer,\n MachineContext,\n MetaObject,\n OutputFrom,\n Snapshot,\n SnapshotFrom,\n StateValue,\n StateSchema,\n SnapshotStatus,\n AnyStateNode\n} from './types.ts';\nimport {\n AnyMachineSchemas,\n DelaySourceMap,\n GuardSourceMap,\n Sources,\n Next_MachineConfig,\n MachineOptions\n} from './types.v6.ts';\nimport {\n matchesEventDescriptor,\n resolveReferencedActor,\n toStatePath\n} from './utils.ts';\nimport { assertValid } from './validation.ts';\nimport type { ActorLogicValidator } from './validation.types.ts';\nimport type { StandardSchemaV1 } from './schema.types.ts';\nimport type { PersistedMachineSnapshot } from './machineVersion.types.ts';\n\nconst STATE_IDENTIFIER = '#';\n\nfunction findEventSchema(\n schemas: Record<string, StandardSchemaV1> | undefined,\n eventType: string\n): StandardSchemaV1 | undefined {\n if (!schemas) {\n return undefined;\n }\n\n if (Object.hasOwn(schemas, eventType)) {\n return schemas[eventType];\n }\n\n const descriptor = Object.keys(schemas).find((key) =>\n matchesEventDescriptor(eventType, key)\n );\n return descriptor === undefined ? undefined : schemas[descriptor];\n}\n\nlet emptyCanActor: AnyActor | undefined;\nlet emptyCanActorScope: AnyActorScope | undefined;\n\nfunction getEmptyCanActor(): AnyActor {\n // A minimal inert actor used purely as the `self`/`parent` argument when\n // dry-running transitions for `snapshot.can(...)`. Intentionally not built\n // on `createLogic` so `can()` does not pull that machinery into bundles.\n return (emptyCanActor ??= createActor({\n transition: (snapshot: any) => [snapshot, []],\n initialTransition: () => [\n { status: 'active', output: undefined, error: undefined },\n []\n ],\n getInitialSnapshot: () => ({\n status: 'active',\n output: undefined,\n error: undefined\n }),\n getPersistedSnapshot: (snapshot: any) => snapshot\n } as any) as AnyActor);\n}\n\nfunction getEmptyCanActorScope(): AnyActorScope {\n if (emptyCanActorScope) {\n return emptyCanActorScope;\n }\n\n const actor = getEmptyCanActor();\n emptyCanActorScope = {\n self: actor,\n logger: () => {},\n id: '',\n sessionId: '',\n defer: () => {},\n system: actor.system,\n stopChild: () => {},\n emit: () => {},\n actionExecutor: () => {}\n };\n return emptyCanActorScope;\n}\n\ntype CompatibleProvidedActorSource<\n TExpected extends AnyActorLogic,\n TActual extends AnyActorLogic\n> =\n IsAny<TActual> extends true\n ? TActual\n : [OutputFrom<TActual>] extends [OutputFrom<TExpected>]\n ? [Omit<SnapshotFrom<TActual>, 'input'>] extends [\n Omit<SnapshotFrom<TExpected>, 'input'>\n ]\n ? [InputFrom<TExpected>] extends [InputFrom<TActual>]\n ? [EventFromLogic<TExpected>] extends [EventFromLogic<TActual>]\n ? [EmittedFrom<TActual>] extends [EmittedFrom<TExpected>]\n ? TActual\n : never\n : never\n : never\n : never\n : never;\n\ntype ProvidedActors<\n TExpectedActorMap extends Sources['actors'],\n TProvidedActorMap extends Partial<\n Record<keyof TExpectedActorMap & string, AnyActorLogic>\n >\n> = {\n [K in keyof TProvidedActorMap]: K extends keyof TExpectedActorMap\n ? TProvidedActorMap[K] extends AnyActorLogic\n ? CompatibleProvidedActorSource<\n TExpectedActorMap[K],\n TProvidedActorMap[K]\n >\n : never\n : never;\n};\n\nexport class StateMachine<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TStateValue extends StateValue,\n TTag extends string,\n TInput,\n TOutput,\n TEmitted extends EventObject,\n TMeta extends MetaObject,\n TConfig extends StateSchema,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays'],\n TInternalEvent extends EventObject = never\n> implements ActorLogic<\n MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n TEvent,\n TInput,\n AnyActorSystem,\n TEmitted\n> {\n /**\n * @internal Type-only marker for the actor's internal event protocol. Not\n * `declare` (the build's babel pipeline rejects declare class fields); the\n * one `undefined` property this emits per machine instance is inert.\n */\n readonly _internalEventType!: TInternalEvent;\n\n /** The machine's own version. */\n public version?: string;\n\n public schemas: AnyMachineSchemas | undefined;\n\n /** Standard Schema for snapshots persisted by this machine version. */\n public readonly snapshotSchema: StandardSchemaV1<\n unknown,\n Snapshot<unknown> & PersistedMachineSnapshot & { context: TContext }\n >;\n\n /** Standard Schema for complete events accepted by this machine version. */\n public readonly eventSchema: StandardSchemaV1<unknown, TEvent>;\n\n public sources: Sources;\n\n /** Runtime options for machine execution. */\n public options: MachineOptions;\n\n /** @internal */\n public idMap: Map<string, AnyStateNode> = new Map();\n\n public root: StateNode<TContext, TEvent>;\n\n public id: string;\n\n public states: StateNode<TContext, TEvent>['states'];\n public events: Array<EventDescriptor<TEvent>>;\n public internalEventDescriptors: ReadonlyArray<string>;\n /** @internal Skips eventless-selection scans for machines without `always`. */\n public _hasEventlessTransitions: boolean;\n constructor(\n /** The raw config used to create the machine. */\n public config: Next_MachineConfig<\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any // TEmitted\n > & {\n schemas?: AnyMachineSchemas;\n internalEvents?: readonly string[];\n },\n sources?: Sources,\n public validator?: ActorLogicValidator\n ) {\n this.id = config.id || '(machine)';\n this.sources = {\n actors: config.actors ?? {},\n actions: config.actions ?? {},\n delays: (config.delays ?? {}) as Sources['delays'],\n guards: config.guards ?? {},\n ...sources\n };\n if (isDevelopment) {\n // The `@xstate.` prefix is reserved for built-in serialized action and\n // guard descriptors — user source names must not collide.\n for (const kind of ['actions', 'guards', 'actors', 'delays'] as const) {\n for (const key of Object.keys(this.sources[kind])) {\n if (key.startsWith('@xstate.')) {\n throw new Error(\n `Invalid ${kind} name '${key}': the '@xstate.' prefix is reserved for built-in descriptors.`\n );\n }\n }\n }\n }\n this.version = this.config.version;\n this.schemas = this.config.schemas;\n this.snapshotSchema = {\n '~standard': {\n version: 1,\n vendor: 'xstate',\n validate: async (value) => {\n if (value === null || typeof value !== 'object') {\n return { issues: [{ message: 'Expected a persisted snapshot.' }] };\n }\n const snapshot: Record<string, unknown> = {\n historyValue: {},\n timers: {},\n ...(value as Record<string, unknown>)\n };\n const contextSchema = this.schemas?.context;\n let context = snapshot.context;\n if (contextSchema) {\n const result = await contextSchema['~standard'].validate(context);\n if (result.issues) {\n return {\n issues: [\n {\n message: `Invalid context for machine '${this.id}' version '${this.version}': ${result.issues[0]?.message}`\n }\n ]\n };\n }\n context = result.value;\n }\n for (const key of ['value', 'children'] as const) {\n if (!(key in snapshot)) {\n return {\n issues: [{ message: `Persisted snapshot is missing '${key}'.` }]\n };\n }\n }\n if (\n !['active', 'done', 'error', 'stopped'].includes(\n snapshot.status as string\n )\n ) {\n return {\n issues: [{ message: 'Persisted snapshot has invalid status.' }]\n };\n }\n for (const key of ['children', 'historyValue', 'timers'] as const) {\n if (\n snapshot[key] === null ||\n typeof snapshot[key] !== 'object' ||\n Array.isArray(snapshot[key])\n ) {\n return {\n issues: [\n { message: `Persisted snapshot has invalid '${key}'.` }\n ]\n };\n }\n }\n try {\n this.resolveState({\n value: snapshot.value as StateValue,\n context\n } as any);\n } catch (error) {\n return {\n issues: [\n {\n message:\n error instanceof Error\n ? error.message\n : 'Persisted snapshot has invalid state value.'\n }\n ]\n };\n }\n return {\n value: { ...snapshot, context } as Snapshot<unknown> &\n PersistedMachineSnapshot & { context: TContext }\n };\n }\n }\n };\n this.eventSchema = {\n '~standard': {\n version: 1,\n vendor: 'xstate',\n validate: async (value) => {\n if (\n value === null ||\n typeof value !== 'object' ||\n typeof (value as EventObject).type !== 'string'\n ) {\n return { issues: [{ message: 'Expected an event object.' }] };\n }\n const event = value as EventObject;\n const eventSchemas = this.schemas?.events;\n const internalEventSchemas = this.schemas?.internalEvents;\n const isFrameworkEvent =\n event.type.startsWith('xstate.') ||\n event.type.startsWith('@xstate.');\n const schema =\n findEventSchema(internalEventSchemas, event.type) ??\n findEventSchema(eventSchemas, event.type);\n if (\n (eventSchemas || internalEventSchemas) &&\n !schema &&\n !isFrameworkEvent\n ) {\n return {\n issues: [\n {\n message: `Unknown event '${event.type}' for machine '${this.id}' version '${this.version}'.`\n }\n ]\n };\n }\n if (!schema) {\n return { value: event as TEvent };\n }\n const { type, ...payload } = event;\n const result = await schema['~standard'].validate(payload);\n if (result.issues) {\n return result;\n }\n if (result.value === null || typeof result.value !== 'object') {\n return { issues: [{ message: 'Expected an event payload.' }] };\n }\n return { value: { ...result.value, type } as TEvent };\n }\n }\n };\n this.internalEventDescriptors = [\n ...Object.keys(this.schemas?.internalEvents ?? {}),\n ...(this.config.internalEvents ?? [])\n ];\n this.options = {\n maxIterations: Infinity,\n ...this.config.options\n };\n\n this.transition = this.transition.bind(this);\n this.initialTransition = this.initialTransition.bind(this);\n this.getInitialSnapshot = this.getInitialSnapshot.bind(this);\n this.getPersistedSnapshot = this.getPersistedSnapshot.bind(this);\n this.restoreSnapshot = this.restoreSnapshot.bind(this);\n this.start = this.start.bind(this);\n\n this.root = new StateNode(config as any, {\n _key: this.id,\n _machine: this as any\n });\n\n this.root._initialize();\n formatRouteTransitions(this.root);\n this.root._refreshEventMetadata();\n this._hasEventlessTransitions = Array.from(this.idMap.values()).some(\n (stateNode) => !!stateNode.always?.length\n );\n\n this.states = this.root.states; // TODO: remove!\n this.events = this.root.events;\n }\n\n /**\n * Clones this state machine with the provided sources.\n *\n * @param sources Options (`actions`, `guards`, `actors`, `delays`) to\n * recursively merge with the existing options.\n * @returns A new `StateMachine` instance with the provided sources.\n */\n public provide<\n const TProvidedActorMap extends Partial<\n Record<keyof TActorMap & string, AnyActorLogic>\n > = {}\n >(sources: {\n actions?: Partial<TActionMap>;\n actors?: TProvidedActorMap & ProvidedActors<TActorMap, TProvidedActorMap>;\n // Mapped over the known names (not an index signature) so unknown source\n // names are still rejected, while entries keep typed args/return values.\n guards?: Partial<TGuardMap> & {\n [K in keyof TGuardMap]?: GuardSourceMap<TContext, TEvent>[string];\n };\n // Delays are widened to `number | fn` per entry (not Partial<TDelayMap>)\n // so a fixed delay can be swapped for a computed one and vice versa.\n delays?: {\n [K in keyof TDelayMap]?: DelaySourceMap<TContext, TEvent>[string];\n };\n }): this {\n const { actions, guards, actors, delays } = this.sources;\n\n const provided = new StateMachine(\n this.config,\n {\n actions: {\n ...actions,\n ...sources.actions\n } as Sources['actions'],\n guards: {\n ...guards,\n ...sources.guards\n } as Sources['guards'],\n actors: {\n ...actors,\n ...sources.actors\n } as Sources['actors'],\n delays: {\n ...delays,\n ...sources.delays\n } as Sources['delays']\n },\n this.validator\n ) as unknown as this;\n // Providing sources does not change the serializable definition.\n provided._json = this._json;\n return provided;\n }\n\n public resolveState(\n config: {\n value: StateValue;\n context?: TContext;\n historyValue?: HistoryValue;\n status?: SnapshotStatus;\n output?: TOutput;\n error?: unknown;\n } & ([TContext] extends [never]\n ? {}\n : Equals<TContext, MachineContext> extends false\n ? { context: unknown }\n : {})\n ): MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n > {\n const resolvedStateValue = resolveStateValue(this.root, config.value);\n const nodeSet = getAllStateNodes(\n getStateNodes(this.root, resolvedStateValue)\n );\n const nodes = [...nodeSet];\n\n return createMachineSnapshot(\n {\n _nodes: nodes,\n value: resolvedStateValue,\n context: config.context || ({} as TContext),\n children: {},\n status: isInFinalState(nodeSet, this.root)\n ? 'done'\n : config.status || 'active',\n output: config.output,\n error: config.error,\n historyValue: config.historyValue\n },\n this\n ) as MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >;\n }\n\n /**\n * Determines the next snapshot given the current `snapshot` and received\n * `event`. Calculates a full macrostep from all microsteps.\n *\n * @param snapshot The current snapshot\n * @param event The received event\n */\n public transition(\n snapshot: MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n event: TEvent,\n actorScope?: ActorScope<typeof snapshot, TEvent, AnyActorSystem, TEmitted>\n ): ActorLogicTransitionResult<\n MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n ExecutableActionObjectFromLogic<this>\n > {\n const usesInertScope = !actorScope;\n const resolvedActorScope = (actorScope ??\n createInertActorScope(\n this,\n snapshot as SnapshotFrom<this>\n )) as NonNullable<typeof actorScope>;\n if (usesInertScope) {\n setInertActorScopeSnapshot(resolvedActorScope, snapshot, false);\n }\n if (this.validator) {\n const sourceRef = actorScope && (actorScope.self as any)._lastSourceRef;\n const eventOrigin = sourceRef ? 'actor' : 'external';\n const error = this.validator.check({\n kind: 'event',\n logic: this,\n event,\n eventOrigin\n });\n if (error) {\n // Boundary fault: an invalid event arriving from outside the machine\n // is rejected (never delivered), not routed to the error channel. The\n // snapshot is returned unchanged; the rejection is represented as an\n // effect so hosts and the actor runtime can report it.\n return [\n snapshot,\n [\n createDeadLetterEffect(\n resolvedActorScope,\n sourceRef,\n event,\n 'invalidEvent',\n {\n issues: (error as { issues?: DeadLetterDetail['issues'] })\n .issues,\n error\n }\n ) as ExecutableActionObjectFromLogic<this>\n ]\n ];\n }\n }\n beginSpawnAllocation(resolvedActorScope);\n const fastSnapshot = this._transitionFast(\n snapshot,\n event,\n resolvedActorScope\n );\n if (fastSnapshot) {\n if (usesInertScope) {\n setInertActorScopeSnapshot(resolvedActorScope, fastSnapshot, false);\n }\n const returnedSnapshot =\n usesInertScope && fastSnapshot !== snapshot\n ? attachSnapshotActorRef(resolvedActorScope, fastSnapshot)\n : this._attachPureActorRef(fastSnapshot, resolvedActorScope);\n if (this.validator) {\n assertValid(this.validator, {\n kind: 'result',\n logic: this,\n snapshot: returnedSnapshot,\n effects: []\n });\n }\n return [returnedSnapshot, []];\n }\n\n const { snapshot: nextSnapshot, microsteps } = macrostep(\n snapshot,\n event,\n resolvedActorScope,\n []\n );\n\n if (usesInertScope) {\n setInertActorScopeSnapshot(resolvedActorScope, nextSnapshot, false);\n }\n const returnedSnapshot = usesInertScope\n ? nextSnapshot === snapshot\n ? nextSnapshot\n : attachSnapshotActorRef(resolvedActorScope, nextSnapshot)\n : this._attachPureActorRef(nextSnapshot, resolvedActorScope);\n const effects = this._collectEffects(microsteps);\n if (this.validator) {\n assertValid(this.validator, {\n kind: 'result',\n logic: this,\n snapshot: returnedSnapshot,\n effects\n });\n }\n return [\n returnedSnapshot as MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n effects\n ];\n }\n\n private _collectEffects(\n microsteps: ReadonlyArray<\n readonly [unknown, ReadonlyArray<ExecutableActionObject>]\n >\n ): ExecutableActionObjectFromLogic<this>[] {\n return microsteps.flatMap(\n ([, actions]) => actions\n ) as ExecutableActionObjectFromLogic<this>[];\n }\n\n private _attachPureActorRef<TSnapshot extends AnyMachineSnapshot>(\n snapshot: TSnapshot,\n actorScope: AnyActorScope,\n skipInitializingActor = false\n ): TSnapshot {\n if (isInertActorScope(actorScope)) {\n return snapshot;\n }\n if (\n skipInitializingActor &&\n (\n actorScope.self as AnyActor & {\n _actorScope?: AnyActorScope;\n _snapshot?: unknown;\n }\n )._actorScope === actorScope &&\n (actorScope.self as AnyActor & { _snapshot?: unknown })._snapshot ===\n undefined\n ) {\n return snapshot;\n }\n setSnapshotActorRef(snapshot, actorScope.self, actorScope.system);\n return snapshot;\n }\n\n private _transitionFast(\n snapshot: MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n event: TEvent,\n actorScope: ActorScope<typeof snapshot, TEvent, AnyActorSystem, TEmitted>\n ):\n | MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >\n | undefined {\n if (\n snapshot.status !== 'active' ||\n typeof snapshot.value !== 'string' ||\n this.root.always?.length\n ) {\n return undefined;\n }\n\n const sourceNode = this.root.states[snapshot.value];\n if (\n !sourceNode ||\n sourceNode.type !== 'atomic' ||\n sourceNode.exit ||\n sourceNode.invoke.length ||\n sourceNode.always?.length ||\n sourceNode.after?.length\n ) {\n return undefined;\n }\n\n const transitions = sourceNode.transitions.get(event.type);\n if (transitions?.length !== 1) {\n return undefined;\n }\n\n const selected = transitions[0];\n if (\n selected.guard ||\n selected.actions ||\n selected.to ||\n selected.reenter ||\n selected.input ||\n typeof selected.context === 'function' ||\n (selected.target && selected.target.length !== 1)\n ) {\n return undefined;\n }\n\n const targetNode = selected.target?.[0] ?? sourceNode;\n const stateChanged = targetNode !== sourceNode;\n if (\n targetNode.parent !== this.root ||\n targetNode.type !== 'atomic' ||\n (stateChanged &&\n (targetNode.entry ||\n targetNode.invoke.length ||\n targetNode.always?.length ||\n targetNode.after?.length))\n ) {\n return undefined;\n }\n\n const context =\n selected.context !== undefined\n ? ({ ...snapshot.context, ...selected.context } as TContext)\n : snapshot.context;\n\n if (\n !isInertActorScope(actorScope) &&\n (actorScope.system._hasInspectionObservers?.() ?? true)\n ) {\n const collectedMicrosteps =\n ((actorScope.self as any)._collectedMicrosteps as any[]) || [];\n collectedMicrosteps.push(selected);\n (actorScope.self as any)._collectedMicrosteps = collectedMicrosteps;\n }\n\n return cloneMachineSnapshot(snapshot, {\n ...(context !== snapshot.context ? { context } : {}),\n ...(stateChanged ? { _nodes: [this.root, targetNode] } : {})\n });\n }\n\n /**\n * Determines the next state given the current `state` and `event`. Calculates\n * a microstep.\n *\n * @param state The current state\n * @param event The received event\n */\n public microstep(\n snapshot: MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n event: TEvent,\n actorScope: AnyActorScope\n ): Array<\n MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >\n > {\n const { microsteps } = macrostep(snapshot, event, actorScope, []);\n const snapshots = new Array(microsteps.length);\n\n for (let i = 0; i < microsteps.length; i++) {\n snapshots[i] = microsteps[i][0];\n }\n\n return snapshots;\n }\n\n public getTransitionData(\n snapshot: MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n event: TEvent,\n actorScope: AnyActorScope,\n selectionResults?: TransitionSelectionResults\n ): Array<AnyTransitionDefinition> {\n return (\n transitionNode(\n this.root,\n snapshot.value,\n snapshot,\n event,\n actorScope,\n selectionResults\n ) || []\n );\n }\n\n public isInternalEventType(eventType: string): boolean {\n if (eventType === XSTATE_TIMER) {\n return true;\n }\n for (const descriptor of this.internalEventDescriptors) {\n if (matchesEventDescriptor(eventType, descriptor)) {\n return true;\n }\n }\n\n return false;\n }\n\n /**\n * Determines whether sending the `event` to the given snapshot would select a\n * non-forbidden transition. Backs `snapshot.can(...)`; lives here so that\n * non-machine bundles don't pay for the transition-resolution machinery.\n *\n * @internal\n */\n public _canTransition(snapshot: AnyMachineSnapshot, event: TEvent): boolean {\n const emptyActorScope = getEmptyCanActorScope();\n const transitionData = this.getTransitionData(\n snapshot as any,\n event,\n emptyActorScope\n );\n\n if (!transitionData?.length) {\n return false;\n }\n\n // Check that at least one transition is not forbidden\n for (const transition of transitionData) {\n if (transition.target !== undefined) {\n return true;\n }\n\n const res = getTransitionResult(\n transition,\n snapshot,\n event,\n emptyActorScope,\n { resolveActions: false }\n );\n if (\n res.targets?.length ||\n res.context ||\n hasEffect(\n transition,\n snapshot.context,\n event,\n snapshot,\n emptyActorScope\n )\n ) {\n return true;\n }\n }\n\n return false;\n }\n\n /**\n * Returns the error event that the actor should transition with to recover\n * from an execution error, if any active state node declares `onError`.\n *\n * @internal\n */\n public getExecutionErrorEvent(\n snapshot: MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n error: unknown\n ): TEvent | undefined {\n if (\n (snapshot as any)?.status !== 'active' ||\n !snapshot.nodes?.some((stateNode) => stateNode.config.onError)\n ) {\n return undefined;\n }\n return createErrorPlatformEvent('execution', error) as unknown as TEvent;\n }\n\n /**\n * The initial state _before_ evaluating any microsteps. This \"pre-initial\"\n * state is provided to initial actions executed in the initial state.\n *\n * @internal\n */\n _getPreInitialState(\n actorScope: AnyActorScope,\n initEvent: any\n ): MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n > {\n const { context } = this.config;\n\n const preInitial = createMachineSnapshot(\n {\n context:\n typeof context !== 'function' && context ? context : ({} as TContext),\n _nodes: [this.root],\n children: {},\n status: 'active'\n },\n this\n );\n\n if (typeof context === 'function') {\n const children = {};\n const spawn = createSpawner(actorScope, this.sources.actors, children);\n const resolvedContext = context(\n withActorSelf(\n {\n spawn,\n input: initEvent.input,\n actors: this.sources.actors\n },\n actorScope\n )\n );\n const [nextState] = resolveActionsWithContext(\n preInitial,\n initEvent,\n actorScope,\n []\n ) as any;\n if (resolvedContext) {\n nextState.context = resolvedContext;\n }\n if (Object.keys(children).length > 0) {\n nextState.children = {\n ...nextState.children,\n ...children\n };\n // Commit the transaction counters so context-factory allocations\n // persist with the snapshot: a freed id is never handed out again\n // after a restore or in a fresh replay process. (The spawner already\n // registered each child for string-id resolution.)\n const counters = takeSpawnAllocationCounters(actorScope);\n if (counters) {\n nextState._nextActorIds = mergeActorIdCounters(\n nextState._nextActorIds,\n counters\n );\n }\n }\n return nextState as SnapshotFrom<this>;\n }\n\n return preInitial as SnapshotFrom<this>;\n }\n\n /**\n * Returns the initial `State` instance, with reference to `self` as an\n * `ActorRef`.\n */\n public getInitialSnapshot(\n actorScope?: ActorScope<\n MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n TEvent,\n AnyActorSystem,\n TEmitted\n >,\n input?: TInput\n ): MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n > {\n return this.initialTransition(input, actorScope)[0];\n }\n\n public initialTransition(\n input: TInput | undefined,\n actorScope?: ActorScope<\n MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n TEvent,\n AnyActorSystem,\n TEmitted\n >\n ): ActorLogicTransitionResult<\n MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n ExecutableActionObjectFromLogic<this>\n > {\n if (this.validator) {\n assertValid(this.validator, {\n kind: 'input',\n logic: this,\n input\n });\n }\n const usesInertScope = !actorScope;\n const resolvedActorScope = (actorScope ??\n createInertActorScope(this)) as NonNullable<typeof actorScope>;\n beginSpawnAllocation(resolvedActorScope);\n const initEvent = createInitEvent(input) as unknown as TEvent; // TODO: fix;\n const internalQueue: AnyEventObject[] = [];\n const preInitialState = this._getPreInitialState(\n resolvedActorScope,\n initEvent\n );\n const contextSpawnEffects = Object.values(preInitialState.children)\n .filter(Boolean)\n .map((actor) => createSpawnEffect(actor as AnyActor));\n const finalizeInitialResult = (\n macroState: AnyMachineSnapshot,\n microsteps: ReadonlyArray<\n readonly [unknown, ReadonlyArray<ExecutableActionObject>]\n >\n ): ActorLogicTransitionResult<\n SnapshotFrom<this>,\n ExecutableActionObjectFromLogic<this>\n > => {\n if (usesInertScope) {\n setInertActorScopeSnapshot(resolvedActorScope, macroState, false);\n }\n const returnedSnapshot = usesInertScope\n ? attachSnapshotActorRef(resolvedActorScope, macroState)\n : this._attachPureActorRef(macroState, resolvedActorScope, true);\n const effects = this._collectEffects(microsteps);\n if (this.validator) {\n assertValid(this.validator, {\n kind: 'result',\n logic: this,\n snapshot: returnedSnapshot,\n effects\n });\n }\n return [returnedSnapshot as SnapshotFrom<this>, effects];\n };\n\n try {\n const [nextState, initialActions] = initialMicrostep(\n this.root,\n preInitialState,\n resolvedActorScope,\n initEvent,\n internalQueue\n );\n\n const { snapshot: macroState, microsteps } = macrostep(\n nextState,\n initEvent as AnyEventObject,\n resolvedActorScope,\n internalQueue,\n [\n [nextState, [...contextSpawnEffects, ...initialActions]] as [\n AnyMachineSnapshot,\n ExecutableActionObject[]\n ]\n ]\n );\n return finalizeInitialResult(macroState, microsteps);\n } catch (err) {\n if (!this.root.config.onError) {\n throw err;\n }\n const errorEvent = createErrorPlatformEvent('execution', err);\n const errorMacrostep = macrostep(\n preInitialState,\n errorEvent,\n resolvedActorScope,\n [],\n [\n [preInitialState, contextSpawnEffects] as [\n AnyMachineSnapshot,\n ExecutableActionObject[]\n ]\n ]\n );\n return finalizeInitialResult(\n errorMacrostep.snapshot,\n errorMacrostep.microsteps\n );\n }\n }\n\n public start(\n snapshot?: MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >\n ): void {\n // Start rehydrated children that were active when persisted. Freshly\n // invoked/spawned children are NOT started here — they start via deferred\n // `@xstate.start` actions so sync start errors route to `onError`.\n if (!snapshot?.children) {\n return;\n }\n const children = snapshot.children as unknown as Record<string, AnyActor>;\n for (const childId in children) {\n if (!Object.hasOwn(children, childId)) {\n continue;\n }\n const child = children[childId];\n if (\n (child as any)._rehydrated &&\n (child as any).getSnapshot?.().status === 'active'\n ) {\n (child as any).start();\n }\n }\n }\n\n public getStateNodeById(stateId: string): StateNode<TContext, TEvent> {\n const fullPath = toStatePath(stateId);\n const relativePath = fullPath.slice(1);\n const resolvedStateId = isStateId(fullPath[0])\n ? fullPath[0].slice(STATE_IDENTIFIER.length)\n : fullPath[0];\n\n const stateNode = this.idMap.get(resolvedStateId);\n if (!stateNode) {\n throw new Error(\n `Child state node '#${resolvedStateId}' does not exist on machine '${this.id}'`\n );\n }\n return getStateNodeByPath(stateNode, relativePath) as StateNode<\n TContext,\n TEvent\n >;\n }\n\n public getPersistedSnapshot(\n snapshot: MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n options?: unknown\n ) {\n return getPersistedSnapshot(snapshot, options);\n }\n\n /**\n * The original JSON definition this machine was created from (set by\n * `createMachineFromConfig`), if any. Used by `serializeMachine` for lossless\n * round-trips.\n *\n * @internal\n */\n public _json?: Record<string, unknown>;\n\n public restoreSnapshot(\n snapshot: Snapshot<unknown>,\n actorScope?: ActorScope<\n MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >,\n TEvent,\n AnyActorSystem,\n TEmitted\n >\n ): MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n > {\n const usesInertScope = !actorScope;\n const resolvedActorScope = (actorScope ??\n createInertActorScope(this)) as NonNullable<typeof actorScope>;\n const snapshotMachine = (snapshot as any).machine;\n // A live machine snapshot carries its producing machine so helpers such as\n // `matches()` can resolve state nodes. That runtime association is not the\n // persisted `{ id, version }` identity written by getPersistedSnapshot().\n const persistedMachine =\n snapshotMachine &&\n typeof snapshotMachine === 'object' &&\n typeof snapshotMachine.transition === 'function' &&\n 'root' in snapshotMachine\n ? undefined\n : snapshotMachine;\n const legacyPersistedVersion: string | undefined = (snapshot as any)\n .version;\n const persistedVersion: string | undefined =\n typeof persistedMachine?.version === 'string'\n ? persistedMachine.version\n : legacyPersistedVersion;\n if (\n legacyPersistedVersion !== undefined &&\n persistedMachine?.version !== undefined &&\n persistedMachine.version !== legacyPersistedVersion\n ) {\n throw new Error(\n `Persisted snapshot version '${legacyPersistedVersion}' conflicts with machine version '${persistedMachine.version}'.`\n );\n }\n if (\n persistedMachine &&\n typeof persistedMachine.id === 'string' &&\n persistedMachine.id !== this.id\n ) {\n throw new Error(\n isDevelopment\n ? `Machine ID mismatch: persisted snapshot was created by machine '${persistedMachine.id}', but machine '${this.id}' was provided.`\n : `Machine ID mismatch: persisted snapshot machine '${persistedMachine.id}' does not match '${this.id}'.`\n );\n }\n if (persistedVersion !== this.version) {\n const migrate = (this.config as any).migrate;\n if (typeof migrate !== 'function') {\n throw new Error(\n isDevelopment\n ? `Persisted snapshot version '${persistedVersion}' does not match machine version '${this.version}' for machine '${this.id}'. Provide a \\`migrate(persistedSnapshot, fromVersion)\\` function in the machine config to migrate old snapshots.`\n : `Persisted snapshot version '${persistedVersion}' does not match machine version '${this.version}'.`\n );\n }\n snapshot = migrate(snapshot, persistedVersion);\n }\n\n const snapshotData = snapshot as any;\n const children: Record<string, AnyActor> = {};\n const snapshotChildren: Record<\n string,\n {\n src: string | AnyActorLogic;\n snapshot?: Snapshot<unknown>;\n address?: string;\n remote?: boolean;\n incarnation?: string;\n syncSnapshot?: boolean;\n registryKey?: string;\n }\n > = snapshotData.children;\n\n for (const actorId of Object.keys(snapshotChildren)) {\n const actorData = snapshotChildren[actorId];\n\n if (actorData.remote === true && actorData.address !== undefined) {\n if (typeof actorData.src !== 'string') {\n // Fail loudly instead of fabricating a source key that hosts would\n // route by.\n throw new Error(\n `Unable to restore remote child '${actorId}': a child referenced by address requires a registered source key.`\n );\n }\n // The child's state lives with another runtime; restore a\n // location-transparent handle constructed from its identity alone.\n // The handle keeps its persisted address verbatim: the owning\n // runtime's identity for the child wins over the local parent chain.\n const handle = createRemoteActorRef(resolvedActorScope.system, {\n id: actorId,\n address: actorData.address,\n src: actorData.src,\n parent: resolvedActorScope.self,\n registryKey: actorData.registryKey,\n syncSnapshot: actorData.syncSnapshot,\n incarnation: actorData.incarnation\n });\n if (actorData.registryKey) {\n resolvedActorScope.system._set(actorData.registryKey, handle);\n }\n children[actorId] = handle;\n continue;\n }\n\n const childState = actorData.snapshot;\n const src = actorData.src;\n\n const logic =\n typeof src === 'string' ? resolveReferencedActor(this, src) : src;\n\n if (!logic) {\n const sourceId = typeof src === 'string' ? src : '<unknown>';\n throw new Error(\n `Unable to restore child actor '${actorId}': child source '${sourceId}' is not provided in machine '${this.id}'.`\n );\n }\n\n const actor = resolvedActorScope.system.createActorRef(logic, {\n id: actorId,\n parent: resolvedActorScope.self,\n syncSnapshot: actorData.syncSnapshot,\n snapshot: childState,\n src,\n registryKey: actorData.registryKey\n });\n // Mark so `start()` knows to start this child (freshly invoked/spawned\n // children are started via deferred `@xstate.start` actions instead).\n (actor as any)._rehydrated = true;\n\n children[actorId] = actor;\n }\n\n const timers: Record<string, LogicalTimer> = {};\n const persistedTimers: Record<\n string,\n {\n id: string;\n delay: number;\n type: '@xstate.raise' | '@xstate.sendTo';\n event: EventObject;\n target: string | { type: 'parent' };\n }\n > = snapshotData.timers ?? {};\n for (const [id, timer] of Object.entries(persistedTimers)) {\n let event = timer.event;\n if (event.type === 'xstate.timeout.actor') {\n const actorId = (event as AnyEventObject).actorId as string;\n const child = children[actorId];\n if (child) {\n event = createInvokeTimeoutEvent(actorId, child.sessionId);\n }\n }\n const target =\n typeof timer.target === 'string'\n ? timer.target === 'self'\n ? 'self'\n : children[timer.target]\n : resolvedActorScope.self._parent;\n if (!target) {\n const targetDescription =\n typeof timer.target === 'string' ? timer.target : timer.target.type;\n throw new Error(\n `Unable to restore timer '${id}': target actor '${targetDescription}' is unavailable.`\n );\n }\n timers[id] = { ...timer, event, target };\n }\n\n const reviveHistoryValue = (\n historyValue: Record<\n string,\n ({ id: string } | StateNode<TContext, TEvent>)[]\n >\n ): HistoryValue => {\n if (!historyValue || typeof historyValue !== 'object') {\n return {};\n }\n const revived: HistoryValue = {};\n for (const key of Object.keys(historyValue)) {\n const arr = historyValue[key];\n\n for (const item of arr) {\n let resolved: StateNode<TContext, TEvent> | undefined;\n\n if (item instanceof StateNode) {\n resolved = item;\n } else {\n try {\n resolved = this.root.machine.getStateNodeById(item.id);\n } catch {\n if (isDevelopment) {\n console.warn(`Could not resolve StateNode for id: ${item.id}`);\n }\n }\n }\n\n if (!resolved) {\n continue;\n }\n\n revived[key] ??= [];\n revived[key].push(resolved);\n }\n }\n return revived;\n };\n\n const revivedHistoryValue = reviveHistoryValue(snapshotData.historyValue);\n\n const validateStateValue = (\n stateValue: StateValue,\n node: AnyStateNode,\n path: string[]\n ): void => {\n const missingStateError = (statePath: string[]) =>\n new Error(\n `Persisted snapshot references state '${statePath.join('.')}' which does not exist on machine '${this.id}'.`\n );\n if (typeof stateValue === 'string') {\n if (!node.states[stateValue]) {\n throw missingStateError(path.concat(stateValue));\n }\n return;\n }\n if (!stateValue || typeof stateValue !== 'object') {\n return;\n }\n for (const key of Object.keys(stateValue)) {\n const childNode = node.states[key];\n if (!childNode) {\n throw missingStateError(path.concat(key));\n }\n validateStateValue(stateValue[key]!, childNode, path.concat(key));\n }\n };\n validateStateValue(snapshotData.value, this.root, []);\n\n const nodes = Array.from(\n getAllStateNodes(getStateNodes(this.root, snapshotData.value))\n );\n\n const {\n version: _persistedSnapshotVersion,\n // The legacy system-wide counter: superseded by per-snapshot\n // `_nextActorIds` plus the child-id fold below; dropped so old and new\n // snapshots round-trip to the same shape.\n _nextActorId: _legacyNextActorId,\n ...persistedRest\n } = snapshot as any;\n // Fold generated-shaped child ids into the counters as a floor: snapshots\n // persisted before per-actor counters (or hand-crafted ones) still must\n // never reuse a live child's id.\n let restoredCounters: Record<string, number> | undefined =\n persistedRest._nextActorIds;\n for (const childId of Object.keys(snapshotChildren)) {\n const generated = parseGeneratedActorId(childId);\n if (\n generated &&\n (restoredCounters?.[generated.prefix] ?? 0) <= generated.index\n ) {\n restoredCounters = {\n ...restoredCounters,\n [generated.prefix]: generated.index + 1\n };\n }\n }\n const restoredSnapshot = createMachineSnapshot(\n {\n ...persistedRest,\n children,\n timers,\n _nextActorIds: restoredCounters,\n _nodes: nodes,\n value: snapshotData.value,\n historyValue: revivedHistoryValue,\n _stateInputs: snapshotData.stateInputs ?? {}\n },\n this,\n resolvedActorScope.self\n ) as MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TConfig\n >;\n\n const seen = new WeakSet<Record<string, unknown>>();\n\n function reviveContext(contextPart: Record<string, unknown>) {\n if (seen.has(contextPart)) {\n return;\n }\n seen.add(contextPart);\n for (const key of Object.keys(contextPart)) {\n const value: unknown = contextPart[key];\n\n if (value && typeof value === 'object') {\n if ('xstate$type' in value && value.xstate$type === ACTOR_REF_TYPE) {\n contextPart[key] = children[(value as any).id];\n continue;\n }\n reviveContext(value as typeof contextPart);\n }\n }\n }\n\n reviveContext(restoredSnapshot.context);\n\n if (usesInertScope) {\n setInertActorScopeSnapshot(resolvedActorScope, restoredSnapshot, false);\n return attachSnapshotActorRef(resolvedActorScope, restoredSnapshot);\n }\n\n return this._attachPureActorRef(restoredSnapshot, resolvedActorScope);\n }\n}\n","import {\n allocateChildId,\n assertChildIdFree,\n reserveChildId\n} from './transitionActions.ts';\nimport { resolveRegisteredActorSource } from './actorSource.ts';\nimport {\n ActorFromLogic,\n AnyActorLogic,\n AnyActorRef,\n AnyActorScope,\n ConditionalRequired,\n InputFrom,\n IsNotNever,\n RegistryKeyForLogic,\n SystemRegistry,\n type RequiredLogicInput\n} from './types.ts';\n\nexport type Spawner<TSystemRegistry extends SystemRegistry = SystemRegistry> = <\n TLogic extends AnyActorLogic\n>(\n src: TLogic,\n ...[options]: ConditionalRequired<\n [\n options?: {\n id?: string;\n registryKey?: RegistryKeyForLogic<TLogic, TSystemRegistry>;\n input?: InputFrom<TLogic>;\n syncSnapshot?: boolean;\n } & { [K in RequiredLogicInput<TLogic>]: unknown }\n ],\n IsNotNever<RequiredLogicInput<TLogic>>\n >\n) => ActorFromLogic<TLogic>;\n\nexport function createSpawner(\n actorScope: AnyActorScope,\n actors: Record<string, AnyActorLogic>,\n spawnedChildren: Record<string, AnyActorRef>\n): Spawner {\n return ((src, options) => {\n const referencedSrc = resolveRegisteredActorSource(actors, src);\n // Generated ids come from the same transaction allocator as `enq.spawn`,\n // so context-factory allocations persist with the snapshot and never\n // collide with later spawns.\n const id =\n options?.id ?? allocateChildId(actorScope, referencedSrc ?? src).id;\n if (options?.id !== undefined) {\n assertChildIdFree(actorScope, options.id);\n reserveChildId(actorScope, options.id);\n }\n const actor = actorScope.system.createActorRef(src, {\n id,\n parent: actorScope.self,\n syncSnapshot: options?.syncSnapshot,\n input: options?.input,\n src: referencedSrc ?? src,\n registryKey: options?.registryKey\n });\n spawnedChildren[actor.id] = actor;\n return actor;\n }) as Spawner;\n}\n","import {\n Action,\n AnyActorLogic,\n AnyActorRef,\n AnyEventObject,\n AnyStateMachine,\n EventObject,\n MachineContext,\n MetaObject\n} from '../types';\nimport { Next_StateNodeConfig } from '../types.v6';\nimport { createMachine } from '../createMachine';\nimport { parseDelayToMilliseconds } from '../delay';\n\nfunction delayToMs(delay: string | number): number {\n const parsedDelay = parseDelayToMilliseconds(delay);\n if (parsedDelay !== undefined) return parsedDelay;\n return typeof delay === 'string' ? parseFloat(delay) || 0 : delay;\n}\n\nfunction normalizeScxmlEventType(eventType: string): string {\n return /^error(\\.|$)/.test(eventType) ? `xstate.${eventType}` : eventType;\n}\n\nfunction toScxmlEventName(eventType: string): string {\n return eventType.startsWith('xstate.error.')\n ? eventType.slice('xstate.'.length)\n : eventType;\n}\n\nfunction matchesScxmlEventDescriptor(\n descriptor: string,\n event: EventObject\n): boolean {\n if (descriptor === '*') return true;\n if (descriptor.endsWith('.*')) {\n const prefix = descriptor.slice(0, -2);\n return event.type === prefix || event.type.startsWith(`${prefix}.`);\n }\n if (descriptor.startsWith('xstate.done.actor.')) {\n return (\n event.type === 'xstate.done.actor' &&\n (event as any).actorId === descriptor.slice('xstate.done.actor.'.length)\n );\n }\n if (descriptor.startsWith('xstate.done.state.')) {\n return (\n event.type === 'xstate.done.state' &&\n (event as any).stateId === descriptor.slice('xstate.done.state.'.length)\n );\n }\n return event.type === descriptor || event.type.startsWith(`${descriptor}.`);\n}\n\nexport interface RaiseJSON {\n type: '@xstate.raise';\n event: EventObject;\n id?: string;\n delay?: number;\n}\n\nexport interface CancelJSON {\n type: '@xstate.cancel';\n id: string;\n}\n\ninterface LogJSON {\n type: '@xstate.log';\n args: any[];\n}\n\nexport interface ScxmlLogJSON {\n type: 'scxml.log';\n label?: string;\n expr?: string;\n}\n\ninterface EmitJSON {\n type: '@xstate.emit';\n event: AnyEventObject;\n}\n\ninterface AssignJSON {\n type: '@xstate.assign';\n context: MachineContext;\n}\n\ninterface ScxmlAssignJSON {\n type: 'scxml.assign';\n /** SCXML location attribute - the context property to assign to */\n location: string;\n /** SCXML expr attribute - expression to evaluate */\n expr: string;\n}\n\nexport interface ScxmlRaiseJSON {\n type: 'scxml.raise';\n /** Event type, or undefined if using eventexpr */\n event?: string;\n /** Expression to evaluate for event type */\n eventexpr?: string;\n /** Params with expressions to evaluate */\n params?: Array<{ name: string; expr?: string; location?: string }>;\n namelist?: string[];\n id?: string;\n idlocation?: string;\n delay?: number;\n /** Expression for delay */\n delayexpr?: string;\n /** Static target (e.g. '#_parent') */\n target?: string;\n /** Expression for target */\n targetexpr?: string;\n processorType?: string;\n content?: ScxmlContentJSON;\n}\n\nexport interface ScxmlXmlJSON {\n name: string;\n attributes?: Record<string, string>;\n children?: ScxmlXmlJSON[];\n}\n\nexport interface ScxmlContentJSON {\n expr?: string;\n text?: string;\n xml?: ScxmlXmlJSON;\n}\n\ninterface ScxmlScriptJSON {\n type: 'scxml.script';\n /** The script code to execute */\n code: string;\n global?: boolean;\n}\n\nexport interface ScxmlForeachJSON {\n type: 'scxml.foreach';\n array: string;\n item: string;\n index?: string;\n actions: ActionJSON[];\n}\n\nexport interface ScxmlCancelJSON {\n type: 'scxml.cancel';\n sendidexpr: string;\n}\n\nexport interface ScxmlDonedataJSON {\n params?: Array<{ name: string; expr: string }>;\n contentExpr?: string;\n contentText?: string;\n}\n\nexport interface ScxmlDataJSON {\n id: string;\n expr?: string;\n content?: string;\n src?: string;\n xml?: ScxmlXmlJSON;\n}\n\n/**\n * Isolated executable-content block. Errors in nested actions stop this block\n * but do not propagate to the surrounding action list. Used to model SCXML's\n * separate <onentry>/<onexit> blocks: each is its own block per spec.\n */\ninterface ScxmlBlockJSON {\n type: 'scxml.block';\n actions: ActionJSON[];\n}\n\ninterface ScxmlDatamodelJSON {\n type: 'scxml.datamodel';\n data: ScxmlDataJSON[];\n}\n\ninterface ScxmlForwardJSON {\n type: 'scxml.forward';\n invokeId: string;\n}\n\ninterface ScxmlFinalizeJSON {\n type: 'scxml.finalize';\n invokeId: string;\n actions: ActionJSON[];\n}\n\ninterface ScxmlIfJSON {\n type: 'scxml.if';\n branches: Array<{\n cond?: string;\n actions: ActionJSON[];\n }>;\n}\n\ntype BuiltInActionJSON =\n | RaiseJSON\n | CancelJSON\n | LogJSON\n | EmitJSON\n | AssignJSON;\n\ninterface CustomActionJSON {\n type: string;\n params?: unknown;\n}\n\nexport type ActionJSON =\n | CustomActionJSON\n | RaiseJSON\n | CancelJSON\n | LogJSON\n | EmitJSON\n | AssignJSON\n | ScxmlAssignJSON\n | ScxmlRaiseJSON\n | ScxmlScriptJSON\n | ScxmlIfJSON\n | ScxmlForeachJSON\n | ScxmlCancelJSON\n | ScxmlLogJSON\n | ScxmlBlockJSON\n | ScxmlDatamodelJSON\n | ScxmlForwardJSON\n | ScxmlFinalizeJSON\n | ExpressionJSON\n | CodeJSON;\n\nexport interface GuardJSON {\n type: string;\n params?: unknown;\n}\n\ninterface ExpressionJSON {\n '@expr': string;\n '@lang'?: string;\n}\n\ninterface CodeJSON {\n '@code': string;\n '@lang'?: string;\n}\n\ntype ResolvableJSON = ExpressionJSON | CodeJSON;\n\ntype ConditionJSON = GuardJSON | ResolvableJSON;\n\ninterface ChoiceBranchJSON {\n when?: ConditionJSON;\n target: string | string[];\n context?: MachineContext;\n input?: unknown;\n description?: string;\n reenter?: boolean;\n meta?: MetaObject;\n}\n\nexport interface InvokeJSON {\n id?: string;\n registryKey?: string;\n src: string;\n input?: unknown;\n onDone?: TransitionConfigJSON | TransitionConfigJSON[];\n onError?: TransitionConfigJSON | TransitionConfigJSON[];\n onSnapshot?: TransitionConfigJSON | TransitionConfigJSON[];\n timeout?: number | string | ResolvableJSON;\n onTimeout?: TransitionConfigJSON | TransitionConfigJSON[];\n /** @internal SCXML invocation input expressions. */\n _scxmlInput?: {\n namelist?: string[];\n params?: Array<{ name: string; expr?: string; location?: string }>;\n };\n}\n\nexport interface TransitionJSON {\n target?: string | string[];\n matches?: Record<string, unknown>;\n context?: MachineContext;\n actions?: ActionJSON[];\n guard?: ConditionJSON;\n description?: string;\n reenter?: boolean;\n meta?: MetaObject;\n input?: unknown;\n /** @internal Strict semantics for transitions produced by the SCXML converter. */\n _scxml?: {\n type?: 'internal' | 'external';\n eventDescriptors?: string[];\n finalize?: Array<{ invokeId: string; actions: ActionJSON[] }>;\n };\n}\n\ntype TransitionConfigJSON = TransitionJSON | ResolvableJSON;\n\nexport interface StateNodeJSON {\n id?: string;\n key?: string;\n type?: 'atomic' | 'compound' | 'parallel' | 'final' | 'history' | 'choice';\n initial?: string;\n states?: Record<string, StateNodeJSON>;\n on?: Record<string, TransitionConfigJSON | TransitionConfigJSON[]>;\n onError?: TransitionConfigJSON | TransitionConfigJSON[];\n after?: Record<string, TransitionConfigJSON | TransitionConfigJSON[]>;\n always?: TransitionConfigJSON | TransitionConfigJSON[];\n choice?: ChoiceBranchJSON[] | ResolvableJSON;\n /**\n * JSON route config. Unlike the authoring API (a function), the JSON layer\n * allows an object form whose `guard` may be a named guard reference (string)\n * resolved against the machine's `guards` sources.\n */\n route?:\n | {\n description?: string;\n reenter?: boolean;\n meta?: MetaObject;\n guard?: string;\n input?: Record<string, unknown>;\n }\n | ResolvableJSON;\n invoke?: InvokeJSON | InvokeJSON[];\n entry?: ActionJSON | ActionJSON[];\n exit?: ActionJSON | ActionJSON[];\n meta?: MetaObject;\n description?: string;\n tags?: string[];\n input?: unknown;\n timeout?: number | string | ResolvableJSON;\n onTimeout?: TransitionConfigJSON | TransitionConfigJSON[];\n history?: 'shallow' | 'deep';\n target?: string | [string, ...string[]];\n output?: unknown;\n context?: Record<string, unknown>;\n _scxmlDonedata?: ScxmlDonedataJSON;\n /** @internal Initial transition emitted by the SCXML converter. */\n _scxmlInitial?: {\n targets: string[];\n actions?: ActionJSON[];\n };\n /** @internal Executable content on an SCXML history default transition. */\n _scxmlHistoryActions?: ActionJSON[];\n /** @internal Datamodel declarations initialized on entry. */\n _scxmlData?: ScxmlDataJSON[];\n}\nexport interface ScxmlIR extends StateNodeJSON {\n '@exprLang'?: string;\n version?: string;\n /** @internal All declared SCXML datamodel identifiers. */\n _scxmlDataIds?: string[];\n actions?: Record<string, ActionJSON | ActionJSON[]>;\n guards?: Record<string, { when: ConditionJSON }>;\n actors?: Record<string, unknown>;\n delays?: Record<\n string,\n number | string | { duration: number | string | ResolvableJSON }\n >;\n schemas?: Record<string, unknown>;\n}\n\ntype EvaluatorSlot =\n | 'context'\n | 'guard'\n | 'choice'\n | 'action'\n | 'actionParams'\n | 'transition'\n | 'input'\n | 'output'\n | 'delay'\n | 'transitionContext'\n | 'unknown';\n\ntype EvaluatorKind = 'expr' | 'code';\n\ninterface EvaluatorArgs {\n source: string;\n kind: EvaluatorKind;\n slot: EvaluatorSlot;\n scope: Record<string, unknown>;\n path: string;\n}\n\ninterface MachineSources {\n actions?: Record<string, (...args: any[]) => unknown>;\n guards?: Record<string, (...args: any[]) => boolean>;\n actors?: Record<string, AnyActorLogic>;\n delays?: Record<string, number | ((...args: any[]) => number)>;\n evaluators?: Record<string, (args: EvaluatorArgs) => unknown>;\n}\n\ntype ProvidedSources = Required<MachineSources>;\n\nfunction isExpression(value: unknown): value is ExpressionJSON {\n return (\n !!value &&\n typeof value === 'object' &&\n typeof (value as any)['@expr'] === 'string'\n );\n}\n\nfunction isCode(value: unknown): value is CodeJSON {\n return (\n !!value &&\n typeof value === 'object' &&\n typeof (value as any)['@code'] === 'string'\n );\n}\n\nfunction isResolvable(value: unknown): value is ResolvableJSON {\n return isExpression(value) || isCode(value);\n}\n\nfunction isBuiltInActionType(type: string): boolean {\n return type.startsWith('@xstate.');\n}\n\nfunction isScxmlActionType(type: string): boolean {\n return type.startsWith('scxml.');\n}\n\nfunction toPath(parent: string, key: string | number): string {\n return typeof key === 'number' ? `${parent}[${key}]` : `${parent}.${key}`;\n}\n\nfunction extractSerializableDelays(\n delays: ScxmlIR['delays'] | undefined\n): Record<string, number> {\n const result: Record<string, number> = {};\n if (!delays) {\n return result;\n }\n for (const key of Object.keys(delays)) {\n const value = delays[key];\n if (typeof value === 'number') {\n result[key] = value;\n } else if (\n value &&\n typeof value === 'object' &&\n typeof value.duration === 'number'\n ) {\n result[key] = value.duration;\n }\n }\n return result;\n}\n\nfunction mergeSources(json: ScxmlIR, sources: MachineSources): ProvidedSources {\n return {\n actions: sources.actions ?? {},\n guards: sources.guards ?? {},\n actors: sources.actors ?? {},\n delays: {\n ...extractSerializableDelays(json.delays),\n ...(sources.delays ?? {})\n },\n evaluators: sources.evaluators ?? {}\n };\n}\n\ninterface ExpressionResolver {\n evaluateResolvable: (\n value: ResolvableJSON,\n slot: EvaluatorSlot,\n scope: Record<string, unknown>,\n path: string\n ) => unknown;\n resolveValue: (\n value: unknown,\n slot: EvaluatorSlot,\n scope: Record<string, unknown>,\n path: string\n ) => unknown;\n makeScope: (\n x: any,\n extra?: Record<string, unknown>\n ) => Record<string, unknown>;\n getDurationConfig: (value: unknown, path: string) => unknown;\n assertResolvable: (value: unknown, path: string) => void;\n}\n\nfunction createExpressionResolver(\n expressionLanguage: string | undefined,\n sources: ProvidedSources\n): ExpressionResolver {\n function getEvaluator(value: ResolvableJSON, path: string) {\n const lang = value['@lang'] ?? expressionLanguage;\n if (!lang) {\n throw new Error(`Missing @exprLang for expression at ${path}`);\n }\n const evaluator = sources.evaluators[lang];\n if (!evaluator) {\n throw new Error(`Missing evaluator for @lang '${lang}' at ${path}`);\n }\n return evaluator;\n }\n\n function evaluateResolvable(\n value: ResolvableJSON,\n slot: EvaluatorSlot,\n scope: Record<string, unknown>,\n path: string\n ) {\n const kind = isExpression(value) ? 'expr' : 'code';\n const source = isExpression(value) ? value['@expr'] : value['@code'];\n return getEvaluator(\n value,\n path\n )({\n source,\n kind,\n slot,\n scope,\n path\n });\n }\n\n function resolveValue(\n value: unknown,\n slot: EvaluatorSlot,\n scope: Record<string, unknown>,\n path: string\n ): unknown {\n if (isResolvable(value)) {\n return evaluateResolvable(value, slot, scope, path);\n }\n if (Array.isArray(value)) {\n return value.map((item, index) =>\n resolveValue(item, slot, scope, toPath(path, index))\n );\n }\n if (!value || typeof value !== 'object') {\n return value;\n }\n const result: Record<string, unknown> = {};\n for (const key of Object.keys(value)) {\n result[key] = resolveValue(\n (value as Record<string, unknown>)[key],\n slot,\n scope,\n toPath(path, key)\n );\n }\n return result;\n }\n\n function makeScope(x: any, extra?: Record<string, unknown>) {\n return {\n context: x.context,\n event: x.event,\n input: x.input,\n self: x.self,\n children: x.children,\n params: x.params,\n ...extra\n };\n }\n\n function getDurationConfig(value: unknown, path: string) {\n if (!isResolvable(value)) {\n return value;\n }\n return (args: any) =>\n delayToMs(\n resolveValue(value, 'delay', makeScope(args), path) as string | number\n );\n }\n\n function assertResolvable(value: unknown, path: string) {\n if (isResolvable(value)) {\n getEvaluator(value, path);\n return;\n }\n if (Array.isArray(value)) {\n value.forEach((item, index) =>\n assertResolvable(item, toPath(path, index))\n );\n return;\n }\n if (!value || typeof value !== 'object') {\n return;\n }\n for (const key of Object.keys(value)) {\n assertResolvable(\n (value as Record<string, unknown>)[key],\n toPath(path, key)\n );\n }\n }\n\n return {\n evaluateResolvable,\n resolveValue,\n makeScope,\n getDurationConfig,\n assertResolvable\n };\n}\n\nfunction toActionArray(\n actions: ActionJSON | ActionJSON[] | undefined\n): ActionJSON[] {\n return actions === undefined\n ? []\n : Array.isArray(actions)\n ? actions\n : [actions];\n}\n\nfunction validateChoiceConfig(choice: StateNodeJSON['choice'], path: string) {\n if (!Array.isArray(choice)) {\n return;\n }\n choice.forEach((branch, index) => {\n if (branch.when === undefined && index !== choice.length - 1) {\n throw new Error(\n `Choice fallback branch at ${path}[${index}] must be last.`\n );\n }\n });\n}\n\nfunction assertMachineJSON(\n json: ScxmlIR,\n resolvedSources: ProvidedSources,\n expressionResolver: ExpressionResolver\n) {\n const { assertResolvable } = expressionResolver;\n\n function assertCondition(condition: ConditionJSON | undefined, path: string) {\n if (!condition) {\n return;\n }\n if (isResolvable(condition)) {\n assertResolvable(condition, path);\n return;\n }\n assertResolvable(condition.params, `${path}.params`);\n if (json.guards?.[condition.type]) {\n assertCondition(\n json.guards[condition.type].when,\n `$.guards.${condition.type}.when`\n );\n return;\n }\n if (\n !resolvedSources.guards[condition.type] &&\n !['scxml.cond', 'xstate.stateIn', 'xstate.not'].includes(condition.type)\n ) {\n throw new Error(`Missing guard source \"${condition.type}\"`);\n }\n }\n\n function assertAction(\n action: ActionJSON,\n path: string,\n stack: string[] = []\n ) {\n if (isResolvable(action)) {\n assertResolvable(action, path);\n return;\n }\n if (!action || typeof action.type !== 'string') {\n throw new Error(`Invalid action at ${path}`);\n }\n assertResolvable((action as CustomActionJSON).params, `${path}.params`);\n if (isBuiltInActionType(action.type) || isScxmlActionType(action.type)) {\n assertResolvable(action, path);\n return;\n }\n const definition = json.actions?.[action.type];\n if (definition) {\n if (stack.includes(action.type)) {\n throw new Error(\n `Circular action reference: ${stack.concat(action.type).join(' -> ')}`\n );\n }\n const definitions = Array.isArray(definition) ? definition : [definition];\n definitions.forEach((item, index) =>\n assertAction(\n item,\n `${path}.actions.${action.type}${definitions.length > 1 ? `[${index}]` : ''}`,\n stack.concat(action.type)\n )\n );\n return;\n }\n if (!resolvedSources.actions[action.type]) {\n throw new Error(`Missing action source \"${action.type}\"`);\n }\n }\n\n function assertActions(\n actions: ActionJSON | ActionJSON[] | undefined,\n path: string\n ) {\n toActionArray(actions).forEach((action, index) =>\n assertAction(action, `${path}[${index}]`)\n );\n }\n\n function assertTransition(\n transition: TransitionConfigJSON | TransitionConfigJSON[] | undefined,\n path: string\n ) {\n const transitions = Array.isArray(transition)\n ? transition\n : transition\n ? [transition]\n : [];\n transitions.forEach((t, index) => {\n const transitionPath = Array.isArray(transition)\n ? `${path}[${index}]`\n : path;\n if (isResolvable(t)) {\n assertResolvable(t, transitionPath);\n return;\n }\n assertCondition(t.guard, `${transitionPath}.guard`);\n assertActions(t.actions, `${transitionPath}.actions`);\n assertResolvable(t.context, `${transitionPath}.context`);\n assertResolvable(t.input, `${transitionPath}.input`);\n });\n }\n\n function assertStateNode(node: StateNodeJSON, path: string) {\n if (\n (node.type === 'history' || node.history !== undefined) &&\n !(\n (typeof node.target === 'string' && node.target.trim().length > 0) ||\n (Array.isArray(node.target) &&\n node.target.length > 0 &&\n node.target.every((target) => target.trim().length > 0))\n )\n ) {\n throw new Error(\n `History state at ${path} must declare a non-empty target.`\n );\n }\n assertResolvable(node.context, `${path}.context`);\n assertResolvable(node.input, `${path}.input`);\n assertResolvable(node.output, `${path}.output`);\n assertResolvable(node.timeout, `${path}.timeout`);\n assertActions(node.entry, `${path}.entry`);\n assertActions(node.exit, `${path}.exit`);\n if (node.type === 'choice') {\n if (!node.choice) {\n throw new Error(`Choice state at ${path} must declare choice.`);\n }\n if (Array.isArray(node.choice)) {\n validateChoiceConfig(node.choice, `${path}.choice`);\n node.choice.forEach((branch, index) => {\n assertCondition(branch.when, `${path}.choice[${index}].when`);\n assertResolvable(branch.context, `${path}.choice[${index}].context`);\n assertResolvable(branch.input, `${path}.choice[${index}].input`);\n });\n } else {\n assertResolvable(node.choice, `${path}.choice`);\n }\n }\n if (isResolvable(node.route)) {\n assertResolvable(node.route, `${path}.route`);\n }\n if (node.invoke) {\n const invokes = Array.isArray(node.invoke) ? node.invoke : [node.invoke];\n invokes.forEach((invoke, index) => {\n const invokePath = `${path}.invoke${Array.isArray(node.invoke) ? `[${index}]` : ''}`;\n const extInv = invoke as InvokeJSON & {\n _nestedScxmlIR?: ScxmlIR;\n };\n if (!extInv._nestedScxmlIR && !resolvedSources.actors[invoke.src]) {\n throw new Error(`Missing actor source \"${invoke.src}\"`);\n }\n assertResolvable(invoke.input, `${invokePath}.input`);\n assertResolvable(invoke.timeout, `${invokePath}.timeout`);\n assertTransition(invoke.onDone, `${invokePath}.onDone`);\n assertTransition(invoke.onError, `${invokePath}.onError`);\n assertTransition(invoke.onSnapshot, `${invokePath}.onSnapshot`);\n assertTransition(invoke.onTimeout, `${invokePath}.onTimeout`);\n });\n }\n if (node.on) {\n for (const descriptor of Object.keys(node.on)) {\n assertTransition(node.on[descriptor], `${path}.on.${descriptor}`);\n }\n }\n if (node.after) {\n for (const delay of Object.keys(node.after)) {\n if (\n Number.isNaN(Number(delay)) &&\n parseDelayToMilliseconds(delay) === undefined &&\n !json.delays?.[delay] &&\n !resolvedSources.delays[delay]\n ) {\n throw new Error(`Missing delay source \"${delay}\"`);\n }\n assertTransition(node.after[delay], `${path}.after.${delay}`);\n }\n }\n assertTransition(node.always, `${path}.always`);\n assertTransition(node.onError, `${path}.onError`);\n assertTransition(node.onTimeout, `${path}.onTimeout`);\n if (node.states) {\n for (const key of Object.keys(node.states)) {\n assertStateNode(node.states[key], `${path}.states.${key}`);\n }\n }\n }\n\n if (json.actions) {\n for (const key of Object.keys(json.actions)) {\n const actions = Array.isArray(json.actions[key])\n ? json.actions[key]\n : [json.actions[key]];\n actions.forEach((action, index) =>\n assertAction(\n action,\n `$.actions.${key}${actions.length > 1 ? `[${index}]` : ''}`,\n [key]\n )\n );\n }\n }\n if (json.guards) {\n for (const key of Object.keys(json.guards)) {\n assertCondition(json.guards[key].when, `$.guards.${key}.when`);\n }\n }\n if (json.delays) {\n for (const key of Object.keys(json.delays)) {\n const delay = json.delays[key];\n assertResolvable(\n delay && typeof delay === 'object' && 'duration' in delay\n ? delay.duration\n : delay,\n `$.delays.${key}`\n );\n }\n }\n assertStateNode(json, '$');\n}\n\nconst SCXML_SYSTEM_VARIABLES = new Set([\n '_sessionid',\n '_name',\n '_ioprocessors',\n '_event',\n '_xstateScxmlInputKeys'\n]);\nconst scxmlScriptEnvironments = new WeakMap<\n AnyActorRef,\n { declarations: string[] }\n>();\nconst scxmlMachineNames = new WeakMap<AnyActorRef, string>();\nconst scxmlIoProcessors = new WeakMap<AnyActorRef, object>();\nconst scxmlEvents = new WeakMap<object, object>();\nconst scxmlEnteringStates = new WeakMap<AnyActorRef, string[]>();\n\nfunction getScxmlIoProcessors(self: AnyActorRef, sessionId: string): object {\n let processors = scxmlIoProcessors.get(self);\n if (!processors) {\n const processor = { location: `#_scxml_${sessionId}` };\n processors = {\n scxml: processor,\n 'http://www.w3.org/TR/scxml/#SCXMLEventProcessor': processor\n };\n scxmlIoProcessors.set(self, processors);\n }\n return processors;\n}\n\nfunction getFunctionDeclarations(code: string): string[] {\n const declarations: string[] = [];\n const pattern = /\\bfunction\\s+[$_a-zA-Z][$_a-zA-Z0-9]*\\s*\\([^)]*\\)\\s*\\{/g;\n for (const match of code.matchAll(pattern)) {\n let depth = 1;\n let index = match.index! + match[0].length;\n while (index < code.length && depth) {\n if (code[index] === '{') depth++;\n if (code[index] === '}') depth--;\n index++;\n }\n declarations.push(code.slice(match.index, index));\n }\n return declarations;\n}\n\n/** Evaluates an SCXML expression with context variables available via `with`. */\nfunction evaluateExpr(\n context: MachineContext,\n expr: string,\n event: AnyEventObject | null,\n self?: AnyActorRef\n): unknown {\n const normalizedExpr = expr.replace(/;+\\s*$/, '');\n const sessionId = (self as any)?.sessionId ?? 'session_scxml';\n const machineName = self\n ? (scxmlMachineNames.get(self) ?? '(machine)')\n : '(machine)';\n const dataContext = Object.fromEntries(\n Object.entries(context).filter(([key]) => !SCXML_SYSTEM_VARIABLES.has(key))\n );\n const fnBody = `\n${self ? (scxmlScriptEnvironments.get(self)?.declarations.join('\\n') ?? '') : ''}\nwith (context) {\n return (${normalizedExpr});\n}\n `.trim();\n // eslint-disable-next-line @typescript-eslint/no-implied-eval\n const fn = new Function(\n 'context',\n '_event',\n '_sessionid',\n '_name',\n '_ioprocessors',\n 'In',\n fnBody\n );\n const In = (stateId: string) => {\n if (!self) return false;\n const sanitized = stateId.replace(/\\./g, '$');\n if (\n scxmlEnteringStates\n .get(self)\n ?.some((id) => id === sanitized || id.endsWith('.' + sanitized))\n ) {\n return true;\n }\n try {\n const snap = (self as any).getSnapshot?.();\n if (snap?.nodes) {\n return snap.nodes.some(\n (node: any) =>\n node.id === sanitized || node.id.endsWith('.' + sanitized)\n );\n }\n } catch {\n // ignore\n }\n return false;\n };\n const SCXML_ORIGIN = `#_scxml_${sessionId}`;\n const SCXML_ORIGIN_TYPE = 'http://www.w3.org/TR/scxml/#SCXMLEventProcessor';\n const isExternal = event && (event as any)._scxmlExternal;\n const isInitEvent = event && event.type === '@xstate.init';\n // Per SCXML spec, _event has these fields. Fields that don't apply to a\n // particular event are present with value `undefined` (so `'name' in _event`\n // is true but `typeof _event.name === 'undefined'` for unset fields).\n // For xstate.done.* events, _event.data is the `output` payload (matches\n // SCXML's done event semantics where data is the donedata).\n const isDoneEvent =\n event &&\n typeof event.type === 'string' &&\n event.type.startsWith('xstate.done.');\n const explicitType =\n event && ((event as any)._scxmlEventType as string | undefined);\n let scxmlEvent: object | undefined;\n if (event && !isInitEvent) {\n scxmlEvent = scxmlEvents.get(event);\n if (!scxmlEvent) {\n scxmlEvent = {\n name:\n ((event as any)._scxmlEventName as string | undefined) ??\n toScxmlEventName(event.type),\n type: explicitType || (isExternal ? 'external' : 'internal'),\n sendid: (event as any)._scxmlSendId as string | undefined,\n origin: isExternal ? SCXML_ORIGIN : undefined,\n origintype: isExternal ? SCXML_ORIGIN_TYPE : undefined,\n invokeid:\n ((event as any)._scxmlInvokeId as string | undefined) ??\n ((event as any).actorId as string | undefined),\n data: isDoneEvent\n ? (event as any).output\n : (event as any)._scxmlEventData !== undefined\n ? (event as any)._scxmlEventData\n : event\n };\n scxmlEvents.set(event, scxmlEvent);\n }\n }\n const result = fn(\n dataContext,\n scxmlEvent,\n sessionId,\n machineName,\n self\n ? getScxmlIoProcessors(self, sessionId)\n : { scxml: { location: `#_scxml_${sessionId}` } },\n In\n );\n\n return result;\n}\n\n/** Executes an SCXML script block and returns updated context values. */\nfunction executeScript(\n context: MachineContext,\n code: string,\n self: AnyActorRef,\n global: boolean\n): Record<string, unknown> {\n // Create a proxy to track which properties are modified\n const updates: Record<string, unknown> = {};\n const contextKeys = Object.keys(context);\n const mutableContextKeys = contextKeys.filter(\n (key) => !SCXML_SYSTEM_VARIABLES.has(key)\n );\n\n // Build variable declarations and reassignment capture\n const varDeclarations = mutableContextKeys\n .map((k) => `var ${k} = context.${k};`)\n .join('\\n');\n const captureUpdates = mutableContextKeys\n .map((k) => `updates.${k} = ${k};`)\n .join('\\n');\n const codeWithoutComments = code.replace(/\\/\\/.*$/gm, '');\n const declarations = getFunctionDeclarations(code);\n const codeWithoutFunctions = declarations.reduce(\n (source, declaration) => source.replace(declaration, ''),\n codeWithoutComments\n );\n const declaredVariables = global\n ? [\n ...codeWithoutFunctions.matchAll(/\\bvar\\s+([$_a-zA-Z][$_a-zA-Z0-9]*)/g)\n ].map((match) => match[1])\n : [];\n const captureVariables = declaredVariables\n .filter(\n (name) => !contextKeys.includes(name) && !SCXML_SYSTEM_VARIABLES.has(name)\n )\n .map((name) => `updates.${name} = ${name};`)\n .join('\\n');\n const environment = scxmlScriptEnvironments.get(self) ?? {\n declarations: []\n };\n scxmlScriptEnvironments.set(self, environment);\n for (const declaration of declarations) {\n if (!environment.declarations.includes(declaration)) {\n environment.declarations.push(declaration);\n }\n }\n\n const fnBody = `\n${varDeclarations}\n${environment.declarations.join('\\n')}\n${code}\n${captureUpdates}\n${captureVariables}\nreturn updates;\n `;\n const sessionId = (self as any).sessionId;\n const machineName = scxmlMachineNames.get(self) ?? '(machine)';\n // eslint-disable-next-line @typescript-eslint/no-implied-eval\n const fn = new Function(\n 'context',\n 'updates',\n '_sessionid',\n '_name',\n '_ioprocessors',\n fnBody\n );\n return fn(\n context,\n updates,\n sessionId,\n machineName,\n getScxmlIoProcessors(self, sessionId)\n );\n}\n\nfunction createScxmlDomElement(element: ScxmlXmlJSON): any {\n const children = (element.children ?? []).map(createScxmlDomElement);\n return {\n tagName: element.name,\n getAttribute: (name: string) => element.attributes?.[name] ?? null,\n getElementsByTagName: (name: string): any[] => [\n ...(element.name === name ? [createScxmlDomElement(element)] : []),\n ...children.flatMap((child: any) => child.getElementsByTagName(name))\n ]\n };\n}\n\nexport function createMachineFromSCXMLConfig(\n json: ScxmlIR,\n sources: MachineSources = {}\n): AnyStateMachine {\n const resolvedSources = mergeSources(json, sources);\n const expressionResolver = createExpressionResolver(\n json['@exprLang'],\n resolvedSources\n );\n const { evaluateResolvable, resolveValue, makeScope, getDurationConfig } =\n expressionResolver;\n const sendCounters = new WeakMap<AnyActorRef, number>();\n\n type ResolvedCondition = ((args: any) => boolean) | undefined;\n\n function resolveCondition(\n condition: ConditionJSON | undefined,\n slot: 'guard' | 'choice',\n path: string\n ): ResolvedCondition {\n if (!condition) {\n return undefined;\n }\n if (isResolvable(condition)) {\n return (args: any) =>\n !!evaluateResolvable(condition, slot, makeScope(args), path);\n }\n return (args: any) => {\n const params = resolveValue(\n condition.params,\n slot,\n makeScope(args),\n `${path}.params`\n );\n const declarativeGuard = json.guards?.[condition.type];\n if (declarativeGuard) {\n const guard = resolveCondition(\n declarativeGuard.when,\n 'guard',\n `$.guards.${condition.type}.when`\n );\n return !!guard?.({ ...args, params });\n }\n const guardImpl = args.guards?.[condition.type];\n if (!guardImpl) {\n throw new Error(\n getMissingGuardMessage(condition.type, args.guards ?? {})\n );\n }\n return guardImpl(args, params);\n };\n }\n\n function makeChoiceConfig(choice: StateNodeJSON['choice'], path: string) {\n if (!choice) {\n return undefined;\n }\n if (isResolvable(choice)) {\n return (args: any) =>\n evaluateResolvable(choice, 'choice', makeScope(args), path);\n }\n validateChoiceConfig(choice, path);\n return (args: any) => {\n for (let index = 0; index < choice.length; index++) {\n const branch = choice[index];\n const guard = resolveCondition(\n branch.when,\n 'choice',\n `${path}[${index}].when`\n );\n if (!guard || guard(args)) {\n return {\n target: branch.target,\n context: branch.context\n ? resolveValue(\n branch.context,\n 'transitionContext',\n makeScope(args),\n `${path}[${index}].context`\n )\n : undefined,\n input:\n branch.input !== undefined\n ? resolveValue(\n branch.input,\n 'input',\n makeScope(args),\n `${path}[${index}].input`\n )\n : undefined,\n description: branch.description,\n reenter: branch.reenter,\n meta: branch.meta\n };\n }\n }\n throw new Error(`Choice state at ${path} did not match any branch.`);\n };\n }\n\n // Pending transition actions: set by .to functions, consumed by entry functions.\n // This bridges SCXML's exit→transition→entry action ordering with XState's\n // .to function receiving pre-exit context.\n // Map keyed by target state ID so parallel transitions don't overwrite each other.\n const pendingTransitionActionsMap: Record<string, ActionJSON[]> = {};\n\n // Ordered queue of ALL transition actions (targeted + targetless) for parallel\n // context sharing. In SCXML, all transition actions execute sequentially in\n // document order with a shared evolving data model.\n const allTransitionActions: ActionJSON[][] = [];\n // Pre-transition context saved when a targetless .to executes. Used by entry\n // functions to re-execute all transition actions from scratch when parallel\n // targetless transitions coexist with targeted transitions.\n let contextBeforeTargetless: MachineContext | null = null;\n let targetlessEvent: AnyEventObject | null = null;\n // Platform errors collected during transition selection (e.g., failing\n // <transition cond>). Drained by the next state's entry into the internal\n // event queue so they're processed before any external events.\n const pendingPlatformErrors: Array<Record<string, unknown>> = [];\n const scxmlDonedataValues = new WeakMap<AnyActorRef, Map<string, unknown>>();\n\n function evaluateDonedataValue(\n donedata: ScxmlDonedataJSON,\n context: MachineContext,\n event: AnyEventObject,\n self: AnyActorRef\n ): unknown {\n if (donedata.params?.length) {\n const out: Record<string, unknown> = {};\n for (const param of donedata.params) {\n out[param.name] = evaluateExpr(context, param.expr, event, self);\n }\n return out;\n }\n if (donedata.contentExpr !== undefined) {\n return evaluateExpr(context, donedata.contentExpr, event, self);\n }\n if (donedata.contentText !== undefined) {\n try {\n return evaluateExpr(context, donedata.contentText, event, self);\n } catch {\n return donedata.contentText;\n }\n }\n return undefined;\n }\n\n function getMissingGuardMessage(type: string, guards: Record<string, any>) {\n return `Guard '${type}' is not implemented in machine '${json.id ?? '(machine)'}'. Available guards: ${\n Object.keys(guards)\n .map((key) => `'${key}'`)\n .join(', ') || '(none)'\n }.`;\n }\n\n function resolveRouteConfig(route: StateNodeJSON['route'], path: string) {\n if (!route || typeof route === 'function') {\n return route;\n }\n if (isResolvable(route)) {\n return (args: any) =>\n evaluateResolvable(route, 'transition', makeScope(args), path);\n }\n const { guard, ...routeConfig } = route;\n if (!guard) {\n return routeConfig;\n }\n const resolvedGuard = resolveCondition({ type: guard }, 'guard', path);\n return (args: any) => (resolvedGuard!(args) ? routeConfig : undefined);\n }\n\n function iterNode(\n node: StateNodeJSON,\n nodeKey?: string,\n ancestorIds: string[] = []\n ) {\n const originalEntryActions: ActionJSON[] = [\n ...(node._scxmlData?.length\n ? [{ type: 'scxml.datamodel' as const, data: node._scxmlData }]\n : []),\n ...toActionArray(node.entry)\n ];\n const stateId = node.id || nodeKey;\n\n // Wrap entry to first execute any pending transition actions, then normal entry.\n // This ensures SCXML execution order: exit → transition_actions → entry_actions\n // because pending transition actions are set by .to (before exit) but executed\n // in entry (after exit), thus seeing post-exit context.\n const entryFn: Action<any, any, any, any, any, any, any> | undefined = (\n x,\n enq\n ) => {\n scxmlMachineNames.set(x.self, json.id ?? '(machine)');\n if (stateId) {\n scxmlEnteringStates.set(x.self, [...ancestorIds, stateId]);\n }\n // Drain any platform errors queued during transition selection (e.g.,\n // failing <transition cond=\"...\"> evaluations). These must be raised\n // internally so they're processed before subsequent external events.\n while (pendingPlatformErrors.length) {\n const err = pendingPlatformErrors.shift()!;\n enq.raise({\n type: 'xstate.error.execution',\n error: err,\n _scxmlEventType: 'platform',\n _scxmlEventName: 'error.execution',\n _scxmlEventData: err\n } as AnyEventObject);\n }\n\n let context: MachineContext | undefined;\n\n // If targetless transitions were interleaved with targeted transitions\n // (parallel state), re-execute ALL transition actions from the original\n // pre-transition context. This overrides any .to-produced context with\n // the correct SCXML document-order sequential execution.\n // Only trigger when BOTH targeted (pending in map) and targetless fired\n // in the same microstep — prevents stale data from previous events.\n if (\n contextBeforeTargetless &&\n targetlessEvent === x.event &&\n allTransitionActions.length > 0 &&\n Object.keys(pendingTransitionActionsMap).length > 0\n ) {\n let ctx = contextBeforeTargetless;\n for (const actions of allTransitionActions) {\n const mergedX = { ...x, context: ctx };\n const result = executeActions(actions, mergedX, enq);\n if (result.context) {\n ctx = result.context;\n }\n }\n allTransitionActions.length = 0;\n contextBeforeTargetless = null;\n targetlessEvent = null;\n // Clear per-target map since we re-processed everything\n for (const key of Object.keys(pendingTransitionActionsMap)) {\n delete pendingTransitionActionsMap[key];\n }\n context = ctx;\n } else {\n // Normal path: consume pending transition actions for THIS state.\n // In parallel states, each target gets its own pending actions.\n const transActions = stateId\n ? pendingTransitionActionsMap[stateId]\n : undefined;\n if (transActions) {\n delete pendingTransitionActionsMap[stateId!];\n const result = executeActions(transActions, x, enq);\n if (result.context) {\n context = result.context;\n }\n }\n // Clear stale targetless data from previous microsteps\n contextBeforeTargetless = null;\n targetlessEvent = null;\n allTransitionActions.length = 0;\n }\n\n // Execute normal entry actions\n if (originalEntryActions.length) {\n const mergedX = context ? { ...x, context } : x;\n const result = executeActions(originalEntryActions, mergedX, enq);\n if (result.context) {\n context = result.context;\n }\n }\n\n if (node._scxmlDonedata && stateId) {\n let values = scxmlDonedataValues.get(x.self);\n if (!values) {\n values = new Map();\n scxmlDonedataValues.set(x.self, values);\n }\n try {\n values.set(\n stateId,\n evaluateDonedataValue(\n node._scxmlDonedata,\n context ?? x.context,\n x.event,\n x.self\n )\n );\n } catch (err) {\n values.set(stateId, undefined);\n raiseErrorExecution(\n { enq, self: x.self, errored: false },\n 'donedata',\n err\n );\n }\n }\n\n scxmlEnteringStates.delete(x.self);\n return { context };\n };\n\n const nodeConfig: any = {\n id: node.id,\n initial: node._scxmlInitial\n ? {\n target: node._scxmlInitial.targets,\n to: node._scxmlInitial.actions\n ? (x: any, enq: any) => ({\n ...executeActions(node._scxmlInitial!.actions!, x, enq),\n target: node._scxmlInitial!.targets\n })\n : undefined\n }\n : node.initial,\n type: node.type,\n history: node.history,\n target: node.target,\n _historyDefaultTransition: node._scxmlHistoryActions\n ? (x: any, enq: any) => ({\n ...executeActions(node._scxmlHistoryActions!, x, enq),\n target: node.target\n })\n : undefined,\n description: node.description,\n tags: node.tags,\n input: node.input,\n timeout: getDurationConfig(node.timeout, `$.states.${nodeKey}.timeout`),\n states: node.states\n ? Object.entries(node.states).reduce(\n (acc, [key, value]) => {\n acc[key] = iterNode(\n value,\n key,\n stateId ? [...ancestorIds, stateId] : ancestorIds\n );\n return acc;\n },\n {} as Record<\n string,\n Next_StateNodeConfig<\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any\n >\n >\n )\n : undefined,\n on: node.on\n ? Object.entries(node.on).reduce(\n (acc, [key, value]) => {\n acc[key] = getTransitionConfig(value);\n return acc;\n },\n {} as Record<string, any>\n )\n : undefined,\n always: node.always ? getTransitionConfig(node.always) : undefined,\n onError: node.onError ? getTransitionConfig(node.onError) : undefined,\n choice: makeChoiceConfig(node.choice, `$.states.${nodeKey}.choice`),\n route: resolveRouteConfig(node.route, `$.states.${nodeKey}.route`),\n after: node.after\n ? Object.entries(node.after).reduce(\n (acc, [key, value]) => {\n acc[key] = getTransitionConfig(value);\n return acc;\n },\n {} as Record<string, any>\n )\n : undefined,\n onTimeout: node.onTimeout\n ? getTransitionConfig(node.onTimeout)\n : undefined,\n entry: node.type === 'choice' ? undefined : (entryFn as any),\n exit: node.exit\n ? (iterActions(toActionArray(node.exit)) as any)\n : undefined,\n invoke: node.invoke ? iterInvokeConfigs(node.invoke) : undefined,\n meta: node.meta,\n output: node._scxmlDonedata\n ? makeDonedataOutput(stateId!)\n : isResolvable(node.output)\n ? ({ context, event, self }: any) =>\n evaluateResolvable(\n node.output as ResolvableJSON,\n 'output',\n { context, event, self },\n `$.states.${nodeKey}.output`\n )\n : node.output\n };\n\n return nodeConfig;\n }\n\n function makeDonedataOutput(stateId: string) {\n return ({ self }: any) => scxmlDonedataValues.get(self)?.get(stateId);\n }\n\n function iterInvokeConfigs(invokes: InvokeJSON | InvokeJSON[]): any {\n const invokeArray = Array.isArray(invokes) ? invokes : [invokes];\n return invokeArray.map((inv) => {\n const extInv = inv as InvokeJSON & { _nestedScxmlIR?: ScxmlIR };\n // Create child machine from nested SCXML JSON\n let src: any;\n if (extInv._nestedScxmlIR) {\n src = createMachineFromSCXMLConfig(\n extInv._nestedScxmlIR,\n resolvedSources\n );\n } else {\n src = resolvedSources.actors[inv.src] ?? inv.src;\n }\n return {\n src,\n id: inv.id,\n registryKey: inv.registryKey,\n input: inv._scxmlInput\n ? ({ context, event, self }: any) => {\n const input: Record<string, unknown> = {};\n for (const name of inv._scxmlInput!.namelist ?? []) {\n if (!(name in context)) {\n throw new ReferenceError(`${name} is not defined`);\n }\n input[name] = context[name];\n }\n for (const param of inv._scxmlInput!.params ?? []) {\n input[param.name] = param.expr\n ? evaluateExpr(context, param.expr, event, self)\n : param.location\n ? evaluateExpr(context, param.location, event, self)\n : undefined;\n }\n return input;\n }\n : inv.input !== undefined\n ? (args: any) =>\n resolveValue(\n inv.input,\n 'input',\n makeScope(args),\n '$.invoke.input'\n )\n : undefined,\n onDone: inv.onDone ? getTransitionConfig(inv.onDone) : undefined,\n onError: inv.onError ? getTransitionConfig(inv.onError) : undefined,\n onSnapshot: inv.onSnapshot\n ? getTransitionConfig(inv.onSnapshot)\n : undefined,\n timeout: getDurationConfig(inv.timeout, '$.invoke.timeout'),\n onTimeout: inv.onTimeout\n ? getTransitionConfig(inv.onTimeout)\n : undefined\n };\n });\n }\n\n /**\n * Raise an SCXML error.execution platform event onto the internal queue. Per\n * spec, error.execution is type='platform' and _event.data contains error\n * info. The surrounding block of executable content stops.\n */\n function raiseErrorExecution(\n state: ExecState,\n tagname: string,\n err: unknown,\n sendId?: string\n ) {\n const message =\n err instanceof Error\n ? err.message\n : typeof err === 'string'\n ? err\n : 'unknown error';\n const errorEvent = {\n type: 'xstate.error.execution',\n error: {\n tagname,\n message,\n line: 0,\n column: 0,\n reason: message\n },\n _scxmlEventType: 'platform',\n _scxmlEventName: 'error.execution',\n ...(sendId ? { _scxmlSendId: sendId } : {}),\n _scxmlEventData: {\n tagname,\n message,\n line: 0,\n column: 0,\n reason: message\n }\n } as AnyEventObject;\n state.enq.raise(errorEvent);\n state.errored = true;\n }\n\n interface ExecState {\n enq: any;\n self: AnyActorRef;\n errored: boolean;\n }\n\n function executeActionDefinition(\n action: CustomActionJSON,\n x: any,\n enq: any,\n params: unknown,\n parentState: ExecState,\n stack: string[]\n ): { context: MachineContext | undefined; errored: boolean } {\n const definition = json.actions?.[action.type];\n if (!definition) {\n enq(x.actions[action.type], params);\n return { context: undefined, errored: parentState.errored };\n }\n if (stack.includes(action.type)) {\n raiseErrorExecution(\n parentState,\n 'action',\n new Error(\n `Circular action reference: ${stack.concat(action.type).join(' -> ')}`\n )\n );\n return { context: undefined, errored: true };\n }\n const definitions = Array.isArray(definition) ? definition : [definition];\n return executeActions(\n definitions,\n { ...x, params },\n enq,\n parentState,\n stack.concat(action.type)\n );\n }\n\n /** Execute an array of SCXML action JSON descriptors with context and enqueue. */\n function executeActions(\n actions: ActionJSON[],\n x: any,\n enq: any,\n parentState?: ExecState,\n stack: string[] = []\n ): { context: MachineContext | undefined; errored: boolean } {\n const state: ExecState = parentState ?? {\n enq,\n self: x.self,\n errored: false\n };\n let context: MachineContext | undefined;\n for (const action of actions) {\n if (state.errored) break;\n if (isResolvable(action)) {\n const result = evaluateResolvable(\n action,\n 'action',\n makeScope(x, { params: x.params, enq }),\n '$.actions'\n );\n if (\n result &&\n typeof result === 'object' &&\n 'context' in result &&\n (result as { context?: MachineContext }).context\n ) {\n context ??= {};\n Object.assign(\n context,\n (result as { context: MachineContext }).context\n );\n }\n } else if (isBuiltInActionJSON(action)) {\n switch (action.type) {\n case '@xstate.raise': {\n // Tag as external if it has a delay (from <send>, not <raise>).\n // Attach _scxmlSendId so _event.sendid can be read in expressions.\n const isExternal = action.delay !== undefined;\n const resolvedEvent = resolveValue(\n action.event,\n 'actionParams',\n makeScope(x, { params: x.params }),\n '$.actions.event'\n ) as EventObject;\n const event =\n isExternal || action.id !== undefined\n ? {\n ...resolvedEvent,\n ...(isExternal ? { _scxmlExternal: true } : {}),\n ...(action.id !== undefined\n ? { _scxmlSendId: action.id }\n : {})\n }\n : resolvedEvent;\n enq.raise(event, {\n id: action.id,\n delay: action.delay\n });\n break;\n }\n case '@xstate.cancel':\n enq.cancel(action.id);\n break;\n case '@xstate.log':\n enq.log(...action.args);\n break;\n case '@xstate.emit':\n enq.emit(\n resolveValue(\n action.event,\n 'actionParams',\n makeScope(x, { params: x.params }),\n '$.actions.event'\n )\n );\n break;\n case '@xstate.assign':\n context ??= {};\n Object.assign(\n context,\n resolveValue(\n action.context,\n 'transitionContext',\n makeScope(x, { params: x.params }),\n '$.actions.context'\n )\n );\n break;\n default:\n throw new Error(`Unknown built-in action: ${(action as any).type}`);\n }\n } else if (action.type === 'scxml.finalize') {\n const finalize = action as ScxmlFinalizeJSON;\n const invokeId =\n (x.event as any)._scxmlInvokeId ?? (x.event as any).actorId;\n if (invokeId === finalize.invokeId) {\n const result = executeActions(\n finalize.actions,\n { ...x, context: { ...x.context, ...context } },\n enq,\n state\n );\n if (result.context) {\n context = result.context;\n }\n }\n } else if (action.type === 'scxml.forward') {\n const child = x.children?.[(action as ScxmlForwardJSON).invokeId];\n if (child) {\n enq.sendTo(child, {\n ...x.event,\n _scxmlExternal: true\n });\n }\n } else if (action.type === 'scxml.log') {\n const scxmlAction = action as ScxmlLogJSON;\n try {\n const value = scxmlAction.expr\n ? evaluateExpr(\n { ...x.context, ...context },\n scxmlAction.expr,\n x.event,\n x.self\n )\n : undefined;\n enq.log(\n ...(scxmlAction.label ? [scxmlAction.label, value] : [value])\n );\n } catch (err) {\n raiseErrorExecution(state, 'log', err);\n }\n } else if (action.type === 'scxml.assign') {\n const scxmlAction = action as ScxmlAssignJSON;\n const mergedContext = { ...x.context, ...context };\n let value: unknown;\n try {\n value = evaluateExpr(\n mergedContext,\n scxmlAction.expr,\n x.event,\n x.self\n );\n } catch (err) {\n raiseErrorExecution(state, 'assign', err);\n continue;\n }\n if (SCXML_SYSTEM_VARIABLES.has(scxmlAction.location.split('.')[0])) {\n raiseErrorExecution(\n state,\n 'assign',\n new Error(\n `Cannot assign to SCXML system variable: ${scxmlAction.location}`\n )\n );\n continue;\n }\n if (scxmlAction.location.includes('.')) {\n const path = scxmlAction.location.split('.');\n const root = path.shift()!;\n let target = mergedContext[root];\n if (!target || typeof target !== 'object') {\n raiseErrorExecution(\n state,\n 'assign',\n new Error(`Invalid assign location: ${scxmlAction.location}`)\n );\n continue;\n }\n const clonedRoot = Array.isArray(target)\n ? [...target]\n : { ...target };\n target = clonedRoot;\n for (const segment of path.slice(0, -1)) {\n const child = (target as Record<string, unknown>)[segment];\n if (!child || typeof child !== 'object') {\n raiseErrorExecution(\n state,\n 'assign',\n new Error(`Invalid assign location: ${scxmlAction.location}`)\n );\n break;\n }\n const clonedChild = Array.isArray(child)\n ? [...child]\n : { ...child };\n (target as Record<string, unknown>)[segment] = clonedChild;\n target = clonedChild;\n }\n if (state.errored) continue;\n (target as Record<string, unknown>)[path.at(-1)!] = value;\n context ??= {};\n context[root] = clonedRoot;\n continue;\n }\n context ??= {};\n context[scxmlAction.location] = value;\n } else if (action.type === 'scxml.datamodel') {\n const scxmlAction = action as ScxmlDatamodelJSON;\n context ??= {};\n for (const data of scxmlAction.data) {\n if (\n Array.isArray(x.context._xstateScxmlInputKeys) &&\n x.context._xstateScxmlInputKeys.includes(data.id)\n ) {\n continue;\n }\n if (data.src) {\n raiseErrorExecution(\n state,\n 'data',\n new Error(`Unresolved data resource: ${data.src}`)\n );\n break;\n }\n if (data.expr !== undefined) {\n try {\n context[data.id] = evaluateExpr(\n { ...x.context, ...context },\n data.expr,\n x.event,\n x.self\n );\n } catch (err) {\n raiseErrorExecution(state, 'data', err);\n break;\n }\n } else if (data.content !== undefined) {\n try {\n context[data.id] = evaluateExpr(\n { ...x.context, ...context },\n data.content,\n x.event,\n x.self\n );\n } catch {\n context[data.id] = data.content.replace(/\\s+/g, ' ').trim();\n }\n } else if (data.xml) {\n context[data.id] = createScxmlDomElement(data.xml);\n } else {\n if (x.context[data.id] === undefined) {\n context[data.id] = undefined;\n }\n }\n }\n } else if (action.type === 'scxml.raise') {\n const scxmlAction = action as ScxmlRaiseJSON;\n const mergedContext = { ...x.context, ...context };\n\n let eventType: string;\n let eventData: Record<string, unknown>;\n let target: string | undefined;\n let delay: number | undefined;\n try {\n if (\n scxmlAction.processorType &&\n ![\n 'scxml',\n 'http://www.w3.org/TR/scxml/#SCXMLEventProcessor'\n ].includes(scxmlAction.processorType)\n ) {\n throw new Error(\n `Unsupported send type: ${scxmlAction.processorType}`\n );\n }\n eventType = scxmlAction.eventexpr\n ? (evaluateExpr(\n mergedContext,\n scxmlAction.eventexpr,\n x.event,\n x.self\n ) as string)\n : scxmlAction.event || 'unknown';\n eventType = normalizeScxmlEventType(eventType);\n\n eventData = {\n type: eventType,\n _scxmlEventName: toScxmlEventName(eventType)\n };\n const payload: Record<string, unknown> = {};\n if (scxmlAction.namelist) {\n for (const name of scxmlAction.namelist) {\n payload[name] = evaluateExpr(\n mergedContext,\n name,\n x.event,\n x.self\n );\n }\n }\n if (scxmlAction.params) {\n for (const param of scxmlAction.params) {\n payload[param.name] = evaluateExpr(\n mergedContext,\n param.expr ?? param.location!,\n x.event,\n x.self\n );\n }\n }\n if (scxmlAction.content) {\n const content = scxmlAction.content;\n let contentValue: unknown;\n if (content.expr !== undefined) {\n contentValue = evaluateExpr(\n mergedContext,\n content.expr,\n x.event,\n x.self\n );\n } else if (content.xml) {\n contentValue = createScxmlDomElement(content.xml);\n } else {\n const text = content.text?.replace(/\\s+/g, ' ').trim() ?? '';\n try {\n contentValue = evaluateExpr(\n mergedContext,\n text,\n x.event,\n x.self\n );\n } catch {\n contentValue = text;\n }\n }\n eventData._scxmlEventData = contentValue;\n } else if (Object.keys(payload).length) {\n Object.assign(eventData, payload);\n eventData._scxmlEventData = payload;\n }\n\n if (scxmlAction.idlocation) {\n const nextId = (sendCounters.get(x.self) ?? 0) + 1;\n sendCounters.set(x.self, nextId);\n const generatedId = `${x.self.sessionId}.send.${nextId}`;\n context ??= {};\n context[scxmlAction.idlocation] = generatedId;\n eventData._scxmlSendId = generatedId;\n }\n\n target = scxmlAction.targetexpr\n ? (evaluateExpr(\n mergedContext,\n scxmlAction.targetexpr,\n x.event,\n x.self\n ) as string)\n : scxmlAction.target;\n\n const isInternalTarget = target === '#_internal';\n delay = scxmlAction.delayexpr\n ? delayToMs(\n evaluateExpr(\n mergedContext,\n scxmlAction.delayexpr,\n x.event,\n x.self\n ) as string | number\n )\n : isInternalTarget\n ? undefined\n : scxmlAction.delay;\n } catch (err) {\n raiseErrorExecution(state, 'send', err);\n continue;\n }\n\n const isInternalTarget = target === '#_internal';\n const isParentTarget = target === '#_parent';\n if (!isInternalTarget) {\n (eventData as any)._scxmlExternal = true;\n }\n if (isParentTarget) {\n (eventData as any)._scxmlInvokeId = x.self.id;\n }\n\n // Validate target. SCXML targets must be '#_internal', '#_parent',\n // or '#_<id>'. A bare string without the '#_' prefix is invalid and\n // raises error.execution.\n if (\n typeof target === 'string' &&\n target.length > 0 &&\n !target.startsWith('#_')\n ) {\n raiseErrorExecution(\n state,\n 'send',\n new Error(`Invalid send target: ${target}`),\n eventData._scxmlSendId as string | undefined\n );\n continue;\n }\n // Attach send id so _event.sendid can be read in expressions.\n if (\n scxmlAction.id !== undefined &&\n eventData._scxmlSendId === undefined\n ) {\n (eventData as any)._scxmlSendId = scxmlAction.id;\n }\n // Resolve target at runtime: parent, child, or self\n if (isParentTarget && x.parent) {\n // Send to parent via sendTo; pass delay if present\n enq.sendTo(\n x.parent,\n eventData as AnyEventObject,\n delay !== undefined ? { delay } : undefined\n );\n } else if (\n typeof target === 'string' &&\n target.startsWith('#_') &&\n !isParentTarget &&\n !isInternalTarget\n ) {\n // #_<invokeId> → try to send to child actor, fall back to self-raise\n const childId = target.slice(2); // strip '#_'\n const childRef = x.children?.[childId];\n if (childRef) {\n enq.sendTo(childRef, eventData as AnyEventObject);\n } else if (\n childId.startsWith('scxml_') &&\n childId !== `scxml_${x.self.sessionId}`\n ) {\n const message = `Unable to dispatch event to target: ${target}`;\n enq.raise({\n type: 'xstate.error.communication',\n error: {\n tagname: 'send',\n message,\n line: NaN,\n column: NaN,\n reason: message\n },\n _scxmlEventType: 'platform',\n _scxmlEventName: 'error.communication',\n _scxmlEventData: {\n tagname: 'send',\n message,\n line: NaN,\n column: NaN,\n reason: message\n }\n } as AnyEventObject);\n } else {\n // This SCXML session id uses the external event queue.\n (eventData as any)._scxmlExternal = true;\n enq.sendTo(x.self, eventData as AnyEventObject, {\n id: scxmlAction.id,\n delay\n });\n }\n } else {\n // #_internal uses the internal queue; self-send/no target use the\n // external event queue.\n if (isInternalTarget) {\n enq.raise(eventData as AnyEventObject, {\n id: scxmlAction.id,\n delay\n });\n } else {\n (eventData as any)._scxmlExternal = true;\n enq.sendTo(x.self, eventData as AnyEventObject, {\n id: scxmlAction.id,\n delay\n });\n }\n }\n } else if (action.type === 'scxml.cancel') {\n const scxmlAction = action as ScxmlCancelJSON;\n const mergedContext = { ...x.context, ...context };\n try {\n const sendId = evaluateExpr(\n mergedContext,\n scxmlAction.sendidexpr,\n x.event,\n x.self\n ) as string;\n if (sendId) {\n enq.cancel(sendId);\n }\n } catch {\n // ignore evaluation errors\n }\n } else if (action.type === 'scxml.script') {\n const scxmlAction = action as ScxmlScriptJSON;\n const mergedContext = { ...x.context, ...context };\n try {\n const updatedContext = executeScript(\n mergedContext,\n scxmlAction.code,\n x.self,\n scxmlAction.global ?? false\n );\n context ??= {};\n Object.assign(context, updatedContext);\n } catch (err) {\n raiseErrorExecution(state, 'script', err);\n }\n } else if (action.type === 'scxml.foreach') {\n const scxmlAction = action as ScxmlForeachJSON;\n const mergedContext = { ...x.context, ...context };\n // SCXML: `item` (and `index` if present) must be valid datamodel\n // locations — i.e. legal identifiers. Reject things like 'continue'\n // (string literal) or '7' (number).\n const isLegalIdentifier = (s: string) =>\n /^[$_a-zA-Z][$_a-zA-Z0-9]*$/.test(s);\n if (\n !isLegalIdentifier(scxmlAction.item) ||\n (scxmlAction.index && !isLegalIdentifier(scxmlAction.index))\n ) {\n raiseErrorExecution(\n state,\n 'foreach',\n new Error('foreach item/index is not a legal location')\n );\n continue;\n }\n let arr: unknown;\n try {\n arr = evaluateExpr(mergedContext, scxmlAction.array, x.event, x.self);\n } catch (err) {\n raiseErrorExecution(state, 'foreach', err);\n continue;\n }\n if (!Array.isArray(arr)) {\n raiseErrorExecution(\n state,\n 'foreach',\n new Error('foreach array is not iterable')\n );\n continue;\n }\n context ??= {};\n for (let i = 0; i < arr.length; i++) {\n context[scxmlAction.item] = arr[i];\n if (scxmlAction.index) {\n context[scxmlAction.index] = i;\n }\n const iterX = { ...x, context: { ...x.context, ...context } };\n const iterResult = executeActions(\n scxmlAction.actions,\n iterX,\n enq,\n state\n );\n if (iterResult.context) {\n Object.assign(context, iterResult.context);\n }\n if (state.errored) break;\n }\n } else if (action.type === 'scxml.block') {\n const scxmlAction = action as ScxmlBlockJSON;\n const blockX = { ...x, context: { ...x.context, ...context } };\n // Block has its own ExecState — errors don't propagate to parent.\n const blockResult = executeActions(scxmlAction.actions, blockX, enq);\n if (blockResult.context) {\n context ??= {};\n for (const key of Object.keys(blockResult.context)) {\n if (blockResult.context[key] !== x.context[key]) {\n context[key] = blockResult.context[key];\n }\n }\n }\n } else if (action.type === 'scxml.if') {\n const scxmlAction = action as ScxmlIfJSON;\n const mergedContext = { ...x.context, ...context };\n for (const branch of scxmlAction.branches) {\n let condResult: boolean;\n if (branch.cond) {\n try {\n condResult = !!evaluateExpr(\n mergedContext,\n branch.cond,\n x.event,\n x.self\n );\n } catch (err) {\n raiseErrorExecution(state, 'if', err);\n condResult = false;\n }\n } else {\n condResult = true;\n }\n if (condResult) {\n if (branch.actions.length) {\n const branchX = { ...x, context: mergedContext };\n const branchResult = executeActions(\n branch.actions,\n branchX,\n enq,\n state\n );\n if (branchResult.context) {\n context ??= {};\n for (const key of Object.keys(branchResult.context)) {\n if (branchResult.context[key] !== x.context[key]) {\n context[key] = branchResult.context[key];\n }\n }\n }\n }\n break;\n }\n }\n } else {\n const params = resolveValue(\n (action as CustomActionJSON).params,\n 'actionParams',\n makeScope(x, { params: x.params }),\n '$.actions.params'\n );\n const result = executeActionDefinition(\n action,\n x,\n enq,\n params,\n state,\n stack\n );\n if (result.context) {\n context ??= {};\n Object.assign(context, result.context);\n }\n }\n }\n return {\n context: context ? { ...x.context, ...context } : undefined,\n errored: state.errored\n };\n }\n\n function iterActions(\n actions: ActionJSON[]\n ): Action<any, any, any, any, any, any, any> {\n return (x, enq) => executeActions(actions, x, enq);\n }\n\n function getFinalizedGuardContext(\n context: MachineContext,\n event: AnyEventObject,\n self: AnyActorRef,\n finalizers: NonNullable<TransitionJSON['_scxml']>['finalize']\n ): MachineContext {\n const invokeId = (event as any)._scxmlInvokeId ?? (event as any).actorId;\n const finalized = { ...context };\n for (const finalizer of finalizers ?? []) {\n if (finalizer.invokeId !== invokeId) continue;\n for (const action of finalizer.actions) {\n if (!('type' in action) || action.type !== 'scxml.assign') continue;\n const assignAction = action as ScxmlAssignJSON;\n finalized[assignAction.location] = evaluateExpr(\n finalized,\n assignAction.expr,\n event,\n self\n );\n }\n }\n return finalized;\n }\n\n function getTransitionConfig(\n transition: TransitionConfigJSON | TransitionConfigJSON[]\n ): any {\n const transitions = Array.isArray(transition) ? transition : [transition];\n\n // Return an array of transition configs. Each SCXML transition becomes\n // a separate XState transition with its own guard and optional .to.\n // This ensures guards are evaluated by XState's evaluateCandidate (once,\n // with pre-exit context) and NOT re-evaluated in computeEntrySet.\n return transitions.map((t, index) => {\n if (isResolvable(t)) {\n return (x: any, enq: any) =>\n evaluateResolvable(\n t,\n 'transition',\n makeScope(x, { enq }),\n `$.transition${transitions.length > 1 ? `[${index}]` : ''}`\n );\n }\n const target = Array.isArray(t.target) ? t.target[0] : t.target;\n const targetConfig = t.target;\n const resolvedGuard = resolveCondition(\n t.guard,\n 'guard',\n '$.transition.guard'\n );\n const guard =\n resolvedGuard && t._scxml?.finalize?.length\n ? (args: any) =>\n resolvedGuard({\n ...args,\n context: getFinalizedGuardContext(\n args.context,\n args.event,\n args.self,\n t._scxml!.finalize\n )\n })\n : resolvedGuard;\n const resolveTransitionContext = (x: any) =>\n t.context\n ? (resolveValue(\n t.context,\n 'transitionContext',\n makeScope(x),\n '$.transition.context'\n ) as MachineContext)\n : undefined;\n const resolveTransitionInput = (x: any) =>\n t.input !== undefined\n ? resolveValue(t.input, 'input', makeScope(x), '$.transition.input')\n : undefined;\n const eventMatcher = t._scxml?.eventDescriptors\n ? (event: EventObject) =>\n t._scxml!.eventDescriptors!.some((descriptor) =>\n matchesScxmlEventDescriptor(descriptor, event)\n )\n : undefined;\n\n // No guard and no actions: simple static config\n if (!guard && !t.actions?.length) {\n if (t.context) {\n return {\n matches: t.matches,\n _transitionDomain: t._scxml?.type,\n _eventMatcher: eventMatcher,\n to: (x: any) => ({\n target: targetConfig,\n context: resolveTransitionContext(x),\n reenter: t.reenter\n }),\n description: t.description,\n meta: t.meta,\n input: t.input !== undefined ? resolveTransitionInput : undefined\n };\n }\n return {\n matches: t.matches,\n _transitionDomain: t._scxml?.type,\n _eventMatcher: eventMatcher,\n target: targetConfig,\n description: t.description,\n reenter: t.reenter,\n meta: t.meta,\n input: t.input !== undefined ? resolveTransitionInput : undefined\n };\n }\n\n // Guard but no actions: static config with guard\n if (guard && !t.actions?.length) {\n if (t.context) {\n return {\n matches: t.matches,\n _transitionDomain: t._scxml?.type,\n _eventMatcher: eventMatcher,\n guard,\n to: (x: any) => ({\n target: targetConfig,\n context: resolveTransitionContext(x),\n reenter: t.reenter\n }),\n description: t.description,\n meta: t.meta,\n input: t.input !== undefined ? resolveTransitionInput : undefined\n };\n }\n return {\n matches: t.matches,\n _transitionDomain: t._scxml?.type,\n _eventMatcher: eventMatcher,\n target: targetConfig,\n guard,\n description: t.description,\n reenter: t.reenter,\n meta: t.meta,\n input: t.input !== undefined ? resolveTransitionInput : undefined\n };\n }\n\n // Targetless transitions: execute actions directly in .to AND track for\n // parallel re-execution. For non-parallel, .to result is used directly.\n // For parallel (entries exist), first entry re-executes all in document order.\n if (!target) {\n return {\n matches: t.matches,\n _transitionDomain: t._scxml?.type,\n _eventMatcher: eventMatcher,\n guard,\n description: t.description,\n reenter: t.reenter,\n meta: t.meta,\n input: t.input !== undefined ? resolveTransitionInput : undefined,\n to: (x: any, enq: any) => {\n const context = resolveTransitionContext(x);\n if (t.actions?.length) {\n // Track for parallel re-execution (dedup by reference)\n if (!allTransitionActions.includes(t.actions)) {\n allTransitionActions.push(t.actions);\n }\n // Save pre-transition context for parallel override\n contextBeforeTargetless ??= x.context;\n targetlessEvent ??= x.event;\n // Execute immediately (fallback for non-parallel case)\n const result = executeActions(t.actions, x, enq);\n if (result.context) {\n return { context: { ...context, ...result.context } };\n }\n }\n return context ? { context } : {};\n }\n };\n }\n\n // Has target + actions: use guard (for XState evaluation) + .to (for pending actions).\n // The .to function does NOT re-check the guard — XState's evaluateCandidate\n // already validated it. The .to just stores actions for entry to execute.\n // Map by target state ID so parallel transitions each get their own actions.\n return {\n matches: t.matches,\n _transitionDomain: t._scxml?.type,\n _eventMatcher: eventMatcher,\n guard,\n description: t.description,\n reenter: t.reenter,\n meta: t.meta,\n input: t.input !== undefined ? resolveTransitionInput : undefined,\n to: (_x: any, _enq: any) => {\n const context = resolveTransitionContext(_x);\n if (t.actions?.length) {\n const targetId = target.replace(/^#/, '');\n pendingTransitionActionsMap[targetId] = t.actions;\n // Track for parallel re-execution (dedup by reference)\n if (!allTransitionActions.includes(t.actions)) {\n allTransitionActions.push(t.actions);\n }\n }\n return {\n target: targetConfig,\n context,\n reenter: t.reenter\n };\n }\n };\n });\n }\n\n if (json.delays) {\n for (const key of Object.keys(json.delays)) {\n const delay = json.delays[key];\n if (typeof delay === 'number') {\n resolvedSources.delays[key] = delay;\n } else if (typeof delay === 'string') {\n resolvedSources.delays[key] = delayToMs(delay);\n } else if (delay && typeof delay === 'object') {\n resolvedSources.delays[key] = (args: any) =>\n delayToMs(\n resolveValue(\n delay.duration,\n 'delay',\n makeScope(args),\n `$.delays.${key}.duration`\n ) as string | number\n );\n }\n }\n }\n\n assertMachineJSON(json, resolvedSources, expressionResolver);\n\n const rootNodeConfig = iterNode(json);\n const contextConfig =\n json.context || json._scxmlDataIds?.length\n ? {\n context: (args: any) => ({\n ...Object.fromEntries(\n (json._scxmlDataIds ?? []).map((id) => [id, undefined])\n ),\n ...(json.context\n ? (resolveValue(\n json.context,\n 'context',\n args,\n '$.context'\n ) as MachineContext)\n : {}),\n ...(json._scxmlDataIds?.length &&\n args.input &&\n typeof args.input === 'object'\n ? args.input\n : {}),\n ...(json._scxmlDataIds?.length &&\n args.input &&\n typeof args.input === 'object'\n ? { _xstateScxmlInputKeys: Object.keys(args.input) }\n : {})\n })\n }\n : {};\n\n const machine = createMachine({\n ...rootNodeConfig,\n ...contextConfig,\n version: json.version\n }) as unknown as AnyStateMachine;\n\n // Register SCXML guard sources\n const providedGuards: Record<string, (args: any, params: any) => boolean> = {\n 'scxml.cond': ({ context, event, self }: any, params: any) => {\n const expr = params?.expr as string;\n if (!expr) return true;\n try {\n return !!evaluateExpr(context, expr, event, self);\n } catch (err) {\n // Per SCXML spec, a cond that fails to evaluate is treated as false\n // AND raises error.execution. We can't enqueue from a guard, so\n // queue it for the next entry to drain.\n const message =\n err instanceof Error\n ? err.message\n : typeof err === 'string'\n ? err\n : 'unknown error';\n pendingPlatformErrors.push({\n tagname: 'cond',\n message,\n line: NaN,\n column: NaN,\n reason: message\n });\n return false;\n }\n },\n 'xstate.stateIn': (args: any, params: any) => {\n const stateId = params?.stateId as string;\n if (!stateId) return false;\n const normalizedId = stateId.replace(/^#/, '');\n const snapshot = args._snapshot;\n if (snapshot?.nodes) {\n return snapshot.nodes.some((node: any) => node.id === normalizedId);\n }\n return false;\n },\n 'xstate.not': (args: any, params: any) => {\n const inner = params?.guard;\n const innerImpl = inner && args.guards?.[inner.type];\n if (!innerImpl) {\n throw new Error(\n `Guard '${inner?.type}' referenced by 'xstate.not' is not implemented.`\n );\n }\n return !innerImpl(args, inner.params);\n }\n };\n const provided = machine.provide({\n actions: resolvedSources.actions,\n actors: resolvedSources.actors,\n guards: {\n ...providedGuards,\n ...resolvedSources.guards\n },\n delays: resolvedSources.delays\n });\n\n // Keep the original JSON so `serializeMachine(machine)`\n // round-trip losslessly.\n (provided as any)._json = json;\n return provided;\n}\n\nfunction isBuiltInActionJSON(action: ActionJSON): action is BuiltInActionJSON {\n return !isResolvable(action) && action.type.startsWith('@xstate.');\n}\n","import { StandardSchemaV1 } from './schema.types.ts';\nimport { StateMachine } from './StateMachine.ts';\nimport {\n AnyActorRef,\n EventObject,\n AnyEventObject,\n Cast,\n MachineContext,\n ProvidedActor,\n StateValueFromStateSchema,\n ToChildren,\n MetaObject,\n StateSchema,\n DoNotInfer,\n RoutableStateId,\n Compute\n} from './types.ts';\nimport {\n Sources,\n DelayMapFromNames,\n InferChildren,\n InferOutput,\n SchemaOrConfigOutput,\n InferEvents,\n InferInternalEvents,\n Next_MachineConfig,\n Next_StateNodeConfig,\n ValidateDelayReferences,\n ValidateHistoryDefaults,\n ValidateStateTargets,\n ValidateTopLevelFinalOutputs,\n WidenLiterals,\n WithDefault\n} from './types.v6.ts';\n\ntype MergeChildren<\n TChildren extends Record<string, AnyActorRef | undefined>,\n TActor extends ProvidedActor\n> = [keyof TChildren] extends [never]\n ? Compute<ToChildren<TActor>>\n : Compute<TChildren>;\n\ntype MachineIdentity<TConfig> = {\n readonly id: TConfig extends { id: infer TId extends string }\n ? TId\n : '(machine)';\n readonly version: TConfig extends { version: infer TVersion extends string }\n ? TVersion\n : undefined;\n};\n\ntype TestValue =\n | string\n | {\n [k: string]: TestValue | undefined;\n };\n\ntype _GroupTestValues<TTestValue extends string | TestValue> =\n TTestValue extends string\n ? TTestValue extends `${string}.${string}`\n ? [never, never]\n : [TTestValue, never]\n : [never, TTestValue];\n\n/**\n * Creates a state machine (statechart) with the given configuration.\n *\n * The state machine represents the pure logic of a state machine actor.\n *\n * @example\n *\n * ```ts\n * import { createMachine } from 'xstate';\n *\n * const lightMachine = createMachine({\n * id: 'light',\n * initial: 'green',\n * states: {\n * green: {\n * on: {\n * TIMER: { target: 'yellow' }\n * }\n * },\n * yellow: {\n * on: {\n * TIMER: { target: 'red' }\n * }\n * },\n * red: {\n * on: {\n * TIMER: { target: 'green' }\n * }\n * }\n * }\n * });\n *\n * const lightActor = createActor(lightMachine);\n * lightActor.start();\n *\n * lightActor.send({ type: 'TIMER' });\n * ```\n *\n * @param config The state machine configuration.\n * @param options DEPRECATED: use `setup({ ... })` or `machine.provide({ ... })`\n * to provide machine sources instead.\n */\n// Overload 1: With schemas.context — context type inferred from schema\nexport function createMachine<\n TContextSchema extends StandardSchemaV1,\n const TEventSchemaMap extends Record<string, StandardSchemaV1>,\n const TInternalEventSchemaMap extends Record<string, StandardSchemaV1>,\n TEmittedSchemaMap extends Record<string, StandardSchemaV1>,\n TInputSchema extends StandardSchemaV1,\n const TOutputSchema extends StandardSchemaV1,\n TMetaSchema extends StandardSchemaV1,\n TTagSchema extends StandardSchemaV1,\n const TChildrenSchemaMap extends Record<string, StandardSchemaV1>,\n _TEvent extends EventObject,\n TActor extends ProvidedActor,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays'],\n TDelays extends string,\n TTag extends StandardSchemaV1.InferOutput<TTagSchema> & string,\n TInput,\n const TSS extends StateSchema\n>(\n config: TSS &\n ValidateDelayReferences<TSS> &\n ValidateHistoryDefaults<TSS> &\n ValidateStateTargets<TSS> &\n Next_MachineConfig<\n TContextSchema,\n TEventSchemaMap,\n TInternalEventSchemaMap,\n TEmittedSchemaMap,\n TInputSchema,\n TOutputSchema,\n TMetaSchema,\n TTagSchema,\n TChildrenSchemaMap,\n InferOutput<TContextSchema, MachineContext>,\n | InferEvents<TEventSchemaMap>\n | InferInternalEvents<TInternalEventSchemaMap>,\n Cast<\n MergeChildren<InferChildren<TChildrenSchemaMap>, TActor>,\n Record<string, AnyActorRef | undefined>\n >,\n TDelays,\n TTag,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap\n > & {\n schemas: { context: TContextSchema; children?: TChildrenSchemaMap };\n } & ValidateTopLevelFinalOutputs<\n TSS,\n InferOutput<TContextSchema, MachineContext>,\n | InferEvents<TEventSchemaMap>\n | InferInternalEvents<TInternalEventSchemaMap>\n >\n): StateMachine<\n InferOutput<TContextSchema, MachineContext>,\n | (\n | InferEvents<TEventSchemaMap>\n | InferInternalEvents<TInternalEventSchemaMap>\n )\n | ([RoutableStateId<TSS>] extends [never]\n ? never\n : {\n type: 'xstate.route';\n to: RoutableStateId<TSS>;\n }),\n Cast<\n MergeChildren<InferChildren<TChildrenSchemaMap>, TActor>,\n Record<string, AnyActorRef | undefined>\n >,\n StateValueFromStateSchema<TSS>,\n TTag & string,\n TInput,\n SchemaOrConfigOutput<TOutputSchema, TSS>,\n WithDefault<InferEvents<TEmittedSchemaMap>, AnyEventObject>,\n InferOutput<TMetaSchema, MetaObject>, // TMeta\n TSS, // TStateSchema\n TActionMap,\n TActorMap,\n TGuardMap,\n DelayMapFromNames<TDelays, TDelayMap>,\n InferInternalEvents<TInternalEventSchemaMap>\n> & {\n states: TSS;\n} & MachineIdentity<TSS>;\n\n// Overload 2: Without schemas.context — context type inferred from config.context\nexport function createMachine<\n TContext extends MachineContext = never,\n const TEventSchemaMap extends Record<string, StandardSchemaV1> = Record<\n string,\n StandardSchemaV1\n >,\n TEmittedSchemaMap extends Record<string, StandardSchemaV1> = Record<\n string,\n StandardSchemaV1\n >,\n TInputSchema extends StandardSchemaV1 = StandardSchemaV1,\n const TOutputSchema extends StandardSchemaV1 = StandardSchemaV1,\n TMetaSchema extends StandardSchemaV1 = StandardSchemaV1,\n TTagSchema extends StandardSchemaV1 = StandardSchemaV1,\n const TChildrenSchemaMap extends Record<string, StandardSchemaV1> = Record<\n string,\n StandardSchemaV1\n >,\n const TInternalEventSchemaMap extends Record<string, StandardSchemaV1> = {},\n _TEvent extends EventObject = EventObject,\n TActor extends ProvidedActor = ProvidedActor,\n TActionMap extends Sources['actions'] = Sources['actions'],\n TActorMap extends Sources['actors'] = Sources['actors'],\n TGuardMap extends Sources['guards'] = Sources['guards'],\n TDelayMap extends Sources['delays'] = Sources['delays'],\n TDelays extends string = string,\n TTag extends StandardSchemaV1.InferOutput<TTagSchema> & string =\n StandardSchemaV1.InferOutput<TTagSchema> & string,\n TInput = unknown,\n const TSS extends StateSchema = StateSchema\n>(\n config: TSS &\n ValidateDelayReferences<TSS> &\n ValidateHistoryDefaults<TSS> &\n ValidateStateTargets<TSS> &\n Next_MachineConfig<\n StandardSchemaV1,\n TEventSchemaMap,\n TInternalEventSchemaMap,\n TEmittedSchemaMap,\n TInputSchema,\n TOutputSchema,\n TMetaSchema,\n TTagSchema,\n TChildrenSchemaMap,\n WidenLiterals<TContext>,\n | InferEvents<TEventSchemaMap>\n | InferInternalEvents<TInternalEventSchemaMap>,\n Cast<\n MergeChildren<InferChildren<TChildrenSchemaMap>, TActor>,\n Record<string, AnyActorRef | undefined>\n >,\n TDelays,\n TTag,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n false\n > & {\n schemas?: { context?: never };\n // TContext inference site: the `const` state-schema inference above\n // suppresses literal widening, so context is widened explicitly via\n // WidenLiterals before being consumed by handlers and the snapshot.\n context?:\n | TContext\n | ((_: {\n spawn: any;\n actors: TActorMap;\n input: InferOutput<TInputSchema, unknown>;\n self: any;\n }) => TContext);\n } & ValidateTopLevelFinalOutputs<\n TSS,\n WidenLiterals<TContext>,\n | InferEvents<TEventSchemaMap>\n | InferInternalEvents<TInternalEventSchemaMap>\n >\n): StateMachine<\n WidenLiterals<TContext>,\n | (\n | InferEvents<TEventSchemaMap>\n | InferInternalEvents<TInternalEventSchemaMap>\n )\n | ([RoutableStateId<TSS>] extends [never]\n ? never\n : {\n type: 'xstate.route';\n to: RoutableStateId<TSS>;\n }),\n Cast<\n MergeChildren<InferChildren<TChildrenSchemaMap>, TActor>,\n Record<string, AnyActorRef | undefined>\n >,\n StateValueFromStateSchema<TSS>,\n TTag & string,\n TInput,\n SchemaOrConfigOutput<TOutputSchema, TSS>,\n WithDefault<InferEvents<TEmittedSchemaMap>, AnyEventObject>,\n InferOutput<TMetaSchema, MetaObject>, // TMeta\n TSS, // TStateSchema\n TActionMap,\n TActorMap,\n TGuardMap,\n DelayMapFromNames<TDelays, TDelayMap>,\n InferInternalEvents<TInternalEventSchemaMap>\n> & {\n states: TSS;\n} & MachineIdentity<TSS>;\n\n// Implementation\nexport function createMachine(config: any): any {\n return new StateMachine<\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any, // TEmitted\n any, // TMeta\n any, // TStateSchema\n any,\n any,\n any,\n any\n >(config) as any;\n}\n\nexport function createStateConfig<\n TContextSchema extends StandardSchemaV1,\n TEventSchema extends StandardSchemaV1,\n TEmittedSchema extends StandardSchemaV1,\n _TInputSchema extends StandardSchemaV1,\n const TOutputSchema extends StandardSchemaV1,\n TMetaSchema extends StandardSchemaV1,\n TTagSchema extends StandardSchemaV1,\n // TContext extends MachineContext,\n _TEvent extends StandardSchemaV1.InferOutput<TEventSchema> & EventObject, // TODO: consider using a stricter `EventObject` here\n _TActor extends ProvidedActor,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays'],\n TDelays extends string,\n _TTag extends StandardSchemaV1.InferOutput<TTagSchema> & string,\n _TInput,\n const TSS extends StateSchema\n>(\n config: TSS &\n Next_StateNodeConfig<\n InferOutput<TContextSchema, MachineContext>,\n DoNotInfer<StandardSchemaV1.InferOutput<TEventSchema> & EventObject>,\n DoNotInfer<TDelays>,\n DoNotInfer<StandardSchemaV1.InferOutput<TTagSchema> & string>,\n DoNotInfer<StandardSchemaV1.InferOutput<TOutputSchema>>,\n DoNotInfer<StandardSchemaV1.InferOutput<TEmittedSchema> & EventObject>,\n DoNotInfer<InferOutput<TMetaSchema, MetaObject>>,\n DoNotInfer<Record<string, AnyActorRef | undefined>>,\n DoNotInfer<TActionMap>,\n DoNotInfer<TActorMap>,\n DoNotInfer<TGuardMap>,\n DoNotInfer<TDelayMap>\n >\n): typeof config {\n return config;\n}\n","import type { MachineSnapshot } from './State.ts';\nimport type { StateMachine } from './StateMachine.ts';\nimport type { StateNode } from './StateNode.ts';\nimport { AsyncActorLogic } from './actors/promise.ts';\nimport type { Actor, ProcessingStatus } from './createActor.ts';\nimport { InspectionEvent } from './inspection.ts';\nimport { Spawner } from './spawn.ts';\nimport type {\n ActorSystemRuntime,\n AnyActorSystem,\n Clock,\n DeadLetterDetail,\n EventRejection,\n EventRejectionReason\n} from './system.ts';\n\n// this is needed to make JSDoc `@link` work properly\n// oxlint-disable-next-line no-unused-vars\nimport type { SimulatedClock } from './SimulatedClock.ts';\nimport { Sources, Next_StateNodeConfig } from './types.v6.ts';\nimport { StandardSchemaV1 } from './schema.types.ts';\nimport { builtInActions } from './actions.ts';\n\nexport type Identity<T> = { [K in keyof T]: T[K] };\n\nexport type HomomorphicPick<T, K extends keyof any> = {\n [P in keyof T as P & K]: T[P];\n};\nexport type HomomorphicOmit<T, K extends keyof any> = {\n [P in keyof T as Exclude<P, K>]: T[P];\n};\n\nexport type Invert<T extends Record<PropertyKey, PropertyKey>> = {\n [K in keyof T as T[K]]: K;\n};\n\nexport type GetParameterizedParams<T extends ParameterizedObject | undefined> =\n T extends any ? ('params' extends keyof T ? T['params'] : undefined) : never;\n\n/**\n * @remarks\n * `T | unknown` reduces to `unknown` and that can be problematic when it comes\n * to contextual typing. It especially is a problem when the union has a\n * function member, like here:\n *\n * ```ts\n * declare function test(\n * cbOrVal: ((arg: number) => unknown) | unknown\n * ): void;\n * test((arg) => {}); // oops, implicit any\n * ```\n *\n * This type can be used to avoid this problem. This union represents the same\n * value space as `unknown`.\n */\nexport type NonReducibleUnknown = {} | null | undefined;\nexport type AnyFunction = (...args: any[]) => any;\n\ntype ReturnTypeOrValue<T> = T extends AnyFunction ? ReturnType<T> : T;\n\n// https://github.com/microsoft/TypeScript/issues/23182#issuecomment-379091887\nexport type IsNever<T> = [T] extends [never] ? true : false;\nexport type IsNotNever<T> = [T] extends [never] ? false : true;\n\nexport type Compute<A> = { [K in keyof A]: A[K] } & unknown;\nexport type Prop<T, K> = K extends keyof T ? T[K] : never;\nexport type Values<T> = T[keyof T];\nexport type Elements<T> = T[keyof T & `${number}`];\nexport type Merge<M, N> = Omit<M, keyof N> & N;\nexport type IndexByProp<T extends Record<P, string>, P extends keyof T> = {\n [E in T as E[P]]: E;\n};\n\nexport type IndexByType<T extends { type: string }> = IndexByProp<T, 'type'>;\n\nexport type IsEmptyObject<T> = keyof T extends never ? true : false;\n\nexport type Equals<A1, A2> =\n (<A>() => A extends A2 ? true : false) extends <A>() => A extends A1\n ? true\n : false\n ? true\n : false;\nexport type IsAny<T> = Equals<T, any>;\nexport type Cast<A, B> = A extends B ? A : B;\n// @TODO: we can't use native `NoInfer` as we need those:\n// https://github.com/microsoft/TypeScript/pull/61092\n// https://github.com/microsoft/TypeScript/pull/61077\n// but even with those fixes native NoInfer still doesn't work - further issues have to be reproduced and fixed\nexport type DoNotInfer<T> = [T][T extends any ? 0 : any];\n/** @deprecated Use the built-in `NoInfer` type instead */\nexport type NoInfer<T> = DoNotInfer<T>;\nexport type LowInfer<T> = T & NonNullable<unknown>;\n\nexport type MetaObject = Record<string, any>;\n\nexport type Lazy<T> = () => T;\nexport type MaybeLazy<T> = T | Lazy<T>;\n\n/** The full definition of an event, with a string `type`. */\nexport type EventObject = {\n /** The type of event that is sent. */\n type: string;\n};\n\nexport type EventPayloadPattern<TEvent extends EventObject> = TEvent extends any\n ? Partial<Omit<TEvent, 'type'>>\n : never;\n\nexport interface AnyEventObject extends EventObject {\n [key: string]: any;\n}\n\nexport interface ParameterizedObject {\n type: string;\n params?: NonReducibleUnknown;\n}\n\nexport type UnifiedArg<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TEvent extends EventObject\n> = {\n context: TContext;\n event: TExpressionEvent;\n self: ActorSelf<\n MachineSnapshot<\n TContext,\n TEvent,\n Record<string, AnyActorRef | undefined>, // TODO: this should be replaced with `TChildren`\n StateValue,\n string,\n unknown,\n TODO, // TMeta\n TODO // State schema\n >,\n TEvent,\n AnyEventObject\n >;\n system: AnyActorSystem;\n} & OutputArg<TExpressionEvent>;\n\nexport type MachineContext = Record<string, any>;\n\ntype DoneEventType = 'xstate.done.actor' | 'xstate.done.state';\n\nexport type OutputArg<TEvent extends EventObject> = TEvent extends {\n type: DoneEventType;\n output: infer TOutput;\n}\n ? { output: TOutput }\n : { output: undefined };\n\nexport type ActionArgs<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TEvent extends EventObject\n> = UnifiedArg<TContext, TExpressionEvent, TEvent> & {\n children: Record<string, AnyActor>;\n};\n\nexport type InputFrom<T> =\n // Resolve the actor-logic contract first. Setup-created machines intersect\n // StateMachine with literal identity metadata; inferring StateMachine's\n // generic parameters through that intersection widens optional input.\n T extends ActorLogic<\n infer _TSnapshot,\n infer _TEvent,\n infer TInput,\n infer _TSystem,\n infer _TEmitted\n >\n ? TInput\n : T extends StateMachine<\n infer _TContext,\n infer _TEvent,\n infer _TChildren,\n infer _TStateValue,\n infer _TTag,\n infer TInput,\n infer _TOutput,\n infer _TEmitted,\n infer _TMeta,\n infer _TStateSchema,\n infer _TActionMap,\n infer _TActorMap,\n infer _TGuardMap,\n infer _TDelayMap\n >\n ? TInput\n : never;\n\nexport type OutputFrom<T> =\n T extends ActorLogic<\n infer TSnapshot,\n infer _TEvent,\n infer _TInput,\n infer _TSystem,\n infer _TEmitted\n >\n ? (TSnapshot & { status: 'done' })['output']\n : T extends ActorRef<infer TSnapshot, infer _TEvent, infer _TEmitted>\n ? (TSnapshot & { status: 'done' })['output']\n : never;\n\nexport type NoRequiredParams<T extends ParameterizedObject> = T extends any\n ? undefined extends T['params']\n ? T['type']\n : never\n : never;\n\nexport type ConditionalRequired<\n T,\n Condition extends boolean\n> = Condition extends true ? Required<T> : T;\n\nexport type WithDynamicParams<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n T extends ParameterizedObject\n> = T extends any\n ? ConditionalRequired<\n {\n type: T['type'];\n params?:\n | T['params']\n | (({\n context,\n event,\n output\n }: {\n context: TContext;\n event: TExpressionEvent;\n } & OutputArg<TExpressionEvent>) => T['params']);\n },\n undefined extends T['params'] ? false : true\n >\n : never;\n\nexport type StateKey = string | AnyMachineSnapshot;\n\nexport interface StateValueMap {\n [key: string]: StateValue | undefined;\n}\n\n/**\n * The string or object representing the state value relative to the parent\n * state node.\n *\n * @remarks\n * - For a child atomic state node, this is a string, e.g., `\"pending\"`.\n * - For complex state nodes, this is an object, e.g., `{ success:\n * \"someChildState\" }`.\n */\nexport type StateValue = string | StateValueMap;\n\nexport type TransitionTarget = SingleOrArray<string>;\n\nexport type TransitionContextPatch<TContext extends MachineContext> =\n Partial<TContext> & {\n call?: never;\n apply?: never;\n bind?: never;\n };\n\nexport type TransitionContextMapper<\n TContext extends MachineContext,\n TCurrentEvent extends EventObject,\n TEvent extends EventObject,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays'],\n _TCtx extends MachineContext = [TContext] extends [never] ? any : TContext\n> = (\n args: TransitionFunctionArgs<\n _TCtx,\n TCurrentEvent,\n TEvent,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap\n >\n) => TransitionContextPatch<_TCtx>;\n\nexport interface TransitionConfig<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TEvent extends EventObject,\n TEmitted extends EventObject,\n TMeta extends MetaObject,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays']\n> {\n actions?: never;\n /** A shallow partial event pattern that must match before guards run. */\n matches?: EventPayloadPattern<TExpressionEvent>;\n guard?: unknown;\n reenter?: boolean;\n target?: TransitionTarget | undefined;\n context?:\n | TransitionContextPatch<TContext>\n | TransitionContextMapper<\n TContext,\n TExpressionEvent,\n TEvent,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap\n >;\n to?: TransitionConfigFunction<\n TContext,\n TExpressionEvent,\n TEvent,\n TEmitted,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TMeta\n >;\n meta?: TMeta;\n description?: string;\n /** @internal Overrides transition-domain selection for compiled formats. */\n _transitionDomain?: 'internal' | 'external';\n}\n\nexport interface InitialTransitionConfig<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TEmitted extends EventObject,\n TMeta extends MetaObject,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays']\n> extends TransitionConfig<\n TContext,\n TEvent,\n TEvent,\n TEmitted,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap\n> {\n target: string;\n}\n\nexport type AnyTransitionConfig = TransitionConfig<\n any, // TContext\n any, // TExpressionEvent\n any, // TEvent\n any, // TEmitted\n any, // TMeta\n any, // TActionMap\n any, // TActorMap\n any, // TGuardMap\n any // TDelayMap\n>;\n\nexport interface InvokeDefinition<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TEmitted extends EventObject,\n TMeta extends MetaObject,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays']\n> {\n id: string;\n\n registryKey: string | undefined;\n\n logic:\n | string\n | AnyActorLogic\n | (({\n actors,\n context,\n event,\n self\n }: {\n actors: TActorMap;\n context: TContext;\n event: TEvent;\n self: AnyActorRef;\n }) => string | AnyActorLogic);\n /** The source of the actor logic to be invoked */\n src: AnyActorLogic | string;\n\n input?:\n | Mapper<TContext, TEvent, NonReducibleUnknown, TEvent>\n | NonReducibleUnknown;\n /**\n * The transition to take upon the invoked child machine reaching its final\n * top-level state.\n */\n onDone?:\n | string\n | SingleOrArray<\n TransitionConfig<\n TContext,\n DoneActorEvent<unknown>,\n TEvent,\n TEmitted,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap\n >\n >;\n /**\n * The transition to take upon the invoked child machine sending an error\n * event.\n */\n onError?:\n | string\n | SingleOrArray<\n TransitionConfig<\n TContext,\n ErrorActorEvent,\n TEvent,\n TEmitted,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap\n >\n >;\n\n onSnapshot?:\n | string\n | SingleOrArray<\n TransitionConfig<\n TContext,\n SnapshotEvent,\n TEvent,\n TEmitted,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap\n >\n >;\n /**\n * The duration (in ms) after which this invocation times out if it has not\n * completed.\n */\n timeout?: number | ((args: { context: TContext; event: TEvent }) => number);\n /** The transition to take when the invoke-level `timeout` expires. */\n onTimeout?:\n | string\n | SingleOrArray<\n TransitionConfig<\n TContext,\n ActorTimeoutEvent,\n TEvent,\n TEmitted,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap\n >\n >;\n}\n\nexport type AnyInvokeDefinition = InvokeDefinition<\n MachineContext,\n EventObject,\n EventObject,\n MetaObject,\n Sources['actions'],\n Sources['actors'],\n Sources['guards'],\n Sources['delays']\n>;\n\ntype Delay<TDelay extends string> = TDelay | number;\n\nexport type DelayedTransitions<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TEmitted extends EventObject,\n TMeta extends MetaObject,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays']\n> = {\n [K in Delay<keyof TDelayMap & string>]?:\n | string\n | SingleOrArray<\n TransitionConfig<\n TContext,\n TEvent,\n TEvent,\n TEmitted,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap\n >\n >\n | TransitionConfigFunction<\n TContext,\n TEvent,\n TEvent,\n TODO,\n any,\n any,\n any,\n any,\n any\n >;\n};\n\nexport type StateTypes =\n | 'atomic'\n | 'compound'\n | 'parallel'\n | 'final'\n | 'choice'\n | 'history'\n | ({} & string);\n\nexport type SingleOrArray<T> = readonly T[] | T;\n\nexport type StateNodesConfig<\n TContext extends MachineContext,\n TEvent extends EventObject\n> = {\n [K in string]: StateNode<TContext, TEvent>;\n};\n\nexport type TransitionConfigTarget = string | undefined;\n\nexport type TransitionConfigOrTarget<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TEvent extends EventObject,\n TEmitted extends EventObject,\n TMeta extends MetaObject,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays']\n> = SingleOrArray<\n | TransitionConfigTarget\n | TransitionConfig<\n TContext,\n TExpressionEvent,\n TEvent,\n TEmitted,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap\n >\n | TransitionConfigFunction<\n TContext,\n TExpressionEvent,\n TEvent,\n TEmitted,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap,\n TMeta\n >\n>;\n\nexport type TransitionConfigFunction<\n TContext extends MachineContext,\n TCurrentEvent extends EventObject,\n TEvent extends EventObject,\n TEmitted extends EventObject,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays'],\n TMeta extends MetaObject,\n TInput = undefined,\n _TCtx extends MachineContext = [TContext] extends [never] ? any : TContext\n> = (\n args: TransitionFunctionArgs<\n _TCtx,\n TCurrentEvent,\n TEvent,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap\n > & { input: TInput },\n enq: EnqueueObject<TEvent, TEmitted, SystemRegistry, TActorMap>\n) => {\n target?: string | string[];\n // target?: keyof TSS['states'];\n context?: TransitionContextPatch<_TCtx>;\n reenter?: boolean;\n meta?: TMeta;\n input?: Record<string, unknown>;\n} | void;\n\ntype TransitionFunctionArgs<\n TContext,\n TCurrentEvent extends EventObject,\n TEvent extends EventObject,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays']\n> = {\n context: TContext;\n event: TCurrentEvent;\n self: ActorSelf<\n MachineSnapshot<\n TContext & MachineContext,\n TEvent,\n TODO,\n TODO,\n TODO,\n TODO,\n TODO,\n TODO\n >,\n TEvent\n >;\n parent: UnknownActorRef | undefined;\n value: StateValue;\n children: Record<string, AnyActor>;\n system: AnyActorSystem;\n actions: TActionMap;\n actors: TActorMap;\n guards: TGuardMap;\n delays: TDelayMap;\n} & OutputArg<TCurrentEvent>;\n\nexport type AnyTransitionConfigFunction = TransitionConfigFunction<\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any\n>;\n\nexport type TransitionsConfig<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TEmitted extends EventObject,\n TMeta extends MetaObject,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays']\n> = {\n [K in EventDescriptor<TEvent>]?: TransitionConfigOrTarget<\n TContext,\n ExtractEvent<TEvent, K>,\n TEvent,\n TEmitted,\n TMeta,\n TActionMap,\n TActorMap,\n TGuardMap,\n TDelayMap\n >;\n};\n\ntype PartialEventDescriptor<TEventType extends string> =\n TEventType extends `${infer TLeading}.${infer TTail}`\n ? `${TLeading}.*` | `${TLeading}.${PartialEventDescriptor<TTail>}`\n : never;\n\nexport type EventDescriptor<TEvent extends EventObject> =\n | TEvent['type']\n | PartialEventDescriptor<TEvent['type']>\n | '*';\n\nexport type NormalizeDescriptor<TDescriptor extends string> =\n TDescriptor extends '*'\n ? string\n : TDescriptor extends `${infer TLeading}.*`\n ? `${TLeading}.${string}`\n : TDescriptor;\n\ntype EventTypeMatchesDescriptor<\n TEventType extends string,\n TDescriptor extends string\n> = TEventType extends NormalizeDescriptor<TDescriptor> ? true : false;\n\ntype IsInternalEventType<\n TEventType extends string,\n TDescriptors extends string\n> =\n // Descriptors that collapsed to broad `string` (an untyped machine's\n // config) cannot classify anything: without the guard they would match\n // every event type and reduce the sendable events to `never`.\n string extends TDescriptors\n ? false\n : true extends (\n TDescriptors extends any\n ? EventTypeMatchesDescriptor<TEventType, TDescriptors>\n : never\n )\n ? true\n : false;\n\ntype ExcludeInternalEvents<\n TEvent extends EventObject,\n TDescriptors extends string\n> = TEvent extends any\n ? IsInternalEventType<TEvent['type'], TDescriptors> extends true\n ? never\n : TEvent\n : never;\n\ntype InternalEventDescriptorsFromConfig<\n TEvent extends EventObject,\n TConfig\n> = TConfig extends { internalEvents?: readonly EventDescriptor<TEvent>[] }\n ? TConfig['internalEvents'] extends readonly (infer TDesc)[]\n ? Extract<TDesc, string>\n : never\n : never;\n\ntype InternalEventTypes<TInternalEvent extends EventObject> =\n TInternalEvent extends any ? TInternalEvent['type'] : never;\n\ntype SendableEventFromMachine<\n TEvent extends EventObject,\n TInternalEvent extends EventObject,\n TConfig\n> =\n IsAny<TInternalEvent> extends true\n ? TEvent\n : ExcludeInternalEvents<\n TEvent,\n | InternalEventTypes<TInternalEvent>\n | InternalEventDescriptorsFromConfig<TEvent, TConfig>\n >;\n\nexport type IsLiteralString<T extends string> = string extends T ? false : true;\n\ntype ActorsBySrc<TActor extends ProvidedActor> = {\n [A in TActor as A['src']]: A['logic'];\n};\n\ntype DistributeActors<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TActor extends ProvidedActor,\n _TAction extends ParameterizedObject,\n _TGuard extends ParameterizedObject,\n _TDelay extends string,\n TEmitted extends EventObject,\n TMeta extends MetaObject,\n TSpecificActor extends ProvidedActor\n> = TSpecificActor extends { src: infer TSrc }\n ?\n | Compute<\n {\n registryKey?: string;\n /** The source of the machine to be invoked, or the machine itself. */\n src:\n | TSrc\n | (({\n actors,\n context,\n event,\n self\n }: {\n actors: ActorsBySrc<TActor>;\n context: TContext;\n event: TEvent;\n self: AnyActorRef;\n }) => TSrc | TSpecificActor['logic']);\n\n /**\n * The unique identifier for the invoked machine. If not specified,\n * this will be the machine's own `id`, or the URL (from `src`).\n */\n id?: TSpecificActor['id'];\n\n // TODO: currently we do not enforce required inputs here\n // in a sense, we shouldn't - they could be provided within the `sources` object\n // how do we verify if the required input has been provided?\n input?:\n | Mapper<\n TContext,\n TEvent,\n InputFrom<TSpecificActor['logic']>,\n TEvent\n >\n | InputFrom<TSpecificActor['logic']>;\n /**\n * The transition to take upon the invoked child machine reaching\n * its final top-level state.\n */\n onDone?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n DoneActorEvent<OutputFrom<TSpecificActor['logic']>>,\n TEvent,\n TEmitted,\n TMeta,\n any,\n any,\n any,\n any\n >\n >;\n /**\n * The transition to take upon the invoked child machine sending an\n * error event.\n */\n onError?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n ErrorActorEvent,\n TEvent,\n TEmitted,\n TMeta,\n any,\n any,\n any,\n any\n >\n >;\n\n onSnapshot?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n SnapshotEvent<SnapshotFrom<TSpecificActor['logic']>>,\n TEvent,\n TEmitted,\n TMeta,\n any,\n any,\n any,\n any\n >\n >;\n timeout?:\n | number\n | ((args: { context: TContext; event: TEvent }) => number);\n onTimeout?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n ActorTimeoutEvent,\n TEvent,\n TEmitted,\n TMeta,\n any,\n any,\n any,\n any\n >\n >;\n } & { [K in RequiredActorOptions<TSpecificActor>]: unknown }\n >\n | {\n id?: never;\n registryKey?: string;\n src:\n | string\n | AnyActorLogic\n | (({\n actors,\n context,\n event,\n self\n }: {\n actors: ActorsBySrc<TActor>;\n context: TContext;\n event: TEvent;\n self: AnyActorRef;\n }) => string | AnyActorLogic);\n input?:\n | Mapper<TContext, TEvent, NonReducibleUnknown, TEvent>\n | NonReducibleUnknown;\n onDone?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n DoneActorEvent<unknown>,\n TEvent,\n TEmitted,\n TMeta,\n any,\n any,\n any,\n any\n >\n >;\n onError?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n ErrorActorEvent,\n TEvent,\n TEmitted,\n TMeta,\n any,\n any,\n any,\n any\n >\n >;\n\n onSnapshot?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n SnapshotEvent,\n TEvent,\n TEmitted,\n TMeta,\n any,\n any,\n any,\n any\n >\n >;\n timeout?:\n | number\n | ((args: { context: TContext; event: TEvent }) => number);\n onTimeout?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n ActorTimeoutEvent,\n TEvent,\n TEmitted,\n TMeta,\n any,\n any,\n any,\n any\n >\n >;\n }\n : never;\n\nexport type InvokeConfig<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TActor extends ProvidedActor,\n TAction extends ParameterizedObject,\n TGuard extends ParameterizedObject,\n TDelay extends string,\n TEmitted extends EventObject,\n TMeta extends MetaObject\n> =\n IsLiteralString<TActor['src']> extends true\n ? DistributeActors<\n TContext,\n TEvent,\n TActor,\n TAction,\n TGuard,\n TDelay,\n TEmitted,\n TMeta,\n TActor\n >\n : {\n /**\n * The unique identifier for the invoked machine. If not specified, this\n * will be the machine's own `id`, or the URL (from `src`).\n */\n id?: string;\n\n registryKey?: string;\n /** The source of the machine to be invoked, or the machine itself. */\n src:\n | string\n | AnyActorLogic\n | (({\n actors,\n context,\n event,\n self\n }: {\n actors: ActorsBySrc<TActor>;\n context: TContext;\n event: TEvent;\n self: AnyActorRef;\n }) => string | AnyActorLogic);\n\n input?:\n | Mapper<TContext, TEvent, NonReducibleUnknown, TEvent>\n | NonReducibleUnknown;\n /**\n * The transition to take upon the invoked child machine reaching its\n * final top-level state.\n */\n onDone?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n DoneActorEvent<unknown>,\n TEvent,\n TEmitted,\n TMeta,\n any,\n any,\n any,\n any\n >\n >;\n /**\n * The transition to take upon the invoked child machine sending an\n * error event.\n */\n onError?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n ErrorActorEvent,\n TEvent,\n TEmitted,\n TMeta,\n any,\n any,\n any,\n any\n >\n >;\n\n onSnapshot?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n SnapshotEvent,\n TEvent,\n TEmitted,\n TMeta,\n any,\n any,\n any,\n any\n >\n >;\n timeout?:\n | number\n | ((args: { context: TContext; event: TEvent }) => number);\n onTimeout?:\n | string\n | SingleOrArray<\n TransitionConfigOrTarget<\n TContext,\n ActorTimeoutEvent,\n TEvent,\n TEmitted,\n TMeta,\n any,\n any,\n any,\n any\n >\n >;\n };\n\nexport type AnyInvokeConfig = InvokeConfig<\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any // TMeta\n>;\n\nexport type AnyStateNodeConfig = Next_StateNodeConfig<\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any\n>;\n\n// Accept any StateNode instance regardless of generic parameters\n// Using a union type to handle variance issues with machine.resolveState\nexport type AnyStateNode =\n | StateNode<any, any>\n | StateNode<never, EventObject>\n | StateNode<any, EventObject>\n | StateNode<never, any>;\n\ntype LoosenMachineSnapshot<TSnapshot> =\n TSnapshot extends MachineSnapshot<any, any, any, any, any, any, any, any>\n ? Omit<TSnapshot, 'matches' | 'can'> & {\n matches(partialStateValue: StateValue): boolean;\n can(event: any): boolean;\n }\n : never;\n\nexport type AnyMachineSnapshot = LoosenMachineSnapshot<\n MachineSnapshot<any, any, any, any, any, any, any, any>\n>;\n\nexport interface AnyStateMachine extends AnyActorLogic {\n id: string;\n root: AnyStateNode;\n /** @internal */\n _hasEventlessTransitions?: boolean;\n /** @internal */\n idMap: Map<string, AnyStateNode>;\n options?: { maxIterations?: number };\n states: StateNodesConfig<any, any>;\n events: Array<EventDescriptor<any>>;\n sources: Sources;\n config: any;\n version?: string | undefined;\n schemas?: import('./types.v6.ts').AnyMachineSchemas | undefined;\n snapshotSchema: import('./machineVersion.types.ts').MachineSnapshotSchema;\n eventSchema: import('./machineVersion.types.ts').MachineEventSchema;\n provide(sources: any): AnyStateMachine;\n resolveState(config: any): any;\n /** @internal */\n _getPreInitialState(actorScope: AnyActorScope, initEvent: EventObject): any;\n getTransitionData(\n snapshot: any,\n event: any,\n actorScope: AnyActorScope,\n selectionResults?: Map<AnyTransitionDefinition, unknown>\n ): AnyTransitionDefinition[];\n /** @internal */\n _canTransition(snapshot: AnyMachineSnapshot, event: any): boolean;\n getStateNodeById(stateId: string): AnyStateNode;\n getPersistedSnapshot(snapshot: any, options?: unknown): Snapshot<unknown>;\n}\n\nexport type AnyStateConfig = StateConfig<any, AnyEventObject>;\n\nexport type DelayConfig<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject\n> = number | DelayExpr<TContext, TExpressionEvent>;\n\nexport type InitialContext<\n TContext extends MachineContext,\n TActorMap extends Sources['actors'],\n TInput,\n TEvent extends EventObject\n> = TContext | ContextFactory<TContext, TActorMap, TInput, TEvent>;\n\nexport type ContextFactory<\n TContext extends MachineContext,\n TActorMap extends Sources['actors'],\n TInput,\n TEvent extends EventObject = EventObject\n> = ({\n spawn,\n actors,\n input,\n self\n}: {\n spawn: Spawner;\n actors: TActorMap;\n input: TInput;\n self: ActorSelf<\n MachineSnapshot<\n [TContext] extends [never] ? any : TContext,\n TEvent,\n Record<string, AnyActorRef | undefined>, // TODO: this should be replaced with `TChildren`\n StateValue,\n string,\n unknown,\n TODO, // TMeta\n TODO // State schema\n >,\n TEvent,\n AnyEventObject\n >;\n}) => [TContext] extends [never] ? MachineContext : TContext;\n\nexport interface ProvidedActor {\n src: string;\n logic: UnknownActorLogic;\n id?: string | undefined; // `| undefined` is required here for compatibility with `exactOptionalPropertyTypes`, see #4613\n}\n\nexport interface SetupTypes<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildrenMap extends Record<string, string>,\n TTag extends string,\n TInput,\n TOutput,\n TEmitted extends EventObject,\n TMeta extends MetaObject\n> {\n context?: TContext;\n events?: TEvent;\n children?: TChildrenMap;\n tags?: TTag;\n input?: TInput;\n output?: TOutput;\n emitted?: TEmitted;\n meta?: TMeta;\n}\n\nexport interface MachineTypes<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TActor extends ProvidedActor,\n TAction extends ParameterizedObject,\n TGuard extends ParameterizedObject,\n TDelay extends string,\n TTag extends string,\n TInput,\n TOutput,\n TEmitted extends EventObject,\n TMeta extends MetaObject\n> extends SetupTypes<\n TContext,\n TEvent,\n // in machine types we currently don't support `TChildren`\n // and IDs can still be configured through `TActor['id']`\n never,\n TTag,\n TInput,\n TOutput,\n TEmitted,\n TMeta\n> {\n actors?: TActor;\n actions?: TAction;\n guards?: TGuard;\n delays?: TDelay;\n meta?: TMeta;\n}\n\nexport interface HistoryStateNode<\n TContext extends MachineContext\n> extends StateNode<TContext> {\n history: 'shallow' | 'deep';\n target: string | undefined;\n}\n\nexport type HistoryValue = Record<string, Array<AnyStateNode>>;\n\nexport type PersistedHistoryValue = Record<string, Array<{ id: string }>>;\n\nexport type AnyHistoryValue = HistoryValue;\n\nexport type StateFrom<\n T extends AnyStateMachine | ((...args: any[]) => AnyStateMachine)\n> = T extends AnyStateMachine\n ? StateSnapshotFromMachine<T>\n : T extends (...args: any[]) => AnyStateMachine\n ? StateSnapshotFromMachine<ReturnType<T>>\n : never;\n\nexport type StateValueFromStateSchema<T extends StateSchema> =\n StateSchema extends T\n ? StateValue\n : ToStateValue<T> extends infer TStateValue\n ? TStateValue extends StateValue\n ? TStateValue\n : StateValue\n : StateValue;\n\ntype MatchingStateValueForStateFrom<\n TStateValue extends StateValue,\n TTestStateValue extends StateValue\n> = TStateValue extends unknown\n ? TTestStateValue extends string\n ? TStateValue extends string\n ? TTestStateValue extends TStateValue\n ? TTestStateValue\n : Extract<TStateValue, TTestStateValue>\n : TStateValue extends StateValueMap\n ? TStateValue & Record<TTestStateValue, StateValue | undefined>\n : never\n : TTestStateValue extends StateValueMap\n ? TStateValue extends StateValueMap\n ? MatchingStateValueMapForStateFrom<TStateValue, TTestStateValue>\n : never\n : never\n : never;\n\ntype MatchingStateValueMapForStateFrom<\n TStateValue extends StateValueMap,\n TTestStateValue extends StateValueMap\n> = false extends {\n [K in keyof TTestStateValue & string]: K extends keyof TStateValue\n ? IsNever<\n MatchingStateValueForStateFrom<\n NonNullable<TStateValue[K]>,\n NonNullable<TTestStateValue[K]>\n >\n > extends true\n ? false\n : true\n : false;\n}[keyof TTestStateValue & string]\n ? never\n : {\n [K in keyof TStateValue]: K extends keyof TTestStateValue\n ? MatchingStateValueForStateFrom<\n NonNullable<TStateValue[K]>,\n NonNullable<TTestStateValue[K]>\n >\n : TStateValue[K];\n };\n\ntype StateSnapshotFromStateValue<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TChildren extends Record<string, AnyActorRef | undefined>,\n TStateValue extends StateValue,\n TTag extends string,\n TOutput,\n TMeta extends MetaObject,\n TStateSchema extends StateSchema,\n TAllStateValue extends StateValue = TStateValue\n> = TStateValue extends unknown\n ? Omit<\n MachineSnapshot<\n StateContextFromStateValue<TStateSchema, TContext, TStateValue>,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n TStateSchema\n >,\n 'matches'\n > & {\n matches<const TTestStateValue extends string>(\n partialStateValue: TTestStateValue,\n ...args: string extends TTestStateValue ? [never] : []\n ): this is StateSnapshotFromStateValue<\n StateContextFromStateValue<TStateSchema, TContext, TTestStateValue>,\n TEvent,\n TChildren,\n MatchingStateValueForStateFrom<TAllStateValue, TTestStateValue>,\n TTag,\n TOutput,\n TMeta,\n TStateSchema,\n TAllStateValue\n >;\n matches<const TTestStateValue extends StateValueMap>(\n partialStateValue: TTestStateValue,\n ...args: string extends keyof TTestStateValue ? [never] : []\n ): this is StateSnapshotFromStateValue<\n StateContextFromStateValue<TStateSchema, TContext, TTestStateValue>,\n TEvent,\n TChildren,\n MatchingStateValueForStateFrom<TAllStateValue, TTestStateValue>,\n TTag,\n TOutput,\n TMeta,\n TStateSchema,\n TAllStateValue\n >;\n matches(partialStateValue: StateValue): boolean;\n }\n : never;\n\ntype StateSnapshotFromMachine<T extends AnyStateMachine> =\n SnapshotFrom<T> extends MachineSnapshot<\n infer TContext,\n infer TEvent,\n infer TChildren,\n infer _TStateValue,\n infer TTag,\n infer TOutput,\n infer TMeta,\n infer TStateSchema\n >\n ? StateSnapshotFromStateValue<\n TContext,\n TEvent,\n TChildren,\n StateValueFromStateSchema<TStateSchema>,\n TTag,\n TOutput,\n TMeta,\n TStateSchema,\n StateValueFromStateSchema<TStateSchema>\n >\n : SnapshotFrom<T>;\n\nexport interface DoneActorEvent<\n TOutput = unknown,\n TId extends string = string\n> extends EventObject {\n type: 'xstate.done.actor';\n output: TOutput;\n actorId: TId;\n sessionId: string;\n}\n\nexport interface ErrorActorEvent<\n TErrorData = unknown,\n TId extends string = string\n> extends EventObject {\n type: 'xstate.error.actor';\n error: TErrorData;\n actorId: TId;\n sessionId: string;\n}\n\nexport interface ErrorPlatformEvent<\n TErrorData = unknown,\n TKind extends string = string\n> extends EventObject {\n type: `xstate.error.${TKind}`;\n error: TErrorData;\n}\n\nexport type ErrorEvent = ErrorActorEvent | ErrorPlatformEvent;\n\nexport interface SnapshotEvent<\n TSnapshot extends Snapshot<unknown> = Snapshot<unknown>\n> extends EventObject {\n type: 'xstate.snapshot.actor';\n actorId: string;\n sessionId: string;\n snapshot: TSnapshot;\n}\n\nexport interface DoneStateEvent<\n TOutput = unknown,\n TId extends string = string\n> extends EventObject {\n type: 'xstate.done.state';\n stateId: TId;\n output: TOutput;\n}\n\nexport interface AfterEvent extends EventObject {\n type: 'xstate.after';\n delay: number | string;\n stateId: string;\n}\n\nexport interface TimeoutEvent extends EventObject {\n type: 'xstate.timeout';\n stateId: string;\n}\n\nexport interface ActorTimeoutEvent extends EventObject {\n type: 'xstate.timeout.actor';\n actorId: string;\n sessionId?: string;\n}\n\nexport enum SpecialTargets {\n Internal = '#_internal'\n}\n\nexport type Mapper<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject,\n TResult,\n TEvent extends EventObject,\n _TCtx = [TContext] extends [never] ? any : TContext\n> = (\n args: {\n context: _TCtx;\n event: TExpressionEvent;\n input?: Record<string, unknown>;\n self: ActorSelf<\n MachineSnapshot<\n _TCtx & MachineContext,\n TEvent,\n Record<string, AnyActorRef>, // TODO: this should be replaced with `TChildren`\n StateValue,\n string,\n unknown,\n TODO, // TMeta\n TODO // State schema\n >,\n TEvent,\n AnyEventObject\n >;\n } & OutputArg<TExpressionEvent>\n) => TResult;\n\nexport interface TransitionDefinition<\n TContext extends MachineContext,\n TEvent extends EventObject\n> extends Omit<\n TransitionConfig<\n TContext,\n TEvent,\n TEvent,\n TODO,\n TODO,\n TODO,\n TODO,\n TODO, // TEmitted\n TODO // TMeta\n >,\n 'target' | 'to'\n> {\n target: ReadonlyArray<AnyStateNode> | undefined;\n source: AnyStateNode;\n reenter: boolean;\n eventType: EventDescriptor<TEvent>;\n /** @internal Additional runtime matching for generated transitions. */\n _eventMatcher?: (event: EventObject, snapshot: AnyMachineSnapshot) => boolean;\n to?: ((...args: any[]) => any) | undefined;\n input?:\n | Record<string, unknown>\n | ((args: {\n context: any;\n event: any;\n output: any;\n }) => Record<string, unknown>);\n}\n\nexport type AnyTransitionDefinition = TransitionDefinition<any, any>;\n\nexport type InitialTransitionDefinition = {\n source: AnyStateNode;\n target: AnyStateNode[] | undefined;\n reenter?: boolean;\n eventType?: EventDescriptor<any>;\n input?:\n | Record<string, unknown>\n | ((args: {\n context: MachineContext;\n event: EventObject;\n }) => Record<string, unknown>);\n to?: ((...args: any[]) => any) | undefined;\n};\n\nexport type TransitionDefinitionMap<\n TContext extends MachineContext,\n TEvent extends EventObject\n> = {\n [K in EventDescriptor<TEvent>]: Array<\n TransitionDefinition<TContext, ExtractEvent<TEvent, K>>\n >;\n};\n\nexport type DelayExpr<\n TContext extends MachineContext,\n TEvent extends EventObject\n> = (args: {\n context: [TContext] extends [never] ? any : TContext;\n event: TEvent;\n stateNode: AnyStateNode;\n}) => number;\n\nexport interface DelayedTransitionDefinition<\n TContext extends MachineContext,\n TEvent extends EventObject\n> extends TransitionDefinition<TContext, TEvent> {\n delay: number | string | DelayExpr<TContext, TEvent>;\n}\n\nexport interface StateLike<TContext extends MachineContext> {\n value: StateValue;\n context: TContext;\n event: EventObject;\n}\n\nexport interface StateConfig<\n TContext extends MachineContext,\n TEvent extends EventObject\n> {\n context: TContext;\n historyValue?: HistoryValue;\n /** @internal */\n _nodes: Array<AnyStateNode>;\n /** @internal */\n value?: StateValue;\n children: Record<string, AnyActorRef | undefined>;\n timers?: Record<string, LogicalTimer>;\n status: SnapshotStatus;\n output?: any;\n error?: unknown;\n /** @internal */\n _stateInputs?: Record<string, Record<string, unknown>>;\n /** @internal */\n _nextTimerId?: number;\n /**\n * Deterministic generated-child-id counters owned by this snapshot, keyed\n * by src prefix.\n *\n * @internal\n */\n _nextActorIds?: Record<string, number>;\n machine?: StateMachine<\n TContext,\n TEvent,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any\n >;\n}\n\n/** A deterministic delayed-delivery declaration owned by a logic snapshot. */\nexport interface LogicalTimer {\n id: string;\n delay: number;\n type: '@xstate.raise' | '@xstate.sendTo';\n event: EventObject;\n /** `self` or the logical actor that will receive `event`. */\n target: 'self' | AnyActor;\n /**\n * The timer's wall-clock start, stamped at persist time by a running\n * wall-clock actor and carried through restore so re-persisting keeps the\n * original deadline.\n */\n startedAt?: number;\n}\n\n/** The logical input delivered to a timer's source when its runtime delay ends. */\nexport interface TimerEvent extends EventObject {\n type: 'xstate.timer';\n id: string;\n}\n\ndeclare const persistedSnapshotLogic: unique symbol;\n\ntype PersistedSnapshotLogicIdentity<TLogic> = TLogic extends {\n readonly id: infer TId extends string;\n}\n ? {\n readonly id: TId;\n readonly version: TLogic extends {\n readonly version: infer TVersion extends string;\n }\n ? TVersion\n : string;\n }\n : never;\n\n/** A persisted snapshot tied to a versioned actor logic identity. */\nexport type PersistedSnapshotFor<TLogic> = {\n readonly [persistedSnapshotLogic]: PersistedSnapshotLogicIdentity<TLogic>;\n};\n\n/**\n * A persisted snapshot restorable into the given actor logic: any snapshot\n * created by logic with the same machine `id` is accepted, regardless of\n * version (version mismatches are handled at runtime, e.g. by `migrate`).\n */\nexport type RestorablePersistedSnapshotFor<TLogic> = {\n readonly [persistedSnapshotLogic]: TLogic extends {\n readonly id: infer TId extends string;\n }\n ? { readonly id: TId; readonly version: string }\n : never;\n};\n\nexport interface ActorOptions<TLogic extends AnyActorLogic> {\n /**\n * The clock that is responsible for setting and clearing timeouts, such as\n * delayed events and transitions.\n *\n * @remarks\n * You can create your own “clock”. The clock interface supports these\n * methods:\n *\n * - `now` - optional; returns the current time in milliseconds\n * - `setTimeout` - same arguments as `window.setTimeout(fn, timeout)`\n * - `clearTimeout` - same arguments as `window.clearTimeout(id)`\n *\n * By default, `Date.now`, native `setTimeout`, and native `clearTimeout` are\n * used.\n *\n * For testing, XState provides `SimulatedClock`.\n * @see {@link Clock}\n * @see {@link SimulatedClock}\n */\n clock?: Clock;\n /**\n * Specifies the logger to be used for `log(...)` actions. Defaults to the\n * native `console.log(...)` method.\n */\n logger?: (...args: any[]) => void;\n parent?: AnyActor;\n /** @internal */\n syncSnapshot?: boolean;\n /** @internal */\n _systemRef?: { current?: AnyActorSystem };\n /** @internal */\n _sessionId?: string;\n /** @internal */\n _inert?: boolean;\n /** The custom `id` for referencing this service. */\n id?: string;\n /** @deprecated Use `inspect` instead. */\n devTools?: never;\n\n /** The registry key to register this actor under. */\n registryKey?: string;\n /** The input data to pass to the actor. */\n input?: InputFrom<TLogic>;\n\n /**\n * Initializes actor logic from a specific persisted internal state.\n *\n * @remarks\n * If the state is compatible with the actor logic, when the actor is started\n * it will be at that persisted state. Actions from machine actors will not be\n * re-executed, because they are assumed to have been already executed.\n * However, invocations will be restarted, and spawned actors will be restored\n * recursively.\n *\n * Can be generated with {@link Actor.getPersistedSnapshot}.\n * @see https://stately.ai/docs/persistence\n */\n snapshot?: Snapshot<unknown> &\n Partial<RestorablePersistedSnapshotFor<DoNotInfer<TLogic>>>;\n\n /** @deprecated Use `snapshot` instead. */\n state?: Snapshot<unknown>;\n\n /** The source actor logic. */\n src?: string | AnyActorLogic;\n\n /**\n * A callback function or observer object which can be used to inspect actor\n * system updates.\n *\n * @remarks\n * If a callback function is provided, it can accept an inspection event\n * argument. The inspection protocol has three event types:\n *\n * - `@xstate.actor` - An actor ref was created in the system (announces actor\n * topology: identity + parent).\n * - `@xstate.transition` - An actor transitioned. Carries every facet of the\n * transition with flat, always-present fields: `event`, `snapshot`,\n * `sourceRef`, `microsteps`, executed `actions`, and `sent`/scheduled\n * events.\n * - `@xstate.deadletter` - An event could not be delivered: the target actor\n * stopped, the payload failed its declared schema, or an internal event\n * type was sent from outside its owning actor. Carries the `event`,\n * `sourceRef`, `reason`, and — for boundary rejections — `issues` and\n * `error`.\n *\n * @example\n *\n * ```ts\n * import { createMachine } from 'xstate';\n *\n * const machine = createMachine({\n * // ...\n * });\n *\n * const actor = createActor(machine, {\n * inspect: (inspectionEvent) => {\n * if (inspectionEvent.actorRef === actor) {\n * // This event is for the root actor\n * }\n *\n * if (inspectionEvent.type === '@xstate.actor') {\n * console.log(inspectionEvent.actorRef, inspectionEvent.parentRef);\n * }\n *\n * if (inspectionEvent.type === '@xstate.transition') {\n * console.log(inspectionEvent.sourceRef);\n * console.log(inspectionEvent.actorRef);\n * console.log(inspectionEvent.event);\n * console.log(inspectionEvent.snapshot);\n * // flat, always-present facets — no narrowing required\n * console.log(inspectionEvent.actions);\n * console.log(inspectionEvent.sent);\n * console.log(inspectionEvent.microsteps);\n * }\n * }\n * });\n * ```\n *\n * Alternately, an observer object (`{ next?, error?, complete? }`) can be\n * provided:\n *\n * @example\n *\n * ```ts\n * const actor = createActor(machine, {\n * inspect: {\n * next: (inspectionEvent) => {\n * if (inspectionEvent.actorRef === actor) {\n * // This event is for the root actor\n * }\n *\n * if (inspectionEvent.type === '@xstate.actor') {\n * console.log(\n * inspectionEvent.actorRef,\n * inspectionEvent.parentRef\n * );\n * }\n *\n * if (inspectionEvent.type === '@xstate.transition') {\n * console.log(inspectionEvent.sourceRef);\n * console.log(inspectionEvent.actorRef);\n * console.log(inspectionEvent.event);\n * console.log(inspectionEvent.snapshot);\n * console.log(inspectionEvent.actions);\n * console.log(inspectionEvent.sent);\n * console.log(inspectionEvent.microsteps);\n * }\n * }\n * }\n * });\n * ```\n */\n inspect?:\n | Observer<InspectionEvent>\n | ((inspectionEvent: InspectionEvent) => void);\n\n /**\n * A dead-letter hook called whenever an event is rejected at the delivery\n * boundary of this actor system — an invalid external event payload or an\n * internal event type sent from outside its owning actor. Rejected events\n * are never delivered and never error the target actor.\n *\n * Only observed when this actor is the root of its system.\n */\n onRejectedEvent?: (rejection: EventRejection) => void;\n}\n\nexport type AnyActor = ActorInstance<any, any, any, any>;\n\n/** @deprecated Use `AnyActor` instead. */\nexport type AnyInterpreter = AnyActor;\n\n// Based on RxJS types\nexport type Observer<T> = {\n next?: (value: T) => void;\n error?: (err: unknown) => void;\n complete?: () => void;\n};\n\nexport interface Subscription {\n unsubscribe(): void;\n}\n\nexport interface Readable<T> extends Subscribable<T> {\n get: () => T;\n}\n\nexport interface InteropObservable<T> {\n [Symbol.observable]: () => InteropSubscribable<T>;\n}\n\nexport interface InteropSubscribable<T> {\n subscribe(observer: Observer<T>): Subscription;\n}\n\nexport interface Subscribable<T> extends InteropSubscribable<T> {\n subscribe(observer: Observer<T>): Subscription;\n subscribe(\n next: (value: T) => void,\n error?: (error: any) => void,\n complete?: () => void\n ): Subscription;\n}\n\ntype EventDescriptorMatches<\n TEventType extends string,\n TNormalizedDescriptor\n> = TEventType extends TNormalizedDescriptor\n ? true\n : TNormalizedDescriptor extends TEventType\n ? true\n : false;\n\nexport type ExtractEvent<\n TEvent extends EventObject,\n TDescriptor extends EventDescriptor<TEvent>\n> = string extends TEvent['type']\n ? TEvent\n : NormalizeDescriptor<TDescriptor> extends infer TNormalizedDescriptor\n ? TEvent extends any\n ? // true is the check type here to match both true and boolean\n true extends EventDescriptorMatches<\n TEvent['type'],\n TNormalizedDescriptor\n >\n ? TEvent\n : never\n : never\n : never;\n\nexport interface BaseActorRef<TEvent extends EventObject> {\n send: (event: TEvent) => void;\n}\n\nexport interface ActorLike<\n TCurrent,\n TEvent extends EventObject\n> extends Subscribable<TCurrent> {\n send: (event: TEvent) => void;\n}\n\n/**\n * A consumer-facing actor handle.\n *\n * `ActorRef` describes the contract a consumer needs: which events can be sent\n * to the actor, which snapshot it publishes for observation, and which emitted\n * events can be listened to. It intentionally does not expose lifecycle control\n * or runtime internals. A concrete `Actor` satisfies this interface, so APIs\n * should accept `ActorRef` whenever they only need to send events, read\n * snapshots, or listen to emitted events.\n */\nexport interface ActorRef<\n TSnapshot extends Snapshot<unknown>,\n TEvent extends EventObject,\n TEmitted extends EventObject = EventObject,\n TSendEvent extends EventObject = TEvent\n>\n extends Subscribable<TSnapshot>, InteropObservable<TSnapshot> {\n send: (event: TSendEvent) => void;\n getSnapshot: () => TSnapshot;\n on: <TType extends TEmitted['type'] | '*'>(\n type: TType,\n handler: (\n emitted: TEmitted & (TType extends '*' ? unknown : { type: TType })\n ) => void\n ) => Subscription;\n}\n\ntype EventPayload<\n TEvent extends EventObject,\n TType extends TEvent['type']\n> = HomomorphicOmit<ExtractEvent<TEvent, TType>, 'type'>;\n\nexport type ActorTrigger<TEvent extends EventObject> = {\n [K in TEvent['type']]: {} extends EventPayload<TEvent, K>\n ? () => void\n : (payload: EventPayload<TEvent, K>) => void;\n};\n\n/**\n * Runtime-only actor capabilities.\n *\n * These members are needed by the interpreter, scheduler, inspection, and child\n * management code. Public consumer APIs should prefer `ActorRef` unless they\n * genuinely need lifecycle control such as starting, stopping, or accessing\n * system-owned runtime state.\n */\nexport interface ActorRuntime<\n TSnapshot extends Snapshot<unknown>,\n TEvent extends EventObject,\n _TEmitted extends EventObject = EventObject,\n TSendEvent extends EventObject = TEvent\n> {\n /** The unique identifier for this actor relative to its parent. */\n id: string;\n /**\n * The deterministic logical address of this actor within its system: the\n * `/`-joined path of actor ids from the root. Stable across persistence and\n * restore, unlike `sessionId`.\n */\n readonly address: string;\n /**\n * The globally unique process ID for this invocation.\n *\n * @remarks\n * This is only defined once the actor is started.\n */\n sessionId: string | undefined;\n /** @internal */\n _send: (event: TEvent) => void;\n start: () => this;\n getPersistedSnapshot: () => Snapshot<unknown>;\n stop: () => void;\n toJSON?: () => any;\n _parent?: any;\n system: any;\n /** @internal Emits the transition inspection event for `snapshot`. */\n _inspectTransition(snapshot: TSnapshot, event: EventObject): void;\n /** @internal */\n _processingStatus: ProcessingStatus;\n /** @internal */\n _isRunning: () => boolean;\n src: string | AnyActorLogic;\n /** Registry key used by the actor system receptionist. */\n registryKey?: string;\n trigger: ActorTrigger<TSendEvent>;\n select<TSelected>(\n selector: (snapshot: TSnapshot) => TSelected,\n equalityFn?: (a: TSelected, b: TSelected) => boolean\n ): Readable<TSelected>;\n}\n\n/**\n * A concrete actor instance type.\n *\n * `ActorInstance` combines the consumer `ActorRef` contract with runtime\n * lifecycle capabilities. Values returned by `createActor(...)` and\n * `spawn(...)` naturally satisfy narrower `ActorRef` contracts.\n */\nexport interface ActorInstance<\n TSnapshot extends Snapshot<unknown>,\n TEvent extends EventObject,\n TEmitted extends EventObject = EventObject,\n TSendEvent extends EventObject = TEvent\n>\n extends\n ActorRuntime<TSnapshot, TEvent, TEmitted, TSendEvent>,\n ActorRef<TSnapshot, TEvent, TEmitted, TSendEvent> {}\n\n/**\n * The actor's own full self handle.\n *\n * Internals and action/guard sources receive this shape because `self` can\n * participate in runtime-owned behavior while still being usable wherever an\n * `ActorRef` is expected.\n */\nexport type ActorSelf<\n TSnapshot extends Snapshot<unknown>,\n TEvent extends EventObject,\n TEmitted extends EventObject = EventObject,\n TSendEvent extends EventObject = TEvent\n> = ActorRuntime<TSnapshot, TEvent, TEmitted, TSendEvent> &\n ActorRef<TSnapshot, TEvent, TEmitted, TSendEvent>;\n\n// TODO: in v6, this should only accept AnyActorLogic, like ActorRefFromLogic\nexport type ActorRefFrom<T> =\n T extends StateMachine<\n infer TContext,\n infer TEvent,\n infer TChildren,\n infer TStateValue,\n infer TTag,\n infer _TInput,\n infer TOutput,\n infer TEmitted,\n infer TMeta,\n infer TConfig,\n infer _TActionMap,\n infer _TActorMap,\n infer _TGuardMap,\n infer _TDelayMap,\n infer TInternalEvent\n >\n ? ActorRef<\n MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n any //TStateSchema\n >,\n TEvent,\n TEmitted,\n SendableEventFromMachine<TEvent, TInternalEvent, TConfig>\n >\n : T extends Promise<infer U>\n ? ActorRefFrom<AsyncActorLogic<U>>\n : T extends ActorLogic<\n infer TSnapshot,\n infer TEvent,\n infer _TInput,\n infer _TSystem,\n infer TEmitted\n >\n ? ActorRef<TSnapshot, TEvent, TEmitted>\n : never;\n\nexport type SendableEventFromLogic<TLogic extends AnyActorLogic> =\n TLogic extends StateMachine<\n infer _TContext,\n infer TEvent,\n infer _TChildren,\n infer _TStateValue,\n infer _TTag,\n infer _TInput,\n infer _TOutput,\n infer _TEmitted,\n infer _TMeta,\n infer TConfig,\n infer _TActionMap,\n infer _TActorMap,\n infer _TGuardMap,\n infer _TDelayMap,\n infer TInternalEvent\n >\n ? SendableEventFromMachine<TEvent, TInternalEvent, TConfig>\n : EventFromLogic<TLogic>;\n\ntype OpaqueMachineSnapshot<TSnapshot extends Snapshot<unknown>> =\n TSnapshot extends MachineSnapshot<\n infer TContext,\n infer TEvent,\n infer TChildren,\n infer TStateValue,\n infer TTag,\n infer TOutput,\n infer TMeta,\n infer _TStateSchema\n >\n ? MachineSnapshot<\n TContext,\n TEvent,\n TChildren,\n TStateValue,\n TTag,\n TOutput,\n TMeta,\n any\n >\n : TSnapshot;\n\nexport type ActorRefFromLogic<T extends AnyActorLogic> = ActorRef<\n OpaqueMachineSnapshot<SnapshotFrom<T>>,\n EventFromLogic<T>,\n EmittedFrom<T>,\n SendableEventFromLogic<T>\n>;\n\nexport interface AnyActorRef extends Subscribable<any>, InteropObservable<any> {\n send(event: any): void;\n getSnapshot(): any;\n on(type: string, handler: (emitted: any) => void): Subscription;\n}\n\n/** The concrete actor instance type produced from actor logic. */\nexport type ActorFromLogic<T extends AnyActorLogic> = ActorInstance<\n SnapshotFrom<T>,\n EventFromLogic<T>,\n EmittedFrom<T>,\n SendableEventFromLogic<T>\n>;\n\ntype SendableEventFromActorRef<\n TActorRef,\n TFallback extends EventObject = AnyEventObject\n> = [NonNullable<TActorRef>] extends [never]\n ? TFallback\n : NonNullable<TActorRef> extends infer TNonNullableActorRef\n ? TNonNullableActorRef extends { send: (event: infer TEvent) => void }\n ? [TEvent] extends [never]\n ? TFallback\n : TEvent extends EventObject\n ? TEvent\n : TFallback\n : never\n : never;\n\nexport type ActorRefLike = Pick<AnyActor, 'sessionId' | 'send' | 'getSnapshot'>;\n\nexport type UnknownActorRef = ActorRef<Snapshot<unknown>, EventObject>;\n\nexport type DevToolsAdapter = (service: AnyActor) => void;\n\nexport type MachineSourcesFrom<\n T extends AnyStateMachine | ((...args: any[]) => AnyStateMachine)\n> =\n T extends StateMachine<\n infer _TContext,\n infer _TEvent,\n infer _TChildren,\n infer _TStateValue,\n infer _TTag,\n infer _TInput,\n infer _TOutput,\n infer _TEmitted,\n infer _TMeta,\n infer _TConfig,\n infer TActionMap,\n infer TActorMap,\n infer TGuardMap,\n infer TDelayMap\n >\n ? {\n actions: TActionMap;\n actors: TActorMap;\n guards: TGuardMap;\n delays: TDelayMap;\n }\n : never;\n\nexport interface ActorScope<\n TSnapshot extends Snapshot<unknown>,\n TEvent extends EventObject,\n TSystem extends AnyActorSystem = AnyActorSystem,\n TEmitted extends EventObject = EventObject,\n TSendEvent extends EventObject = TEvent\n> {\n self: ActorSelf<TSnapshot, TEvent, TEmitted, TSendEvent>;\n id: string;\n sessionId: string;\n logger: (...args: any[]) => void;\n defer: (fn: () => void) => void;\n emit: (event: TEmitted) => void | PromiseLike<void>;\n system: TSystem;\n stopChild: (child: AnyActor) => void;\n actionExecutor: ActionExecutor;\n}\n\nexport type AnyActorScope = ActorScope<\n any, // TSnapshot\n any, // TEvent\n AnyActorSystem,\n any, // TEmitted\n any // TSendEvent\n>;\n\nexport type SnapshotStatus = 'active' | 'done' | 'error' | 'stopped';\n\nexport type Snapshot<TOutput> =\n | {\n status: 'active';\n output: undefined;\n error: undefined;\n }\n | {\n status: 'done';\n output: TOutput;\n error: undefined;\n }\n | {\n status: 'error';\n output: undefined;\n error: unknown;\n }\n | {\n status: 'stopped';\n output: undefined;\n error: undefined;\n };\n\nexport type ActorLogicTransitionResult<\n TSnapshot extends Snapshot<unknown>,\n TEffect = ExecutableActionObject\n> = [nextSnapshot: TSnapshot, effects: TEffect[]];\n\n/**\n * Represents logic which can be used by an actor.\n *\n * @template TSnapshot - The type of the snapshot.\n * @template TEvent - The type of the event object.\n * @template TInput - The type of the input.\n * @template TSystem - The type of the actor system.\n */\nexport interface ActorLogic<\n in out TSnapshot extends Snapshot<unknown>, // it's invariant because it's also part of `ActorScope[\"self\"][\"getSnapshot\"]`\n in out TEvent extends EventObject, // it's invariant because it's also part of `ActorScope[\"self\"][\"send\"]`\n in TInput = NonReducibleUnknown,\n TSystem extends AnyActorSystem = AnyActorSystem,\n in out TEmitted extends EventObject = EventObject // it's invariant because it's also aprt of `ActorScope[\"self\"][\"on\"]`\n> {\n /** The initial setup/configuration used to create the actor logic. */\n config?: unknown;\n /** Optional runtime validator for pure calculation boundaries. */\n validator?: import('./validation.types.ts').ActorLogicValidator | undefined;\n /**\n * Transition function that processes the current state and an incoming event\n * to produce a new state and effects.\n *\n * @param snapshot - The current state.\n * @param event - The incoming event.\n * @param actorScope - The actor scope.\n * @returns A tuple of the next state and effects.\n */\n transition: (\n snapshot: TSnapshot,\n event: TEvent,\n actorScope: ActorScope<TSnapshot, TEvent, TSystem, TEmitted>\n ) => ActorLogicTransitionResult<TSnapshot>;\n /**\n * Transition function that produces the initial state and effects.\n *\n * @param actorScope - The actor scope.\n * @param input - The input for the initial state.\n * @returns A tuple of the initial state and effects.\n */\n initialTransition: (\n input: TInput,\n actorScope: ActorScope<TSnapshot, TEvent, TSystem, TEmitted>\n ) => ActorLogicTransitionResult<TSnapshot>;\n /**\n * Called to provide the initial state of the actor.\n *\n * @param actorScope - The actor scope.\n * @param input - The input for the initial state.\n * @returns The initial state.\n */\n getInitialSnapshot: (\n actorScope: ActorScope<TSnapshot, TEvent, TSystem, TEmitted>,\n input: TInput\n ) => TSnapshot;\n /**\n * Called when Actor is created to restore the internal state of the actor\n * given a persisted state. The persisted state can be created by\n * `getPersistedSnapshot`.\n *\n * @param persistedState - The persisted state to restore from.\n * @param actorScope - The actor scope.\n * @returns The restored state.\n */\n restoreSnapshot?: (\n persistedState: Snapshot<unknown>,\n actorScope: ActorScope<TSnapshot, TEvent, AnyActorSystem, TEmitted>\n ) => TSnapshot;\n /**\n * Called when the actor is started.\n *\n * @param snapshot - The starting state.\n * @param actorScope - The actor scope.\n * @param options - Start metadata, including whether the snapshot was\n * restored.\n */\n start?: (\n snapshot: TSnapshot,\n actorScope: ActorScope<TSnapshot, TEvent, AnyActorSystem, TEmitted>,\n options?: { restored: boolean }\n ) => void;\n /**\n * Obtains the internal state of the actor in a representation which can be be\n * persisted. The persisted state can be restored by `restoreSnapshot`.\n *\n * @param snapshot - The current state.\n * @returns The a representation of the internal state to be persisted.\n */\n getPersistedSnapshot: (\n snapshot: TSnapshot,\n options?: unknown\n ) => Snapshot<unknown>;\n /**\n * Returns an event that the actor should transition with to recover from an\n * execution error, or `undefined` if the given snapshot cannot handle it.\n * Actor logic without error-recovery semantics can omit this.\n */\n getExecutionErrorEvent?: (\n snapshot: TSnapshot,\n error: unknown\n ) => TEvent | undefined;\n}\n\nexport interface AnyActorLogic {\n config?: unknown;\n validator?: import('./validation.types.ts').ActorLogicValidator | undefined;\n transition(\n snapshot: any,\n event: any,\n actorScope: any\n ): ActorLogicTransitionResult<any>;\n initialTransition(\n input: any,\n actorScope: any\n ): ActorLogicTransitionResult<any>;\n getInitialSnapshot(actorScope: any, input: any): any;\n restoreSnapshot?(persistedState: Snapshot<unknown>, actorScope: any): any;\n start?(snapshot: any, actorScope: any, options?: { restored: boolean }): void;\n getPersistedSnapshot(snapshot: any, options?: unknown): Snapshot<unknown>;\n getExecutionErrorEvent?(snapshot: any, error: unknown): any;\n}\n\nexport type UnknownActorLogic = ActorLogic<\n any, // snapshot\n any, // event\n any, // input\n AnyActorSystem,\n any // emitted\n>;\n\nexport type SnapshotFrom<T> =\n ReturnTypeOrValue<T> extends infer R\n ? R extends ActorRef<infer TSnapshot, infer _, infer __>\n ? TSnapshot\n : R extends Actor<infer TLogic>\n ? SnapshotFrom<TLogic>\n : R extends ActorLogic<\n infer TSnapshot,\n infer _TEvent,\n infer _TInput,\n infer _TSystem,\n infer _TEmitted\n >\n ? TSnapshot\n : R extends ActorScope<\n infer TSnapshot,\n infer _TEvent,\n infer _TEmitted,\n infer _TSystem\n >\n ? TSnapshot\n : never\n : never;\n\nexport type EventFromLogic<TLogic extends AnyActorLogic> =\n TLogic extends ActorLogic<\n infer _TSnapshot,\n infer TEvent,\n infer _TInput,\n infer _TSystem,\n infer _TEmitted\n >\n ? TEvent\n : never;\n\nexport type EmittedFrom<TLogic extends AnyActorLogic> =\n TLogic extends StateMachine<\n infer _TContext,\n infer _TEvent,\n infer _TChildren,\n infer _TStateValue,\n infer _TTag,\n infer _TInput,\n infer _TOutput,\n infer TEmitted,\n infer _TMeta,\n infer _TStateSchema,\n infer _TActionMap,\n infer _TActorMap,\n infer _TGuardMap,\n infer _TDelayMap\n >\n ? TEmitted\n : [TLogic] extends [AnyStateMachine]\n ? AnyEventObject\n : TLogic extends ActorLogic<\n infer _TSnapshot,\n infer _TEvent,\n infer _TInput,\n infer _TSystem,\n infer TEmitted\n >\n ? TEmitted\n : AnyEventObject;\n\ntype ResolveEventType<T> = T extends infer R\n ? R extends StateMachine<\n infer _TContext,\n infer TEvent,\n infer _TChildren,\n infer _TStateValue,\n infer _TTag,\n infer _TInput,\n infer _TOutput,\n infer _TEmitted,\n infer _TMeta,\n infer _TConfig,\n infer _TActionMap,\n infer _TActorMap,\n infer _TGuardMap,\n infer _TDelayMap\n >\n ? TEvent\n : R extends MachineSnapshot<\n infer _TContext,\n infer TEvent,\n infer _TChildren,\n infer _TStateValue,\n infer _TTag,\n infer _TOutput,\n infer _TMeta,\n infer _TStateSchema\n >\n ? TEvent\n : R extends ActorRef<infer _TSnapshot, infer TEvent, infer _TEmitted>\n ? TEvent\n : never\n : never;\n\nexport type EventFrom<\n T,\n K extends Prop<TEvent, 'type'> = never,\n TEvent extends EventObject = ResolveEventType<T>\n> = IsNever<K> extends true ? TEvent : ExtractEvent<TEvent, K>;\n\nexport type ContextFrom<T> =\n T extends StateMachine<\n infer TContext,\n infer _TEvent,\n infer _TChildren,\n infer _TStateValue,\n infer _TTag,\n infer _TInput,\n infer _TOutput,\n infer _TEmitted,\n infer _TMeta,\n infer _TConfig,\n infer _TActionMap,\n infer _TActorMap,\n infer _TGuardMap,\n infer _TDelayMap\n >\n ? TContext\n : T extends MachineSnapshot<\n infer TContext,\n infer _TEvent,\n infer _TChildren,\n infer _TStateValue,\n infer _TTag,\n infer _TOutput,\n infer _TMeta,\n infer _TStateSchema\n >\n ? TContext\n : T extends Actor<infer TActorLogic>\n ? TActorLogic extends AnyStateMachine\n ? ContextFrom<TActorLogic>\n : never\n : never;\n\nexport type InferEvent<E extends EventObject> = {\n [T in E['type']]: { type: T } & Extract<E, { type: T }>;\n}[E['type']];\n\nexport type TODO = any;\n\nexport type StateValueFrom<TMachine extends AnyStateMachine> = Parameters<\n StateFrom<TMachine>['matches']\n>[0];\n\nexport type TagsFrom<TMachine extends AnyStateMachine> = Parameters<\n StateFrom<TMachine>['hasTag']\n>[0];\n\nexport interface ActorSystemInfo {\n actors: Record<string, AnyActorRef>;\n}\n\nexport type SystemRegistry = Record<string, AnyActorLogic>;\n\nexport type RegistryKeyForLogic<\n TLogic extends AnyActorLogic,\n TSystemRegistry extends SystemRegistry\n> = string extends keyof TSystemRegistry\n ? string\n : Values<{\n [K in keyof TSystemRegistry &\n string]: ActorRefFromLogic<TLogic> extends ActorRefFromLogic<\n TSystemRegistry[K]\n >\n ? K\n : never;\n }>;\n\nexport type RequiredActorOptions<TActor extends ProvidedActor> =\n | (undefined extends TActor['id'] ? never : 'id')\n | (undefined extends InputFrom<TActor['logic']> ? never : 'input');\n\nexport type RequiredLogicInput<TLogic extends AnyActorLogic> =\n undefined extends InputFrom<TLogic> ? never : 'input';\n\ntype ExtractLiteralString<T extends string | undefined> = T extends string\n ? string extends T\n ? never\n : T\n : never;\n\ntype ToConcreteChildren<TActor extends ProvidedActor> = {\n [A in TActor as ExtractLiteralString<A['id']>]?: ActorFromLogic<A['logic']>;\n};\n\n// Actors that don't have literal string IDs — these are the only ones\n// that should appear in the index signature fallback, since actors with\n// literal IDs are already covered by ToConcreteChildren.\ntype NonConcreteActors<TActor extends ProvidedActor> = TActor extends any\n ? ExtractLiteralString<TActor['id']> extends never\n ? TActor\n : never\n : never;\n\nexport type ToChildren<TActor extends ProvidedActor> =\n // only proceed further if all configured `src`s are literal strings\n string extends TActor['src']\n ? // TODO: replace `AnyActorRef` with `UnknownActorRef`~\n // or maybe even `TActor[\"logic\"]` since it's possible to configure `{ src: string; logic: SomeConcreteLogic }`\n // TODO: consider adding `| undefined` here\n Record<string, AnyActor>\n : Compute<\n ToConcreteChildren<TActor> &\n {\n include: {\n [id: string]: NonConcreteActors<TActor> extends never\n ? AnyActor | undefined\n : NonConcreteActors<TActor> extends any\n ?\n | ActorFromLogic<NonConcreteActors<TActor>['logic']>\n | undefined\n : never;\n };\n exclude: unknown;\n }[NonConcreteActors<TActor> extends never ? 'exclude' : 'include']\n >;\n\nexport type StateSchema = {\n id?: string;\n route?: unknown;\n states?: Record<string, StateSchema>;\n contextSchema?: StandardSchemaV1;\n outputSchema?: StandardSchemaV1;\n input?: unknown;\n initial?: unknown;\n\n // Other types\n // Needed because TS treats objects with all optional properties as a \"weak\" object\n // https://github.com/statelyai/xstate/issues/5031\n type?: unknown;\n history?: unknown;\n target?: unknown;\n invoke?: unknown;\n on?: unknown;\n entry?: unknown;\n exit?: unknown;\n onDone?: unknown;\n onError?: unknown;\n timeout?: unknown;\n onTimeout?: unknown;\n after?: unknown;\n always?: unknown;\n choice?: unknown;\n meta?: unknown;\n output?: unknown;\n tags?: unknown;\n description?: unknown;\n};\n\nexport type StateSchemaFrom<T extends AnyStateMachine> =\n T extends StateMachine<\n infer _TContext,\n infer _TEvent,\n infer _TChildren,\n infer _TStateValue,\n infer _TTag,\n infer _TInput,\n infer _TOutput,\n infer _TEmitted,\n infer _TMeta,\n infer TStateSchema,\n infer _TActionMap,\n infer _TActorMap,\n infer _TGuardMap,\n infer _TDelayMap\n >\n ? TStateSchema\n : never;\n\nexport type StateId<\n TSchema extends StateSchema,\n TKey extends string = '(machine)',\n TParentKey extends string | null = null\n> =\n | (TSchema extends { id: string }\n ? TSchema['id']\n : TParentKey extends null\n ? TKey\n : `${TParentKey}.${TKey}`)\n | (TSchema['states'] extends Record<string, any>\n ? Values<{\n [K in keyof TSchema['states'] & string]: StateId<\n TSchema['states'][K],\n K,\n TParentKey extends string\n ? `${TParentKey}.${TKey}`\n : TSchema['id'] extends string\n ? TSchema['id']\n : TKey\n >;\n }>\n : never);\n\n/** Maps state IDs to their input types based on the StateSchema. */\nexport type StateIdInputs<\n TSchema extends StateSchema,\n TKey extends string = '(machine)',\n TParentKey extends string | null = null\n> = {\n [K in TSchema extends { id: string }\n ? TSchema['id']\n : TParentKey extends null\n ? TKey\n : `${TParentKey}.${TKey}`]: TSchema['input'] extends undefined\n ? undefined\n : TSchema['input'];\n} & (TSchema['states'] extends Record<string, StateSchema>\n ? UnionToIntersection<\n Values<{\n [K in keyof TSchema['states'] & string]: StateIdInputs<\n TSchema['states'][K],\n K,\n TParentKey extends string\n ? `${TParentKey}.${TKey}`\n : TSchema['id'] extends string\n ? TSchema['id']\n : TKey\n >;\n }>\n >\n : {});\n\ntype UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (\n k: infer I\n) => void\n ? I\n : never;\n\ntype ContextFromStateSchema<\n TSchema extends StateSchema,\n TFallbackContext extends MachineContext\n> = TSchema['contextSchema'] extends StandardSchemaV1\n ? StandardSchemaV1.InferOutput<TSchema['contextSchema']> &\n TFallbackContext &\n MachineContext\n : TFallbackContext;\n\ntype ContextFromChildStateValue<\n TChildSchema extends StateSchema,\n TFallbackContext extends MachineContext,\n TChildValue\n> = ContextFromStateSchema<TChildSchema, TFallbackContext> &\n StateContextFromStateValue<\n TChildSchema,\n ContextFromStateSchema<TChildSchema, TFallbackContext>,\n TChildValue\n >;\n\nexport type StateContextFromStateValue<\n TSchema extends StateSchema,\n TFallbackContext extends MachineContext,\n TStateValue\n> = (TSchema['states'] extends Record<string, StateSchema>\n ? TStateValue extends keyof TSchema['states'] & string\n ? ContextFromStateSchema<TSchema['states'][TStateValue], TFallbackContext>\n : TStateValue extends Record<string, unknown>\n ? UnionToIntersection<\n Values<{\n [K in keyof TStateValue &\n keyof TSchema['states'] &\n string]: ContextFromChildStateValue<\n TSchema['states'][K],\n TFallbackContext,\n NonNullable<TStateValue[K]>\n >;\n }>\n >\n : TFallbackContext\n : TFallbackContext) &\n MachineContext;\n\nexport type RoutableStateId<TSchema extends StateSchema> =\n | (TSchema extends { route: any; id: string } ? `#${TSchema['id']}` : never)\n | (TSchema['states'] extends Record<string, any>\n ? Values<{\n [K in keyof TSchema['states'] & string]: RoutableStateId<\n TSchema['states'][K]\n >;\n }>\n : never);\n\nexport interface StateMachineTypes {\n context: MachineContext;\n events: EventObject;\n actors: ProvidedActor;\n actions: ParameterizedObject;\n guards: ParameterizedObject;\n delays: string;\n tags: string;\n emitted: EventObject;\n}\n\n/** @deprecated */\nexport interface ResolvedStateMachineTypes<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TActor extends ProvidedActor,\n TAction extends ParameterizedObject,\n TGuard extends ParameterizedObject,\n TDelay extends string,\n TTag extends string,\n TEmitted extends EventObject = EventObject\n> {\n context: TContext;\n events: TEvent;\n actors: TActor;\n actions: TAction;\n guards: TGuard;\n delays: TDelay;\n tags: TTag;\n emitted: TEmitted;\n}\n\nexport type GetConcreteByKey<\n T,\n TKey extends keyof T,\n TValue extends T[TKey]\n> = T & Record<TKey, TValue>;\n\ntype _GroupStateKeys<\n T extends StateSchema,\n S extends keyof T['states']\n> = S extends any\n ? T['states'][S] extends { type: 'history' }\n ? [never, never]\n : T extends { type: 'parallel' }\n ? [S, never]\n : T['states'][S] extends { states: Record<string, StateSchema> }\n ? [S, never]\n : [never, S]\n : never;\n\ntype GroupStateKeys<T extends StateSchema, S extends keyof T['states']> = {\n nonLeaf: _GroupStateKeys<T, S & string>[0];\n leaf: _GroupStateKeys<T, S & string>[1];\n};\n\nexport type ToStateValue<T extends StateSchema> = T extends {\n states: Record<infer S, any>;\n}\n ? IsNever<S> extends true\n ? {}\n :\n | GroupStateKeys<T, S>['leaf']\n | (IsNever<GroupStateKeys<T, S>['nonLeaf']> extends false\n ? T extends { type: 'parallel' }\n ? {\n [K in GroupStateKeys<T, S>['nonLeaf']]: ToStateValue<\n T['states'][K]\n >;\n }\n : Compute<\n Values<{\n [K in GroupStateKeys<T, S>['nonLeaf']]: {\n [StateKey in K]: ToStateValue<T['states'][K]>;\n };\n }>\n >\n : never)\n : {};\n\nexport interface BaseExecutableActionObject {\n params: NonReducibleUnknown;\n args: unknown[];\n exec(\n runtime?: Partial<ActorSystemRuntime>\n ): void | PromiseLike<void> | undefined;\n}\n\n/** The terminal result published when an actor completes or errors. */\nexport type ActorTermination =\n | { status: 'done'; output: unknown; error: undefined }\n | { status: 'error'; output: undefined; error: unknown };\n\nexport interface CustomExecutableActionObject<\n TType extends string = string & {}\n> extends BaseExecutableActionObject {\n kind: 'action';\n type: TType;\n action: ((...args: any[]) => void | PromiseLike<void>) | undefined;\n}\n\nexport interface EmitExecutableActionObject<\n TType extends string = string & {}\n> extends BaseExecutableActionObject {\n kind: 'emit';\n type: TType;\n source: AnyActor;\n event: EventObject & { type: TType };\n}\n\nexport interface SpawnExecutableActionObject extends BaseExecutableActionObject {\n kind: 'builtin';\n type: '@xstate.spawn';\n source: AnyActor | undefined;\n actor: AnyActor;\n id: string;\n logic: AnyActorLogic;\n src: string | AnyActorLogic;\n input: unknown;\n args: Parameters<(typeof builtInActions)['@xstate.spawn']>;\n}\n\nexport interface StartExecutableActionObject extends BaseExecutableActionObject {\n kind: 'builtin';\n type: '@xstate.start';\n source: AnyActor | undefined;\n actor: AnyActor;\n id: string;\n args: Parameters<(typeof builtInActions)['@xstate.start']>;\n}\n\nexport interface RaiseExecutableActionObject extends BaseExecutableActionObject {\n kind: 'builtin';\n type: '@xstate.raise';\n source: AnyActor;\n event: EventObject;\n id: string | undefined;\n delay: number | undefined;\n args: Parameters<(typeof builtInActions)['@xstate.raise']>;\n}\n\nexport interface SendToExecutableActionObject extends BaseExecutableActionObject {\n kind: 'builtin';\n type: '@xstate.sendTo';\n source: AnyActor;\n target: AnyActor;\n event: EventObject;\n id: string | undefined;\n delay: number | undefined;\n args: Parameters<(typeof builtInActions)['@xstate.sendTo']>;\n}\n\nexport interface CancelExecutableActionObject extends BaseExecutableActionObject {\n kind: 'builtin';\n type: '@xstate.cancel';\n source: AnyActor;\n id: string;\n args: Parameters<(typeof builtInActions)['@xstate.cancel']>;\n}\n\nexport interface StopExecutableActionObject extends BaseExecutableActionObject {\n kind: 'builtin';\n type: '@xstate.stop';\n source: AnyActor;\n actor: AnyActor;\n id: string;\n args: Parameters<(typeof builtInActions)['@xstate.stop']>;\n}\n\n/** An executable effect that publishes an actor's terminal result. */\nexport type TerminateExecutableActionObject = BaseExecutableActionObject & {\n kind: 'builtin';\n type: '@xstate.terminate';\n source: AnyActor;\n actor: AnyActor;\n id: string;\n args: Parameters<(typeof builtInActions)['@xstate.terminate']>;\n} & ActorTermination;\n\n/**\n * An executable effect that reports an event rejected at the delivery boundary\n * (a dead letter). The snapshot paired with this effect is unchanged.\n */\nexport interface DeadLetterExecutableActionObject extends BaseExecutableActionObject {\n kind: 'builtin';\n type: '@xstate.deadLetter';\n /** The actor that sent the event, or `undefined` for an external send. */\n source: AnyActor | undefined;\n /** The actor that rejected the event. */\n target: AnyActor;\n /** The rejected event. */\n event: AnyEventObject;\n /** Why the event was rejected, such as `'invalidEvent'`. */\n reason: EventRejectionReason;\n detail?: DeadLetterDetail;\n args: [];\n}\n\nexport type BuiltInExecutableActionObject = Values<{\n '@xstate.spawn': SpawnExecutableActionObject;\n '@xstate.start': StartExecutableActionObject;\n '@xstate.raise': RaiseExecutableActionObject;\n '@xstate.sendTo': SendToExecutableActionObject;\n '@xstate.cancel': CancelExecutableActionObject;\n '@xstate.stop': StopExecutableActionObject;\n '@xstate.terminate': TerminateExecutableActionObject;\n '@xstate.deadLetter': DeadLetterExecutableActionObject;\n}>;\n\nexport type SpecialExecutableAction = BuiltInExecutableActionObject;\n\ntype TransitionExecutableActionObject<TType extends string = never> =\n | BuiltInExecutableActionObject\n | EmitExecutableActionObject\n | CustomExecutableActionObject<TType | (string & {})>;\n\ntype KnownSourceKeys<TSourceMap> = string extends keyof TSourceMap\n ? never\n : Extract<keyof TSourceMap, string>;\n\nexport type ExecutableActionObjectFromLogic<T extends AnyActorLogic> =\n T extends StateMachine<\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n infer TActionMap,\n any,\n any,\n any\n >\n ? TransitionExecutableActionObject<KnownSourceKeys<TActionMap>>\n : ExecutableActionObject;\n\nexport type ExecutableActionObject<TType extends string = string & {}> =\n | BuiltInExecutableActionObject\n | EmitExecutableActionObject\n | CustomExecutableActionObject<TType>;\n\nexport interface ToExecutableAction<\n T extends ParameterizedObject\n> extends CustomExecutableActionObject<T['type']> {\n type: T['type'];\n params: T['params'];\n action: undefined;\n}\n\nexport type ActionExecutor = (actionToExecute: ExecutableActionObject) => void;\n\n/** Mappers for subscribeTo - maps lifecycle events to machine events */\nexport interface SubscribeToMappers<\n TSnapshot extends Snapshot<unknown>,\n TOutput,\n TMappedEvent extends EventObject\n> {\n snapshot?: (snapshot: TSnapshot) => TMappedEvent;\n done?: (output: TOutput) => TMappedEvent;\n error?: (error: unknown) => TMappedEvent;\n}\n\ntype EnqueueSpawnOptions<\n TLogic extends AnyActorLogic,\n TSystemRegistry extends SystemRegistry\n> = {\n input?: InputFrom<TLogic>;\n id?: string;\n syncSnapshot?: boolean;\n registryKey?: RegistryKeyForLogic<TLogic, TSystemRegistry>;\n};\n\ntype EnqueueSpawnArgs<\n TLogic extends AnyActorLogic,\n TSystemRegistry extends SystemRegistry\n> = ConditionalRequired<\n [\n options?: EnqueueSpawnOptions<TLogic, TSystemRegistry> & {\n [K in RequiredLogicInput<TLogic>]: unknown;\n }\n ],\n IsNotNever<RequiredLogicInput<TLogic>>\n>;\n\ntype EnqueueSpawner<\n TActorMap extends Sources['actors'],\n TSystemRegistry extends SystemRegistry\n> = {\n <TSource extends keyof TActorMap & string>(\n src: TSource,\n ...[options]: EnqueueSpawnArgs<TActorMap[TSource], TSystemRegistry>\n ): ActorFromLogic<TActorMap[TSource]>;\n <TLogic extends AnyActorLogic>(\n logic: TLogic,\n ...[options]: EnqueueSpawnArgs<TLogic, TSystemRegistry>\n ): ActorFromLogic<TLogic>;\n};\n\nexport type EnqueueObject<\n TEvent extends EventObject,\n TEmittedEvent extends EventObject,\n TSystemRegistry extends SystemRegistry = SystemRegistry,\n TActorMap extends Sources['actors'] = Sources['actors']\n> = {\n cancel: (id: string) => void;\n raise: (ev: TEvent, options?: { id?: string; delay?: number }) => void;\n /**\n * Spawns a child actor from a registered source key or logic. Without an\n * explicit `id`, the child gets a deterministic src-keyed id (`worker:0`,\n * `worker:1`, …) allocated from the parent snapshot's own counters, so ids\n * replay identically and persist with the parent.\n */\n spawn: EnqueueSpawner<TActorMap, TSystemRegistry>;\n emit: (emittedEvent: TEmittedEvent) => void;\n <T extends (...args: any[]) => any>(fn: T, ...args: Parameters<T>): void;\n log: (...args: any[]) => void;\n sendTo: <TActorRef extends { send: (...args: any[]) => void } | undefined>(\n actorRef: TActorRef,\n event: SendableEventFromActorRef<NoInfer<TActorRef>>,\n options?: { id?: string; delay?: number }\n ) => void;\n stop: (actor?: AnyActorRef) => void;\n /**\n * Listen to emitted events from an actor. Returns a listener actor that can\n * be stopped via `enq.stop()`.\n *\n * @param actor - The actor to listen to\n * @param eventType - The emitted event type to listen for (supports\n * wildcards: 'event._', '_')\n * @param mapper - Function to transform emitted events into machine events\n */\n listen: <TEmitted extends EventObject, TMappedEvent extends TEvent>(\n actor: AnyActorRef,\n eventType: string,\n mapper: (event: TEmitted) => TMappedEvent\n ) => AnyActor;\n /**\n * Subscribe to lifecycle events (done/error/snapshot) from an actor. Returns\n * a subscription actor that can be stopped via `enq.stop()`.\n *\n * @param actor - The actor to subscribe to\n * @param mappers - Object with done/error/snapshot mappers, or a single\n * snapshot mapper function\n */\n subscribeTo: <TActor extends AnyActorRef, TMappedEvent extends TEvent>(\n actor: TActor,\n mappers:\n | SubscribeToMappers<\n SnapshotFrom<TActor>,\n OutputFrom<TActor>,\n TMappedEvent\n >\n | ((snapshot: SnapshotFrom<TActor>) => TMappedEvent)\n ) => AnyActor;\n};\n\nexport type Action<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TEmittedEvent extends EventObject,\n TActionMap extends Sources['actions'],\n TActorMap extends Sources['actors'],\n TGuardMap extends Sources['guards'],\n TDelayMap extends Sources['delays'],\n TParams = Record<string, unknown> | undefined,\n _TCtx = [TContext] extends [never] ? any : TContext\n> = (\n _: {\n context: _TCtx;\n event: TEvent;\n parent: AnyActorRef | undefined;\n self: ActorSelf<\n MachineSnapshot<\n _TCtx & MachineContext,\n TEvent,\n TODO,\n TODO,\n TODO,\n TODO,\n TODO,\n TODO\n >,\n TEvent\n >;\n children: Record<string, AnyActor | undefined>;\n actions: TActionMap;\n actors: TActorMap;\n guards: TGuardMap;\n delays: TDelayMap;\n system?: AnyActorSystem;\n params: TParams;\n },\n enqueue: EnqueueObject<TEvent, TEmittedEvent, SystemRegistry, TActorMap>\n) => {\n context?: Partial<_TCtx>;\n children?: Record<string, AnyActor | undefined>;\n} | void;\n\nexport type AnyAction =\n | Action<\n MachineContext,\n EventObject,\n EventObject,\n Sources['actions'],\n Sources['actors'],\n Sources['guards'],\n Sources['delays']\n >\n | { action: (...args: any[]) => any; args: any[] }\n | AnyEventObject;\n","/**\n * SCXML machine creation and conversion utilities for the `xstate/scxml`\n * entry point. Only createMachineFromSCXML and SCXMLConversionOptions are\n * public; the compiler representation remains internal.\n */\nimport { SaxesParser } from 'saxes';\nimport {\n ActionJSON,\n CancelJSON,\n GuardJSON,\n InvokeJSON,\n ScxmlIR,\n RaiseJSON,\n ScxmlCancelJSON,\n ScxmlContentJSON,\n ScxmlDataJSON,\n ScxmlDonedataJSON,\n ScxmlForeachJSON,\n ScxmlLogJSON,\n ScxmlRaiseJSON,\n ScxmlXmlJSON,\n StateNodeJSON,\n TransitionJSON,\n createMachineFromSCXMLConfig\n} from './runtime.ts';\nimport { parseDelayToMilliseconds } from '../delay.ts';\nimport { AnyStateMachine, SpecialTargets } from '../types.ts';\n\ninterface XMLElement {\n type?: 'element' | 'text' | 'cdata' | 'comment';\n name?: string;\n attributes?: Record<string, string>;\n elements?: XMLElement[];\n text?: string;\n cdata?: string;\n}\n\nfunction parseXml(xml: string): XMLElement {\n const root: XMLElement = { elements: [] };\n const stack = [root];\n const append = (element: XMLElement) =>\n stack[stack.length - 1].elements!.push(element);\n const parser = new SaxesParser();\n\n parser.on('opentag', (tag) => {\n const attributes = { ...tag.attributes };\n const element: XMLElement = {\n type: 'element',\n name: tag.name,\n ...(Object.keys(attributes).length ? { attributes } : undefined),\n elements: []\n };\n append(element);\n stack.push(element);\n });\n parser.on('closetag', () => {\n const element = stack.pop()!;\n if (!element.elements?.length) {\n delete element.elements;\n }\n });\n parser.on('text', (text) => {\n if (text.trim()) append({ type: 'text', text });\n });\n parser.on('cdata', (cdata) => append({ type: 'cdata', cdata }));\n parser.on('comment', (text) => append({ type: 'comment', text }));\n parser.write(xml).close();\n return root;\n}\n\nexport function sanitizeStateId(id: string) {\n return id.replace(/\\./g, '$');\n}\n\nexport interface SCXMLConversionOptions {\n resolveResource?: (src: string, kind: 'data' | 'script' | 'invoke') => string;\n}\n\nfunction normalizeElementNames(element: XMLElement): XMLElement {\n if (element.name?.includes(':')) {\n element.name = element.name.slice(element.name.lastIndexOf(':') + 1);\n }\n for (const child of element.elements ?? []) {\n normalizeElementNames(child);\n }\n return element;\n}\n\nfunction resolveResource(\n options: SCXMLConversionOptions,\n src: string,\n kind: 'data' | 'script' | 'invoke'\n): string {\n if (!options.resolveResource) {\n throw new Error(`No SCXML resource resolver provided for ${kind}: ${src}`);\n }\n return options.resolveResource(src, kind);\n}\n\nfunction getAttribute(\n element: XMLElement,\n attribute: string\n): string | number | undefined {\n return element.attributes ? element.attributes[attribute] : undefined;\n}\n\nfunction toScxmlXmlJSON(element: XMLElement): ScxmlXmlJSON {\n return {\n name: element.name!,\n ...(element.attributes\n ? {\n attributes: Object.fromEntries(\n Object.entries(element.attributes).map(([key, value]) => [\n key,\n String(value)\n ])\n )\n }\n : undefined),\n ...((element.elements ?? []).some((child) => child.name)\n ? {\n children: (element.elements ?? [])\n .filter((child) => child.name)\n .map(toScxmlXmlJSON)\n }\n : undefined)\n };\n}\n\nfunction getContentDescriptor(element: XMLElement): ScxmlContentJSON {\n if (element.attributes?.expr !== undefined) {\n return { expr: String(element.attributes.expr) };\n }\n const xml = element.elements?.find((child) => child.name);\n if (xml) {\n return { xml: toScxmlXmlJSON(xml) };\n }\n return {\n text: (element.elements ?? [])\n .filter((child) => child.type === 'text' || child.type === 'cdata')\n .map((child) => String(child.text ?? child.cdata ?? ''))\n .join('')\n };\n}\n\nfunction delayToMs(delay?: string | number): number | undefined {\n if (!delay) {\n return undefined;\n }\n\n const parsedDelay = parseDelayToMilliseconds(delay);\n if (parsedDelay !== undefined) {\n return parsedDelay;\n }\n\n throw new Error(`Can't parse \"${delay} delay.\"`);\n}\n\nfunction getTargets(targetAttr?: string | number): string[] | undefined {\n return targetAttr\n ? `${targetAttr}`\n .split(/\\s+/)\n .map((target) => `#${sanitizeStateId(target)}`)\n : undefined;\n}\n\nfunction normalizeScxmlEventType(eventType: string): string {\n return /^error(\\.|$)/.test(eventType) ? `xstate.${eventType}` : eventType;\n}\n\ninterface ScxmlIfBranch {\n cond?: string;\n actions: ActionJSON[];\n}\n\nfunction parseIfElement(\n element: XMLElement,\n options: SCXMLConversionOptions\n): ActionJSON {\n const branches: ScxmlIfBranch[] = [];\n let currentCond: string | undefined = element.attributes?.cond as string;\n let currentActions: ActionJSON[] = [];\n\n if (element.elements) {\n for (const child of element.elements) {\n if (child.type === 'comment') continue;\n if (child.name === 'elseif') {\n branches.push({ cond: currentCond, actions: currentActions });\n currentCond = child.attributes?.cond as string;\n currentActions = [];\n } else if (child.name === 'else') {\n branches.push({ cond: currentCond, actions: currentActions });\n currentCond = undefined; // else has no condition\n currentActions = [];\n } else {\n currentActions.push(mapAction(child, options));\n }\n }\n }\n // Push the last branch\n branches.push({ cond: currentCond, actions: currentActions });\n\n return {\n type: 'scxml.if',\n branches\n } as any;\n}\n\nfunction mapAction(\n element: XMLElement,\n options: SCXMLConversionOptions\n): ActionJSON {\n switch (element.name) {\n case 'raise': {\n const action: RaiseJSON = {\n type: '@xstate.raise',\n event: {\n type: normalizeScxmlEventType(element.attributes!.event as string)\n }\n };\n return action;\n }\n case 'assign': {\n // SCXML assign uses location and expr attributes\n const location = element.attributes!.location as string;\n const expr =\n element.attributes?.expr !== undefined\n ? String(element.attributes.expr)\n : JSON.stringify(\n toScxmlXmlJSON(element.elements!.find((child) => child.name)!)\n );\n return {\n type: 'scxml.assign' as const,\n location,\n expr\n };\n }\n case 'cancel': {\n if ('sendid' in element.attributes!) {\n const action: CancelJSON = {\n type: '@xstate.cancel',\n id: element.attributes.sendid as string\n };\n return action;\n }\n if ('sendidexpr' in element.attributes!) {\n return {\n type: 'scxml.cancel',\n sendidexpr: element.attributes.sendidexpr as string\n } as ScxmlCancelJSON;\n }\n return {\n type: '@xstate.cancel',\n id: ''\n };\n }\n case 'send': {\n const {\n event,\n eventexpr,\n target,\n targetexpr,\n id,\n idlocation,\n delay,\n delayexpr,\n namelist,\n type\n } = element.attributes!;\n\n // Extract params from child elements\n const params: Array<{\n name: string;\n expr?: string;\n location?: string;\n }> = [];\n let content: ScxmlContentJSON | undefined;\n if (element.elements) {\n for (const child of element.elements) {\n if (child.name === 'param') {\n params.push({\n name: child.attributes!.name as string,\n ...(child.attributes!.expr !== undefined\n ? { expr: child.attributes!.expr as string }\n : { location: child.attributes!.location as string })\n });\n } else if (child.name === 'content') {\n content = getContentDescriptor(child);\n }\n }\n }\n\n const isInternal = target === String(SpecialTargets.Internal);\n const resolvedDelay = delay ? delayToMs(delay) : undefined;\n\n // Any send with a special target (except internal), params, or expressions\n // uses ScxmlRaiseJSON. Target resolution happens at runtime in executeActions.\n const hasNonInternalTarget =\n typeof target === 'string' && target.length > 0 && !isInternal;\n if (\n hasNonInternalTarget ||\n params.length ||\n eventexpr ||\n delayexpr ||\n targetexpr ||\n namelist ||\n content ||\n idlocation ||\n type\n ) {\n const action: ScxmlRaiseJSON = {\n type: 'scxml.raise',\n event:\n typeof event === 'string'\n ? normalizeScxmlEventType(event)\n : undefined,\n eventexpr: eventexpr as string | undefined,\n params: params.length ? params : undefined,\n namelist:\n typeof namelist === 'string'\n ? namelist.trim().split(/\\s+/)\n : undefined,\n id: id as string | undefined,\n idlocation: idlocation as string | undefined,\n delay: resolvedDelay,\n delayexpr: delayexpr as string | undefined,\n target: target as string | undefined,\n targetexpr: targetexpr as string | undefined,\n processorType: type as string | undefined,\n content\n };\n return action;\n }\n\n // Simple send (no special target, no expressions)\n const action: ScxmlRaiseJSON = {\n type: 'scxml.raise',\n event: event as string | undefined,\n eventexpr: undefined,\n params: undefined,\n namelist: undefined,\n id: id as string | undefined,\n idlocation: idlocation as string | undefined,\n delay: resolvedDelay,\n target: target as string | undefined,\n targetexpr: undefined,\n processorType: type as string | undefined,\n content\n };\n return action;\n }\n case 'log': {\n const label = element.attributes!.label;\n const expr = element.attributes!.expr;\n const action: ScxmlLogJSON = {\n type: 'scxml.log',\n ...(label !== undefined ? { label: String(label) } : undefined),\n ...(expr !== undefined ? { expr: String(expr) } : undefined)\n };\n return action;\n }\n case 'if': {\n return parseIfElement(element, options);\n }\n case 'foreach': {\n const array = element.attributes!.array as string;\n const item = element.attributes!.item as string;\n const index = element.attributes?.index as string | undefined;\n const actions = element.elements\n ? mapActions(element.elements, options)\n : [];\n const foreach: ScxmlForeachJSON = {\n type: 'scxml.foreach',\n array,\n item,\n index,\n actions\n };\n return foreach;\n }\n case 'script': {\n if (element.attributes?.src) {\n return {\n type: 'scxml.script',\n code: resolveResource(\n options,\n String(element.attributes.src),\n 'script'\n )\n };\n }\n // Get the script text content\n const textElement = element.elements?.find((el) => el.type === 'text');\n const code = (textElement?.text as string) || '';\n return { type: 'scxml.script', code: code.trim() };\n }\n default:\n throw new Error(\n `Conversion of \"${element.name}\" elements is not implemented yet.`\n );\n }\n}\n\nfunction mapActions(\n elements: XMLElement[],\n options: SCXMLConversionOptions\n): ActionJSON[] {\n const mapped: ActionJSON[] = [];\n\n for (const element of elements) {\n if (element.type === 'comment') {\n continue;\n }\n\n mapped.push(mapAction(element, options));\n }\n\n return mapped;\n}\n\nfunction createGuard(cond: string): GuardJSON {\n // Handle In() predicate\n if (cond.startsWith('In')) {\n const inMatch = cond.trim().match(/^In\\('(.*)'\\)/);\n if (inMatch) {\n return {\n type: 'xstate.stateIn',\n params: { stateId: `#${sanitizeStateId(inMatch[1])}` }\n };\n }\n }\n\n // Handle !In() predicate\n if (cond.startsWith('!In')) {\n const notInMatch = cond.trim().match(/^!In\\('(.*)'\\)/);\n if (notInMatch) {\n return {\n type: 'xstate.not',\n params: {\n guard: {\n type: 'xstate.stateIn',\n params: { stateId: `#${sanitizeStateId(notInMatch[1])}` }\n }\n }\n };\n }\n }\n\n // For other conditions, store the expression for runtime evaluation\n return {\n type: 'scxml.cond',\n params: { expr: cond }\n };\n}\n\ntype HistoryAttributeValue = 'shallow' | 'deep' | undefined;\n\nfunction getDataDescriptors(\n element: XMLElement,\n options: SCXMLConversionOptions\n): ScxmlDataJSON[] {\n return (element.elements ?? [])\n .filter((child) => child.name === 'datamodel')\n .flatMap((datamodel) =>\n (datamodel.elements ?? [])\n .filter((child) => child.name === 'data')\n .map((data) => {\n const src = data.attributes?.src;\n const resolvedSource =\n src !== undefined\n ? resolveResource(options, String(src), 'data')\n : undefined;\n const text = (data.elements ?? [])\n .filter((child) => child.type === 'text' || child.type === 'cdata')\n .map((child) => String(child.text ?? child.cdata ?? ''))\n .join('')\n .trim();\n const xml = data.elements?.find((child) => child.name);\n let resourceXml: XMLElement | undefined;\n if (resolvedSource !== undefined) {\n try {\n resourceXml = normalizeElementNames(\n parseXml(resolvedSource)\n ).elements?.find((child) => child.name);\n } catch {\n resourceXml = undefined;\n }\n }\n return {\n id: String(data.attributes!.id),\n ...(data.attributes?.expr !== undefined\n ? { expr: String(data.attributes.expr) }\n : undefined),\n ...(resolvedSource !== undefined && !resourceXml\n ? { content: resolvedSource.trim() }\n : text\n ? { content: text }\n : undefined),\n ...(resourceXml\n ? { xml: toScxmlXmlJSON(resourceXml) }\n : xml\n ? { xml: toScxmlXmlJSON(xml) }\n : undefined)\n };\n })\n );\n}\n\nfunction collectDataDescriptors(\n element: XMLElement,\n options: SCXMLConversionOptions\n): ScxmlDataJSON[] {\n return [\n ...getDataDescriptors(element, options),\n ...(element.elements ?? [])\n .filter((child) =>\n ['state', 'parallel', 'final'].includes(child.name ?? '')\n )\n .flatMap((child) => collectDataDescriptors(child, options))\n ];\n}\n\nfunction toStateNodeJSON(\n nodeJson: XMLElement,\n id: string,\n parentId?: string,\n binding: 'early' | 'late' = 'early',\n options: SCXMLConversionOptions = {}\n): StateNodeJSON {\n const parallel = nodeJson.name === 'parallel';\n let initial = parallel ? undefined : (nodeJson.attributes?.initial as string);\n let initialActions: ActionJSON[] | undefined;\n const hasInitialAttribute = initial !== undefined;\n const { elements } = nodeJson;\n\n const stateId = parentId ? `${parentId}.${id}` : id;\n\n // Handle history states\n if (nodeJson.name === 'history') {\n const history =\n (getAttribute(nodeJson, 'type') as HistoryAttributeValue) || 'shallow';\n if (!elements) {\n return {\n id: sanitizeStateId(id),\n type: 'history',\n history\n };\n }\n\n const [transitionElement] = elements.filter(\n (element) => element.name === 'transition'\n );\n\n const target = getAttribute(transitionElement, 'target');\n\n return {\n id: sanitizeStateId(id),\n type: 'history',\n history,\n target: target ? `#${sanitizeStateId(target as string)}` : undefined,\n ...(transitionElement.elements?.length\n ? {\n _scxmlHistoryActions: mapActions(\n transitionElement.elements,\n options\n )\n }\n : undefined)\n };\n }\n\n if (!nodeJson.elements) {\n return {\n id: sanitizeStateId(id),\n ...(nodeJson.name === 'final' ? { type: 'final' } : undefined)\n };\n }\n\n // Parse <donedata> for final states\n let donedataConfig: ScxmlDonedataJSON | undefined;\n if (nodeJson.name === 'final') {\n const donedataElement = nodeJson.elements.find(\n (el) => el.name === 'donedata'\n );\n if (donedataElement?.elements) {\n const params: Array<{ name: string; expr: string }> = [];\n let contentExpr: string | undefined;\n let contentText: string | undefined;\n for (const child of donedataElement.elements) {\n if (child.name === 'param') {\n params.push({\n name: child.attributes!.name as string,\n expr: String(\n child.attributes?.expr ?? child.attributes?.location ?? ''\n ).trim()\n });\n } else if (child.name === 'content') {\n if (child.attributes?.expr) {\n contentExpr = child.attributes.expr as string;\n } else if (child.elements) {\n const textEl = child.elements.find(\n (el) => el.type === 'text' || el.type === 'cdata'\n );\n contentText = textEl\n ? String(textEl.text ?? textEl.cdata ?? '').trim()\n : '';\n }\n }\n }\n donedataConfig = { params, contentExpr, contentText };\n }\n }\n\n const stateElements = nodeJson.elements.filter(\n (element) =>\n element.name === 'state' ||\n element.name === 'parallel' ||\n element.name === 'final' ||\n element.name === 'history'\n );\n stateElements.forEach((element, index) => {\n if (element.attributes?.id === undefined) {\n element.attributes = {\n ...element.attributes,\n id: `${id}.anonymous.${index}`\n };\n }\n });\n\n const transitionElements = nodeJson.elements.filter(\n (element) => element.name === 'transition'\n );\n\n const invokeElements = nodeJson.elements.filter(\n (element) => element.name === 'invoke'\n );\n\n const onEntryElements = nodeJson.elements.filter(\n (element) => element.name === 'onentry'\n );\n\n const onExitElements = nodeJson.elements.filter(\n (element) => element.name === 'onexit'\n );\n const directScripts = nodeJson.elements\n .filter((element) => element.name === 'script')\n .map((element) => ({\n ...mapAction(element, options),\n global: true\n }));\n\n // Build states object\n const states: Record<string, StateNodeJSON> = {};\n for (const stateElement of stateElements) {\n const childId = sanitizeStateId(`${stateElement.attributes!.id}`);\n states[childId] = toStateNodeJSON(\n stateElement,\n childId,\n stateId,\n binding,\n options\n );\n }\n\n // Determine initial state\n const initialElement = !initial\n ? nodeJson.elements.find((element) => element.name === 'initial')\n : undefined;\n\n if (initialElement && initialElement.elements?.length) {\n const initialTransition = initialElement.elements.find(\n (element) => element.name === 'transition'\n )!;\n initial = initialTransition.attributes!.target as string;\n initialActions = initialTransition.elements?.length\n ? mapActions(initialTransition.elements, options)\n : undefined;\n } else if (!initial && !initialElement && stateElements.length) {\n initial = stateElements[0].attributes!.id as string;\n }\n\n // Build transitions\n const always: TransitionJSON[] = [];\n const on: Record<string, TransitionJSON | TransitionJSON[]> = {};\n\n transitionElements.forEach((value) => {\n const eventTypes = ((getAttribute(value, 'event') as string) || '')\n .trim()\n .split(/\\s+/);\n const targets = getAttribute(value, 'target');\n const internal = getAttribute(value, 'type') === 'internal';\n const hasTarget = targets !== undefined;\n const eventDescriptors = eventTypes.filter(Boolean).map((eventType) => {\n if (/^(error|done\\.state)(\\.|$)/.test(eventType)) {\n return `xstate.${eventType}`;\n }\n if (/^done\\.invoke(\\.|$)/.test(eventType)) {\n return eventType.replace(/^done\\.invoke/, 'xstate.done.actor');\n }\n return eventType;\n });\n const transitionConfig: TransitionJSON = {\n target: getTargets(targets),\n _scxml: {\n ...(hasTarget && { type: internal ? 'internal' : 'external' }),\n ...(eventDescriptors.length && { eventDescriptors })\n },\n ...(value.elements?.length\n ? { actions: mapActions(value.elements, options) }\n : undefined),\n ...(value.attributes?.cond\n ? { guard: createGuard(value.attributes.cond as string) }\n : undefined),\n ...(hasTarget && !internal && { reenter: true })\n };\n\n if (!eventDescriptors.length) {\n always.push(transitionConfig);\n return;\n }\n\n const existing = on['*'];\n if (!existing) {\n on['*'] = transitionConfig;\n } else if (Array.isArray(existing)) {\n existing.push(transitionConfig);\n } else {\n on['*'] = [existing, transitionConfig];\n }\n });\n\n // Build entry/exit actions. Per SCXML, each <onentry>/<onexit> block is a\n // separate executable-content block — errors in one block must not stop\n // execution of subsequent blocks. Wrap each block in scxml.block so the\n // runtime executes them with isolated error state.\n const entry: ActionJSON[] = [\n ...directScripts,\n ...onEntryElements.map((onEntryElement) => ({\n type: 'scxml.block' as const,\n actions: mapActions(onEntryElement.elements || [], options)\n }))\n ];\n\n const exit = onExitElements.length\n ? onExitElements.map((onExitElement) => ({\n type: 'scxml.block' as const,\n actions: mapActions(onExitElement.elements || [], options)\n }))\n : undefined;\n\n // Build invokes\n const invoke: InvokeJSON[] = invokeElements.map((element, invokeIndex) => {\n const invokeType = element.attributes?.type as string | undefined;\n if (\n invokeType !== undefined &&\n ![\n 'scxml',\n 'http://www.w3.org/TR/scxml',\n 'http://www.w3.org/TR/scxml/'\n ].includes(invokeType)\n ) {\n throw new Error(\n `Currently only converting invoke elements of type SCXML is supported (received ${String(invokeType)}).`\n );\n }\n\n const content = element.elements?.find((el) => el.name === 'content');\n\n // Convert nested SCXML content to a machine JSON\n const nestedScxml = content?.elements?.find((el) => el.name === 'scxml');\n\n const findEntryAssignment = (location: string) =>\n onEntryElements\n .flatMap((onEntry) => onEntry.elements ?? [])\n .find(\n (child) =>\n child.name === 'assign' && child.attributes?.location === location\n );\n\n let _nestedScxmlIR: ScxmlIR | undefined;\n if (nestedScxml) {\n // Create a wrapper that looks like parser output: { elements: [scxmlElement] }\n const wrapper: XMLElement = { elements: [nestedScxml] };\n _nestedScxmlIR = compileScxmlElement(wrapper, options);\n } else if (element.attributes?.src) {\n const source = resolveResource(\n options,\n String(element.attributes.src),\n 'invoke'\n );\n _nestedScxmlIR = compileScxmlElement(\n normalizeElementNames(parseXml(source)),\n options\n );\n } else if (element.attributes?.srcexpr) {\n const assignment = findEntryAssignment(\n String(element.attributes.srcexpr)\n );\n const assignedSource = String(assignment?.attributes?.expr ?? '').match(\n /^(['\"])(.*)\\1$/s\n )?.[2];\n if (assignedSource) {\n _nestedScxmlIR = compileScxmlElement(\n normalizeElementNames(\n parseXml(resolveResource(options, assignedSource, 'invoke'))\n ),\n options\n );\n }\n } else if (content?.attributes?.expr) {\n const assignment = findEntryAssignment(String(content.attributes.expr));\n const assignedScxml = assignment?.elements?.find(\n (child) => child.name === 'scxml'\n );\n if (assignedScxml) {\n _nestedScxmlIR = compileScxmlElement(\n { elements: [assignedScxml] },\n options\n );\n }\n }\n\n const invokeId = String(\n element.attributes?.id ?? `${sanitizeStateId(id)}.invoke.${invokeIndex}`\n );\n const params = (element.elements ?? [])\n .filter((child) => child.name === 'param')\n .map((param) => ({\n name: String(param.attributes!.name),\n ...(param.attributes?.expr !== undefined\n ? { expr: String(param.attributes.expr) }\n : undefined),\n ...(param.attributes?.location !== undefined\n ? { location: String(param.attributes.location) }\n : undefined)\n }));\n const namelist = String(element.attributes?.namelist ?? '')\n .trim()\n .split(/\\s+/)\n .filter(Boolean);\n\n if (element.attributes?.idlocation) {\n entry.push({\n type: 'scxml.assign',\n location: String(element.attributes.idlocation),\n expr: JSON.stringify(invokeId)\n });\n }\n\n return {\n id: invokeId,\n src: 'scxml.nested',\n _nestedScxmlIR,\n ...((params.length || namelist.length) && {\n _scxmlInput: {\n ...(params.length ? { params } : undefined),\n ...(namelist.length ? { namelist } : undefined)\n }\n })\n } as InvokeJSON & { _nestedScxmlIR?: ScxmlIR };\n });\n\n const autoForwardIds = invokeElements.flatMap((element, index) =>\n String(element.attributes?.autoforward) === 'true'\n ? [invoke[index].id!]\n : []\n );\n const finalizers = invokeElements.flatMap((element, index) => {\n const finalize = element.elements?.find(\n (child) => child.name === 'finalize'\n );\n return finalize\n ? [\n {\n invokeId: invoke[index].id!,\n actions: mapActions(finalize.elements ?? [], options)\n }\n ]\n : [];\n });\n if (finalizers.length) {\n for (const transitions of Object.values(on)) {\n for (const transition of Array.isArray(transitions)\n ? transitions\n : [transitions]) {\n transition._scxml = {\n ...transition._scxml,\n finalize: finalizers\n };\n transition.actions = [\n ...finalizers.map((finalizer) => ({\n type: 'scxml.finalize',\n ...finalizer\n })),\n ...(transition.actions ?? [])\n ];\n }\n }\n }\n if (autoForwardIds.length) {\n for (const transitions of Object.values(on)) {\n for (const transition of Array.isArray(transitions)\n ? transitions\n : [transitions]) {\n transition.actions = [\n ...autoForwardIds.map((invokeId) => ({\n type: 'scxml.forward',\n invokeId\n })),\n ...(transition.actions ?? [])\n ];\n }\n }\n }\n\n const resolvedInitial = initial && String(initial).split(' ');\n const hasExplicitInitial = hasInitialAttribute || !!initialElement;\n\n return {\n id: sanitizeStateId(id),\n ...(resolvedInitial && !hasExplicitInitial\n ? { initial: sanitizeStateId(resolvedInitial[0]) }\n : undefined),\n ...(resolvedInitial && hasExplicitInitial\n ? {\n _scxmlInitial: {\n targets: resolvedInitial.map(\n (target) => `#${sanitizeStateId(target)}`\n ),\n ...(initialActions?.length\n ? { actions: initialActions }\n : undefined)\n }\n }\n : undefined),\n ...(parallel ? { type: 'parallel' } : undefined),\n ...(nodeJson.name === 'final' ? { type: 'final' } : undefined),\n ...(donedataConfig ? { _scxmlDonedata: donedataConfig } : undefined),\n ...(Object.keys(states).length ? { states } : undefined),\n ...(Object.keys(on).length ? { on } : undefined),\n ...(always.length ? { always } : undefined),\n ...(entry.length ? { entry } : undefined),\n ...(exit?.length ? { exit } : undefined),\n ...(invoke.length ? { invoke } : undefined),\n ...(binding === 'late' && getDataDescriptors(nodeJson, options).length\n ? { _scxmlData: getDataDescriptors(nodeJson, options) }\n : undefined)\n };\n}\n\nfunction compileScxmlElement(\n scxmlJson: XMLElement,\n options: SCXMLConversionOptions\n): ScxmlIR {\n const machineElement = scxmlJson.elements!.find(\n (element) => element.name === 'scxml'\n );\n if (!machineElement) {\n throw new Error('SCXML document must contain an <scxml> root element.');\n }\n\n const binding =\n machineElement.attributes?.binding === 'late' ? 'late' : 'early';\n const data = collectDataDescriptors(machineElement, options);\n const machineId = (machineElement.attributes?.name as string) || '(machine)';\n const stateNodeJSON = toStateNodeJSON(\n machineElement,\n machineId,\n undefined,\n binding,\n options\n );\n const declaredData = new Set(data.map(({ id }) => id));\n const removeStaticallyInvalidInvokes = (node: StateNodeJSON) => {\n if (node.invoke) {\n const invokes = Array.isArray(node.invoke) ? node.invoke : [node.invoke];\n const valid = invokes.filter((invocation) =>\n (invocation._scxmlInput?.namelist ?? []).every((name) =>\n declaredData.has(name)\n )\n );\n node.invoke = valid.length ? valid : undefined;\n }\n for (const child of Object.values(node.states ?? {})) {\n removeStaticallyInvalidInvokes(child);\n }\n };\n removeStaticallyInvalidInvokes(stateNodeJSON);\n\n return {\n ...stateNodeJSON,\n ...(binding === 'early' && data.length ? { _scxmlData: data } : undefined),\n ...(data.length ? { _scxmlDataIds: data.map(({ id }) => id) } : undefined)\n };\n}\n\n/**\n * Converts an SCXML string to a JSON representation that can be used with\n * the SCXML runtime compiler.\n */\nexport function compileSCXML(\n xml: string,\n options: SCXMLConversionOptions = {}\n): ScxmlIR {\n const json = normalizeElementNames(parseXml(xml));\n return compileScxmlElement(json, options);\n}\n\n/**\n * Creates an XState machine from an SCXML document.\n *\n * Expressions and external resources are evaluated using SCXML semantics.\n * Only create machines from trusted SCXML because ECMAScript expressions and\n * script elements execute JavaScript in the current environment.\n */\nexport function createMachineFromSCXML(\n xml: string,\n options: SCXMLConversionOptions = {}\n): AnyStateMachine {\n return createMachineFromSCXMLConfig(compileSCXML(xml, options));\n}\n"],"names":["Object","defineProperty","exports","value","CHAR","S","NAME_START_CHAR","NAME_CHAR","CHAR_RE","RegExp","S_RE","NAME_START_CHAR_RE","NAME_CHAR_RE","NAME_RE","NMTOKEN_RE","isNameStartChar","c","S_LIST","isChar","isS","isNameChar","RESTRICTED_CHAR","RESTRICTED_CHAR_RE","isRestrictedChar","isCharAndNotRestricted","isNCNameStartChar","NC_NAME_START_CHAR","NC_NAME_CHAR","NC_NAME_START_CHAR_RE","NC_NAME_CHAR_RE","NC_NAME_RE","isNCNameChar","SaxesParser","EVENTS","ed5","isChar10","isChar11","ed2","NSed3","XML_NAMESPACE","XMLNS_NAMESPACE","rootNS","__proto__","xml","xmlns","XML_ENTITIES","amp","gt","lt","quot","apos","EOC","NL_LIKE","S_TEXT","S_XML_DECL_ENDING","NL","LESS","EQUAL","GREATER","QUESTION","CLOSE_BRACKET","isQuote","QUOTES","DOCTYPE_TERMINATOR","DTD_TERMINATOR","XML_DECL_NAME_TERMINATOR","ATTRIB_VALUE_UNQUOTED_TERMINATOR","nsPairCheck","parser","prefix","uri","fail","isNCName","name","test","isName","EVENT_NAME_TO_HANDLER_NAME","xmldecl","text","processinginstruction","doctype","comment","opentagstart","attribute","opentag","closetag","cdata","error","end","ready","constructor","opt","this","fragmentOpt","fragment","xmlnsOpt","trackPosition","position","fileName","nameStartCheck","nameCheck","processAttribs","processAttribsNS","pushAttrib","pushAttribNS","ns","assign","additional","additionalNamespaces","mapping","local","keys","nsMappingCheck","processAttribsPlain","pushAttribPlain","stateTable","sBegin","sBeginWhitespace","sDoctype","sDoctypeQuote","sDTD","sDTDQuoted","sDTDOpenWaka","sDTDOpenWakaBang","sDTDComment","sDTDCommentEnding","sDTDCommentEnded","sDTDPI","sDTDPIEnding","sText","sEntity","sOpenWaka","sOpenWakaBang","sComment","sCommentEnding","sCommentEnded","sCData","sCDataEnding","sCDataEnding2","sPIFirstChar","sPIRest","sPIBody","sPIEnding","sXMLDeclNameStart","sXMLDeclName","sXMLDeclEq","sXMLDeclValueStart","sXMLDeclValue","sXMLDeclSeparator","sXMLDeclEnding","sOpenTag","sOpenTagSlash","sAttrib","sAttribName","sAttribNameSawWhite","sAttribValue","sAttribValueQuoted","sAttribValueClosed","sAttribValueUnquoted","sCloseTag","sCloseTagSawWhite","_init","closed","_closed","_a","openWakaBang","piTarget","entity","q","tags","tag","topNS","chunk","chunkPosition","i","prevI","carriedFromPrevious","undefined","forbiddenState","attribList","state","reportedTextBeforeRoot","reportedTextAfterRoot","closedRoot","sawRoot","xmlDeclPossible","xmlDeclExpects","entityReturnState","defaultXMLVersion","forceXMLVersion","Error","setXMLVersion","positionAtNewLine","xmlDecl","version","encoding","standalone","line","column","ENTITIES","create","readyHandler","call","columnIndex","on","handler","off","makeError","message","msg","length","err","errorHandler","write","toString","limit","lastCode","charCodeAt","slice","close","getCode10","code","final","getCode11","next","getCodeNorm","getCode","unget","captureTo","chars","start","isNLLike","includes","captureToChar","char","captureNameChars","skipSpaces","currentXMLVersion","iBefore","doctypeHandler","String","fromCodePoint","owb","handleTextInRoot","handleTextOutsideRoot","loop","parsed","parseEntity","textHandler","commentHandler","cdataHandler","isQuestion","toLowerCase","piHandler","target","body","join","xmldeclHandler","attributes","openTagStartHandler","openTag","openSelfClosingTag","closeTag","scanLoop","nonSpace","outRootLoop","qname","attr","push","attributeHandler","trimmed","trim","_b","pop","endHandler","resolve","index","resolvePrefix","colon","indexOf","JSON","stringify","seen","Set","eqname","has","add","isSelfClosing","openTagHandler","_c","closeTagHandler","l","defined","num","NaN","parseInt","Mailbox","_process","_active","_current","_last","flush","clear","enqueue","event","enqueued","consumed","XSTATE_INIT","XSTATE_SPAWN","XSTATE_STOP","XSTATE_TERMINATE","XSTATE_TIMER","createAfterEvent","delayRef","id","type","delay","stateId","createAfterEventId","createTimeoutEventId","createInvokeTimeoutEvent","invokeId","sessionId","actorId","createInvokeTimeoutEventId","createDoneStateEvent","output","createErrorPlatformEvent","kind","createInitEvent","input","reportUnhandledError","setTimeout","symbolObservable","Symbol","observable","assertSendToEvent","builtInActions","actor","system","spawnActor","_parent","startActor","@xstate.raise","actorScope","_event","options","scheduleTimer","self","@xstate.sendTo","_relay","@xstate.cancel","sendId","cancelTimer","@xstate.stop","stopActor","@xstate.terminate","termination","terminateActor","sourceKeyCaches","WeakMap","resolveRegisteredActorSource","actors","logic","cache","get","Map","key","registeredLogic","set","subscriptions","createAttachedLogic","attach","initialTransition","_","status","getSnapshot","subscription","parentSubscription","torndown","teardown","unsubscribe","parent","subscribe","complete","transition","delete","getInitialSnapshot","getPersistedSnapshot","snapshot","restoreSnapshot","relayMappedToParent","getEvent","createListenerLogic","eventType","mapper","isPartialWildcard","endsWith","emittedEvent","matchesEventDescriptor","listenerLogic","createSubscriptionLogic","mappers","done","onSnapshot","subscriptionLogic","lazyActorScope","isLazyActorScope","getActorScopeParent","withActorScope","args","actorArgs","defineProperties","enumerable","execCustomEffect","action","execEmitEffect","runtime","source","emitEvent","execDeadLetterEffect","deadLetter","reason","detail","createDeadLetterEffect","exec","params","execSpawnEffect","execStartEffect","execStopEffect","execTerminateEffect","execRaiseEffect","execSendToEffect","sendEvent","execCancelEffect","updateLogicalTimers","effect","isBuiltInExecutableAction","timers","nextTimerId","_nextTimerId","mergeContextPatch","context","patch","pushBuiltInAction","actions","actionRecord","mergeActorIdCounters","current","update","merged","Math","max","applyChildUpdate","children","counters","_nextActorIds","owned","_unregister","getTransitionActionRecord","spawnAllocations","createSpawnAllocation","explicitIds","stoppedIds","beginSpawnAllocation","getWorkingSnapshotOf","_snapshot","nextChildIndex","allocation","allocateChildId","src","localAllocation","getActorIdPrefix","assertChildIdFree","existing","occupied","reserveChildId","generated","parseGeneratedActorId","createTransitionEnqueue","internalEvents","actorSubscriptions","createActors","props","cancel","emit","log","logger","raise","raisedEvent","spawn","registeredActors","sources","getRegisteredActors","resolveTransitionSpawnSource","registryKey","createActorRef","childUpdate","pushSpawnedChild","sendTo","stop","actorInstance","recordStoppedChild","listen","listenerActor","subscribeTo","subscriptionActor","createEnqueueObject","getBuiltInActionFields","createStartEffect","createSendToEffect","createTerminationEffect","finalizeTransitionResult","previousSnapshot","nextSnapshot","effects","becameTerminal","wasTerminal","hasTerminationEffect","some","resolveActionsWithContext","currentSnapshot","intermediateSnapshot","executableActions","actionArgs","getEventOutput","machine","isInline","resolvedAction","bind","actionParams","_childUpdate","emittedEventParams","res","emptyEnqueueObject","builtInFields","isEmittedEvent","typedExecutableAction","enqueueFn","fn","noop","emptyActor","parseDurationToMilliseconds","duration","normalizedDuration","millisecondsMatch","match","secondsMatch","wholePart","hasDecimal","fracPart","padEnd","iso8601DurationMatch","groups","weeks","days","hours","minutes","seconds","toNumber","Number","replace","parseDelayToMilliseconds","snapshotActorRefs","lazySnapshotActorRefs","emptyKeyedActors","getKeyedActors","peek","_peekKeyedActors","keyedActors","markSystemSnapshotDirty","_snapshotVersion","getSystemSnapshotVersion","createSnapshotSystem","baseSystem","baseState","root","copyRegisteredActors","reverseKeyedActors","sourceVersion","_register","_set","getAll","fromEntries","_hasInspectionObservers","_sendInspectionEvent","values","getSnapshotActorRef","created","copySnapshotActorRef","ref","setSnapshotActorRef","previousRef","reusableRef","systemState","sourceSystem","capturedActors","_getRootActor","peekedChildren","_peekChildren","size","captureRegisteredActors","baseKeyedActors","child","getSnapshotChildren","setInertActorScopeSnapshot","attachActorRef","lazyState","getLazyInertActorState","materialized","isInertActorScope","_inert","attachSnapshotActorRef","snapshotActorScopes","identityProvider","setLazySnapshotActorRef","lazyInertActorState","materializeInertActorScope","materialize","lazyInertActorScopePrototype","parentKnown","defer","stopChild","actionExecutor","createMaterializedInertActorScope","actorLogic","sourceRef","sourceChildren","sourceSelf","snapshotRef","previousSelf","createActor","_sessionId","_systemRef","_address","_actorScope","_stop","createInertActorScope","sourceActorScope","sourceScope","sourceState","eagerSourceRef","peekSnapshotActorRef","getSnapshotActorRefProvider","isMachineSnapshot","identitySnapshot","identitySourceRef","identitySourceChildren","identityScope","identityRef","getIdentityScope","scope","resolveDelay","delaySource","configuredDelay","referencedDelay","getConfiguredDelayValue","getStateInput","stateNodeId","_stateInputs","isAtomicStateNode","stateNode","getChildren","states","filter","sn","getProperAncestors","toStateNode","ancestors","m","getAllStateNodes","stateNodes","nodeSet","activeParentSet","s","initialStates","getInitialStateNodes","initialStateNode","getStateValue","rootNode","config","adjList","getValueFromAdj","baseNode","childStateNodes","childStateNode","stateValue","isInFinalState","stateNodeSet","every","isStateId","str","getLegacyEventType","matchesActorSession","getCandidates","eventTypes","legacyType","getEventTypeAliases","exactMatches","flatMap","transitions","wildcardCandidates","eventDescriptor","sort","a","b","scheduleDelayedEvent","timerId","resolveEvent","resolveScheduledDelay","oldEntry","entry","x","enq","oldExit","exit","formatTransition","descriptor","transitionConfig","normalizedTarget","normalizeTarget","reenter","resolveTarget","assertLegalTargetSet","toJSON","map","t","isStateNodeDescendantOf","ancestor","getLeastCommonStateNodeAncestor","left","right","leftAncestors","targets","leftIndex","rightIndex","commonAncestor","getStateNodeById","isInternalTarget","getStateNodeByPath","resolvedTarget","resolveHistoryDefaultTransition","initial","to","_historyDefaultTransition","isHistoryNode","iter","descStateNode","initialState","getStateNode","stateKey","result","statePath","arrayStatePath","toStatePath","currentStateNode","shift","getStateNodes","childStateKeys","Array","allStateNodes","subStateNode","transitionNode","selectionResults","subStateKeys","subStateKey","allInnerTransitions","subStateValue","innerTransitions","isDescendant","parentStateNode","marker","hasDescendantState","hasIntersection","s1","s2","s1Size","isArray","s2Size","set1","item","removeConflictingTransitions","enabledTransitions","resolveTransition","filteredTransitions","exitSets","getExitSet","exitSet","computeExitSet","t1","t1Preempted","transitionsToRemove","t2","t3","from","createTransitionResultResolver","resolveActions","getTransitionResult","selectionResult","getEffectiveTargetStates","historyValue","targetSet","targetNode","node","narrowParallelDomain","domain","targetStates","narrowed","region","find","getTransitionDomain","_transitionDomain","head","tail","concat","statesToExit","microstep","isInitial","internalQueue","mutStateNodeSet","nodes","originalContext","getCurrentTransitionResult","changesState","getStateActionsAndContext","transitionFn","updatedContext","guards","delays","_special","nextState","getInvokeStopActions","invokeDef","invoke","exitStates","changedHistory","order","currentStateNodes","exitStateNode","historyNode","predicate","history","stateInput","exitActions","nextContext","cloneMachineSnapshot","resolvedState","resolvedActions","invokeStopActions","stoppedState","stopEffects","transitionActions","toArray","enterStates","getMachineOutput","rootCompletionNode","completionOutput","rootDoneEvent","e","resolveOutput","stateInputMap","parallelDoneEvent","statesToEnter","statesForDefaultEntry","historyDefaultsByParent","addAncestorStatesToEnter","reentrancyDomain","anc","addDescendantStatesToEnter","historyStateNodes","historyDefaultTransition","historyParent","defaults","_statesForDefaultEntry","stateInputsChanged","completedNodes","stateNodeToEnter","invoked","resolveReferencedActor","syncSnapshot","contextChangedByEntry","resultActions","nextInternalEvents","defaultTransitions","Boolean","defaultTransition","initialActions","initialContext","initialInput","initialInternalEvents","ancestorMarker","regionOutput","regionDoneEvent","finalChild","resolvedTransitionState","transitionExecutableActions","nextStateNodes","allExitActions","forEach","stopChildren","withoutTimers","cancelEffects","cancelTimers","_nodes","transitionArgs","getTransitionArgs","reusable","resolvedInput","resolvedContext","macrostep","initialMicrosteps","microsteps","removeTerminatedChild","terminalEvent","lastEffects","at","completeMacrostep","starts","attachedStarts","childStarts","deriveDeferredStarts","shouldTerminate","terminalEffects","lastSnapshot","addMicrostep","step","collectedMicrosteps","_collectedMicrosteps","stoppedChildrenSnapshot","nextEvent","normalizeWithId","idKey","startsWith","normalized","afterPrefix","idMap","delayText","isNaN","normalizeLegacyInternalEvent","timer","currentEvent","isErr","isErrorEvent","getTransitionData","_hasEventlessTransitions","shouldSelectEventlessTransitions","maxIterations","Infinity","iterationCount","microstepCount","selectEventlessTransitions","previousState","hasEffect","evaluateTransitionFunction","enabled","triggerTransitionEffect","transitionEffectSignal","transitionEffectEnqueue","transitionTo","sourceId","transitionEffectTargets","timerIds","enabledTransitionSet","atomicStates","atomicStateNode","always","evaluateCandidate","candidate","matches","pattern","entries","is","matchesEvent","_eventMatcher","guard","guardArgs","withActorSelfAndParent","evaluation","emptySubscription","restoreHint","isRemoteActorRef","actorRef","_remote","remoteSnapshot","freeze","createRemoteActorRef","handle","address","incarnation","_syncSnapshot","send","_send","select","trigger","_isRunning","xstate$type","ACTOR_REF_TYPE","emptySnapshotRecord","compactSnapshotRecord","machineSnapshotMatches","testValue","matchesState","machineSnapshotHasTag","machineSnapshotCan","_canTransition","machineSnapshotToJSON","getMeta","getInputs","can","hasTag","jsonValues","machineSnapshotGetMeta","meta","machineSnapshotGetInputs","collectTags","createMachineSnapshot","configWithSnapshot","clonedSnapshot","serializeHistoryValue","persistContext","contextPart","copy","parentStateId","childStateId","parentStateValue","toStateValue","childStateValue","segment","previous","pathToStateValue","toArrayStrict","isDoneEvent","toTransitionConfigArray","configLike","transitionLike","toObserver","nextHandler","completionHandler","isObserver","indexStr","nodeId","invokeConfig","configSrc","partialEventTokens","split","eventTokens","tokenIndex","partialEventToken","eventToken","async","runStep","sendSelf","getStepEffect","Promise","reject","waitForStep","rejectUndeliverableEvent","runtimeTarget","isInternalEventType","getEventBoundaryError","systemIdPrefix","nextSystemId","createSystemId","crypto","globalThis","getRandomValues","Uint32Array","padStart","randomUUID","replaceAll","Date","now","random","createSystemIdPrefix","logicId","encodeAddressSegment","separator","lastIndexOf","isSafeInteger","getActorIdCounterKey","bumpActorIdCounter","counterKey","emptyScheduledTimers","createScheduledTimerId","RuntimeSystem","_children","_rootActor","_keyedActors","_reverseKeyedActors","_identity","systemId","nextSessionId","scheduler","_clock","_logger","_onRejectedEvent","onRejectedEvent","restoredSnapshot","clock","ambientInspector","getAmbientInspector","_scheduledTimers","_recordSent","_inspectionObservers","inspectionSource","_collectedSent","targetRef","targetId","schedule","existingId","_timerMap","scheduledAt","scheduledTimer","dueAt","scheduledTimerId","timeout","_deliver","clearTimeout","cancelAll","_lastSourceRef","deliverEvent","changed","inspect","observerOrFn","observer","resolvedInspectionEvent","rootId","override","stopActorLocally","_terminate","terminateActorLocally","_emit","issues","eventOrigin","runLogic","cancelAllTimers","scheduledTimers","resetScheduledTimers","scheduledId","executingCustomAction","emptyInspectionRecords","ProcessingStatus","defaultOptions","ms","console","safeCall","arg","executeExecutableEffects","Actor","_trigger","Proxy","payload","_boundSend","_sendPublic","_boundProcess","mailbox","_mailboxStarted","observers","eventListeners","_processingStatus","NotStarted","_forceDeferredActions","_collectedActions","_initialEffects","_deferred","_restored","resolvedOptions","rootActor","createRuntimeSystem","requestedId","counter","resolveActorId","persistedState","_setSnapshot","parentRef","_getLogger","_defer","_stopChild","_executeAction","Running","saveExecutingCustomAction","_setErrorSnapshot","_recoverOrError","_tryHandleExecutionError","_error","errorEvent","getExecutionErrorEvent","_next","deferred","deferredFn","_inspectTransition","sent","_flushInitialEffects","nextListenerOrObserver","errorListener","completeListener","Stopped","listeners","selector","equalityFn","selected","_stopProcedure","_complete","restored","refreshSnapshotActorRefRoot","wallClock","startedAt","min","caughtError","reportError","EMPTY_OBJECT","StateNode","path","description","schemas","after","events","ownEvents","_candidateCache","_key","_machine","firstStateKey","choice","validateStateNodeConfig","collection","iteratee","collectionKeys","mapValues","stateConfig","resolvedId","sourceName","_initialize","afterConfig","timeoutConfig","onTimeoutConfig","onTimeout","invokeDefs","fromDelaysMap","eventMatcher","delayedTransitions","eventPattern","delayedTransition","getDelayedTransitions","addTransitions","additions","transitionsConfig","mapTransitionConfigs","onDone","onError","createCancelInvokeTimeoutTransition","timeoutEventId","_args","formatInvokeCompletionTransition","rest","didEnqueue","trackingEnqueue","apply","thisArg","argArray","Reflect","prop","receiver","withInvokeMatch","invokeTimeoutEventId","invokeDoneTransitions","rawTransition","formatTransitions","validateChoiceResult","formatChoiceTransitions","_refreshEventMetadata","object","memoizedData","memo","_target","targetString","resolvedTargets","formatInitialTransition","descriptorKey","getEventDescriptorKey","candidates","transitionConfigs","assertValid","validator","request","check","findEventSchema","hasOwn","emptyCanActor","emptyCanActorScope","getEmptyCanActorScope","StateMachine","_internalEventType","snapshotSchema","eventSchema","internalEventDescriptors","_json","vendor","validate","contextSchema","resolveState","eventSchemas","internalEventSchemas","isFrameworkEvent","schema","rootStateNode","routeTransitions","collectRoutes","route","routeId","routeConfig","routeMatches","_guard","routeOptions","formatRouteTransitions","provide","provided","resolvedStateValue","usesInertScope","resolvedActorScope","fastSnapshot","_transitionFast","returnedSnapshot","_attachPureActorRef","_collectEffects","skipInitializingActor","sourceNode","stateChanged","snapshots","emptyActorScope","transitionData","_getPreInitialState","initEvent","preInitial","spawnedChildren","referencedSrc","createSpawner","withActorSelf","takeSpawnAllocationCounters","preInitialState","contextSpawnEffects","createSpawnEffect","finalizeInitialResult","macroState","initialStateNodes","collectDefaultEntryStates","other","initialMicrostep","errorMacrostep","childId","_rehydrated","fullPath","relativePath","resolvedStateId","STATE_IDENTIFIER","childrenJson","timersJson","embedChildren","embed","remote","snapshotActor","scheduled","persisted","stateInputs","snapshotMachine","persistedMachine","legacyPersistedVersion","persistedVersion","migrate","snapshotData","snapshotChildren","actorData","childState","persistedTimers","targetDescription","revivedHistoryValue","revived","arr","resolved","reviveHistoryValue","validateStateValue","missingStateError","childNode","_persistedSnapshotVersion","_nextActorId","_legacyNextActorId","persistedRest","restoredCounters","WeakSet","reviveContext","delayToMs","parsedDelay","parseFloat","normalizeScxmlEventType","toScxmlEventName","isExpression","isResolvable","isCode","toPath","extractSerializableDelays","toActionArray","validateChoiceConfig","branch","when","SCXML_SYSTEM_VARIABLES","scxmlScriptEnvironments","scxmlMachineNames","scxmlIoProcessors","scxmlEvents","scxmlEnteringStates","getScxmlIoProcessors","processors","processor","location","scxml","evaluateExpr","expr","normalizedExpr","machineName","dataContext","fnBody","declarations","Function","SCXML_ORIGIN","isExternal","_scxmlExternal","isInitEvent","explicitType","_scxmlEventType","scxmlEvent","_scxmlEventName","sendid","_scxmlSendId","origin","origintype","invokeid","_scxmlInvokeId","data","_scxmlEventData","sanitized","snap","executeScript","global","contextKeys","mutableContextKeys","varDeclarations","k","captureUpdates","codeWithoutComments","matchAll","depth","getFunctionDeclarations","codeWithoutFunctions","reduce","declaration","captureVariables","environment","createScxmlDomElement","element","tagName","getAttribute","getElementsByTagName","createMachineFromSCXMLConfig","json","resolvedSources","evaluators","mergeSources","expressionResolver","expressionLanguage","getEvaluator","lang","evaluator","evaluateResolvable","slot","resolveValue","makeScope","extra","getDurationConfig","assertResolvable","createExpressionResolver","sendCounters","resolveCondition","condition","declarativeGuard","guardImpl","makeChoiceConfig","pendingTransitionActionsMap","allTransitionActions","contextBeforeTargetless","targetlessEvent","pendingPlatformErrors","scxmlDonedataValues","resolveRouteConfig","resolvedGuard","makeDonedataOutput","iterInvokeConfigs","invokes","inv","extInv","_nestedScxmlIR","_scxmlInput","namelist","ReferenceError","param","getTransitionConfig","raiseErrorExecution","tagname","errored","executeActionDefinition","parentState","stack","definition","executeActions","isBuiltInActionJSON","resolvedEvent","finalize","scxmlAction","label","mergedContext","clonedRoot","clonedChild","_xstateScxmlInputKeys","content","eventData","processorType","eventexpr","contentValue","idlocation","nextId","generatedId","targetexpr","delayexpr","isParentTarget","childRef","sendidexpr","isLegalIdentifier","array","iterX","iterResult","blockX","blockResult","branches","condResult","cond","branchX","branchResult","getFinalizedGuardContext","finalizers","finalized","finalizer","assignAction","targetConfig","_scxml","resolveTransitionContext","resolveTransitionInput","eventDescriptors","matchesScxmlEventDescriptor","_x","_enq","assertCondition","assertAction","definitions","assertActions","assertTransition","transitionPath","assertStateNode","invokePath","assertMachineJSON","rootNodeConfig","iterNode","nodeKey","ancestorIds","originalEntryActions","_scxmlData","_scxmlInitial","_scxmlHistoryActions","acc","entryFn","ctx","transActions","mergedX","_scxmlDonedata","donedata","out","contentExpr","contentText","evaluateDonedataValue","contextConfig","_scxmlDataIds","providedGuards","scxml.cond","xstate.stateIn","normalizedId","xstate.not","inner","innerImpl","SpecialTargets","parseXml","elements","append","sanitizeStateId","normalizeElementNames","resolveResource","toScxmlXmlJSON","getContentDescriptor","mapAction","isInternal","Internal","resolvedDelay","currentCond","currentActions","parseIfElement","mapActions","textElement","el","mapped","createGuard","inMatch","notInMatch","getDataDescriptors","datamodel","resolvedSource","resourceXml","collectDataDescriptors","toStateNodeJSON","nodeJson","parentId","binding","parallel","hasInitialAttribute","transitionElement","donedataConfig","donedataElement","textEl","stateElements","transitionElements","invokeElements","onEntryElements","onExitElements","directScripts","stateElement","initialElement","internal","hasTarget","targetAttr","onEntryElement","onExitElement","invokeIndex","invokeType","nestedScxml","findEntryAssignment","onEntry","compileScxmlElement","srcexpr","assignment","assignedSource","assignedScxml","autoForwardIds","autoforward","resolvedInitial","hasExplicitInitial","scxmlJson","machineElement","stateNodeJSON","declaredData","removeStaticallyInvalidInvokes","valid","invocation","compileSCXML"],"mappings":";;;;;;;;AAQAA,OAAOC,eAAeC,EAAS,aAAc,CAAEC,OAAO,IAItDD,EAAYE,KAAG,oBACfF,EAASG,EAAG,UAEZH,EAAuBI,gBAAG,gDAC1BJ,EAAiBK,UAAG,IAAML,EAAQI,gBAAkB,cAIpDJ,EAAAM,QAAkB,IAAIC,OAAO,KAAOP,EAAQE,KAAO,KAAM,KACzDF,EAAAQ,KAAe,IAAID,OAAO,KAAOP,EAAQG,EAAI,MAAO,KACpDH,EAAAS,mBAA6B,IAAIF,OAAO,KAAOP,EAAQI,gBAAkB,KAAM,KAC/EJ,EAAAU,aAAuB,IAAIH,OAAO,KAAOP,EAAQK,UAAY,KAAM,KACnEL,EAAeW,QAAG,IAAIJ,OAAO,KAAOP,EAAQI,gBAAkB,KAAOJ,EAAQK,UAAY,MAAO,KAChGL,EAAAY,WAAqB,IAAIL,OAAO,KAAOP,EAAQK,UAAY,MAAO,KA0ClE,SAASQ,EAAgBC,GACrB,OAASA,GAAK,IAAQA,GAAK,IACtBA,GAAK,IAAQA,GAAK,KACb,KAANA,GACM,KAANA,GACM,OAANA,GACM,OAANA,GACCA,GAAK,KAAQA,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