sanity 3.74.2-corel.18 → 3.74.2-coreui.20

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.
Files changed (121) hide show
  1. package/lib/_chunks-cjs/runtime.js +8 -4
  2. package/lib/_chunks-cjs/runtime.js.map +1 -1
  3. package/lib/_chunks-cjs/version.js +1 -1
  4. package/lib/_chunks-es/version.mjs +1 -1
  5. package/lib/_legacy/version.esm.js +1 -1
  6. package/package.json +10 -11
  7. package/src/_internal/cli/server/renderDocument.tsx +12 -0
  8. package/src/_internal/cli/server/runtime.ts +13 -10
  9. package/src/_internal/cli/server/vite/plugin-sanity-build-entries.ts +14 -12
  10. package/dist/BroadcastDisplayedDocument-BHYI8o6u.mjs +0 -19
  11. package/dist/BroadcastDisplayedDocument-BHYI8o6u.mjs.map +0 -1
  12. package/dist/DisplayedDocumentBroadcaster-DfHPxc7C.mjs +0 -58
  13. package/dist/DisplayedDocumentBroadcaster-DfHPxc7C.mjs.map +0 -1
  14. package/dist/LiveQueries-sYvgBCKh.mjs +0 -267
  15. package/dist/LiveQueries-sYvgBCKh.mjs.map +0 -1
  16. package/dist/LoaderQueries-AQneabiG.mjs +0 -581
  17. package/dist/LoaderQueries-AQneabiG.mjs.map +0 -1
  18. package/dist/Observable-wwWYwtkh.mjs +0 -551
  19. package/dist/Observable-wwWYwtkh.mjs.map +0 -1
  20. package/dist/PostMessageDocuments-DLMdHDk6.mjs +0 -75
  21. package/dist/PostMessageDocuments-DLMdHDk6.mjs.map +0 -1
  22. package/dist/PostMessageFeatures-CazMQz3f.mjs +0 -21
  23. package/dist/PostMessageFeatures-CazMQz3f.mjs.map +0 -1
  24. package/dist/PostMessagePerspective-m4uZ6sI5.mjs +0 -23
  25. package/dist/PostMessagePerspective-m4uZ6sI5.mjs.map +0 -1
  26. package/dist/PostMessagePreviewSnapshots-Dr7CEAiM.mjs +0 -66
  27. package/dist/PostMessagePreviewSnapshots-Dr7CEAiM.mjs.map +0 -1
  28. package/dist/PostMessageRefreshMutations-CWb9UqSy.mjs +0 -66
  29. package/dist/PostMessageRefreshMutations-CWb9UqSy.mjs.map +0 -1
  30. package/dist/PostMessageSchema-BVFyZOH1.mjs +0 -514
  31. package/dist/PostMessageSchema-BVFyZOH1.mjs.map +0 -1
  32. package/dist/PostMessageTelemetry-CSluBvcC.mjs +0 -51
  33. package/dist/PostMessageTelemetry-CSluBvcC.mjs.map +0 -1
  34. package/dist/PresentationToolGrantsCheck-4zo266wj.mjs +0 -3919
  35. package/dist/PresentationToolGrantsCheck-4zo266wj.mjs.map +0 -1
  36. package/dist/QRCodeSVG-D6VfGEbM.mjs +0 -648
  37. package/dist/QRCodeSVG-D6VfGEbM.mjs.map +0 -1
  38. package/dist/SourceContext-T8zcpOpp.mjs +0 -33
  39. package/dist/SourceContext-T8zcpOpp.mjs.map +0 -1
  40. package/dist/StructureToolProvider-BMLps71e.mjs +0 -13815
  41. package/dist/StructureToolProvider-BMLps71e.mjs.map +0 -1
  42. package/dist/Subject-DP0DoUP_.mjs +0 -108
  43. package/dist/Subject-DP0DoUP_.mjs.map +0 -1
  44. package/dist/ViteDevServerStopped-DdibXNvO.mjs +0 -44
  45. package/dist/ViteDevServerStopped-DdibXNvO.mjs.map +0 -1
  46. package/dist/_createContext.mjs +0 -36
  47. package/dist/_createContext.mjs.map +0 -1
  48. package/dist/_singletons.mjs +0 -195
  49. package/dist/_singletons.mjs.map +0 -1
  50. package/dist/browser-BzDH2pyp.mjs +0 -455
  51. package/dist/browser-BzDH2pyp.mjs.map +0 -1
  52. package/dist/browser-DWCoWoiH.mjs +0 -3988
  53. package/dist/browser-DWCoWoiH.mjs.map +0 -1
  54. package/dist/debounceTime-BeoKrERE.mjs +0 -130
  55. package/dist/debounceTime-BeoKrERE.mjs.map +0 -1
  56. package/dist/desk.mjs +0 -52
  57. package/dist/desk.mjs.map +0 -1
  58. package/dist/first-Di4GZDIY.mjs +0 -42
  59. package/dist/first-Di4GZDIY.mjs.map +0 -1
  60. package/dist/get-psIoeD-z.mjs +0 -327
  61. package/dist/get-psIoeD-z.mjs.map +0 -1
  62. package/dist/hooks-4sgcd521.mjs +0 -90
  63. package/dist/hooks-4sgcd521.mjs.map +0 -1
  64. package/dist/index-9PJcXUTv.mjs +0 -87
  65. package/dist/index-9PJcXUTv.mjs.map +0 -1
  66. package/dist/index-ByFK-IwD.mjs +0 -528
  67. package/dist/index-ByFK-IwD.mjs.map +0 -1
  68. package/dist/index-C2OAo3To.mjs +0 -7079
  69. package/dist/index-C2OAo3To.mjs.map +0 -1
  70. package/dist/index-C3OvVLVP.mjs +0 -4636
  71. package/dist/index-C3OvVLVP.mjs.map +0 -1
  72. package/dist/index-DBPVDKJN.mjs +0 -1198
  73. package/dist/index-DBPVDKJN.mjs.map +0 -1
  74. package/dist/index-DkvUNBNf.mjs +0 -73
  75. package/dist/index-DkvUNBNf.mjs.map +0 -1
  76. package/dist/index-Sp9w8lMg.mjs +0 -118
  77. package/dist/index-Sp9w8lMg.mjs.map +0 -1
  78. package/dist/index.browser-BxT2qp9y.mjs +0 -104
  79. package/dist/index.browser-BxT2qp9y.mjs.map +0 -1
  80. package/dist/index.mjs +0 -129019
  81. package/dist/index.mjs.map +0 -1
  82. package/dist/isObservable-ByOheaM8.mjs +0 -8
  83. package/dist/isObservable-ByOheaM8.mjs.map +0 -1
  84. package/dist/never-ChKjLemk.mjs +0 -6
  85. package/dist/never-ChKjLemk.mjs.map +0 -1
  86. package/dist/pane-C4tskUPg.mjs +0 -5
  87. package/dist/pane-C4tskUPg.mjs.map +0 -1
  88. package/dist/pane-Dhx8FvsK.mjs +0 -5
  89. package/dist/pane-Dhx8FvsK.mjs.map +0 -1
  90. package/dist/presentation-CSS9GR9X.mjs +0 -984
  91. package/dist/presentation-CSS9GR9X.mjs.map +0 -1
  92. package/dist/presentation.mjs +0 -14
  93. package/dist/presentation.mjs.map +0 -1
  94. package/dist/resources-4cbq8YlR.mjs +0 -124
  95. package/dist/resources-4cbq8YlR.mjs.map +0 -1
  96. package/dist/resources-BVETz6Ur.mjs +0 -57
  97. package/dist/resources-BVETz6Ur.mjs.map +0 -1
  98. package/dist/resources-D4AaU75F.mjs +0 -434
  99. package/dist/resources-D4AaU75F.mjs.map +0 -1
  100. package/dist/resources-Dc-6ZcPg.mjs +0 -157
  101. package/dist/resources-Dc-6ZcPg.mjs.map +0 -1
  102. package/dist/resources-DgU0prBM.mjs +0 -179
  103. package/dist/resources-DgU0prBM.mjs.map +0 -1
  104. package/dist/resources-MD8RsYhH.mjs +0 -288
  105. package/dist/resources-MD8RsYhH.mjs.map +0 -1
  106. package/dist/router.mjs +0 -689
  107. package/dist/router.mjs.map +0 -1
  108. package/dist/share-bcOpIdQz.mjs +0 -71
  109. package/dist/share-bcOpIdQz.mjs.map +0 -1
  110. package/dist/shareReplay-Dj1O6fKV.mjs +0 -43
  111. package/dist/shareReplay-Dj1O6fKV.mjs.map +0 -1
  112. package/dist/stegaEncodeSourceMap-DXdUZQye.mjs +0 -342
  113. package/dist/stegaEncodeSourceMap-DXdUZQye.mjs.map +0 -1
  114. package/dist/structure.mjs +0 -56
  115. package/dist/structure.mjs.map +0 -1
  116. package/dist/takeUntil-CgZP1bze.mjs +0 -111
  117. package/dist/takeUntil-CgZP1bze.mjs.map +0 -1
  118. package/dist/v4-C78sE4Gb.mjs +0 -27082
  119. package/dist/v4-C78sE4Gb.mjs.map +0 -1
  120. package/dist/version-D7UZEoYI.mjs +0 -5
  121. package/dist/version-D7UZEoYI.mjs.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"index-C3OvVLVP.mjs","sources":["../../../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm5/internal/util/argsOrArgArray.js","../../../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm5/internal/operators/combineLatest.js","../../../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/dist/esm5/internal/operators/combineLatestWith.js","../../../node_modules/.pnpm/get-it@8.6.6_debug@4.4.0/node_modules/get-it/dist/_chunks-es/_commonjsHelpers.js","../../../node_modules/.pnpm/get-it@8.6.6_debug@4.4.0/node_modules/get-it/dist/index.browser.js","../../../node_modules/.pnpm/get-it@8.6.6_debug@4.4.0/node_modules/get-it/dist/middleware.browser.js","../../../node_modules/.pnpm/@sanity+client@6.24.3_debug@4.4.0/node_modules/@sanity/client/dist/_chunks-es/stegaClean.js","../../../node_modules/.pnpm/@sanity+client@6.24.3_debug@4.4.0/node_modules/@sanity/client/dist/index.browser.js","../../../node_modules/.pnpm/xstate@5.19.1/node_modules/xstate/dev/dist/xstate-dev.esm.js","../../../node_modules/.pnpm/xstate@5.19.1/node_modules/xstate/dist/raise-c17ec2bc.esm.js","../../../node_modules/.pnpm/xstate@5.19.1/node_modules/xstate/actors/dist/xstate-actors.esm.js","../../../node_modules/.pnpm/xstate@5.19.1/node_modules/xstate/dist/log-3d9d72a9.esm.js","../../../node_modules/.pnpm/xstate@5.19.1/node_modules/xstate/dist/xstate.esm.js","../../../node_modules/.pnpm/@sanity+logos@2.1.13_@sanity+color@3.0.6_react@18.3.1/node_modules/@sanity/logos/dist/index.js"],"sourcesContent":["var isArray = Array.isArray;\nexport function argsOrArgArray(args) {\n return args.length === 1 && isArray(args[0]) ? args[0] : args;\n}\n//# sourceMappingURL=argsOrArgArray.js.map","import { __read, __spreadArray } from \"tslib\";\nimport { combineLatestInit } from '../observable/combineLatest';\nimport { operate } from '../util/lift';\nimport { argsOrArgArray } from '../util/argsOrArgArray';\nimport { mapOneOrManyArgs } from '../util/mapOneOrManyArgs';\nimport { pipe } from '../util/pipe';\nimport { popResultSelector } from '../util/args';\nexport function combineLatest() {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n var resultSelector = popResultSelector(args);\n return resultSelector\n ? pipe(combineLatest.apply(void 0, __spreadArray([], __read(args))), mapOneOrManyArgs(resultSelector))\n : operate(function (source, subscriber) {\n combineLatestInit(__spreadArray([source], __read(argsOrArgArray(args))))(subscriber);\n });\n}\n//# sourceMappingURL=combineLatest.js.map","import { __read, __spreadArray } from \"tslib\";\nimport { combineLatest } from './combineLatest';\nexport function combineLatestWith() {\n var otherSources = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n otherSources[_i] = arguments[_i];\n }\n return combineLatest.apply(void 0, __spreadArray([], __read(otherSources)));\n}\n//# sourceMappingURL=combineLatestWith.js.map","const e=!(typeof navigator>\"u\")&&\"ReactNative\"===navigator.product,t={timeout:e?6e4:12e4},r=function(r){const a={...t,...\"string\"==typeof r?{url:r}:r};if(a.timeout=n(a.timeout),a.query){const{url:t,searchParams:r}=function(t){const r=t.indexOf(\"?\");if(-1===r)return{url:t,searchParams:new URLSearchParams};const n=t.slice(0,r),a=t.slice(r+1);if(!e)return{url:n,searchParams:new URLSearchParams(a)};if(\"function\"!=typeof decodeURIComponent)throw new Error(\"Broken `URLSearchParams` implementation, and `decodeURIComponent` is not defined\");const s=new URLSearchParams;for(const e of a.split(\"&\")){const[t,r]=e.split(\"=\");t&&s.append(o(t),o(r||\"\"))}return{url:n,searchParams:s}}(a.url);for(const[e,o]of Object.entries(a.query)){if(void 0!==o)if(Array.isArray(o))for(const t of o)r.append(e,t);else r.append(e,o);const n=r.toString();n&&(a.url=`${t}?${n}`)}}return a.method=a.body&&!a.method?\"POST\":(a.method||\"GET\").toUpperCase(),a};function o(e){return decodeURIComponent(e.replace(/\\+/g,\" \"))}function n(e){if(!1===e||0===e)return!1;if(e.connect||e.socket)return e;const r=Number(e);return isNaN(r)?n(t.timeout):{connect:r,socket:r}}const a=/^https?:\\/\\//i,s=function(e){if(!a.test(e.url))throw new Error(`\"${e.url}\" is not a valid URL`)};function c(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,\"default\")?e.default:e}export{c as g,r as p,s as v};//# sourceMappingURL=_commonjsHelpers.js.map\n","import{p as e,v as t,g as r}from\"./_chunks-es/_commonjsHelpers.js\";const o=[\"request\",\"response\",\"progress\",\"error\",\"abort\"],s=[\"processOptions\",\"validateOptions\",\"interceptRequest\",\"finalizeOptions\",\"onRequest\",\"onResponse\",\"onError\",\"onReturn\",\"onHeaders\"];function n(r,a){const i=[],u=s.reduce(((e,t)=>(e[t]=e[t]||[],e)),{processOptions:[e],validateOptions:[t]});function l(e){const t=o.reduce(((e,t)=>(e[t]=function(){const e=/* @__PURE__ */Object.create(null);let t=0;return{publish:function(t){for(const r in e)e[r](t)},subscribe:function(r){const o=t++;return e[o]=r,function(){delete e[o]}}}}(),e)),{}),r=(e=>function(t,r,...o){const s=\"onError\"===t;let n=r;for(let r=0;r<e[t].length&&(n=(0,e[t][r])(n,...o),!s||n);r++);return n})(u),s=r(\"processOptions\",e);r(\"validateOptions\",s);const n={options:s,channels:t,applyMiddleware:r};let i;const l=t.request.subscribe((e=>{i=a(e,((o,s)=>((e,o,s)=>{let n=e,a=o;if(!n)try{a=r(\"onResponse\",o,s)}catch(e){a=null,n=e}n=n&&r(\"onError\",n,s),n?t.error.publish(n):a&&t.response.publish(a)})(o,s,e)))}));t.abort.subscribe((()=>{l(),i&&i.abort()}));const c=r(\"onReturn\",t,n);return c===t&&t.request.publish(n),c}return l.use=function(e){if(!e)throw new Error(\"Tried to add middleware that resolved to falsey value\");if(\"function\"==typeof e)throw new Error(\"Tried to add middleware that was a function. It probably expects you to pass options to it.\");if(e.onReturn&&u.onReturn.length>0)throw new Error(\"Tried to add new middleware with `onReturn` handler, but another handler has already been registered for this event\");return s.forEach((t=>{e[t]&&u[t].push(e[t])})),i.push(e),l},l.clone=()=>n(i,a),r.forEach(l.use),l}var a,i,u=/* @__PURE__ */r(function(){if(i)return a;i=1;var e=function(e){return e.replace(/^\\s+|\\s+$/g,\"\")};return a=function(t){if(!t)return{};for(var r={},o=e(t).split(\"\\n\"),s=0;s<o.length;s++){var n=o[s],a=n.indexOf(\":\"),i=e(n.slice(0,a)).toLowerCase(),u=e(n.slice(a+1));typeof r[i]>\"u\"?r[i]=u:(l=r[i],\"[object Array]\"===Object.prototype.toString.call(l)?r[i].push(u):r[i]=[r[i],u])}var l;return r}}());class l{onabort;onerror;onreadystatechange;ontimeout;readyState=0;response;responseText=\"\";responseType=\"\";status;statusText;withCredentials;#e;#t;#r;#o={};#s;#n={};#a;open(e,t,r){this.#e=e,this.#t=t,this.#r=\"\",this.readyState=1,this.onreadystatechange?.(),this.#s=void 0}abort(){this.#s&&this.#s.abort()}getAllResponseHeaders(){return this.#r}setRequestHeader(e,t){this.#o[e]=t}setInit(e,t=!0){this.#n=e,this.#a=t}send(e){const t=\"arraybuffer\"!==this.responseType,r={...this.#n,method:this.#e,headers:this.#o,body:e};\"function\"==typeof AbortController&&this.#a&&(this.#s=new AbortController,typeof EventTarget<\"u\"&&this.#s.signal instanceof EventTarget&&(r.signal=this.#s.signal)),typeof document<\"u\"&&(r.credentials=this.withCredentials?\"include\":\"omit\"),fetch(this.#t,r).then((e=>(e.headers.forEach(((e,t)=>{this.#r+=`${t}: ${e}\\r\\n`})),this.status=e.status,this.statusText=e.statusText,this.readyState=3,this.onreadystatechange?.(),t?e.text():e.arrayBuffer()))).then((e=>{\"string\"==typeof e?this.responseText=e:this.response=e,this.readyState=4,this.onreadystatechange?.()})).catch((e=>{\"AbortError\"!==e.name?this.onerror?.(e):this.onabort?.()}))}}const c=\"function\"==typeof XMLHttpRequest?\"xhr\":\"fetch\",h=\"xhr\"===c?XMLHttpRequest:l,d=(e,t)=>{const r=e.options,o=e.applyMiddleware(\"finalizeOptions\",r),s={},n=e.applyMiddleware(\"interceptRequest\",void 0,{adapter:c,context:e});if(n){const e=setTimeout(t,0,null,n);return{abort:()=>clearTimeout(e)}}let a=new h;a instanceof l&&\"object\"==typeof o.fetch&&a.setInit(o.fetch,o.useAbortSignal??!0);const i=o.headers,d=o.timeout;let p=!1,f=!1,b=!1;if(a.onerror=e=>{m(a instanceof l?e instanceof Error?e:new Error(`Request error while attempting to reach is ${o.url}`,{cause:e}):new Error(`Request error while attempting to reach is ${o.url}${e.lengthComputable?`(${e.loaded} of ${e.total} bytes transferred)`:\"\"}`))},a.ontimeout=e=>{m(new Error(`Request timeout while attempting to reach ${o.url}${e.lengthComputable?`(${e.loaded} of ${e.total} bytes transferred)`:\"\"}`))},a.onabort=()=>{w(!0),p=!0},a.onreadystatechange=()=>{d&&(w(),s.socket=setTimeout((()=>y(\"ESOCKETTIMEDOUT\")),d.socket)),!p&&4===a.readyState&&0!==a.status&&function(){if(!(p||f||b)){if(0===a.status)return void m(new Error(\"Unknown XHR error\"));w(),f=!0,t(null,{body:a.response||(\"\"===a.responseType||\"text\"===a.responseType?a.responseText:\"\"),url:o.url,method:o.method,headers:u(a.getAllResponseHeaders()),statusCode:a.status,statusMessage:a.statusText})}}()},a.open(o.method,o.url,!0),a.withCredentials=!!o.withCredentials,i&&a.setRequestHeader)for(const e in i)i.hasOwnProperty(e)&&a.setRequestHeader(e,i[e]);return o.rawBody&&(a.responseType=\"arraybuffer\"),e.applyMiddleware(\"onRequest\",{options:o,adapter:c,request:a,context:e}),a.send(o.body||null),d&&(s.connect=setTimeout((()=>y(\"ETIMEDOUT\")),d.connect)),{abort:function(){p=!0,a&&a.abort()}};function y(t){b=!0,a.abort();const r=new Error(\"ESOCKETTIMEDOUT\"===t?`Socket timed out on request to ${o.url}`:`Connection timed out on request to ${o.url}`);r.code=t,e.channels.error.publish(r)}function w(e){(e||p||a.readyState>=2&&s.connect)&&clearTimeout(s.connect),s.socket&&clearTimeout(s.socket)}function m(e){if(f)return;w(!0),f=!0,a=null;const r=e||new Error(`Network error while attempting to reach ${o.url}`);r.isNetworkError=!0,r.request=o,t(r)}},p=(e=[],t=d)=>n(e,t),f=\"browser\";export{c as adapter,f as environment,p as getIt};//# sourceMappingURL=index.browser.js.map\n","import{g as e}from\"./_chunks-es/_commonjsHelpers.js\";import{p as t,v as s}from\"./_chunks-es/_commonjsHelpers.js\";function n(e){return{}}const r=/^\\//,o=/\\/$/;function i(e){const t=e.replace(o,\"\");return{processOptions:e=>{if(/^https?:\\/\\//i.test(e.url))return e;const s=[t,e.url.replace(r,\"\")].join(\"/\");return Object.assign({},e,{url:s})}}}var a,c,u,l,p,d={exports:{}},f=/* @__PURE__ */e((p||(p=1,function(e,t){t.formatArgs=function(t){if(t[0]=(this.useColors?\"%c\":\"\")+this.namespace+(this.useColors?\" %c\":\" \")+t[0]+(this.useColors?\"%c \":\" \")+\"+\"+e.exports.humanize(this.diff),!this.useColors)return;const s=\"color: \"+this.color;t.splice(1,0,s,\"color: inherit\");let n=0,r=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{\"%%\"!==e&&(n++,\"%c\"===e&&(r=n))})),t.splice(r,0,s)},t.save=function(e){try{e?t.storage.setItem(\"debug\",e):t.storage.removeItem(\"debug\")}catch{}},t.load=function(){let e;try{e=t.storage.getItem(\"debug\")}catch{}return!e&&typeof process<\"u\"&&\"env\"in process&&(e=process.env.DEBUG),e},t.useColors=function(){return!(!(typeof window<\"u\"&&window.process)||\"renderer\"!==window.process.type&&!window.process.__nwjs)||!(typeof navigator<\"u\"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\\/(\\d+)/))&&(typeof document<\"u\"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<\"u\"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<\"u\"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator<\"u\"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/))},t.storage=function(){try{return localStorage}catch{}}(),t.destroy=/* @__PURE__ */(()=>{let e=!1;return()=>{e||(e=!0,console.warn(\"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.\"))}})(),t.colors=[\"#0000CC\",\"#0000FF\",\"#0033CC\",\"#0033FF\",\"#0066CC\",\"#0066FF\",\"#0099CC\",\"#0099FF\",\"#00CC00\",\"#00CC33\",\"#00CC66\",\"#00CC99\",\"#00CCCC\",\"#00CCFF\",\"#3300CC\",\"#3300FF\",\"#3333CC\",\"#3333FF\",\"#3366CC\",\"#3366FF\",\"#3399CC\",\"#3399FF\",\"#33CC00\",\"#33CC33\",\"#33CC66\",\"#33CC99\",\"#33CCCC\",\"#33CCFF\",\"#6600CC\",\"#6600FF\",\"#6633CC\",\"#6633FF\",\"#66CC00\",\"#66CC33\",\"#9900CC\",\"#9900FF\",\"#9933CC\",\"#9933FF\",\"#99CC00\",\"#99CC33\",\"#CC0000\",\"#CC0033\",\"#CC0066\",\"#CC0099\",\"#CC00CC\",\"#CC00FF\",\"#CC3300\",\"#CC3333\",\"#CC3366\",\"#CC3399\",\"#CC33CC\",\"#CC33FF\",\"#CC6600\",\"#CC6633\",\"#CC9900\",\"#CC9933\",\"#CCCC00\",\"#CCCC33\",\"#FF0000\",\"#FF0033\",\"#FF0066\",\"#FF0099\",\"#FF00CC\",\"#FF00FF\",\"#FF3300\",\"#FF3333\",\"#FF3366\",\"#FF3399\",\"#FF33CC\",\"#FF33FF\",\"#FF6600\",\"#FF6633\",\"#FF9900\",\"#FF9933\",\"#FFCC00\",\"#FFCC33\"],t.log=console.debug||console.log||(()=>{}),e.exports=(l?u:(l=1,u=function(e){function t(e){let n,r,o,i=null;function a(...e){if(!a.enabled)return;const s=a,r=Number(/* @__PURE__ */new Date),o=r-(n||r);s.diff=o,s.prev=n,s.curr=r,n=r,e[0]=t.coerce(e[0]),\"string\"!=typeof e[0]&&e.unshift(\"%O\");let i=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((n,r)=>{if(\"%%\"===n)return\"%\";i++;const o=t.formatters[r];if(\"function\"==typeof o){const t=e[i];n=o.call(s,t),e.splice(i,1),i--}return n})),t.formatArgs.call(s,e),(s.log||t.log).apply(s,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=s,a.destroy=t.destroy,Object.defineProperty(a,\"enabled\",{enumerable:!0,configurable:!1,get:()=>null!==i?i:(r!==t.namespaces&&(r=t.namespaces,o=t.enabled(e)),o),set:e=>{i=e}}),\"function\"==typeof t.init&&t.init(a),a}function s(e,s){const n=t(this.namespace+(typeof s>\"u\"?\":\":s)+e);return n.log=this.log,n}function n(e){return e.toString().substring(2,e.toString().length-2).replace(/\\.\\*\\?$/,\"*\")}return t.debug=t,t.default=t,t.coerce=function(e){return e instanceof Error?e.stack||e.message:e},t.disable=function(){const e=[...t.names.map(n),...t.skips.map(n).map((e=>\"-\"+e))].join(\",\");return t.enable(\"\"),e},t.enable=function(e){let s;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const n=(\"string\"==typeof e?e:\"\").split(/[\\s,]+/),r=n.length;for(s=0;s<r;s++)n[s]&&(\"-\"===(e=n[s].replace(/\\*/g,\".*?\"))[0]?t.skips.push(new RegExp(\"^\"+e.slice(1)+\"$\")):t.names.push(new RegExp(\"^\"+e+\"$\")))},t.enabled=function(e){if(\"*\"===e[e.length-1])return!0;let s,n;for(s=0,n=t.skips.length;s<n;s++)if(t.skips[s].test(e))return!1;for(s=0,n=t.names.length;s<n;s++)if(t.names[s].test(e))return!0;return!1},t.humanize=function(){if(c)return a;c=1;var e=1e3,t=60*e,s=60*t,n=24*s,r=7*n;function o(e,t,s,n){var r=t>=1.5*s;return Math.round(e/s)+\" \"+n+(r?\"s\":\"\")}return a=function(i,a){a=a||{};var c,u,l=typeof i;if(\"string\"===l&&i.length>0)return function(o){if(!((o=String(o)).length>100)){var i=/^(-?(?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(o);if(i){var a=parseFloat(i[1]);switch((i[2]||\"ms\").toLowerCase()){case\"years\":case\"year\":case\"yrs\":case\"yr\":case\"y\":return 315576e5*a;case\"weeks\":case\"week\":case\"w\":return a*r;case\"days\":case\"day\":case\"d\":return a*n;case\"hours\":case\"hour\":case\"hrs\":case\"hr\":case\"h\":return a*s;case\"minutes\":case\"minute\":case\"mins\":case\"min\":case\"m\":return a*t;case\"seconds\":case\"second\":case\"secs\":case\"sec\":case\"s\":return a*e;case\"milliseconds\":case\"millisecond\":case\"msecs\":case\"msec\":case\"ms\":return a;default:return}}}}(i);if(\"number\"===l&&isFinite(i))return a.long?(c=i,(u=Math.abs(c))>=n?o(c,u,n,\"day\"):u>=s?o(c,u,s,\"hour\"):u>=t?o(c,u,t,\"minute\"):u>=e?o(c,u,e,\"second\"):c+\" ms\"):function(r){var o=Math.abs(r);return o>=n?Math.round(r/n)+\"d\":o>=s?Math.round(r/s)+\"h\":o>=t?Math.round(r/t)+\"m\":o>=e?Math.round(r/e)+\"s\":r+\"ms\"}(i);throw new Error(\"val is not a non-empty string or a valid number. val=\"+JSON.stringify(i))}}(),t.destroy=function(){console.warn(\"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.\")},Object.keys(e).forEach((s=>{t[s]=e[s]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let s=0;for(let t=0;t<e.length;t++)s=(s<<5)-s+e.charCodeAt(t),s|=0;return t.colors[Math.abs(s)%t.colors.length]},t.enable(t.load()),t}))(t);const{formatters:s}=e.exports;s.j=function(e){try{return JSON.stringify(e)}catch(e){return\"[UnexpectedJSONParseError]: \"+e.message}}}(d,d.exports)),d.exports));const m=[\"cookie\",\"authorization\"],C=Object.prototype.hasOwnProperty;function h(e={}){const t=e.verbose,s=e.namespace||\"get-it\",n=f(s),r=e.log||n,o=r===n&&!f.enabled(s);let i=0;return{processOptions:e=>(e.debug=r,e.requestId=e.requestId||++i,e),onRequest:s=>{if(o||!s)return s;const n=s.options;if(r(\"[%s] HTTP %s %s\",n.requestId,n.method,n.url),t&&n.body&&\"string\"==typeof n.body&&r(\"[%s] Request body: %s\",n.requestId,n.body),t&&n.headers){const t=!1===e.redactSensitiveHeaders?n.headers:((e,t)=>{const s={};for(const n in e)C.call(e,n)&&(s[n]=t.indexOf(n.toLowerCase())>-1?\"<redacted>\":e[n]);return s})(n.headers,m);r(\"[%s] Request headers: %s\",n.requestId,JSON.stringify(t,null,2))}return s},onResponse:(e,s)=>{if(o||!e)return e;const n=s.options.requestId;return r(\"[%s] Response code: %s %s\",n,e.statusCode,e.statusMessage),t&&e.body&&r(\"[%s] Response body: %s\",n,function(e){return-1!==(e.headers[\"content-type\"]||\"\").toLowerCase().indexOf(\"application/json\")?function(e){try{const t=\"string\"==typeof e?JSON.parse(e):e;return JSON.stringify(t,null,2)}catch{return e}}(e.body):e.body}(e)),e},onError:(e,t)=>{const s=t.options.requestId;return e?(r(\"[%s] ERROR: %s\",s,e.message),e):(r(\"[%s] Error encountered, but handled by an earlier middleware\",s),e)}}}function g(e,t={}){return{processOptions:s=>{const n=s.headers||{};return s.headers=t.override?Object.assign({},n,e):Object.assign({},e,n),s}}}class b extends Error{response;request;constructor(e,t){super();const s=e.url.length>400?`${e.url.slice(0,399)}…`:e.url;let n=`${e.method}-request to ${s} resulted in `;n+=`HTTP ${e.statusCode} ${e.statusMessage}`,this.message=n.trim(),this.response=e,this.request=t.options}}function y(){return{onResponse:(e,t)=>{if(!(e.statusCode>=400))return e;throw new b(e,t)}}}function w(e={}){if(\"function\"!=typeof e.inject)throw new Error(\"`injectResponse` middleware requires a `inject` function\");return{interceptRequest:function(t,s){const n=e.inject(s,t);if(!n)return t;const r=s.context.options;return{body:\"\",url:r.url,method:r.method,headers:{},statusCode:200,statusMessage:\"OK\",...n}}}}const F=typeof Buffer>\"u\"?()=>!1:e=>Buffer.isBuffer(e);function O(e){return\"[object Object]\"===Object.prototype.toString.call(e)}function j(e){if(!1===O(e))return!1;const t=e.constructor;if(void 0===t)return!0;const s=t.prototype;return!(!1===O(s)||!1===s.hasOwnProperty(\"isPrototypeOf\"))}const v=[\"boolean\",\"string\",\"number\"];function x(){return{processOptions:e=>{const t=e.body;return!t||\"function\"==typeof t.pipe||F(t)||-1===v.indexOf(typeof t)&&!Array.isArray(t)&&!j(t)?e:Object.assign({},e,{body:JSON.stringify(e.body),headers:Object.assign({},e.headers,{\"Content-Type\":\"application/json\"})})}}}function E(e){return{onResponse:s=>{const n=s.headers[\"content-type\"]||\"\",r=e&&e.force||-1!==n.indexOf(\"application/json\");return s.body&&n&&r?Object.assign({},s,{body:t(s.body)}):s},processOptions:e=>Object.assign({},e,{headers:Object.assign({Accept:\"application/json\"},e.headers)})};function t(e){try{return JSON.parse(e)}catch(e){throw e.message=`Failed to parsed response body as JSON: ${e.message}`,e}}}function R(e={}){if(!e.ca)throw new Error('Required mtls option \"ca\" is missing');if(!e.cert)throw new Error('Required mtls option \"cert\" is missing');if(!e.key)throw new Error('Required mtls option \"key\" is missing');return{finalizeOptions:t=>{if(function(e){return\"object\"==typeof e&&null!==e&&!(\"protocol\"in e)}(t))return t;const s={cert:e.cert,key:e.key,ca:e.ca};return Object.assign({},t,s)}}}let k={};typeof globalThis<\"u\"?k=globalThis:typeof window<\"u\"?k=window:typeof global<\"u\"?k=global:typeof self<\"u\"&&(k=self);var q=k;function A(e={}){const t=e.implementation||q.Observable;if(!t)throw new Error(\"`Observable` is not available in global scope, and no implementation was passed\");return{onReturn:(e,s)=>new t((t=>(e.error.subscribe((e=>t.error(e))),e.progress.subscribe((e=>t.next(Object.assign({type:\"progress\"},e)))),e.response.subscribe((e=>{t.next(Object.assign({type:\"response\"},e)),t.complete()})),e.request.publish(s),()=>e.abort.publish())))}}function S(){return{onRequest:e=>{if(\"xhr\"!==e.adapter)return;const t=e.request,s=e.context;function n(e){return t=>{const n=t.lengthComputable?t.loaded/t.total*100:-1;s.channels.progress.publish({stage:e,percent:n,total:t.total,loaded:t.loaded,lengthComputable:t.lengthComputable})}}\"upload\"in t&&\"onprogress\"in t.upload&&(t.upload.onprogress=n(\"upload\")),\"onprogress\"in t&&(t.onprogress=n(\"download\"))}}}const N=(e={})=>{const t=e.implementation||Promise;if(!t)throw new Error(\"`Promise` is not available in global scope, and no implementation was passed\");return{onReturn:(s,n)=>new t(((t,r)=>{const o=n.options.cancelToken;o&&o.promise.then((e=>{s.abort.publish(e),r(e)})),s.error.subscribe(r),s.response.subscribe((s=>{t(e.onlyBody?s.body:s)})),setTimeout((()=>{try{s.request.publish(n)}catch(e){r(e)}}),0)}))}};class ${__CANCEL__=!0;message;constructor(e){this.message=e}toString(){return\"Cancel\"+(this.message?`: ${this.message}`:\"\")}}class T{promise;reason;constructor(e){if(\"function\"!=typeof e)throw new TypeError(\"executor must be a function.\");let t=null;this.promise=new Promise((e=>{t=e})),e((e=>{this.reason||(this.reason=new $(e),t(this.reason))}))}static source=()=>{let e;return{token:new T((t=>{e=t})),cancel:e}}}function I(e){if(!(!1===e||e&&e.host))throw new Error(\"Proxy middleware takes an object of host, port and auth properties\");return{processOptions:t=>Object.assign({proxy:e},t)}}N.Cancel=$,N.CancelToken=T,N.isCancel=e=>!(!e||!e?.__CANCEL__);var M=(e,t,s)=>(\"GET\"===s.method||\"HEAD\"===s.method)&&(e.isNetworkError||!1);function _(e){return 100*Math.pow(2,e)+100*Math.random()}const P=(e={})=>(e=>{const t=e.maxRetries||5,s=e.retryDelay||_,n=e.shouldRetry;return{onError:(e,r)=>{const o=r.options,i=o.maxRetries||t,a=o.retryDelay||s,c=o.shouldRetry||n,u=o.attemptNumber||0;if(null!==(l=o.body)&&\"object\"==typeof l&&\"function\"==typeof l.pipe||!c(e,u,o)||u>=i)return e;var l;const p=Object.assign({},r,{options:Object.assign({},o,{attemptNumber:u+1})});return setTimeout((()=>r.channels.request.publish(p)),a(u)),null}}})({shouldRetry:M,...e});function J(e){const t=new URLSearchParams,s=(e,n)=>{const r=n instanceof Set?Array.from(n):n;if(Array.isArray(r))if(r.length)for(const t in r)s(`${e}[${t}]`,r[t]);else t.append(`${e}[]`,\"\");else if(\"object\"==typeof r&&null!==r)for(const[t,n]of Object.entries(r))s(`${e}[${t}]`,n);else t.append(e,r)};for(const[t,n]of Object.entries(e))s(t,n);return t.toString()}function L(){return{processOptions:e=>{const t=e.body;return t&&\"function\"!=typeof t.pipe&&!F(t)&&j(t)?{...e,body:J(e.body),headers:{...e.headers,\"Content-Type\":\"application/x-www-form-urlencoded\"}}:e}}}P.shouldRetry=M;class z extends Error{request;code;constructor(e,t){super(e.message),this.request=t,this.code=e.code}}const H=(B=n,function(e={}){const{maxRetries:t=3,ms:s=1e3,maxFree:n=256}=e,{finalizeOptions:r}=B({keepAlive:!0,keepAliveMsecs:s,maxFreeSockets:n});return{finalizeOptions:r,onError:(e,s)=>{if((\"GET\"===s.options.method||\"POST\"===s.options.method)&&e instanceof z&&\"ECONNRESET\"===e.code&&e.request.reusedSocket){const e=s.options.attemptNumber||0;if(e<t){const t=Object.assign({},s,{options:Object.assign({},s.options,{attemptNumber:e+1})});return setImmediate((()=>s.channels.request.publish(t))),null}}return e}}});var B;export{$ as Cancel,T as CancelToken,n as agent,i as base,h as debug,g as headers,y as httpErrors,w as injectResponse,x as jsonRequest,E as jsonResponse,H as keepAlive,R as mtls,A as observable,t as processOptions,S as progress,N as promise,I as proxy,P as retry,L as urlEncoded,s as validateOptions};//# sourceMappingURL=middleware.browser.js.map\n","var s = { 0: 8203, 1: 8204, 2: 8205, 3: 8290, 4: 8291, 5: 8288, 6: 65279, 7: 8289, 8: 119155, 9: 119156, a: 119157, b: 119158, c: 119159, d: 119160, e: 119161, f: 119162 }, c = { 0: 8203, 1: 8204, 2: 8205, 3: 65279 }, u = new Array(4).fill(String.fromCodePoint(c[0])).join(\"\");\nfunction E(t) {\n let e = JSON.stringify(t);\n return `${u}${Array.from(e).map((r) => {\n let n = r.charCodeAt(0);\n if (n > 255) throw new Error(`Only ASCII edit info can be encoded. Error attempting to encode ${e} on character ${r} (${n})`);\n return Array.from(n.toString(4).padStart(4, \"0\")).map((o) => String.fromCodePoint(c[o])).join(\"\");\n }).join(\"\")}`;\n}\nfunction I(t) {\n return !Number.isNaN(Number(t)) || /[a-z]/i.test(t) && !/\\d+(?:[-:\\/]\\d+){2}(?:T\\d+(?:[-:\\/]\\d+){1,2}(\\.\\d+)?Z?)?/.test(t) ? !1 : !!Date.parse(t);\n}\nfunction T(t) {\n try {\n new URL(t, t.startsWith(\"/\") ? \"https://acme.com\" : void 0);\n } catch {\n return !1;\n }\n return !0;\n}\nfunction C(t, e, r = \"auto\") {\n return r === !0 || r === \"auto\" && (I(t) || T(t)) ? t : `${t}${E(e)}`;\n}\nObject.fromEntries(Object.entries(c).map((t) => t.reverse()));\nObject.fromEntries(Object.entries(s).map((t) => t.reverse()));\nvar S = `${Object.values(s).map((t) => `\\\\u{${t.toString(16)}}`).join(\"\")}`, f = new RegExp(`[${S}]{4,}`, \"gu\");\nfunction _(t) {\n var e;\n return { cleaned: t.replace(f, \"\"), encoded: ((e = t.match(f)) == null ? void 0 : e[0]) || \"\" };\n}\nfunction O(t) {\n return t && JSON.parse(_(JSON.stringify(t)).cleaned);\n}\nfunction stegaClean(result) {\n return O(result);\n}\nconst vercelStegaCleanAll = stegaClean;\nexport {\n C,\n stegaClean,\n vercelStegaCleanAll\n};\n//# sourceMappingURL=stegaClean.js.map\n","import { getIt } from \"get-it\";\nimport { adapter, environment } from \"get-it\";\nimport { retry, jsonRequest, jsonResponse, progress, observable } from \"get-it/middleware\";\nimport { Observable, from, lastValueFrom } from \"rxjs\";\nimport { stegaClean } from \"./_chunks-es/stegaClean.js\";\nimport { combineLatestWith, map, filter } from \"rxjs/operators\";\nclass ClientError extends Error {\n response;\n statusCode = 400;\n responseBody;\n details;\n constructor(res) {\n const props = extractErrorProps(res);\n super(props.message), Object.assign(this, props);\n }\n}\nclass ServerError extends Error {\n response;\n statusCode = 500;\n responseBody;\n details;\n constructor(res) {\n const props = extractErrorProps(res);\n super(props.message), Object.assign(this, props);\n }\n}\nfunction extractErrorProps(res) {\n const body = res.body, props = {\n response: res,\n statusCode: res.statusCode,\n responseBody: stringifyBody(body, res),\n message: \"\",\n details: void 0\n };\n if (body.error && body.message)\n return props.message = `${body.error} - ${body.message}`, props;\n if (isMutationError(body) || isActionError(body)) {\n const allItems = body.error.items || [], items = allItems.slice(0, 5).map((item) => item.error?.description).filter(Boolean);\n let itemsStr = items.length ? `:\n- ${items.join(`\n- `)}` : \"\";\n return allItems.length > 5 && (itemsStr += `\n...and ${allItems.length - 5} more`), props.message = `${body.error.description}${itemsStr}`, props.details = body.error, props;\n }\n return body.error && body.error.description ? (props.message = body.error.description, props.details = body.error, props) : (props.message = body.error || body.message || httpErrorMessage(res), props);\n}\nfunction isMutationError(body) {\n return isPlainObject(body) && isPlainObject(body.error) && body.error.type === \"mutationError\" && typeof body.error.description == \"string\";\n}\nfunction isActionError(body) {\n return isPlainObject(body) && isPlainObject(body.error) && body.error.type === \"actionError\" && typeof body.error.description == \"string\";\n}\nfunction isPlainObject(obj) {\n return typeof obj == \"object\" && obj !== null && !Array.isArray(obj);\n}\nfunction httpErrorMessage(res) {\n const statusMessage = res.statusMessage ? ` ${res.statusMessage}` : \"\";\n return `${res.method}-request to ${res.url} resulted in HTTP ${res.statusCode}${statusMessage}`;\n}\nfunction stringifyBody(body, res) {\n return (res.headers[\"content-type\"] || \"\").toLowerCase().indexOf(\"application/json\") !== -1 ? JSON.stringify(body, null, 2) : body;\n}\nclass CorsOriginError extends Error {\n projectId;\n addOriginUrl;\n constructor({ projectId: projectId2 }) {\n super(\"CorsOriginError\"), this.name = \"CorsOriginError\", this.projectId = projectId2;\n const url = new URL(`https://sanity.io/manage/project/${projectId2}/api`);\n if (typeof location < \"u\") {\n const { origin } = location;\n url.searchParams.set(\"cors\", \"add\"), url.searchParams.set(\"origin\", origin), this.addOriginUrl = url, this.message = `The current origin is not allowed to connect to the Live Content API. Add it here: ${url}`;\n } else\n this.message = `The current origin is not allowed to connect to the Live Content API. Change your configuration here: ${url}`;\n }\n}\nconst httpError = {\n onResponse: (res) => {\n if (res.statusCode >= 500)\n throw new ServerError(res);\n if (res.statusCode >= 400)\n throw new ClientError(res);\n return res;\n }\n}, printWarnings = {\n onResponse: (res) => {\n const warn = res.headers[\"x-sanity-warning\"];\n return (Array.isArray(warn) ? warn : [warn]).filter(Boolean).forEach((msg) => console.warn(msg)), res;\n }\n};\nfunction defineHttpRequest(envMiddleware2) {\n return getIt([\n retry({ shouldRetry }),\n ...envMiddleware2,\n printWarnings,\n jsonRequest(),\n jsonResponse(),\n progress(),\n httpError,\n observable({ implementation: Observable })\n ]);\n}\nfunction shouldRetry(err, attempt, options) {\n if (options.maxRetries === 0) return !1;\n const isSafe = options.method === \"GET\" || options.method === \"HEAD\", isQuery = (options.uri || options.url).startsWith(\"/data/query\"), isRetriableResponse = err.response && (err.response.statusCode === 429 || err.response.statusCode === 502 || err.response.statusCode === 503);\n return (isSafe || isQuery) && isRetriableResponse ? !0 : retry.shouldRetry(err, attempt, options);\n}\nconst BASE_URL = \"https://www.sanity.io/help/\";\nfunction generateHelpUrl(slug) {\n return BASE_URL + slug;\n}\nconst VALID_ASSET_TYPES = [\"image\", \"file\"], VALID_INSERT_LOCATIONS = [\"before\", \"after\", \"replace\"], dataset = (name) => {\n if (!/^(~[a-z0-9]{1}[-\\w]{0,63}|[a-z0-9]{1}[-\\w]{0,63})$/.test(name))\n throw new Error(\n \"Datasets can only contain lowercase characters, numbers, underscores and dashes, and start with tilde, and be maximum 64 characters\"\n );\n}, projectId = (id) => {\n if (!/^[-a-z0-9]+$/i.test(id))\n throw new Error(\"`projectId` can only contain only a-z, 0-9 and dashes\");\n}, validateAssetType = (type) => {\n if (VALID_ASSET_TYPES.indexOf(type) === -1)\n throw new Error(`Invalid asset type: ${type}. Must be one of ${VALID_ASSET_TYPES.join(\", \")}`);\n}, validateObject = (op, val) => {\n if (val === null || typeof val != \"object\" || Array.isArray(val))\n throw new Error(`${op}() takes an object of properties`);\n}, validateDocumentId = (op, id) => {\n if (typeof id != \"string\" || !/^[a-z0-9_][a-z0-9_.-]{0,127}$/i.test(id) || id.includes(\"..\"))\n throw new Error(`${op}(): \"${id}\" is not a valid document ID`);\n}, requireDocumentId = (op, doc) => {\n if (!doc._id)\n throw new Error(`${op}() requires that the document contains an ID (\"_id\" property)`);\n validateDocumentId(op, doc._id);\n}, validateInsert = (at, selector, items) => {\n const signature = \"insert(at, selector, items)\";\n if (VALID_INSERT_LOCATIONS.indexOf(at) === -1) {\n const valid = VALID_INSERT_LOCATIONS.map((loc) => `\"${loc}\"`).join(\", \");\n throw new Error(`${signature} takes an \"at\"-argument which is one of: ${valid}`);\n }\n if (typeof selector != \"string\")\n throw new Error(`${signature} takes a \"selector\"-argument which must be a string`);\n if (!Array.isArray(items))\n throw new Error(`${signature} takes an \"items\"-argument which must be an array`);\n}, hasDataset = (config) => {\n if (!config.dataset)\n throw new Error(\"`dataset` must be provided to perform queries\");\n return config.dataset || \"\";\n}, requestTag = (tag) => {\n if (typeof tag != \"string\" || !/^[a-z0-9._-]{1,75}$/i.test(tag))\n throw new Error(\n \"Tag can only contain alphanumeric characters, underscores, dashes and dots, and be between one and 75 characters long.\"\n );\n return tag;\n};\nfunction once(fn) {\n let didCall = !1, returnValue;\n return (...args) => (didCall || (returnValue = fn(...args), didCall = !0), returnValue);\n}\nconst createWarningPrinter = (message) => (\n // eslint-disable-next-line no-console\n once((...args) => console.warn(message.join(\" \"), ...args))\n), printCdnAndWithCredentialsWarning = createWarningPrinter([\n \"Because you set `withCredentials` to true, we will override your `useCdn`\",\n \"setting to be false since (cookie-based) credentials are never set on the CDN\"\n]), printCdnWarning = createWarningPrinter([\n \"Since you haven't set a value for `useCdn`, we will deliver content using our\",\n \"global, edge-cached API-CDN. If you wish to have content delivered faster, set\",\n \"`useCdn: false` to use the Live API. Note: You may incur higher costs using the live API.\"\n]), printCdnPreviewDraftsWarning = createWarningPrinter([\n \"The Sanity client is configured with the `perspective` set to `previewDrafts`, which doesn't support the API-CDN.\",\n \"The Live API will be used instead. Set `useCdn: false` in your configuration to hide this warning.\"\n]), printBrowserTokenWarning = createWarningPrinter([\n \"You have configured Sanity client to use a token in the browser. This may cause unintentional security issues.\",\n `See ${generateHelpUrl(\n \"js-client-browser-token\"\n )} for more information and how to hide this warning.`\n]), printNoApiVersionSpecifiedWarning = createWarningPrinter([\n \"Using the Sanity client without specifying an API version is deprecated.\",\n `See ${generateHelpUrl(\"js-client-api-version\")}`\n]), printNoDefaultExport = createWarningPrinter([\n \"The default export of @sanity/client has been deprecated. Use the named export `createClient` instead.\"\n]), defaultCdnHost = \"apicdn.sanity.io\", defaultConfig = {\n apiHost: \"https://api.sanity.io\",\n apiVersion: \"1\",\n useProjectHostname: !0,\n stega: { enabled: !1 }\n}, LOCALHOSTS = [\"localhost\", \"127.0.0.1\", \"0.0.0.0\"], isLocal = (host) => LOCALHOSTS.indexOf(host) !== -1;\nfunction validateApiVersion(apiVersion) {\n if (apiVersion === \"1\" || apiVersion === \"X\")\n return;\n const apiDate = new Date(apiVersion);\n if (!(/^\\d{4}-\\d{2}-\\d{2}$/.test(apiVersion) && apiDate instanceof Date && apiDate.getTime() > 0))\n throw new Error(\"Invalid API version string, expected `1` or date in format `YYYY-MM-DD`\");\n}\nfunction validateApiPerspective(perspective) {\n if (Array.isArray(perspective)) {\n for (const perspectiveValue of perspective)\n if (perspectiveValue !== \"published\" && perspectiveValue !== \"drafts\" && !(typeof perspectiveValue == \"string\" && perspectiveValue.startsWith(\"r\") && perspectiveValue !== \"raw\"))\n throw new TypeError(\n \"Invalid API perspective value, expected `published`, `drafts` or a valid release identifier string\"\n );\n return;\n }\n switch (perspective) {\n case \"previewDrafts\":\n case \"drafts\":\n case \"published\":\n case \"raw\":\n return;\n default:\n throw new TypeError(\n \"Invalid API perspective string, expected `published`, `previewDrafts` or `raw`\"\n );\n }\n}\nconst initConfig = (config, prevConfig) => {\n const specifiedConfig = {\n ...prevConfig,\n ...config,\n stega: {\n ...typeof prevConfig.stega == \"boolean\" ? { enabled: prevConfig.stega } : prevConfig.stega || defaultConfig.stega,\n ...typeof config.stega == \"boolean\" ? { enabled: config.stega } : config.stega || {}\n }\n };\n specifiedConfig.apiVersion || printNoApiVersionSpecifiedWarning();\n const newConfig = {\n ...defaultConfig,\n ...specifiedConfig\n }, projectBased = newConfig.useProjectHostname;\n if (typeof Promise > \"u\") {\n const helpUrl = generateHelpUrl(\"js-client-promise-polyfill\");\n throw new Error(`No native Promise-implementation found, polyfill needed - see ${helpUrl}`);\n }\n if (projectBased && !newConfig.projectId)\n throw new Error(\"Configuration must contain `projectId`\");\n if (typeof newConfig.perspective < \"u\" && validateApiPerspective(newConfig.perspective), \"encodeSourceMap\" in newConfig)\n throw new Error(\n \"It looks like you're using options meant for '@sanity/preview-kit/client'. 'encodeSourceMap' is not supported in '@sanity/client'. Did you mean 'stega.enabled'?\"\n );\n if (\"encodeSourceMapAtPath\" in newConfig)\n throw new Error(\n \"It looks like you're using options meant for '@sanity/preview-kit/client'. 'encodeSourceMapAtPath' is not supported in '@sanity/client'. Did you mean 'stega.filter'?\"\n );\n if (typeof newConfig.stega.enabled != \"boolean\")\n throw new Error(`stega.enabled must be a boolean, received ${newConfig.stega.enabled}`);\n if (newConfig.stega.enabled && newConfig.stega.studioUrl === void 0)\n throw new Error(\"stega.studioUrl must be defined when stega.enabled is true\");\n if (newConfig.stega.enabled && typeof newConfig.stega.studioUrl != \"string\" && typeof newConfig.stega.studioUrl != \"function\")\n throw new Error(\n `stega.studioUrl must be a string or a function, received ${newConfig.stega.studioUrl}`\n );\n const isBrowser = typeof window < \"u\" && window.location && window.location.hostname, isLocalhost = isBrowser && isLocal(window.location.hostname);\n isBrowser && isLocalhost && newConfig.token && newConfig.ignoreBrowserTokenWarning !== !0 ? printBrowserTokenWarning() : typeof newConfig.useCdn > \"u\" && printCdnWarning(), projectBased && projectId(newConfig.projectId), newConfig.dataset && dataset(newConfig.dataset), \"requestTagPrefix\" in newConfig && (newConfig.requestTagPrefix = newConfig.requestTagPrefix ? requestTag(newConfig.requestTagPrefix).replace(/\\.+$/, \"\") : void 0), newConfig.apiVersion = `${newConfig.apiVersion}`.replace(/^v/, \"\"), newConfig.isDefaultApi = newConfig.apiHost === defaultConfig.apiHost, newConfig.useCdn === !0 && newConfig.withCredentials && printCdnAndWithCredentialsWarning(), newConfig.useCdn = newConfig.useCdn !== !1 && !newConfig.withCredentials, validateApiVersion(newConfig.apiVersion);\n const hostParts = newConfig.apiHost.split(\"://\", 2), protocol = hostParts[0], host = hostParts[1], cdnHost = newConfig.isDefaultApi ? defaultCdnHost : host;\n return newConfig.useProjectHostname ? (newConfig.url = `${protocol}://${newConfig.projectId}.${host}/v${newConfig.apiVersion}`, newConfig.cdnUrl = `${protocol}://${newConfig.projectId}.${cdnHost}/v${newConfig.apiVersion}`) : (newConfig.url = `${newConfig.apiHost}/v${newConfig.apiVersion}`, newConfig.cdnUrl = newConfig.url), newConfig;\n};\nfunction getSelection(sel) {\n if (typeof sel == \"string\")\n return { id: sel };\n if (Array.isArray(sel))\n return { query: \"*[_id in $ids]\", params: { ids: sel } };\n if (typeof sel == \"object\" && sel !== null && \"query\" in sel && typeof sel.query == \"string\")\n return \"params\" in sel && typeof sel.params == \"object\" && sel.params !== null ? { query: sel.query, params: sel.params } : { query: sel.query };\n const selectionOpts = [\n \"* Document ID (<docId>)\",\n \"* Array of document IDs\",\n \"* Object containing `query`\"\n ].join(`\n`);\n throw new Error(`Unknown selection - must be one of:\n\n${selectionOpts}`);\n}\nclass BasePatch {\n selection;\n operations;\n constructor(selection, operations = {}) {\n this.selection = selection, this.operations = operations;\n }\n /**\n * Sets the given attributes to the document. Does NOT merge objects.\n * The operation is added to the current patch, ready to be commited by `commit()`\n *\n * @param attrs - Attributes to set. To set a deep attribute, use JSONMatch, eg: \\{\"nested.prop\": \"value\"\\}\n */\n set(attrs) {\n return this._assign(\"set\", attrs);\n }\n /**\n * Sets the given attributes to the document if they are not currently set. Does NOT merge objects.\n * The operation is added to the current patch, ready to be commited by `commit()`\n *\n * @param attrs - Attributes to set. To set a deep attribute, use JSONMatch, eg: \\{\"nested.prop\": \"value\"\\}\n */\n setIfMissing(attrs) {\n return this._assign(\"setIfMissing\", attrs);\n }\n /**\n * Performs a \"diff-match-patch\" operation on the string attributes provided.\n * The operation is added to the current patch, ready to be commited by `commit()`\n *\n * @param attrs - Attributes to perform operation on. To set a deep attribute, use JSONMatch, eg: \\{\"nested.prop\": \"dmp\"\\}\n */\n diffMatchPatch(attrs) {\n return validateObject(\"diffMatchPatch\", attrs), this._assign(\"diffMatchPatch\", attrs);\n }\n /**\n * Unsets the attribute paths provided.\n * The operation is added to the current patch, ready to be commited by `commit()`\n *\n * @param attrs - Attribute paths to unset.\n */\n unset(attrs) {\n if (!Array.isArray(attrs))\n throw new Error(\"unset(attrs) takes an array of attributes to unset, non-array given\");\n return this.operations = Object.assign({}, this.operations, { unset: attrs }), this;\n }\n /**\n * Increment a numeric value. Each entry in the argument is either an attribute or a JSON path. The value may be a positive or negative integer or floating-point value. The operation will fail if target value is not a numeric value, or doesn't exist.\n *\n * @param attrs - Object of attribute paths to increment, values representing the number to increment by.\n */\n inc(attrs) {\n return this._assign(\"inc\", attrs);\n }\n /**\n * Decrement a numeric value. Each entry in the argument is either an attribute or a JSON path. The value may be a positive or negative integer or floating-point value. The operation will fail if target value is not a numeric value, or doesn't exist.\n *\n * @param attrs - Object of attribute paths to decrement, values representing the number to decrement by.\n */\n dec(attrs) {\n return this._assign(\"dec\", attrs);\n }\n /**\n * Provides methods for modifying arrays, by inserting, appending and replacing elements via a JSONPath expression.\n *\n * @param at - Location to insert at, relative to the given selector, or 'replace' the matched path\n * @param selector - JSONPath expression, eg `comments[-1]` or `blocks[_key==\"abc123\"]`\n * @param items - Array of items to insert/replace\n */\n insert(at, selector, items) {\n return validateInsert(at, selector, items), this._assign(\"insert\", { [at]: selector, items });\n }\n /**\n * Append the given items to the array at the given JSONPath\n *\n * @param selector - Attribute/path to append to, eg `comments` or `person.hobbies`\n * @param items - Array of items to append to the array\n */\n append(selector, items) {\n return this.insert(\"after\", `${selector}[-1]`, items);\n }\n /**\n * Prepend the given items to the array at the given JSONPath\n *\n * @param selector - Attribute/path to prepend to, eg `comments` or `person.hobbies`\n * @param items - Array of items to prepend to the array\n */\n prepend(selector, items) {\n return this.insert(\"before\", `${selector}[0]`, items);\n }\n /**\n * Change the contents of an array by removing existing elements and/or adding new elements.\n *\n * @param selector - Attribute or JSONPath expression for array\n * @param start - Index at which to start changing the array (with origin 0). If greater than the length of the array, actual starting index will be set to the length of the array. If negative, will begin that many elements from the end of the array (with origin -1) and will be set to 0 if absolute value is greater than the length of the array.x\n * @param deleteCount - An integer indicating the number of old array elements to remove.\n * @param items - The elements to add to the array, beginning at the start index. If you don't specify any elements, splice() will only remove elements from the array.\n */\n splice(selector, start, deleteCount, items) {\n const delAll = typeof deleteCount > \"u\" || deleteCount === -1, startIndex = start < 0 ? start - 1 : start, delCount = delAll ? -1 : Math.max(0, start + deleteCount), delRange = startIndex < 0 && delCount >= 0 ? \"\" : delCount, rangeSelector = `${selector}[${startIndex}:${delRange}]`;\n return this.insert(\"replace\", rangeSelector, items || []);\n }\n /**\n * Adds a revision clause, preventing the document from being patched if the `_rev` property does not match the given value\n *\n * @param rev - Revision to lock the patch to\n */\n ifRevisionId(rev) {\n return this.operations.ifRevisionID = rev, this;\n }\n /**\n * Return a plain JSON representation of the patch\n */\n serialize() {\n return { ...getSelection(this.selection), ...this.operations };\n }\n /**\n * Return a plain JSON representation of the patch\n */\n toJSON() {\n return this.serialize();\n }\n /**\n * Clears the patch of all operations\n */\n reset() {\n return this.operations = {}, this;\n }\n _assign(op, props, merge = !0) {\n return validateObject(op, props), this.operations = Object.assign({}, this.operations, {\n [op]: Object.assign({}, merge && this.operations[op] || {}, props)\n }), this;\n }\n _set(op, props) {\n return this._assign(op, props, !1);\n }\n}\nclass ObservablePatch extends BasePatch {\n #client;\n constructor(selection, operations, client) {\n super(selection, operations), this.#client = client;\n }\n /**\n * Clones the patch\n */\n clone() {\n return new ObservablePatch(this.selection, { ...this.operations }, this.#client);\n }\n commit(options) {\n if (!this.#client)\n throw new Error(\n \"No `client` passed to patch, either provide one or pass the patch to a clients `mutate()` method\"\n );\n const returnFirst = typeof this.selection == \"string\", opts = Object.assign({ returnFirst, returnDocuments: !0 }, options);\n return this.#client.mutate({ patch: this.serialize() }, opts);\n }\n}\nclass Patch extends BasePatch {\n #client;\n constructor(selection, operations, client) {\n super(selection, operations), this.#client = client;\n }\n /**\n * Clones the patch\n */\n clone() {\n return new Patch(this.selection, { ...this.operations }, this.#client);\n }\n commit(options) {\n if (!this.#client)\n throw new Error(\n \"No `client` passed to patch, either provide one or pass the patch to a clients `mutate()` method\"\n );\n const returnFirst = typeof this.selection == \"string\", opts = Object.assign({ returnFirst, returnDocuments: !0 }, options);\n return this.#client.mutate({ patch: this.serialize() }, opts);\n }\n}\nconst defaultMutateOptions = { returnDocuments: !1 };\nclass BaseTransaction {\n operations;\n trxId;\n constructor(operations = [], transactionId) {\n this.operations = operations, this.trxId = transactionId;\n }\n /**\n * Creates a new Sanity document. If `_id` is provided and already exists, the mutation will fail. If no `_id` is given, one will automatically be generated by the database.\n * The operation is added to the current transaction, ready to be commited by `commit()`\n *\n * @param doc - Document to create. Requires a `_type` property.\n */\n create(doc) {\n return validateObject(\"create\", doc), this._add({ create: doc });\n }\n /**\n * Creates a new Sanity document. If a document with the same `_id` already exists, the create operation will be ignored.\n * The operation is added to the current transaction, ready to be commited by `commit()`\n *\n * @param doc - Document to create if it does not already exist. Requires `_id` and `_type` properties.\n */\n createIfNotExists(doc) {\n const op = \"createIfNotExists\";\n return validateObject(op, doc), requireDocumentId(op, doc), this._add({ [op]: doc });\n }\n /**\n * Creates a new Sanity document, or replaces an existing one if the same `_id` is already used.\n * The operation is added to the current transaction, ready to be commited by `commit()`\n *\n * @param doc - Document to create or replace. Requires `_id` and `_type` properties.\n */\n createOrReplace(doc) {\n const op = \"createOrReplace\";\n return validateObject(op, doc), requireDocumentId(op, doc), this._add({ [op]: doc });\n }\n /**\n * Deletes the document with the given document ID\n * The operation is added to the current transaction, ready to be commited by `commit()`\n *\n * @param documentId - Document ID to delete\n */\n delete(documentId) {\n return validateDocumentId(\"delete\", documentId), this._add({ delete: { id: documentId } });\n }\n transactionId(id) {\n return id ? (this.trxId = id, this) : this.trxId;\n }\n /**\n * Return a plain JSON representation of the transaction\n */\n serialize() {\n return [...this.operations];\n }\n /**\n * Return a plain JSON representation of the transaction\n */\n toJSON() {\n return this.serialize();\n }\n /**\n * Clears the transaction of all operations\n */\n reset() {\n return this.operations = [], this;\n }\n _add(mut) {\n return this.operations.push(mut), this;\n }\n}\nclass Transaction extends BaseTransaction {\n #client;\n constructor(operations, client, transactionId) {\n super(operations, transactionId), this.#client = client;\n }\n /**\n * Clones the transaction\n */\n clone() {\n return new Transaction([...this.operations], this.#client, this.trxId);\n }\n commit(options) {\n if (!this.#client)\n throw new Error(\n \"No `client` passed to transaction, either provide one or pass the transaction to a clients `mutate()` method\"\n );\n return this.#client.mutate(\n this.serialize(),\n Object.assign({ transactionId: this.trxId }, defaultMutateOptions, options || {})\n );\n }\n patch(patchOrDocumentId, patchOps) {\n const isBuilder = typeof patchOps == \"function\";\n if (typeof patchOrDocumentId != \"string\" && patchOrDocumentId instanceof Patch)\n return this._add({ patch: patchOrDocumentId.serialize() });\n if (isBuilder) {\n const patch = patchOps(new Patch(patchOrDocumentId, {}, this.#client));\n if (!(patch instanceof Patch))\n throw new Error(\"function passed to `patch()` must return the patch\");\n return this._add({ patch: patch.serialize() });\n }\n return this._add({ patch: { id: patchOrDocumentId, ...patchOps } });\n }\n}\nclass ObservableTransaction extends BaseTransaction {\n #client;\n constructor(operations, client, transactionId) {\n super(operations, transactionId), this.#client = client;\n }\n /**\n * Clones the transaction\n */\n clone() {\n return new ObservableTransaction([...this.operations], this.#client, this.trxId);\n }\n commit(options) {\n if (!this.#client)\n throw new Error(\n \"No `client` passed to transaction, either provide one or pass the transaction to a clients `mutate()` method\"\n );\n return this.#client.mutate(\n this.serialize(),\n Object.assign({ transactionId: this.trxId }, defaultMutateOptions, options || {})\n );\n }\n patch(patchOrDocumentId, patchOps) {\n const isBuilder = typeof patchOps == \"function\";\n if (typeof patchOrDocumentId != \"string\" && patchOrDocumentId instanceof ObservablePatch)\n return this._add({ patch: patchOrDocumentId.serialize() });\n if (isBuilder) {\n const patch = patchOps(new ObservablePatch(patchOrDocumentId, {}, this.#client));\n if (!(patch instanceof ObservablePatch))\n throw new Error(\"function passed to `patch()` must return the patch\");\n return this._add({ patch: patch.serialize() });\n }\n return this._add({ patch: { id: patchOrDocumentId, ...patchOps } });\n }\n}\nconst projectHeader = \"X-Sanity-Project-ID\";\nfunction requestOptions(config, overrides = {}) {\n const headers = {}, token = overrides.token || config.token;\n token && (headers.Authorization = `Bearer ${token}`), !overrides.useGlobalApi && !config.useProjectHostname && config.projectId && (headers[projectHeader] = config.projectId);\n const withCredentials = !!(typeof overrides.withCredentials > \"u\" ? config.token || config.withCredentials : overrides.withCredentials), timeout = typeof overrides.timeout > \"u\" ? config.timeout : overrides.timeout;\n return Object.assign({}, overrides, {\n headers: Object.assign({}, headers, overrides.headers || {}),\n timeout: typeof timeout > \"u\" ? 5 * 60 * 1e3 : timeout,\n proxy: overrides.proxy || config.proxy,\n json: !0,\n withCredentials,\n fetch: typeof overrides.fetch == \"object\" && typeof config.fetch == \"object\" ? { ...config.fetch, ...overrides.fetch } : overrides.fetch || config.fetch\n });\n}\nconst encodeQueryString = ({\n query,\n params = {},\n options = {}\n}) => {\n const searchParams = new URLSearchParams(), { tag, includeMutations, returnQuery, ...opts } = options;\n tag && searchParams.append(\"tag\", tag), searchParams.append(\"query\", query);\n for (const [key, value] of Object.entries(params))\n searchParams.append(`$${key}`, JSON.stringify(value));\n for (const [key, value] of Object.entries(opts))\n value && searchParams.append(key, `${value}`);\n return returnQuery === !1 && searchParams.append(\"returnQuery\", \"false\"), includeMutations === !1 && searchParams.append(\"includeMutations\", \"false\"), `?${searchParams}`;\n}, excludeFalsey = (param, defValue) => param === !1 ? void 0 : typeof param > \"u\" ? defValue : param, getMutationQuery = (options = {}) => ({\n dryRun: options.dryRun,\n returnIds: !0,\n returnDocuments: excludeFalsey(options.returnDocuments, !0),\n visibility: options.visibility || \"sync\",\n autoGenerateArrayKeys: options.autoGenerateArrayKeys,\n skipCrossDatasetReferenceValidation: options.skipCrossDatasetReferenceValidation\n}), isResponse = (event) => event.type === \"response\", getBody = (event) => event.body, indexBy = (docs, attr) => docs.reduce((indexed, doc) => (indexed[attr(doc)] = doc, indexed), /* @__PURE__ */ Object.create(null)), getQuerySizeLimit = 11264;\nfunction _fetch(client, httpRequest, _stega, query, _params = {}, options = {}) {\n const stega = \"stega\" in options ? {\n ..._stega || {},\n ...typeof options.stega == \"boolean\" ? { enabled: options.stega } : options.stega || {}\n } : _stega, params = stega.enabled ? stegaClean(_params) : _params, mapResponse = options.filterResponse === !1 ? (res) => res : (res) => res.result, { cache, next, ...opts } = {\n // Opt out of setting a `signal` on an internal `fetch` if one isn't provided.\n // This is necessary in React Server Components to avoid opting out of Request Memoization.\n useAbortSignal: typeof options.signal < \"u\",\n // Set `resultSourceMap' when stega is enabled, as it's required for encoding.\n resultSourceMap: stega.enabled ? \"withKeyArraySelector\" : options.resultSourceMap,\n ...options,\n // Default to not returning the query, unless `filterResponse` is `false`,\n // or `returnQuery` is explicitly set. `true` is the default in Content Lake, so skip if truthy\n returnQuery: options.filterResponse === !1 && options.returnQuery !== !1\n }, reqOpts = typeof cache < \"u\" || typeof next < \"u\" ? { ...opts, fetch: { cache, next } } : opts, $request = _dataRequest(client, httpRequest, \"query\", { query, params }, reqOpts);\n return stega.enabled ? $request.pipe(\n combineLatestWith(\n from(\n import(\"./_chunks-es/stegaEncodeSourceMap.js\").then(function(n) {\n return n.stegaEncodeSourceMap$1;\n }).then(\n ({ stegaEncodeSourceMap }) => stegaEncodeSourceMap\n )\n )\n ),\n map(\n ([res, stegaEncodeSourceMap]) => {\n const result = stegaEncodeSourceMap(res.result, res.resultSourceMap, stega);\n return mapResponse({ ...res, result });\n }\n )\n ) : $request.pipe(map(mapResponse));\n}\nfunction _getDocument(client, httpRequest, id, opts = {}) {\n const options = {\n uri: _getDataUrl(client, \"doc\", id),\n json: !0,\n tag: opts.tag,\n signal: opts.signal\n };\n return _requestObservable(client, httpRequest, options).pipe(\n filter(isResponse),\n map((event) => event.body.documents && event.body.documents[0])\n );\n}\nfunction _getDocuments(client, httpRequest, ids, opts = {}) {\n const options = {\n uri: _getDataUrl(client, \"doc\", ids.join(\",\")),\n json: !0,\n tag: opts.tag,\n signal: opts.signal\n };\n return _requestObservable(client, httpRequest, options).pipe(\n filter(isResponse),\n map((event) => {\n const indexed = indexBy(event.body.documents || [], (doc) => doc._id);\n return ids.map((id) => indexed[id] || null);\n })\n );\n}\nfunction _createIfNotExists(client, httpRequest, doc, options) {\n return requireDocumentId(\"createIfNotExists\", doc), _create(client, httpRequest, doc, \"createIfNotExists\", options);\n}\nfunction _createOrReplace(client, httpRequest, doc, options) {\n return requireDocumentId(\"createOrReplace\", doc), _create(client, httpRequest, doc, \"createOrReplace\", options);\n}\nfunction _delete(client, httpRequest, selection, options) {\n return _dataRequest(\n client,\n httpRequest,\n \"mutate\",\n { mutations: [{ delete: getSelection(selection) }] },\n options\n );\n}\nfunction _mutate(client, httpRequest, mutations, options) {\n let mut;\n mutations instanceof Patch || mutations instanceof ObservablePatch ? mut = { patch: mutations.serialize() } : mutations instanceof Transaction || mutations instanceof ObservableTransaction ? mut = mutations.serialize() : mut = mutations;\n const muts = Array.isArray(mut) ? mut : [mut], transactionId = options && options.transactionId || void 0;\n return _dataRequest(client, httpRequest, \"mutate\", { mutations: muts, transactionId }, options);\n}\nfunction _action(client, httpRequest, actions, options) {\n const acts = Array.isArray(actions) ? actions : [actions], transactionId = options && options.transactionId || void 0, skipCrossDatasetReferenceValidation = options && options.skipCrossDatasetReferenceValidation || void 0, dryRun = options && options.dryRun || void 0;\n return _dataRequest(\n client,\n httpRequest,\n \"actions\",\n { actions: acts, transactionId, skipCrossDatasetReferenceValidation, dryRun },\n options\n );\n}\nfunction _dataRequest(client, httpRequest, endpoint, body, options = {}) {\n const isMutation = endpoint === \"mutate\", isAction = endpoint === \"actions\", isQuery = endpoint === \"query\", strQuery = isMutation || isAction ? \"\" : encodeQueryString(body), useGet = !isMutation && !isAction && strQuery.length < getQuerySizeLimit, stringQuery = useGet ? strQuery : \"\", returnFirst = options.returnFirst, { timeout, token, tag, headers, returnQuery, lastLiveEventId, cacheMode } = options, uri = _getDataUrl(client, endpoint, stringQuery), reqOptions = {\n method: useGet ? \"GET\" : \"POST\",\n uri,\n json: !0,\n body: useGet ? void 0 : body,\n query: isMutation && getMutationQuery(options),\n timeout,\n headers,\n token,\n tag,\n returnQuery,\n perspective: options.perspective,\n resultSourceMap: options.resultSourceMap,\n lastLiveEventId: Array.isArray(lastLiveEventId) ? lastLiveEventId[0] : lastLiveEventId,\n cacheMode,\n canUseCdn: isQuery,\n signal: options.signal,\n fetch: options.fetch,\n useAbortSignal: options.useAbortSignal,\n useCdn: options.useCdn\n };\n return _requestObservable(client, httpRequest, reqOptions).pipe(\n filter(isResponse),\n map(getBody),\n map((res) => {\n if (!isMutation)\n return res;\n const results = res.results || [];\n if (options.returnDocuments)\n return returnFirst ? results[0] && results[0].document : results.map((mut) => mut.document);\n const key = returnFirst ? \"documentId\" : \"documentIds\", ids = returnFirst ? results[0] && results[0].id : results.map((mut) => mut.id);\n return {\n transactionId: res.transactionId,\n results,\n [key]: ids\n };\n })\n );\n}\nfunction _create(client, httpRequest, doc, op, options = {}) {\n const mutation = { [op]: doc }, opts = Object.assign({ returnFirst: !0, returnDocuments: !0 }, options);\n return _dataRequest(client, httpRequest, \"mutate\", { mutations: [mutation] }, opts);\n}\nfunction _requestObservable(client, httpRequest, options) {\n const uri = options.url || options.uri, config = client.config(), canUseCdn = typeof options.canUseCdn > \"u\" ? [\"GET\", \"HEAD\"].indexOf(options.method || \"GET\") >= 0 && uri.indexOf(\"/data/\") === 0 : options.canUseCdn;\n let useCdn = (options.useCdn ?? config.useCdn) && canUseCdn;\n const tag = options.tag && config.requestTagPrefix ? [config.requestTagPrefix, options.tag].join(\".\") : options.tag || config.requestTagPrefix;\n if (tag && options.tag !== null && (options.query = { tag: requestTag(tag), ...options.query }), [\"GET\", \"HEAD\", \"POST\"].indexOf(options.method || \"GET\") >= 0 && uri.indexOf(\"/data/query/\") === 0) {\n const resultSourceMap = options.resultSourceMap ?? config.resultSourceMap;\n resultSourceMap !== void 0 && resultSourceMap !== !1 && (options.query = { resultSourceMap, ...options.query });\n const perspectiveOption = options.perspective || config.perspective;\n typeof perspectiveOption < \"u\" && (validateApiPerspective(perspectiveOption), options.query = {\n perspective: Array.isArray(perspectiveOption) ? perspectiveOption.join(\",\") : perspectiveOption,\n ...options.query\n }, perspectiveOption === \"previewDrafts\" && useCdn && (useCdn = !1, printCdnPreviewDraftsWarning())), options.lastLiveEventId && (options.query = { ...options.query, lastLiveEventId: options.lastLiveEventId }), options.returnQuery === !1 && (options.query = { returnQuery: \"false\", ...options.query }), useCdn && options.cacheMode == \"noStale\" && (options.query = { cacheMode: \"noStale\", ...options.query });\n }\n const reqOptions = requestOptions(\n config,\n Object.assign({}, options, {\n url: _getUrl(client, uri, useCdn)\n })\n ), request = new Observable(\n (subscriber) => httpRequest(reqOptions, config.requester).subscribe(subscriber)\n );\n return options.signal ? request.pipe(_withAbortSignal(options.signal)) : request;\n}\nfunction _request(client, httpRequest, options) {\n return _requestObservable(client, httpRequest, options).pipe(\n filter((event) => event.type === \"response\"),\n map((event) => event.body)\n );\n}\nfunction _getDataUrl(client, operation, path) {\n const config = client.config(), catalog = hasDataset(config), baseUri = `/${operation}/${catalog}`;\n return `/data${path ? `${baseUri}/${path}` : baseUri}`.replace(/\\/($|\\?)/, \"$1\");\n}\nfunction _getUrl(client, uri, canUseCdn = !1) {\n const { url, cdnUrl } = client.config();\n return `${canUseCdn ? cdnUrl : url}/${uri.replace(/^\\//, \"\")}`;\n}\nfunction _withAbortSignal(signal) {\n return (input) => new Observable((observer) => {\n const abort = () => observer.error(_createAbortError(signal));\n if (signal && signal.aborted) {\n abort();\n return;\n }\n const subscription = input.subscribe(observer);\n return signal.addEventListener(\"abort\", abort), () => {\n signal.removeEventListener(\"abort\", abort), subscription.unsubscribe();\n };\n });\n}\nconst isDomExceptionSupported = !!globalThis.DOMException;\nfunction _createAbortError(signal) {\n if (isDomExceptionSupported)\n return new DOMException(signal?.reason ?? \"The operation was aborted.\", \"AbortError\");\n const error = new Error(signal?.reason ?? \"The operation was aborted.\");\n return error.name = \"AbortError\", error;\n}\nclass ObservableAssetsClient {\n #client;\n #httpRequest;\n constructor(client, httpRequest) {\n this.#client = client, this.#httpRequest = httpRequest;\n }\n upload(assetType, body, options) {\n return _upload(this.#client, this.#httpRequest, assetType, body, options);\n }\n}\nclass AssetsClient {\n #client;\n #httpRequest;\n constructor(client, httpRequest) {\n this.#client = client, this.#httpRequest = httpRequest;\n }\n upload(assetType, body, options) {\n const observable2 = _upload(this.#client, this.#httpRequest, assetType, body, options);\n return lastValueFrom(\n observable2.pipe(\n filter((event) => event.type === \"response\"),\n map(\n (event) => event.body.document\n )\n )\n );\n }\n}\nfunction _upload(client, httpRequest, assetType, body, opts = {}) {\n validateAssetType(assetType);\n let meta = opts.extract || void 0;\n meta && !meta.length && (meta = [\"none\"]);\n const dataset2 = hasDataset(client.config()), assetEndpoint = assetType === \"image\" ? \"images\" : \"files\", options = optionsFromFile(opts, body), { tag, label, title, description, creditLine, filename, source } = options, query = {\n label,\n title,\n description,\n filename,\n meta,\n creditLine\n };\n return source && (query.sourceId = source.id, query.sourceName = source.name, query.sourceUrl = source.url), _requestObservable(client, httpRequest, {\n tag,\n method: \"POST\",\n timeout: options.timeout || 0,\n uri: `/assets/${assetEndpoint}/${dataset2}`,\n headers: options.contentType ? { \"Content-Type\": options.contentType } : {},\n query,\n body\n });\n}\nfunction optionsFromFile(opts, file) {\n return typeof File > \"u\" || !(file instanceof File) ? opts : Object.assign(\n {\n filename: opts.preserveFilename === !1 ? void 0 : file.name,\n contentType: file.type\n },\n opts\n );\n}\nvar defaults = (obj, defaults2) => Object.keys(defaults2).concat(Object.keys(obj)).reduce((target, prop) => (target[prop] = typeof obj[prop] > \"u\" ? defaults2[prop] : obj[prop], target), {});\nconst pick = (obj, props) => props.reduce((selection, prop) => (typeof obj[prop] > \"u\" || (selection[prop] = obj[prop]), selection), {}), MAX_URL_LENGTH = 14800, possibleOptions = [\n \"includePreviousRevision\",\n \"includeResult\",\n \"includeMutations\",\n \"visibility\",\n \"effectFormat\",\n \"tag\"\n], defaultOptions = {\n includeResult: !0\n};\nfunction _listen(query, params, opts = {}) {\n const { url, token, withCredentials, requestTagPrefix } = this.config(), tag = opts.tag && requestTagPrefix ? [requestTagPrefix, opts.tag].join(\".\") : opts.tag, options = { ...defaults(opts, defaultOptions), tag }, listenOpts = pick(options, possibleOptions), qs = encodeQueryString({ query, params, options: { tag, ...listenOpts } }), uri = `${url}${_getDataUrl(this, \"listen\", qs)}`;\n if (uri.length > MAX_URL_LENGTH)\n return new Observable((observer) => observer.error(new Error(\"Query too large for listener\")));\n const listenFor = options.events ? options.events : [\"mutation\"], shouldEmitReconnect = listenFor.indexOf(\"reconnect\") !== -1, esOptions = {};\n return (token || withCredentials) && (esOptions.withCredentials = !0), token && (esOptions.headers = {\n Authorization: `Bearer ${token}`\n }), new Observable((observer) => {\n let es, reconnectTimer, stopped = !1, unsubscribed = !1;\n open();\n function onError() {\n stopped || (emitReconnect(), !stopped && es.readyState === es.CLOSED && (unsubscribe(), clearTimeout(reconnectTimer), reconnectTimer = setTimeout(open, 100)));\n }\n function onChannelError(err) {\n observer.error(cooerceError(err));\n }\n function onMessage(evt) {\n const event = parseEvent$1(evt);\n return event instanceof Error ? observer.error(event) : observer.next(event);\n }\n function onDisconnect() {\n stopped = !0, unsubscribe(), observer.complete();\n }\n function unsubscribe() {\n es && (es.removeEventListener(\"error\", onError), es.removeEventListener(\"channelError\", onChannelError), es.removeEventListener(\"disconnect\", onDisconnect), listenFor.forEach((type) => es.removeEventListener(type, onMessage)), es.close());\n }\n function emitReconnect() {\n shouldEmitReconnect && observer.next({ type: \"reconnect\" });\n }\n async function getEventSource() {\n const { default: EventSource2 } = await import(\"@sanity/eventsource\");\n if (unsubscribed)\n return;\n const evs = new EventSource2(uri, esOptions);\n return evs.addEventListener(\"error\", onError), evs.addEventListener(\"channelError\", onChannelError), evs.addEventListener(\"disconnect\", onDisconnect), listenFor.forEach((type) => evs.addEventListener(type, onMessage)), evs;\n }\n function open() {\n getEventSource().then((eventSource) => {\n eventSource && (es = eventSource, unsubscribed && unsubscribe());\n }).catch((reason) => {\n observer.error(reason), stop();\n });\n }\n function stop() {\n stopped = !0, unsubscribe(), unsubscribed = !0;\n }\n return stop;\n });\n}\nfunction parseEvent$1(event) {\n try {\n const data = event.data && JSON.parse(event.data) || {};\n return Object.assign({ type: event.type }, data);\n } catch (err) {\n return err;\n }\n}\nfunction cooerceError(err) {\n if (err instanceof Error)\n return err;\n const evt = parseEvent$1(err);\n return evt instanceof Error ? evt : new Error(extractErrorMessage(evt));\n}\nfunction extractErrorMessage(err) {\n return err.error ? err.error.description ? err.error.description : typeof err.error == \"string\" ? err.error : JSON.stringify(err.error, null, 2) : err.message || \"Unknown listener error\";\n}\nconst requiredApiVersion = \"2021-03-26\";\nclass LiveClient {\n #client;\n constructor(client) {\n this.#client = client;\n }\n /**\n * Requires `apiVersion` to be `2021-03-26` or later.\n */\n events({\n includeDrafts = !1,\n tag: _tag\n } = {}) {\n const {\n projectId: projectId2,\n apiVersion: _apiVersion,\n token,\n withCredentials,\n requestTagPrefix\n } = this.#client.config(), apiVersion = _apiVersion.replace(/^v/, \"\");\n if (apiVersion !== \"X\" && apiVersion < requiredApiVersion)\n throw new Error(\n `The live events API requires API version ${requiredApiVersion} or later. The current API version is ${apiVersion}. Please update your API version to use this feature.`\n );\n if (includeDrafts && !token && !withCredentials)\n throw new Error(\n \"The live events API requires a token or withCredentials when 'includeDrafts: true'. Please update your client configuration. The token should have the lowest possible access role.\"\n );\n if (includeDrafts && apiVersion !== \"X\")\n throw new Error(\n \"The live events API requires API version X when 'includeDrafts: true'. This API is experimental and may change or even be removed.\"\n );\n const path = _getDataUrl(this.#client, \"live/events\"), url = new URL(this.#client.getUrl(path, !1)), tag = _tag && requestTagPrefix ? [requestTagPrefix, _tag].join(\".\") : _tag;\n tag && url.searchParams.set(\"tag\", tag), includeDrafts && url.searchParams.set(\"includeDrafts\", \"true\");\n const listenFor = [\"restart\", \"message\", \"welcome\", \"reconnect\"], esOptions = {};\n return includeDrafts && token && (esOptions.headers = {\n Authorization: `Bearer ${token}`\n }), includeDrafts && withCredentials && (esOptions.withCredentials = !0), new Observable((observer) => {\n let es, reconnectTimer, stopped = !1, unsubscribed = !1;\n open();\n function onError(evt) {\n if (!stopped) {\n if (\"data\" in evt) {\n const event = parseEvent(evt);\n observer.error(new Error(event.message, { cause: event }));\n }\n es.readyState === es.CLOSED && (unsubscribe(), clearTimeout(reconnectTimer), reconnectTimer = setTimeout(open, 100));\n }\n }\n function onMessage(evt) {\n const event = parseEvent(evt);\n return event instanceof Error ? observer.error(event) : observer.next(event);\n }\n function unsubscribe() {\n if (es) {\n es.removeEventListener(\"error\", onError);\n for (const type of listenFor)\n es.removeEventListener(type, onMessage);\n es.close();\n }\n }\n async function getEventSource() {\n const EventSourceImplementation = typeof EventSource > \"u\" || esOptions.headers || esOptions.withCredentials ? (await import(\"@sanity/eventsource\")).default : EventSource;\n if (unsubscribed)\n return;\n try {\n if (await fetch(url, {\n method: \"OPTIONS\",\n mode: \"cors\",\n credentials: esOptions.withCredentials ? \"include\" : \"omit\",\n headers: esOptions.headers\n }), unsubscribed)\n return;\n } catch {\n throw new CorsOriginError({ projectId: projectId2 });\n }\n const evs = new EventSourceImplementation(url.toString(), esOptions);\n evs.addEventListener(\"error\", onError);\n for (const type of listenFor)\n evs.addEventListener(type, onMessage);\n return evs;\n }\n function open() {\n getEventSource().then((eventSource) => {\n eventSource && (es = eventSource, unsubscribed && unsubscribe());\n }).catch((reason) => {\n observer.error(reason), stop();\n });\n }\n function stop() {\n stopped = !0, unsubscribe(), unsubscribed = !0;\n }\n return stop;\n });\n }\n}\nfunction parseEvent(event) {\n try {\n const data = event.data && JSON.parse(event.data) || {};\n return { type: event.type, id: event.lastEventId, ...data };\n } catch (err) {\n return err;\n }\n}\nclass ObservableDatasetsClient {\n #client;\n #httpRequest;\n constructor(client, httpRequest) {\n this.#client = client, this.#httpRequest = httpRequest;\n }\n /**\n * Create a new dataset with the given name\n *\n * @param name - Name of the dataset to create\n * @param options - Options for the dataset\n */\n create(name, options) {\n return _modify(this.#client, this.#httpRequest, \"PUT\", name, options);\n }\n /**\n * Edit a dataset with the given name\n *\n * @param name - Name of the dataset to edit\n * @param options - New options for the dataset\n */\n edit(name, options) {\n return _modify(this.#client, this.#httpRequest, \"PATCH\", name, options);\n }\n /**\n * Delete a dataset with the given name\n *\n * @param name - Name of the dataset to delete\n */\n delete(name) {\n return _modify(this.#client, this.#httpRequest, \"DELETE\", name);\n }\n /**\n * Fetch a list of datasets for the configured project\n */\n list() {\n return _request(this.#client, this.#httpRequest, {\n uri: \"/datasets\",\n tag: null\n });\n }\n}\nclass DatasetsClient {\n #client;\n #httpRequest;\n constructor(client, httpRequest) {\n this.#client = client, this.#httpRequest = httpRequest;\n }\n /**\n * Create a new dataset with the given name\n *\n * @param name - Name of the dataset to create\n * @param options - Options for the dataset\n */\n create(name, options) {\n return lastValueFrom(\n _modify(this.#client, this.#httpRequest, \"PUT\", name, options)\n );\n }\n /**\n * Edit a dataset with the given name\n *\n * @param name - Name of the dataset to edit\n * @param options - New options for the dataset\n */\n edit(name, options) {\n return lastValueFrom(\n _modify(this.#client, this.#httpRequest, \"PATCH\", name, options)\n );\n }\n /**\n * Delete a dataset with the given name\n *\n * @param name - Name of the dataset to delete\n */\n delete(name) {\n return lastValueFrom(_modify(this.#client, this.#httpRequest, \"DELETE\", name));\n }\n /**\n * Fetch a list of datasets for the configured project\n */\n list() {\n return lastValueFrom(\n _request(this.#client, this.#httpRequest, { uri: \"/datasets\", tag: null })\n );\n }\n}\nfunction _modify(client, httpRequest, method, name, options) {\n return dataset(name), _request(client, httpRequest, {\n method,\n uri: `/datasets/${name}`,\n body: options,\n tag: null\n });\n}\nclass ObservableProjectsClient {\n #client;\n #httpRequest;\n constructor(client, httpRequest) {\n this.#client = client, this.#httpRequest = httpRequest;\n }\n list(options) {\n const uri = options?.includeMembers === !1 ? \"/projects?includeMembers=false\" : \"/projects\";\n return _request(this.#client, this.#httpRequest, { uri });\n }\n /**\n * Fetch a project by project ID\n *\n * @param projectId - ID of the project to fetch\n */\n getById(projectId2) {\n return _request(this.#client, this.#httpRequest, { uri: `/projects/${projectId2}` });\n }\n}\nclass ProjectsClient {\n #client;\n #httpRequest;\n constructor(client, httpRequest) {\n this.#client = client, this.#httpRequest = httpRequest;\n }\n list(options) {\n const uri = options?.includeMembers === !1 ? \"/projects?includeMembers=false\" : \"/projects\";\n return lastValueFrom(_request(this.#client, this.#httpRequest, { uri }));\n }\n /**\n * Fetch a project by project ID\n *\n * @param projectId - ID of the project to fetch\n */\n getById(projectId2) {\n return lastValueFrom(\n _request(this.#client, this.#httpRequest, { uri: `/projects/${projectId2}` })\n );\n }\n}\nclass ObservableUsersClient {\n #client;\n #httpRequest;\n constructor(client, httpRequest) {\n this.#client = client, this.#httpRequest = httpRequest;\n }\n /**\n * Fetch a user by user ID\n *\n * @param id - User ID of the user to fetch. If `me` is provided, a minimal response including the users role is returned.\n */\n getById(id) {\n return _request(\n this.#client,\n this.#httpRequest,\n { uri: `/users/${id}` }\n );\n }\n}\nclass UsersClient {\n #client;\n #httpRequest;\n constructor(client, httpRequest) {\n this.#client = client, this.#httpRequest = httpRequest;\n }\n /**\n * Fetch a user by user ID\n *\n * @param id - User ID of the user to fetch. If `me` is provided, a minimal response including the users role is returned.\n */\n getById(id) {\n return lastValueFrom(\n _request(this.#client, this.#httpRequest, {\n uri: `/users/${id}`\n })\n );\n }\n}\nclass ObservableSanityClient {\n assets;\n datasets;\n live;\n projects;\n users;\n /**\n * Private properties\n */\n #clientConfig;\n #httpRequest;\n /**\n * Instance properties\n */\n listen = _listen;\n constructor(httpRequest, config = defaultConfig) {\n this.config(config), this.#httpRequest = httpRequest, this.assets = new ObservableAssetsClient(this, this.#httpRequest), this.datasets = new ObservableDatasetsClient(this, this.#httpRequest), this.live = new LiveClient(this), this.projects = new ObservableProjectsClient(this, this.#httpRequest), this.users = new ObservableUsersClient(this, this.#httpRequest);\n }\n /**\n * Clone the client - returns a new instance\n */\n clone() {\n return new ObservableSanityClient(this.#httpRequest, this.config());\n }\n config(newConfig) {\n if (newConfig === void 0)\n return { ...this.#clientConfig };\n if (this.#clientConfig && this.#clientConfig.allowReconfigure === !1)\n throw new Error(\n \"Existing client instance cannot be reconfigured - use `withConfig(newConfig)` to return a new client\"\n );\n return this.#clientConfig = initConfig(newConfig, this.#clientConfig || {}), this;\n }\n /**\n * Clone the client with a new (partial) configuration.\n *\n * @param newConfig - New client configuration properties, shallowly merged with existing configuration\n */\n withConfig(newConfig) {\n const thisConfig = this.config();\n return new ObservableSanityClient(this.#httpRequest, {\n ...thisConfig,\n ...newConfig,\n stega: {\n ...thisConfig.stega || {},\n ...typeof newConfig?.stega == \"boolean\" ? { enabled: newConfig.stega } : newConfig?.stega || {}\n }\n });\n }\n fetch(query, params, options) {\n return _fetch(\n this,\n this.#httpRequest,\n this.#clientConfig.stega,\n query,\n params,\n options\n );\n }\n /**\n * Fetch a single document with the given ID.\n *\n * @param id - Document ID to fetch\n * @param options - Request options\n */\n getDocument(id, options) {\n return _getDocument(this, this.#httpRequest, id, options);\n }\n /**\n * Fetch multiple documents in one request.\n * Should be used sparingly - performing a query is usually a better option.\n * The order/position of documents is preserved based on the original array of IDs.\n * If any of the documents are missing, they will be replaced by a `null` entry in the returned array\n *\n * @param ids - Document IDs to fetch\n * @param options - Request options\n */\n getDocuments(ids, options) {\n return _getDocuments(this, this.#httpRequest, ids, options);\n }\n create(document, options) {\n return _create(this, this.#httpRequest, document, \"create\", options);\n }\n createIfNotExists(document, options) {\n return _createIfNotExists(this, this.#httpRequest, document, options);\n }\n createOrReplace(document, options) {\n return _createOrReplace(this, this.#httpRequest, document, options);\n }\n delete(selection, options) {\n return _delete(this, this.#httpRequest, selection, options);\n }\n mutate(operations, options) {\n return _mutate(this, this.#httpRequest, operations, options);\n }\n /**\n * Create a new buildable patch of operations to perform\n *\n * @param selection - Document ID, an array of document IDs, or an object with `query` and optional `params`, defining which document(s) to patch\n * @param operations - Optional object of patch operations to initialize the patch instance with\n * @returns Patch instance - call `.commit()` to perform the operations defined\n */\n patch(selection, operations) {\n return new ObservablePatch(selection, operations, this);\n }\n /**\n * Create a new transaction of mutations\n *\n * @param operations - Optional array of mutation operations to initialize the transaction instance with\n */\n transaction(operations) {\n return new ObservableTransaction(operations, this);\n }\n /**\n * Perform action operations against the configured dataset\n *\n * @param operations - Action operation(s) to execute\n * @param options - Action options\n */\n action(operations, options) {\n return _action(this, this.#httpRequest, operations, options);\n }\n /**\n * Perform an HTTP request against the Sanity API\n *\n * @param options - Request options\n */\n request(options) {\n return _request(this, this.#httpRequest, options);\n }\n /**\n * Get a Sanity API URL for the URI provided\n *\n * @param uri - URI/path to build URL for\n * @param canUseCdn - Whether or not to allow using the API CDN for this route\n */\n getUrl(uri, canUseCdn) {\n return _getUrl(this, uri, canUseCdn);\n }\n /**\n * Get a Sanity API URL for the data operation and path provided\n *\n * @param operation - Data operation (eg `query`, `mutate`, `listen` or similar)\n * @param path - Path to append after the operation\n */\n getDataUrl(operation, path) {\n return _getDataUrl(this, operation, path);\n }\n}\nclass SanityClient {\n assets;\n datasets;\n live;\n projects;\n users;\n /**\n * Observable version of the Sanity client, with the same configuration as the promise-based one\n */\n observable;\n /**\n * Private properties\n */\n #clientConfig;\n #httpRequest;\n /**\n * Instance properties\n */\n listen = _listen;\n constructor(httpRequest, config = defaultConfig) {\n this.config(config), this.#httpRequest = httpRequest, this.assets = new AssetsClient(this, this.#httpRequest), this.datasets = new DatasetsClient(this, this.#httpRequest), this.live = new LiveClient(this), this.projects = new ProjectsClient(this, this.#httpRequest), this.users = new UsersClient(this, this.#httpRequest), this.observable = new ObservableSanityClient(httpRequest, config);\n }\n /**\n * Clone the client - returns a new instance\n */\n clone() {\n return new SanityClient(this.#httpRequest, this.config());\n }\n config(newConfig) {\n if (newConfig === void 0)\n return { ...this.#clientConfig };\n if (this.#clientConfig && this.#clientConfig.allowReconfigure === !1)\n throw new Error(\n \"Existing client instance cannot be reconfigured - use `withConfig(newConfig)` to return a new client\"\n );\n return this.observable && this.observable.config(newConfig), this.#clientConfig = initConfig(newConfig, this.#clientConfig || {}), this;\n }\n /**\n * Clone the client with a new (partial) configuration.\n *\n * @param newConfig - New client configuration properties, shallowly merged with existing configuration\n */\n withConfig(newConfig) {\n const thisConfig = this.config();\n return new SanityClient(this.#httpRequest, {\n ...thisConfig,\n ...newConfig,\n stega: {\n ...thisConfig.stega || {},\n ...typeof newConfig?.stega == \"boolean\" ? { enabled: newConfig.stega } : newConfig?.stega || {}\n }\n });\n }\n fetch(query, params, options) {\n return lastValueFrom(\n _fetch(\n this,\n this.#httpRequest,\n this.#clientConfig.stega,\n query,\n params,\n options\n )\n );\n }\n /**\n * Fetch a single document with the given ID.\n *\n * @param id - Document ID to fetch\n * @param options - Request options\n */\n getDocument(id, options) {\n return lastValueFrom(_getDocument(this, this.#httpRequest, id, options));\n }\n /**\n * Fetch multiple documents in one request.\n * Should be used sparingly - performing a query is usually a better option.\n * The order/position of documents is preserved based on the original array of IDs.\n * If any of the documents are missing, they will be replaced by a `null` entry in the returned array\n *\n * @param ids - Document IDs to fetch\n * @param options - Request options\n */\n getDocuments(ids, options) {\n return lastValueFrom(_getDocuments(this, this.#httpRequest, ids, options));\n }\n create(document, options) {\n return lastValueFrom(\n _create(this, this.#httpRequest, document, \"create\", options)\n );\n }\n createIfNotExists(document, options) {\n return lastValueFrom(\n _createIfNotExists(this, this.#httpRequest, document, options)\n );\n }\n createOrReplace(document, options) {\n return lastValueFrom(\n _createOrReplace(this, this.#httpRequest, document, options)\n );\n }\n delete(selection, options) {\n return lastValueFrom(_delete(this, this.#httpRequest, selection, options));\n }\n mutate(operations, options) {\n return lastValueFrom(_mutate(this, this.#httpRequest, operations, options));\n }\n /**\n * Create a new buildable patch of operations to perform\n *\n * @param selection - Document ID, an array of document IDs, or an object with `query` and optional `params`, defining which document(s) to patch\n * @param operations - Optional object of patch operations to initialize the patch instance with\n * @returns Patch instance - call `.commit()` to perform the operations defined\n */\n patch(documentId, operations) {\n return new Patch(documentId, operations, this);\n }\n /**\n * Create a new transaction of mutations\n *\n * @param operations - Optional array of mutation operations to initialize the transaction instance with\n */\n transaction(operations) {\n return new Transaction(operations, this);\n }\n /**\n * Perform action operations against the configured dataset\n * Returns a promise that resolves to the transaction result\n *\n * @param operations - Action operation(s) to execute\n * @param options - Action options\n */\n action(operations, options) {\n return lastValueFrom(_action(this, this.#httpRequest, operations, options));\n }\n /**\n * Perform a request against the Sanity API\n * NOTE: Only use this for Sanity API endpoints, not for your own APIs!\n *\n * @param options - Request options\n * @returns Promise resolving to the response body\n */\n request(options) {\n return lastValueFrom(_request(this, this.#httpRequest, options));\n }\n /**\n * Perform an HTTP request a `/data` sub-endpoint\n * NOTE: Considered internal, thus marked as deprecated. Use `request` instead.\n *\n * @deprecated - Use `request()` or your own HTTP library instead\n * @param endpoint - Endpoint to hit (mutate, query etc)\n * @param body - Request body\n * @param options - Request options\n * @internal\n */\n dataRequest(endpoint, body, options) {\n return lastValueFrom(_dataRequest(this, this.#httpRequest, endpoint, body, options));\n }\n /**\n * Get a Sanity API URL for the URI provided\n *\n * @param uri - URI/path to build URL for\n * @param canUseCdn - Whether or not to allow using the API CDN for this route\n */\n getUrl(uri, canUseCdn) {\n return _getUrl(this, uri, canUseCdn);\n }\n /**\n * Get a Sanity API URL for the data operation and path provided\n *\n * @param operation - Data operation (eg `query`, `mutate`, `listen` or similar)\n * @param path - Path to append after the operation\n */\n getDataUrl(operation, path) {\n return _getDataUrl(this, operation, path);\n }\n}\nfunction defineCreateClientExports(envMiddleware2, ClassConstructor) {\n const defaultRequester = defineHttpRequest(envMiddleware2);\n return { requester: defaultRequester, createClient: (config) => new ClassConstructor(\n (options, requester2) => (requester2 || defaultRequester)({\n maxRedirects: 0,\n maxRetries: config.maxRetries,\n retryDelay: config.retryDelay,\n ...options\n }),\n config\n ) };\n}\nfunction defineDeprecatedCreateClient(createClient2) {\n return function(config) {\n return printNoDefaultExport(), createClient2(config);\n };\n}\nvar envMiddleware = [];\nconst exp = defineCreateClientExports(envMiddleware, SanityClient), requester = exp.requester, createClient = exp.createClient, deprecatedCreateClient = defineDeprecatedCreateClient(createClient);\nexport {\n BasePatch,\n BaseTransaction,\n ClientError,\n CorsOriginError,\n ObservablePatch,\n ObservableSanityClient,\n ObservableTransaction,\n Patch,\n SanityClient,\n ServerError,\n Transaction,\n createClient,\n deprecatedCreateClient as default,\n requester,\n adapter as unstable__adapter,\n environment as unstable__environment,\n validateApiPerspective\n};\n//# sourceMappingURL=index.browser.js.map\n","// From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis\nfunction getGlobal() {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n }\n if (typeof self !== 'undefined') {\n return self;\n }\n if (typeof window !== 'undefined') {\n return window;\n }\n if (typeof global !== 'undefined') {\n return global;\n }\n}\nfunction getDevTools() {\n const w = getGlobal();\n if (w.__xstate__) {\n return w.__xstate__;\n }\n return undefined;\n}\nfunction registerService(service) {\n if (typeof window === 'undefined') {\n return;\n }\n const devTools = getDevTools();\n if (devTools) {\n devTools.register(service);\n }\n}\nconst devToolsAdapter = service => {\n if (typeof window === 'undefined') {\n return;\n }\n const devTools = getDevTools();\n if (devTools) {\n devTools.register(service);\n }\n};\n\nexport { devToolsAdapter, getGlobal, registerService };\n","import { devToolsAdapter } from '../dev/dist/xstate-dev.esm.js';\n\nclass Mailbox {\n constructor(_process) {\n this._process = _process;\n this._active = false;\n this._current = null;\n this._last = null;\n }\n start() {\n this._active = true;\n this.flush();\n }\n clear() {\n // we can't set _current to null because we might be currently processing\n // and enqueue following clear shouldnt start processing the enqueued item immediately\n if (this._current) {\n this._current.next = null;\n this._last = this._current;\n }\n }\n enqueue(event) {\n const enqueued = {\n value: event,\n next: null\n };\n if (this._current) {\n this._last.next = enqueued;\n this._last = enqueued;\n return;\n }\n this._current = enqueued;\n this._last = enqueued;\n if (this._active) {\n this.flush();\n }\n }\n 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\nconst STATE_DELIMITER = '.';\nconst TARGETLESS_KEY = '';\nconst NULL_EVENT = '';\nconst STATE_IDENTIFIER = '#';\nconst WILDCARD = '*';\nconst XSTATE_INIT = 'xstate.init';\nconst XSTATE_ERROR = 'xstate.error';\nconst XSTATE_STOP = 'xstate.stop';\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 */\nfunction createAfterEvent(delayRef, id) {\n return {\n type: `xstate.after.${delayRef}.${id}`\n };\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 */\nfunction createDoneStateEvent(id, output) {\n return {\n type: `xstate.done.state.${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 */\nfunction createDoneActorEvent(invokeId, output) {\n return {\n type: `xstate.done.actor.${invokeId}`,\n output,\n actorId: invokeId\n };\n}\nfunction createErrorActorEvent(id, error) {\n return {\n type: `xstate.error.actor.${id}`,\n error,\n actorId: id\n };\n}\nfunction createInitEvent(input) {\n return {\n type: XSTATE_INIT,\n input\n };\n}\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 */\nfunction reportUnhandledError(err) {\n setTimeout(() => {\n throw err;\n });\n}\n\nconst symbolObservable = (() => typeof Symbol === 'function' && Symbol.observable || '@@observable')();\n\nfunction matchesState(parentStateId, childStateId) {\n const parentStateValue = toStateValue(parentStateId);\n const childStateValue = toStateValue(childStateId);\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 if (typeof parentStateValue === 'string') {\n return parentStateValue in childStateValue;\n }\n return Object.keys(parentStateValue).every(key => {\n if (!(key in childStateValue)) {\n return false;\n }\n return matchesState(parentStateValue[key], childStateValue[key]);\n });\n}\nfunction toStatePath(stateId) {\n if (isArray(stateId)) {\n return stateId;\n }\n const result = [];\n let segment = '';\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 result.push(segment);\n return result;\n}\nfunction toStateValue(stateValue) {\n if (isMachineSnapshot(stateValue)) {\n return stateValue.value;\n }\n if (typeof stateValue !== 'string') {\n return stateValue;\n }\n const statePath = toStatePath(stateValue);\n return pathToStateValue(statePath);\n}\nfunction pathToStateValue(statePath) {\n if (statePath.length === 1) {\n return statePath[0];\n }\n const value = {};\n let marker = value;\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 return value;\n}\nfunction mapValues(collection, iteratee) {\n const result = {};\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 return result;\n}\nfunction toArrayStrict(value) {\n if (isArray(value)) {\n return value;\n }\n return [value];\n}\nfunction toArray(value) {\n if (value === undefined) {\n return [];\n }\n return toArrayStrict(value);\n}\nfunction resolveOutput(mapper, context, event, self) {\n if (typeof mapper === 'function') {\n return mapper({\n context,\n event,\n self\n });\n }\n return mapper;\n}\nfunction isArray(value) {\n return Array.isArray(value);\n}\nfunction isErrorActorEvent(event) {\n return event.type.startsWith('xstate.error.actor');\n}\nfunction toTransitionConfigArray(configLike) {\n return toArrayStrict(configLike).map(transitionLike => {\n if (typeof transitionLike === 'undefined' || typeof transitionLike === 'string') {\n return {\n target: transitionLike\n };\n }\n return transitionLike;\n });\n}\nfunction normalizeTarget(target) {\n if (target === undefined || target === TARGETLESS_KEY) {\n return undefined;\n }\n return toArray(target);\n}\nfunction toObserver(nextHandler, errorHandler, completionHandler) {\n const isObserver = typeof nextHandler === 'object';\n const self = isObserver ? nextHandler : undefined;\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(self)\n };\n}\nfunction createInvokeId(stateNodeId, index) {\n return `${index}.${stateNodeId}`;\n}\nfunction resolveReferencedActor(machine, src) {\n const match = src.match(/^xstate\\.invoke\\.(\\d+)\\.(.*)/);\n if (!match) {\n return machine.implementations.actors[src];\n }\n const [, indexStr, nodeId] = match;\n const node = machine.getStateNodeById(nodeId);\n const invokeConfig = node.config.invoke;\n return (Array.isArray(invokeConfig) ? invokeConfig[indexStr] : invokeConfig).src;\n}\nfunction getAllOwnEventDescriptors(snapshot) {\n return [...new Set([...snapshot._nodes.flatMap(sn => sn.ownEvents)])];\n}\n\nfunction createScheduledEventId(actorRef, id) {\n return `${actorRef.sessionId}.${id}`;\n}\nlet idCounter = 0;\nfunction createSystem(rootActor, options) {\n const children = new Map();\n const keyedActors = new Map();\n const reverseKeyedActors = new WeakMap();\n const inspectionObservers = new Set();\n const timerMap = {};\n const {\n clock,\n logger\n } = options;\n const scheduler = {\n schedule: (source, target, event, delay, id = Math.random().toString(36).slice(2)) => {\n const scheduledEvent = {\n source,\n target,\n event,\n delay,\n id,\n startedAt: Date.now()\n };\n const scheduledEventId = createScheduledEventId(source, id);\n system._snapshot._scheduledEvents[scheduledEventId] = scheduledEvent;\n const timeout = clock.setTimeout(() => {\n delete timerMap[scheduledEventId];\n delete system._snapshot._scheduledEvents[scheduledEventId];\n system._relay(source, target, event);\n }, delay);\n timerMap[scheduledEventId] = timeout;\n },\n cancel: (source, id) => {\n const scheduledEventId = createScheduledEventId(source, id);\n const timeout = timerMap[scheduledEventId];\n delete timerMap[scheduledEventId];\n delete system._snapshot._scheduledEvents[scheduledEventId];\n if (timeout !== undefined) {\n clock.clearTimeout(timeout);\n }\n },\n cancelAll: actorRef => {\n for (const scheduledEventId in system._snapshot._scheduledEvents) {\n const scheduledEvent = system._snapshot._scheduledEvents[scheduledEventId];\n if (scheduledEvent.source === actorRef) {\n scheduler.cancel(actorRef, scheduledEvent.id);\n }\n }\n }\n };\n const sendInspectionEvent = event => {\n if (!inspectionObservers.size) {\n return;\n }\n const resolvedInspectionEvent = {\n ...event,\n rootId: rootActor.sessionId\n };\n inspectionObservers.forEach(observer => observer.next?.(resolvedInspectionEvent));\n };\n const system = {\n _snapshot: {\n _scheduledEvents: (options?.snapshot && options.snapshot.scheduler) ?? {}\n },\n _bookId: () => `x:${idCounter++}`,\n _register: (sessionId, actorRef) => {\n children.set(sessionId, actorRef);\n return sessionId;\n },\n _unregister: actorRef => {\n children.delete(actorRef.sessionId);\n const systemId = reverseKeyedActors.get(actorRef);\n if (systemId !== undefined) {\n keyedActors.delete(systemId);\n reverseKeyedActors.delete(actorRef);\n }\n },\n get: systemId => {\n return keyedActors.get(systemId);\n },\n _set: (systemId, actorRef) => {\n const existing = keyedActors.get(systemId);\n if (existing && existing !== actorRef) {\n throw new Error(`Actor with system ID '${systemId}' already exists.`);\n }\n keyedActors.set(systemId, actorRef);\n reverseKeyedActors.set(actorRef, systemId);\n },\n inspect: observerOrFn => {\n const observer = toObserver(observerOrFn);\n inspectionObservers.add(observer);\n return {\n unsubscribe() {\n inspectionObservers.delete(observer);\n }\n };\n },\n _sendInspectionEvent: sendInspectionEvent,\n _relay: (source, target, event) => {\n system._sendInspectionEvent({\n type: '@xstate.event',\n sourceRef: source,\n actorRef: target,\n event\n });\n target._send(event);\n },\n scheduler,\n getSnapshot: () => {\n return {\n _scheduledEvents: {\n ...system._snapshot._scheduledEvents\n }\n };\n },\n start: () => {\n const scheduledEvents = system._snapshot._scheduledEvents;\n system._snapshot._scheduledEvents = {};\n for (const scheduledId in scheduledEvents) {\n const {\n source,\n target,\n event,\n delay,\n id\n } = scheduledEvents[scheduledId];\n scheduler.schedule(source, target, event, delay, id);\n }\n },\n _clock: clock,\n _logger: logger\n };\n return system;\n}\n\nlet executingCustomAction = false;\nconst $$ACTOR_TYPE = 1;\n\n// those values are currently used by @xstate/react directly so it's important to keep the assigned values in sync\nlet ProcessingStatus = /*#__PURE__*/function (ProcessingStatus) {\n ProcessingStatus[ProcessingStatus[\"NotStarted\"] = 0] = \"NotStarted\";\n ProcessingStatus[ProcessingStatus[\"Running\"] = 1] = \"Running\";\n ProcessingStatus[ProcessingStatus[\"Stopped\"] = 2] = \"Stopped\";\n return ProcessingStatus;\n}({});\nconst defaultOptions = {\n clock: {\n setTimeout: (fn, ms) => {\n return setTimeout(fn, ms);\n },\n clearTimeout: id => {\n return clearTimeout(id);\n }\n },\n logger: console.log.bind(console),\n devTools: false\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 */\nclass Actor {\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(logic, options) {\n this.logic = logic;\n /** The current internal state of the actor. */\n this._snapshot = void 0;\n /**\n * The clock that is responsible for setting and clearing timeouts, such as\n * delayed events and transitions.\n */\n this.clock = void 0;\n this.options = void 0;\n /** The unique identifier for this actor relative to its parent. */\n this.id = void 0;\n this.mailbox = new Mailbox(this._process.bind(this));\n this.observers = new Set();\n this.eventListeners = new Map();\n this.logger = void 0;\n /** @internal */\n this._processingStatus = ProcessingStatus.NotStarted;\n // Actor Ref\n this._parent = void 0;\n /** @internal */\n this._syncSnapshot = void 0;\n this.ref = void 0;\n // TODO: add typings for system\n this._actorScope = void 0;\n this._systemId = void 0;\n /** The globally unique process ID for this invocation. */\n this.sessionId = void 0;\n /** The system to which this actor belongs. */\n this.system = void 0;\n this._doneEvent = void 0;\n this.src = void 0;\n // array of functions to defer\n this._deferred = [];\n const resolvedOptions = {\n ...defaultOptions,\n ...options\n };\n const {\n clock,\n logger,\n parent,\n syncSnapshot,\n id,\n systemId,\n inspect\n } = resolvedOptions;\n this.system = parent ? parent.system : createSystem(this, {\n clock,\n logger\n });\n if (inspect && !parent) {\n // Always inspect at the system-level\n this.system.inspect(toObserver(inspect));\n }\n this.sessionId = this.system._bookId();\n this.id = id ?? this.sessionId;\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;\n this.src = resolvedOptions.src ?? logic;\n this.ref = this;\n this._actorScope = {\n self: this,\n id: this.id,\n sessionId: this.sessionId,\n logger: this.logger,\n defer: fn => {\n this._deferred.push(fn);\n },\n system: this.system,\n stopChild: child => {\n if (child._parent !== this) {\n throw new Error(`Cannot stop child actor ${child.id} of ${this.id} because it is not a child`);\n }\n child._stop();\n },\n emit: emittedEvent => {\n const listeners = this.eventListeners.get(emittedEvent.type);\n const wildcardListener = this.eventListeners.get('*');\n if (!listeners && !wildcardListener) {\n return;\n }\n const allListeners = [...(listeners ? listeners.values() : []), ...(wildcardListener ? wildcardListener.values() : [])];\n for (const handler of allListeners) {\n handler(emittedEvent);\n }\n },\n actionExecutor: action => {\n const exec = () => {\n this._actorScope.system._sendInspectionEvent({\n type: '@xstate.action',\n actorRef: this,\n action: {\n type: action.type,\n params: action.params\n }\n });\n if (!action.exec) {\n return;\n }\n const saveExecutingCustomAction = executingCustomAction;\n try {\n executingCustomAction = true;\n action.exec(action.info, action.params);\n } finally {\n executingCustomAction = saveExecutingCustomAction;\n }\n };\n if (this._processingStatus === ProcessingStatus.Running) {\n exec();\n } else {\n this._deferred.push(exec);\n }\n }\n };\n\n // Ensure that the send method is bound to this Actor instance\n // if destructured\n this.send = this.send.bind(this);\n this.system._sendInspectionEvent({\n type: '@xstate.actor',\n actorRef: this\n });\n if (systemId) {\n this._systemId = systemId;\n this.system._set(systemId, this);\n }\n this._initState(options?.snapshot ?? options?.state);\n if (systemId && this._snapshot.status !== 'active') {\n this.system._unregister(this);\n }\n }\n _initState(persistedState) {\n try {\n this._snapshot = persistedState ? this.logic.restoreSnapshot ? this.logic.restoreSnapshot(persistedState, this._actorScope) : persistedState : this.logic.getInitialSnapshot(this._actorScope, this.options?.input);\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._snapshot = {\n status: 'error',\n output: undefined,\n error: err\n };\n }\n }\n update(snapshot, event) {\n // Update state\n this._snapshot = snapshot;\n\n // Execute deferred effects\n let deferredFn;\n while (deferredFn = this._deferred.shift()) {\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 this._deferred.length = 0;\n this._snapshot = {\n ...snapshot,\n status: 'error',\n error: err\n };\n }\n }\n switch (this._snapshot.status) {\n case 'active':\n for (const observer of this.observers) {\n try {\n observer.next?.(snapshot);\n } catch (err) {\n reportUnhandledError(err);\n }\n }\n break;\n case 'done':\n // next observers are meant to be notified about done snapshots\n // this can be seen as something that is different from how observable work\n // but with observables `complete` callback is called without any arguments\n // it's more ergonomic for XState to treat a done snapshot as a \"next\" value\n // and the completion event as something that is separate,\n // something that merely follows emitting that done snapshot\n for (const observer of this.observers) {\n try {\n observer.next?.(snapshot);\n } catch (err) {\n reportUnhandledError(err);\n }\n }\n this._stopProcedure();\n this._complete();\n this._doneEvent = createDoneActorEvent(this.id, this._snapshot.output);\n if (this._parent) {\n this.system._relay(this, this._parent, this._doneEvent);\n }\n break;\n case 'error':\n this._error(this._snapshot.error);\n break;\n }\n this.system._sendInspectionEvent({\n type: '@xstate.snapshot',\n actorRef: this,\n event,\n snapshot\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\n subscribe(nextListenerOrObserver, errorListener, completeListener) {\n const observer = toObserver(nextListenerOrObserver, errorListener, completeListener);\n if (this._processingStatus !== ProcessingStatus.Stopped) {\n this.observers.add(observer);\n } else {\n switch (this._snapshot.status) {\n case 'done':\n try {\n observer.complete?.();\n } catch (err) {\n reportUnhandledError(err);\n }\n break;\n case 'error':\n {\n const err = this._snapshot.error;\n if (!observer.error) {\n reportUnhandledError(err);\n } else {\n try {\n observer.error(err);\n } catch (err) {\n reportUnhandledError(err);\n }\n }\n break;\n }\n }\n }\n return {\n unsubscribe: () => {\n this.observers.delete(observer);\n }\n };\n }\n on(type, handler) {\n let listeners = this.eventListeners.get(type);\n if (!listeners) {\n listeners = new Set();\n this.eventListeners.set(type, listeners);\n }\n const wrappedHandler = handler.bind(undefined);\n listeners.add(wrappedHandler);\n return {\n unsubscribe: () => {\n listeners.delete(wrappedHandler);\n }\n };\n }\n\n /** Starts the Actor from the initial state */\n start() {\n if (this._processingStatus === ProcessingStatus.Running) {\n // Do not restart the service if it is already started\n return this;\n }\n if (this._syncSnapshot) {\n this.subscribe({\n next: snapshot => {\n if (snapshot.status === 'active') {\n this.system._relay(this, this._parent, {\n type: `xstate.snapshot.${this.id}`,\n snapshot\n });\n }\n },\n error: () => {}\n });\n }\n this.system._register(this.sessionId, this);\n if (this._systemId) {\n this.system._set(this._systemId, this);\n }\n this._processingStatus = ProcessingStatus.Running;\n\n // TODO: this isn't correct when rehydrating\n const initEvent = createInitEvent(this.options.input);\n this.system._sendInspectionEvent({\n type: '@xstate.event',\n sourceRef: this._parent,\n actorRef: this,\n event: initEvent\n });\n const status = this._snapshot.status;\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 this.update(this._snapshot, initEvent);\n // TODO: rethink cleanup of observers, mailbox, etc\n return this;\n case 'error':\n this._error(this._snapshot.error);\n return this;\n }\n if (!this._parent) {\n this.system.start();\n }\n if (this.logic.start) {\n try {\n this.logic.start(this._snapshot, this._actorScope);\n } catch (err) {\n this._snapshot = {\n ...this._snapshot,\n status: 'error',\n error: err\n };\n this._error(err);\n return this;\n }\n }\n\n // TODO: this notifies all subscribers but usually this is redundant\n // there is no real change happening here\n // we need to rethink if this needs to be refactored\n this.update(this._snapshot, initEvent);\n if (this.options.devTools) {\n this.attachDevTools();\n }\n this.mailbox.start();\n return this;\n }\n _process(event) {\n let nextState;\n let caughtError;\n try {\n nextState = this.logic.transition(this._snapshot, event, this._actorScope);\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 = {\n err\n };\n }\n if (caughtError) {\n const {\n err\n } = caughtError;\n this._snapshot = {\n ...this._snapshot,\n status: 'error',\n error: err\n };\n this._error(err);\n return;\n }\n this.update(nextState, event);\n if (event.type === XSTATE_STOP) {\n this._stopProcedure();\n this._complete();\n }\n }\n _stop() {\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 return this;\n }\n this.mailbox.enqueue({\n type: XSTATE_STOP\n });\n return this;\n }\n\n /** Stops the Actor and unsubscribe all listeners. */\n stop() {\n if (this._parent) {\n throw new Error('A non-root actor cannot be stopped directly.');\n }\n return this._stop();\n }\n _complete() {\n for (const observer of this.observers) {\n try {\n observer.complete?.();\n } catch (err) {\n reportUnhandledError(err);\n }\n }\n this.observers.clear();\n }\n _reportError(err) {\n if (!this.observers.size) {\n if (!this._parent) {\n reportUnhandledError(err);\n }\n return;\n }\n let reportError = false;\n for (const observer of this.observers) {\n const errorListener = observer.error;\n reportError ||= !errorListener;\n try {\n errorListener?.(err);\n } catch (err2) {\n reportUnhandledError(err2);\n }\n }\n this.observers.clear();\n if (reportError) {\n reportUnhandledError(err);\n }\n }\n _error(err) {\n this._stopProcedure();\n this._reportError(err);\n if (this._parent) {\n this.system._relay(this, this._parent, createErrorActorEvent(this.id, err));\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 _stopProcedure() {\n if (this._processingStatus !== ProcessingStatus.Running) {\n // Actor already stopped; do nothing\n return this;\n }\n\n // Cancel all delayed events\n this.system.scheduler.cancelAll(this);\n\n // TODO: mailbox.reset\n this.mailbox.clear();\n // TODO: after `stop` we must prepare ourselves for receiving events again\n // events sent *after* stop signal must be queued\n // it seems like this should be the common behavior for all of our consumers\n // so perhaps this should be unified somehow for all of them\n this.mailbox = new Mailbox(this._process.bind(this));\n this._processingStatus = ProcessingStatus.Stopped;\n this.system._unregister(this);\n return this;\n }\n\n /** @internal */\n _send(event) {\n if (this._processingStatus === ProcessingStatus.Stopped) {\n return;\n }\n this.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 send(event) {\n this.system._relay(undefined, this, event);\n }\n attachDevTools() {\n const {\n devTools\n } = this.options;\n if (devTools) {\n const resolvedDevToolsAdapter = typeof devTools === 'function' ? devTools : devToolsAdapter;\n resolvedDevToolsAdapter(this);\n }\n }\n toJSON() {\n return {\n xstate$$type: $$ACTOR_TYPE,\n id: this.id\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\n getPersistedSnapshot(options) {\n return this.logic.getPersistedSnapshot(this._snapshot, options);\n }\n [symbolObservable]() {\n return this;\n }\n\n /**\n * Read an actor’s snapshot synchronously.\n *\n * @remarks\n * The snapshot represent an actor's last emitted value.\n *\n * When an actor receives an event, its internal state may change. An actor\n * may emit a snapshot when a state transition occurs.\n *\n * Note that some actors, such as callback actors generated with\n * `fromCallback`, 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 getSnapshot() {\n return this._snapshot;\n }\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 fromCallback}, {@link fromEventObservable},\n * {@link fromObservable}, {@link fromPromise}, and {@link fromTransition}.\n * @param options - Actor options\n */\nfunction createActor(logic, ...[options]) {\n return new Actor(logic, options);\n}\n\n/**\n * Creates a new Interpreter instance for the given machine with the provided\n * options, if any.\n *\n * @deprecated Use `createActor` instead\n * @alias\n */\nconst interpret = createActor;\n\n/**\n * @deprecated Use `Actor` instead.\n * @alias\n */\n\nfunction resolveCancel(_, snapshot, actionArgs, actionParams, {\n sendId\n}) {\n const resolvedSendId = typeof sendId === 'function' ? sendId(actionArgs, actionParams) : sendId;\n return [snapshot, {\n sendId: resolvedSendId\n }, undefined];\n}\nfunction executeCancel(actorScope, params) {\n actorScope.defer(() => {\n actorScope.system.scheduler.cancel(actorScope.self, params.sendId);\n });\n}\n/**\n * Cancels a delayed `sendTo(...)` action that is waiting to be executed. The\n * canceled `sendTo(...)` action will not send its event or execute, unless the\n * `delay` has already elapsed before `cancel(...)` is called.\n *\n * @example\n *\n * ```ts\n * import { createMachine, sendTo, cancel } from 'xstate';\n *\n * const machine = createMachine({\n * // ...\n * on: {\n * sendEvent: {\n * actions: sendTo(\n * 'some-actor',\n * { type: 'someEvent' },\n * {\n * id: 'some-id',\n * delay: 1000\n * }\n * )\n * },\n * cancelEvent: {\n * actions: cancel('some-id')\n * }\n * }\n * });\n * ```\n *\n * @param sendId The `id` of the `sendTo(...)` action to cancel.\n */\nfunction cancel(sendId) {\n function cancel(_args, _params) {\n }\n cancel.type = 'xstate.cancel';\n cancel.sendId = sendId;\n cancel.resolve = resolveCancel;\n cancel.execute = executeCancel;\n return cancel;\n}\n\nfunction resolveSpawn(actorScope, snapshot, actionArgs, _actionParams, {\n id,\n systemId,\n src,\n input,\n syncSnapshot\n}) {\n const logic = typeof src === 'string' ? resolveReferencedActor(snapshot.machine, src) : src;\n const resolvedId = typeof id === 'function' ? id(actionArgs) : id;\n let actorRef;\n let resolvedInput = undefined;\n if (logic) {\n resolvedInput = typeof input === 'function' ? input({\n context: snapshot.context,\n event: actionArgs.event,\n self: actorScope.self\n }) : input;\n actorRef = createActor(logic, {\n id: resolvedId,\n src,\n parent: actorScope.self,\n syncSnapshot,\n systemId,\n input: resolvedInput\n });\n }\n return [cloneMachineSnapshot(snapshot, {\n children: {\n ...snapshot.children,\n [resolvedId]: actorRef\n }\n }), {\n id,\n systemId,\n actorRef,\n src,\n input: resolvedInput\n }, undefined];\n}\nfunction executeSpawn(actorScope, {\n actorRef\n}) {\n if (!actorRef) {\n return;\n }\n actorScope.defer(() => {\n if (actorRef._processingStatus === ProcessingStatus.Stopped) {\n return;\n }\n actorRef.start();\n });\n}\nfunction spawnChild(...[src, {\n id,\n systemId,\n input,\n syncSnapshot = false\n} = {}]) {\n function spawnChild(_args, _params) {\n }\n spawnChild.type = 'xstate.spawnChild';\n spawnChild.id = id;\n spawnChild.systemId = systemId;\n spawnChild.src = src;\n spawnChild.input = input;\n spawnChild.syncSnapshot = syncSnapshot;\n spawnChild.resolve = resolveSpawn;\n spawnChild.execute = executeSpawn;\n return spawnChild;\n}\n\nfunction resolveStop(_, snapshot, args, actionParams, {\n actorRef\n}) {\n const actorRefOrString = typeof actorRef === 'function' ? actorRef(args, actionParams) : actorRef;\n const resolvedActorRef = typeof actorRefOrString === 'string' ? snapshot.children[actorRefOrString] : actorRefOrString;\n let children = snapshot.children;\n if (resolvedActorRef) {\n children = {\n ...children\n };\n delete children[resolvedActorRef.id];\n }\n return [cloneMachineSnapshot(snapshot, {\n children\n }), resolvedActorRef, undefined];\n}\nfunction executeStop(actorScope, actorRef) {\n if (!actorRef) {\n return;\n }\n\n // we need to eagerly unregister it here so a new actor with the same systemId can be registered immediately\n // since we defer actual stopping of the actor but we don't defer actor creations (and we can't do that)\n // this could throw on `systemId` collision, for example, when dealing with reentering transitions\n actorScope.system._unregister(actorRef);\n\n // this allows us to prevent an actor from being started if it gets stopped within the same macrostep\n // this can happen, for example, when the invoking state is being exited immediately by an always transition\n if (actorRef._processingStatus !== ProcessingStatus.Running) {\n actorScope.stopChild(actorRef);\n return;\n }\n // stopping a child enqueues a stop event in the child actor's mailbox\n // we need for all of the already enqueued events to be processed before we stop the child\n // the parent itself might want to send some events to a child (for example from exit actions on the invoking state)\n // and we don't want to ignore those events\n actorScope.defer(() => {\n actorScope.stopChild(actorRef);\n });\n}\n/**\n * Stops a child actor.\n *\n * @param actorRef The actor to stop.\n */\nfunction stopChild(actorRef) {\n function stop(_args, _params) {\n }\n stop.type = 'xstate.stopChild';\n stop.actorRef = actorRef;\n stop.resolve = resolveStop;\n stop.execute = executeStop;\n return stop;\n}\n\n/**\n * Stops a child actor.\n *\n * @deprecated Use `stopChild(...)` instead\n * @alias\n */\nconst stop = stopChild;\n\nfunction checkStateIn(snapshot, _, {\n 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 return snapshot.matches(stateValue);\n}\nfunction stateIn(stateValue) {\n function stateIn() {\n return false;\n }\n stateIn.check = checkStateIn;\n stateIn.stateValue = stateValue;\n return stateIn;\n}\nfunction checkNot(snapshot, {\n context,\n event\n}, {\n guards\n}) {\n return !evaluateGuard(guards[0], context, event, snapshot);\n}\n\n/**\n * Higher-order guard that evaluates to `true` if the `guard` passed to it\n * evaluates to `false`.\n *\n * @category Guards\n * @example\n *\n * ```ts\n * import { setup, not } from 'xstate';\n *\n * const machine = setup({\n * guards: {\n * someNamedGuard: () => false\n * }\n * }).createMachine({\n * on: {\n * someEvent: {\n * guard: not('someNamedGuard'),\n * actions: () => {\n * // will be executed if guard in `not(...)`\n * // evaluates to `false`\n * }\n * }\n * }\n * });\n * ```\n *\n * @returns A guard\n */\nfunction not(guard) {\n function not(_args, _params) {\n return false;\n }\n not.check = checkNot;\n not.guards = [guard];\n return not;\n}\nfunction checkAnd(snapshot, {\n context,\n event\n}, {\n guards\n}) {\n return guards.every(guard => evaluateGuard(guard, context, event, snapshot));\n}\n\n/**\n * Higher-order guard that evaluates to `true` if all `guards` passed to it\n * evaluate to `true`.\n *\n * @category Guards\n * @example\n *\n * ```ts\n * import { setup, and } from 'xstate';\n *\n * const machine = setup({\n * guards: {\n * someNamedGuard: () => true\n * }\n * }).createMachine({\n * on: {\n * someEvent: {\n * guard: and([({ context }) => context.value > 0, 'someNamedGuard']),\n * actions: () => {\n * // will be executed if all guards in `and(...)`\n * // evaluate to true\n * }\n * }\n * }\n * });\n * ```\n *\n * @returns A guard action object\n */\nfunction and(guards) {\n function and(_args, _params) {\n return false;\n }\n and.check = checkAnd;\n and.guards = guards;\n return and;\n}\nfunction checkOr(snapshot, {\n context,\n event\n}, {\n guards\n}) {\n return guards.some(guard => evaluateGuard(guard, context, event, snapshot));\n}\n\n/**\n * Higher-order guard that evaluates to `true` if any of the `guards` passed to\n * it evaluate to `true`.\n *\n * @category Guards\n * @example\n *\n * ```ts\n * import { setup, or } from 'xstate';\n *\n * const machine = setup({\n * guards: {\n * someNamedGuard: () => true\n * }\n * }).createMachine({\n * on: {\n * someEvent: {\n * guard: or([({ context }) => context.value > 0, 'someNamedGuard']),\n * actions: () => {\n * // will be executed if any of the guards in `or(...)`\n * // evaluate to true\n * }\n * }\n * }\n * });\n * ```\n *\n * @returns A guard action object\n */\nfunction or(guards) {\n function or(_args, _params) {\n return false;\n }\n or.check = checkOr;\n or.guards = guards;\n return or;\n}\n\n// TODO: throw on cycles (depth check should be enough)\nfunction evaluateGuard(guard, context, event, snapshot) {\n const {\n machine\n } = snapshot;\n const isInline = typeof guard === 'function';\n const resolved = isInline ? guard : machine.implementations.guards[typeof guard === 'string' ? guard : guard.type];\n if (!isInline && !resolved) {\n throw new Error(`Guard '${typeof guard === 'string' ? guard : guard.type}' is not implemented.'.`);\n }\n if (typeof resolved !== 'function') {\n return evaluateGuard(resolved, context, event, snapshot);\n }\n const guardArgs = {\n context,\n event\n };\n const guardParams = isInline || typeof guard === 'string' ? undefined : 'params' in guard ? typeof guard.params === 'function' ? guard.params({\n context,\n event\n }) : guard.params : undefined;\n if (!('check' in resolved)) {\n // the existing type of `.guards` assumes non-nullable `TExpressionGuard`\n // inline guards expect `TExpressionGuard` to be set to `undefined`\n // it's fine to cast this here, our logic makes sure that we call those 2 \"variants\" correctly\n return resolved(guardArgs, guardParams);\n }\n const builtinGuard = resolved;\n return builtinGuard.check(snapshot, guardArgs, resolved // this holds all params\n );\n}\n\nconst isAtomicStateNode = stateNode => stateNode.type === 'atomic' || stateNode.type === 'final';\nfunction getChildren(stateNode) {\n return Object.values(stateNode.states).filter(sn => sn.type !== 'history');\n}\nfunction getProperAncestors(stateNode, toStateNode) {\n const ancestors = [];\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 return ancestors;\n}\nfunction getAllStateNodes(stateNodes) {\n const nodeSet = new Set(stateNodes);\n const adjList = getAdjList(nodeSet);\n\n // add descendants\n for (const s of nodeSet) {\n // if previously active, add existing child nodes\n if (s.type === 'compound' && (!adjList.get(s) || !adjList.get(s).length)) {\n getInitialStateNodesWithTheirAncestors(s).forEach(sn => nodeSet.add(sn));\n } else {\n if (s.type === 'parallel') {\n for (const child of getChildren(s)) {\n if (child.type === 'history') {\n continue;\n }\n if (!nodeSet.has(child)) {\n const initialStates = getInitialStateNodesWithTheirAncestors(child);\n for (const initialStateNode of initialStates) {\n nodeSet.add(initialStateNode);\n }\n }\n }\n }\n }\n }\n\n // add all ancestors\n for (const s of nodeSet) {\n let m = s.parent;\n while (m) {\n nodeSet.add(m);\n m = m.parent;\n }\n }\n return nodeSet;\n}\nfunction getValueFromAdj(baseNode, adjList) {\n const childStateNodes = adjList.get(baseNode);\n if (!childStateNodes) {\n return {}; // todo: fix?\n }\n if (baseNode.type === 'compound') {\n const childStateNode = childStateNodes[0];\n if (childStateNode) {\n if (isAtomicStateNode(childStateNode)) {\n return childStateNode.key;\n }\n } else {\n return {};\n }\n }\n const stateValue = {};\n for (const childStateNode of childStateNodes) {\n stateValue[childStateNode.key] = getValueFromAdj(childStateNode, adjList);\n }\n return stateValue;\n}\nfunction getAdjList(stateNodes) {\n const adjList = new Map();\n for (const s of stateNodes) {\n if (!adjList.has(s)) {\n adjList.set(s, []);\n }\n if (s.parent) {\n if (!adjList.has(s.parent)) {\n adjList.set(s.parent, []);\n }\n adjList.get(s.parent).push(s);\n }\n }\n return adjList;\n}\nfunction getStateValue(rootNode, stateNodes) {\n const config = getAllStateNodes(stateNodes);\n return getValueFromAdj(rootNode, getAdjList(config));\n}\nfunction isInFinalState(stateNodeSet, stateNode) {\n if (stateNode.type === 'compound') {\n return getChildren(stateNode).some(s => s.type === 'final' && stateNodeSet.has(s));\n }\n if (stateNode.type === 'parallel') {\n return getChildren(stateNode).every(sn => isInFinalState(stateNodeSet, sn));\n }\n return stateNode.type === 'final';\n}\nconst isStateId = str => str[0] === STATE_IDENTIFIER;\nfunction getCandidates(stateNode, receivedEventType) {\n const candidates = stateNode.transitions.get(receivedEventType) || [...stateNode.transitions.keys()].filter(eventDescriptor => {\n // check if transition is a wildcard transition,\n // which matches any non-transient events\n if (eventDescriptor === WILDCARD) {\n return true;\n }\n if (!eventDescriptor.endsWith('.*')) {\n return false;\n }\n const partialEventTokens = eventDescriptor.split('.');\n const eventTokens = receivedEventType.split('.');\n for (let tokenIndex = 0; tokenIndex < partialEventTokens.length; tokenIndex++) {\n const partialEventToken = partialEventTokens[tokenIndex];\n const eventToken = eventTokens[tokenIndex];\n if (partialEventToken === '*') {\n const isLastToken = tokenIndex === partialEventTokens.length - 1;\n return isLastToken;\n }\n if (partialEventToken !== eventToken) {\n return false;\n }\n }\n return true;\n }).sort((a, b) => b.length - a.length).flatMap(key => stateNode.transitions.get(key));\n return candidates;\n}\n\n/** All delayed transitions from the config. */\nfunction getDelayedTransitions(stateNode) {\n const afterConfig = stateNode.config.after;\n if (!afterConfig) {\n return [];\n }\n const mutateEntryExit = delay => {\n const afterEvent = createAfterEvent(delay, stateNode.id);\n const eventType = afterEvent.type;\n stateNode.entry.push(raise(afterEvent, {\n id: eventType,\n delay\n }));\n stateNode.exit.push(cancel(eventType));\n return eventType;\n };\n const delayedTransitions = Object.keys(afterConfig).flatMap(delay => {\n const configTransition = afterConfig[delay];\n const resolvedTransition = typeof configTransition === 'string' ? {\n target: configTransition\n } : configTransition;\n const resolvedDelay = Number.isNaN(+delay) ? delay : +delay;\n const eventType = mutateEntryExit(resolvedDelay);\n return toArray(resolvedTransition).map(transition => ({\n ...transition,\n event: eventType,\n delay: resolvedDelay\n }));\n });\n return delayedTransitions.map(delayedTransition => {\n const {\n delay\n } = delayedTransition;\n return {\n ...formatTransition(stateNode, delayedTransition.event, delayedTransition),\n delay\n };\n });\n}\nfunction formatTransition(stateNode, descriptor, transitionConfig) {\n const normalizedTarget = normalizeTarget(transitionConfig.target);\n const reenter = transitionConfig.reenter ?? false;\n const target = resolveTarget(stateNode, normalizedTarget);\n const transition = {\n ...transitionConfig,\n actions: toArray(transitionConfig.actions),\n guard: transitionConfig.guard,\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 return transition;\n}\nfunction formatTransitions(stateNode) {\n const transitions = new Map();\n if (stateNode.config.on) {\n for (const descriptor of Object.keys(stateNode.config.on)) {\n if (descriptor === NULL_EVENT) {\n throw new Error('Null events (\"\") cannot be specified as a transition key. Use `always: { ... }` instead.');\n }\n const transitionsConfig = stateNode.config.on[descriptor];\n transitions.set(descriptor, toTransitionConfigArray(transitionsConfig).map(t => formatTransition(stateNode, descriptor, t)));\n }\n }\n if (stateNode.config.onDone) {\n const descriptor = `xstate.done.state.${stateNode.id}`;\n transitions.set(descriptor, toTransitionConfigArray(stateNode.config.onDone).map(t => formatTransition(stateNode, descriptor, t)));\n }\n for (const invokeDef of stateNode.invoke) {\n if (invokeDef.onDone) {\n const descriptor = `xstate.done.actor.${invokeDef.id}`;\n transitions.set(descriptor, toTransitionConfigArray(invokeDef.onDone).map(t => formatTransition(stateNode, descriptor, t)));\n }\n if (invokeDef.onError) {\n const descriptor = `xstate.error.actor.${invokeDef.id}`;\n transitions.set(descriptor, toTransitionConfigArray(invokeDef.onError).map(t => formatTransition(stateNode, descriptor, t)));\n }\n if (invokeDef.onSnapshot) {\n const descriptor = `xstate.snapshot.${invokeDef.id}`;\n transitions.set(descriptor, toTransitionConfigArray(invokeDef.onSnapshot).map(t => formatTransition(stateNode, descriptor, t)));\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(delayedTransition);\n }\n return transitions;\n}\nfunction formatInitialTransition(stateNode, _target) {\n const resolvedTarget = typeof _target === 'string' ? stateNode.states[_target] : _target ? stateNode.states[_target.target] : undefined;\n if (!resolvedTarget && _target) {\n throw new Error(\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions, @typescript-eslint/no-base-to-string\n `Initial state node \"${_target}\" not found on parent state node #${stateNode.id}`);\n }\n const transition = {\n source: stateNode,\n actions: !_target || typeof _target === 'string' ? [] : toArray(_target.actions),\n eventType: null,\n reenter: false,\n target: resolvedTarget ? [resolvedTarget] : [],\n toJSON: () => ({\n ...transition,\n source: `#${stateNode.id}`,\n target: resolvedTarget ? [`#${resolvedTarget.id}`] : []\n })\n };\n return transition;\n}\nfunction resolveTarget(stateNode, targets) {\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 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(stateNode.parent, resolvedTarget);\n return targetStateNode;\n } catch (err) {\n throw new Error(`Invalid transition definition for state node '${stateNode.id}':\\n${err.message}`);\n }\n } else {\n throw new Error(`Invalid target: \"${target}\" is not a valid target from the root node. Did you mean \".${target}\"?`);\n }\n });\n}\nfunction resolveHistoryDefaultTransition(stateNode) {\n const normalizedTarget = normalizeTarget(stateNode.config.target);\n if (!normalizedTarget) {\n return stateNode.parent.initial;\n }\n return {\n target: normalizedTarget.map(t => typeof t === 'string' ? getStateNodeByPath(stateNode.parent, t) : t)\n };\n}\nfunction isHistoryNode(stateNode) {\n return stateNode.type === 'history';\n}\nfunction getInitialStateNodesWithTheirAncestors(stateNode) {\n const states = getInitialStateNodes(stateNode);\n for (const initialState of states) {\n for (const ancestor of getProperAncestors(initialState, stateNode)) {\n states.add(ancestor);\n }\n }\n return states;\n}\nfunction getInitialStateNodes(stateNode) {\n const set = new Set();\n function iter(descStateNode) {\n if (set.has(descStateNode)) {\n return;\n }\n set.add(descStateNode);\n if (descStateNode.type === 'compound') {\n iter(descStateNode.initial.target[0]);\n } else if (descStateNode.type === 'parallel') {\n for (const child of getChildren(descStateNode)) {\n iter(child);\n }\n }\n }\n iter(stateNode);\n return set;\n}\n/** Returns the child state node from its relative `stateKey`, or throws. */\nfunction getStateNode(stateNode, stateKey) {\n if (isStateId(stateKey)) {\n return stateNode.machine.getStateNodeById(stateKey);\n }\n if (!stateNode.states) {\n throw new Error(`Unable to retrieve child state '${stateKey}' from '${stateNode.id}'; no child states exist.`);\n }\n const result = stateNode.states[stateKey];\n if (!result) {\n throw new Error(`Child state '${stateKey}' does not exist on '${stateNode.id}'`);\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 */\nfunction getStateNodeByPath(stateNode, statePath) {\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 = 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 */\nfunction getStateNodes(stateNode, stateValue) {\n if (typeof stateValue === 'string') {\n const childStateNode = stateNode.states[stateValue];\n if (!childStateNode) {\n throw new Error(`State '${stateValue}' does not exist on '${stateNode.id}'`);\n }\n return [stateNode, childStateNode];\n }\n const childStateKeys = Object.keys(stateValue);\n const childStateNodes = childStateKeys.map(subStateKey => getStateNode(stateNode, subStateKey)).filter(Boolean);\n return [stateNode.machine.root, stateNode].concat(childStateNodes, childStateKeys.reduce((allSubStateNodes, subStateKey) => {\n const subStateNode = getStateNode(stateNode, subStateKey);\n if (!subStateNode) {\n return allSubStateNodes;\n }\n const subStateNodes = getStateNodes(subStateNode, stateValue[subStateKey]);\n return allSubStateNodes.concat(subStateNodes);\n }, []));\n}\nfunction transitionAtomicNode(stateNode, stateValue, snapshot, event) {\n const childStateNode = getStateNode(stateNode, stateValue);\n const next = childStateNode.next(snapshot, event);\n if (!next || !next.length) {\n return stateNode.next(snapshot, event);\n }\n return next;\n}\nfunction transitionCompoundNode(stateNode, stateValue, snapshot, event) {\n const subStateKeys = Object.keys(stateValue);\n const childStateNode = getStateNode(stateNode, subStateKeys[0]);\n const next = transitionNode(childStateNode, stateValue[subStateKeys[0]], snapshot, event);\n if (!next || !next.length) {\n return stateNode.next(snapshot, event);\n }\n return next;\n}\nfunction transitionParallelNode(stateNode, stateValue, snapshot, event) {\n const allInnerTransitions = [];\n for (const subStateKey of Object.keys(stateValue)) {\n const subStateValue = stateValue[subStateKey];\n if (!subStateValue) {\n continue;\n }\n const subStateNode = getStateNode(stateNode, subStateKey);\n const innerTransitions = transitionNode(subStateNode, subStateValue, snapshot, event);\n if (innerTransitions) {\n allInnerTransitions.push(...innerTransitions);\n }\n }\n if (!allInnerTransitions.length) {\n return stateNode.next(snapshot, event);\n }\n return allInnerTransitions;\n}\nfunction transitionNode(stateNode, stateValue, snapshot, event) {\n // leaf node\n if (typeof stateValue === 'string') {\n return transitionAtomicNode(stateNode, stateValue, snapshot, event);\n }\n\n // compound node\n if (Object.keys(stateValue).length === 1) {\n return transitionCompoundNode(stateNode, stateValue, snapshot, event);\n }\n\n // parallel node\n return transitionParallelNode(stateNode, stateValue, snapshot, event);\n}\nfunction getHistoryNodes(stateNode) {\n return Object.keys(stateNode.states).map(key => stateNode.states[key]).filter(sn => sn.type === 'history');\n}\nfunction isDescendant(childStateNode, parentStateNode) {\n let marker = childStateNode;\n while (marker.parent && marker.parent !== parentStateNode) {\n marker = marker.parent;\n }\n return marker.parent === parentStateNode;\n}\nfunction hasIntersection(s1, s2) {\n const set1 = new Set(s1);\n const set2 = new Set(s2);\n for (const item of set1) {\n if (set2.has(item)) {\n return true;\n }\n }\n for (const item of set2) {\n if (set1.has(item)) {\n return true;\n }\n }\n return false;\n}\nfunction removeConflictingTransitions(enabledTransitions, stateNodeSet, historyValue) {\n const filteredTransitions = new Set();\n for (const t1 of enabledTransitions) {\n let t1Preempted = false;\n const transitionsToRemove = new Set();\n for (const t2 of filteredTransitions) {\n if (hasIntersection(computeExitSet([t1], stateNodeSet, historyValue), computeExitSet([t2], stateNodeSet, historyValue))) {\n if (isDescendant(t1.source, t2.source)) {\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 return Array.from(filteredTransitions);\n}\nfunction findLeastCommonAncestor(stateNodes) {\n const [head, ...tail] = stateNodes;\n for (const ancestor of getProperAncestors(head, undefined)) {\n if (tail.every(sn => isDescendant(sn, ancestor))) {\n return ancestor;\n }\n }\n}\nfunction getEffectiveTargetStates(transition, historyValue) {\n if (!transition.target) {\n return [];\n }\n const targets = new Set();\n for (const targetNode of transition.target) {\n if (isHistoryNode(targetNode)) {\n if (historyValue[targetNode.id]) {\n for (const node of historyValue[targetNode.id]) {\n targets.add(node);\n }\n } else {\n for (const node of getEffectiveTargetStates(resolveHistoryDefaultTransition(targetNode), historyValue)) {\n targets.add(node);\n }\n }\n } else {\n targets.add(targetNode);\n }\n }\n return [...targets];\n}\nfunction getTransitionDomain(transition, historyValue) {\n const targetStates = getEffectiveTargetStates(transition, historyValue);\n if (!targetStates) {\n return;\n }\n if (!transition.reenter && targetStates.every(target => target === transition.source || isDescendant(target, transition.source))) {\n return transition.source;\n }\n const lca = findLeastCommonAncestor(targetStates.concat(transition.source));\n if (lca) {\n return lca;\n }\n\n // at this point we know that it's a root transition since LCA couldn't be found\n if (transition.reenter) {\n return;\n }\n return transition.source.machine.root;\n}\nfunction computeExitSet(transitions, stateNodeSet, historyValue) {\n const statesToExit = new Set();\n for (const t of transitions) {\n if (t.target?.length) {\n const domain = getTransitionDomain(t, historyValue);\n if (t.reenter && t.source === domain) {\n statesToExit.add(domain);\n }\n for (const stateNode of stateNodeSet) {\n if (isDescendant(stateNode, domain)) {\n statesToExit.add(stateNode);\n }\n }\n }\n }\n return [...statesToExit];\n}\nfunction areStateNodeCollectionsEqual(prevStateNodes, nextStateNodeSet) {\n if (prevStateNodes.length !== nextStateNodeSet.size) {\n return false;\n }\n for (const node of prevStateNodes) {\n if (!nextStateNodeSet.has(node)) {\n return false;\n }\n }\n return true;\n}\n\n/** https://www.w3.org/TR/scxml/#microstepProcedure */\nfunction microstep(transitions, currentSnapshot, actorScope, event, isInitial, internalQueue) {\n if (!transitions.length) {\n return currentSnapshot;\n }\n const mutStateNodeSet = new Set(currentSnapshot._nodes);\n let historyValue = currentSnapshot.historyValue;\n const filteredTransitions = removeConflictingTransitions(transitions, mutStateNodeSet, historyValue);\n let nextState = currentSnapshot;\n\n // Exit states\n if (!isInitial) {\n [nextState, historyValue] = exitStates(nextState, event, actorScope, filteredTransitions, mutStateNodeSet, historyValue, internalQueue, actorScope.actionExecutor);\n }\n\n // Execute transition content\n nextState = resolveActionsAndContext(nextState, event, actorScope, filteredTransitions.flatMap(t => t.actions), internalQueue, undefined);\n\n // Enter states\n nextState = enterStates(nextState, event, actorScope, filteredTransitions, mutStateNodeSet, internalQueue, historyValue, isInitial);\n const nextStateNodes = [...mutStateNodeSet];\n if (nextState.status === 'done') {\n nextState = resolveActionsAndContext(nextState, event, actorScope, nextStateNodes.sort((a, b) => b.order - a.order).flatMap(state => state.exit), internalQueue, undefined);\n }\n\n // eslint-disable-next-line no-useless-catch\n try {\n if (historyValue === currentSnapshot.historyValue && areStateNodeCollectionsEqual(currentSnapshot._nodes, mutStateNodeSet)) {\n return nextState;\n }\n return cloneMachineSnapshot(nextState, {\n _nodes: nextStateNodes,\n historyValue\n });\n } catch (e) {\n // TODO: Refactor this once proper error handling is implemented.\n // See https://github.com/statelyai/rfcs/pull/4\n throw e;\n }\n}\nfunction getMachineOutput(snapshot, event, actorScope, rootNode, rootCompletionNode) {\n if (rootNode.output === undefined) {\n return;\n }\n const doneStateEvent = createDoneStateEvent(rootCompletionNode.id, rootCompletionNode.output !== undefined && rootCompletionNode.parent ? resolveOutput(rootCompletionNode.output, snapshot.context, event, actorScope.self) : undefined);\n return resolveOutput(rootNode.output, snapshot.context, doneStateEvent, actorScope.self);\n}\nfunction enterStates(currentSnapshot, event, actorScope, filteredTransitions, mutStateNodeSet, internalQueue, historyValue, isInitial) {\n let nextSnapshot = currentSnapshot;\n const statesToEnter = new Set();\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();\n computeEntrySet(filteredTransitions, historyValue, statesForDefaultEntry, statesToEnter);\n\n // In the initial state, the root state node is \"entered\".\n if (isInitial) {\n statesForDefaultEntry.add(currentSnapshot.machine.root);\n }\n const completedNodes = new Set();\n for (const stateNodeToEnter of [...statesToEnter].sort((a, b) => a.order - b.order)) {\n mutStateNodeSet.add(stateNodeToEnter);\n const actions = [];\n\n // Add entry actions\n actions.push(...stateNodeToEnter.entry);\n for (const invokeDef of stateNodeToEnter.invoke) {\n actions.push(spawnChild(invokeDef.src, {\n ...invokeDef,\n syncSnapshot: !!invokeDef.onSnapshot\n }));\n }\n if (statesForDefaultEntry.has(stateNodeToEnter)) {\n const initialActions = stateNodeToEnter.initial.actions;\n actions.push(...initialActions);\n }\n nextSnapshot = resolveActionsAndContext(nextSnapshot, event, actorScope, actions, internalQueue, stateNodeToEnter.invoke.map(invokeDef => invokeDef.id));\n if (stateNodeToEnter.type === 'final') {\n const parent = stateNodeToEnter.parent;\n let ancestorMarker = parent?.type === 'parallel' ? parent : parent?.parent;\n let rootCompletionNode = ancestorMarker || stateNodeToEnter;\n if (parent?.type === 'compound') {\n internalQueue.push(createDoneStateEvent(parent.id, stateNodeToEnter.output !== undefined ? resolveOutput(stateNodeToEnter.output, nextSnapshot.context, event, actorScope.self) : undefined));\n }\n while (ancestorMarker?.type === 'parallel' && !completedNodes.has(ancestorMarker) && isInFinalState(mutStateNodeSet, ancestorMarker)) {\n completedNodes.add(ancestorMarker);\n internalQueue.push(createDoneStateEvent(ancestorMarker.id));\n rootCompletionNode = ancestorMarker;\n ancestorMarker = ancestorMarker.parent;\n }\n if (ancestorMarker) {\n continue;\n }\n nextSnapshot = cloneMachineSnapshot(nextSnapshot, {\n status: 'done',\n output: getMachineOutput(nextSnapshot, event, actorScope, nextSnapshot.machine.root, rootCompletionNode)\n });\n }\n }\n return nextSnapshot;\n}\nfunction computeEntrySet(transitions, historyValue, statesForDefaultEntry, statesToEnter) {\n for (const t of transitions) {\n const domain = getTransitionDomain(t, historyValue);\n for (const s of t.target || []) {\n if (!isHistoryNode(s) && (\n // if the target is different than the source then it will *definitely* be entered\n t.source !== s ||\n // we know that the domain can't lie within the source\n // if it's different than the source then it's outside of it and it means that the target has to be entered as well\n t.source !== domain ||\n // reentering transitions always enter the target, even if it's the source itself\n t.reenter)) {\n statesToEnter.add(s);\n statesForDefaultEntry.add(s);\n }\n addDescendantStatesToEnter(s, historyValue, statesForDefaultEntry, statesToEnter);\n }\n const targetStates = getEffectiveTargetStates(t, historyValue);\n for (const s of targetStates) {\n const ancestors = getProperAncestors(s, domain);\n if (domain?.type === 'parallel') {\n ancestors.push(domain);\n }\n addAncestorStatesToEnter(statesToEnter, historyValue, statesForDefaultEntry, ancestors, !t.source.parent && t.reenter ? undefined : domain);\n }\n }\n}\nfunction addDescendantStatesToEnter(stateNode, historyValue, statesForDefaultEntry, statesToEnter) {\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, historyValue, statesForDefaultEntry, statesToEnter);\n }\n for (const s of historyStateNodes) {\n addProperAncestorStatesToEnter(s, stateNode.parent, statesToEnter, historyValue, statesForDefaultEntry);\n }\n } else {\n const historyDefaultTransition = resolveHistoryDefaultTransition(stateNode);\n for (const s of historyDefaultTransition.target) {\n statesToEnter.add(s);\n if (historyDefaultTransition === stateNode.parent?.initial) {\n statesForDefaultEntry.add(stateNode.parent);\n }\n addDescendantStatesToEnter(s, historyValue, statesForDefaultEntry, statesToEnter);\n }\n for (const s of historyDefaultTransition.target) {\n addProperAncestorStatesToEnter(s, stateNode.parent, statesToEnter, historyValue, statesForDefaultEntry);\n }\n }\n } else {\n if (stateNode.type === 'compound') {\n const [initialState] = stateNode.initial.target;\n if (!isHistoryNode(initialState)) {\n statesToEnter.add(initialState);\n statesForDefaultEntry.add(initialState);\n }\n addDescendantStatesToEnter(initialState, historyValue, statesForDefaultEntry, statesToEnter);\n addProperAncestorStatesToEnter(initialState, stateNode, statesToEnter, historyValue, statesForDefaultEntry);\n } else {\n if (stateNode.type === 'parallel') {\n for (const child of getChildren(stateNode).filter(sn => !isHistoryNode(sn))) {\n if (![...statesToEnter].some(s => isDescendant(s, child))) {\n if (!isHistoryNode(child)) {\n statesToEnter.add(child);\n statesForDefaultEntry.add(child);\n }\n addDescendantStatesToEnter(child, historyValue, statesForDefaultEntry, statesToEnter);\n }\n }\n }\n }\n }\n}\nfunction addAncestorStatesToEnter(statesToEnter, historyValue, statesForDefaultEntry, ancestors, reentrancyDomain) {\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).filter(sn => !isHistoryNode(sn))) {\n if (![...statesToEnter].some(s => isDescendant(s, child))) {\n statesToEnter.add(child);\n addDescendantStatesToEnter(child, historyValue, statesForDefaultEntry, statesToEnter);\n }\n }\n }\n }\n}\nfunction addProperAncestorStatesToEnter(stateNode, toStateNode, statesToEnter, historyValue, statesForDefaultEntry) {\n addAncestorStatesToEnter(statesToEnter, historyValue, statesForDefaultEntry, getProperAncestors(stateNode, toStateNode));\n}\nfunction exitStates(currentSnapshot, event, actorScope, transitions, mutStateNodeSet, historyValue, internalQueue, _actionExecutor) {\n let nextSnapshot = currentSnapshot;\n const statesToExit = computeExitSet(transitions, mutStateNodeSet, historyValue);\n statesToExit.sort((a, b) => b.order - a.order);\n let changedHistory;\n\n // From SCXML algorithm: https://www.w3.org/TR/scxml/#exitStates\n for (const exitStateNode of statesToExit) {\n for (const historyNode of getHistoryNodes(exitStateNode)) {\n let predicate;\n if (historyNode.history === 'deep') {\n predicate = sn => isAtomicStateNode(sn) && isDescendant(sn, exitStateNode);\n } else {\n predicate = sn => {\n return sn.parent === exitStateNode;\n };\n }\n changedHistory ??= {\n ...historyValue\n };\n changedHistory[historyNode.id] = Array.from(mutStateNodeSet).filter(predicate);\n }\n }\n for (const s of statesToExit) {\n nextSnapshot = resolveActionsAndContext(nextSnapshot, event, actorScope, [...s.exit, ...s.invoke.map(def => stopChild(def.id))], internalQueue, undefined);\n mutStateNodeSet.delete(s);\n }\n return [nextSnapshot, changedHistory || historyValue];\n}\nfunction getAction(machine, actionType) {\n return machine.implementations.actions[actionType];\n}\nfunction resolveAndExecuteActionsWithContext(currentSnapshot, event, actorScope, actions, extra, retries) {\n const {\n machine\n } = currentSnapshot;\n let intermediateSnapshot = currentSnapshot;\n for (const action of actions) {\n const isInline = typeof action === 'function';\n const resolvedAction = isInline ? action :\n // the existing type of `.actions` assumes non-nullable `TExpressionAction`\n // it's fine to cast this here to get a common type and lack of errors in the rest of the code\n // our logic below makes sure that we call those 2 \"variants\" correctly\n\n getAction(machine, typeof action === 'string' ? action : action.type);\n const actionArgs = {\n context: intermediateSnapshot.context,\n event,\n self: actorScope.self,\n system: actorScope.system\n };\n const actionParams = isInline || typeof action === 'string' ? undefined : 'params' in action ? typeof action.params === 'function' ? action.params({\n context: intermediateSnapshot.context,\n event\n }) : action.params : undefined;\n if (!resolvedAction || !('resolve' in resolvedAction)) {\n actorScope.actionExecutor({\n type: typeof action === 'string' ? action : typeof action === 'object' ? action.type : action.name || '(anonymous)',\n info: actionArgs,\n params: actionParams,\n exec: resolvedAction\n });\n continue;\n }\n const builtinAction = resolvedAction;\n const [nextState, params, actions] = builtinAction.resolve(actorScope, intermediateSnapshot, actionArgs, actionParams, resolvedAction,\n // this holds all params\n extra);\n intermediateSnapshot = nextState;\n if ('retryResolve' in builtinAction) {\n retries?.push([builtinAction, params]);\n }\n if ('execute' in builtinAction) {\n actorScope.actionExecutor({\n type: builtinAction.type,\n info: actionArgs,\n params,\n exec: builtinAction.execute.bind(null, actorScope, params)\n });\n }\n if (actions) {\n intermediateSnapshot = resolveAndExecuteActionsWithContext(intermediateSnapshot, event, actorScope, actions, extra, retries);\n }\n }\n return intermediateSnapshot;\n}\nfunction resolveActionsAndContext(currentSnapshot, event, actorScope, actions, internalQueue, deferredActorIds) {\n const retries = deferredActorIds ? [] : undefined;\n const nextState = resolveAndExecuteActionsWithContext(currentSnapshot, event, actorScope, actions, {\n internalQueue,\n deferredActorIds\n }, retries);\n retries?.forEach(([builtinAction, params]) => {\n builtinAction.retryResolve(actorScope, nextState, params);\n });\n return nextState;\n}\nfunction macrostep(snapshot, event, actorScope, internalQueue) {\n let nextSnapshot = snapshot;\n const microstates = [];\n function addMicrostate(microstate, event, transitions) {\n actorScope.system._sendInspectionEvent({\n type: '@xstate.microstep',\n actorRef: actorScope.self,\n event,\n snapshot: microstate,\n _transitions: transitions\n });\n microstates.push(microstate);\n }\n\n // Handle stop event\n if (event.type === XSTATE_STOP) {\n nextSnapshot = cloneMachineSnapshot(stopChildren(nextSnapshot, event, actorScope), {\n status: 'stopped'\n });\n addMicrostate(nextSnapshot, event, []);\n return {\n snapshot: nextSnapshot,\n microstates\n };\n }\n let nextEvent = event;\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) {\n const currentEvent = nextEvent;\n const isErr = isErrorActorEvent(currentEvent);\n const transitions = selectTransitions(currentEvent, nextSnapshot);\n if (isErr && !transitions.length) {\n // TODO: we should likely only allow transitions selected by very explicit descriptors\n // `*` shouldn't be matched, likely `xstate.error.*` shouldnt be either\n // similarly `xstate.error.actor.*` and `xstate.error.actor.todo.*` have to be considered too\n nextSnapshot = cloneMachineSnapshot(snapshot, {\n status: 'error',\n error: currentEvent.error\n });\n addMicrostate(nextSnapshot, currentEvent, []);\n return {\n snapshot: nextSnapshot,\n microstates\n };\n }\n nextSnapshot = microstep(transitions, snapshot, actorScope, nextEvent, false,\n // isInitial\n internalQueue);\n addMicrostate(nextSnapshot, currentEvent, transitions);\n }\n let shouldSelectEventlessTransitions = true;\n while (nextSnapshot.status === 'active') {\n let enabledTransitions = shouldSelectEventlessTransitions ? selectEventlessTransitions(nextSnapshot, nextEvent) : [];\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 if (!enabledTransitions.length) {\n if (!internalQueue.length) {\n break;\n }\n nextEvent = internalQueue.shift();\n enabledTransitions = selectTransitions(nextEvent, nextSnapshot);\n }\n nextSnapshot = microstep(enabledTransitions, nextSnapshot, actorScope, nextEvent, false, internalQueue);\n shouldSelectEventlessTransitions = nextSnapshot !== previousState;\n addMicrostate(nextSnapshot, nextEvent, enabledTransitions);\n }\n if (nextSnapshot.status !== 'active') {\n stopChildren(nextSnapshot, nextEvent, actorScope);\n }\n return {\n snapshot: nextSnapshot,\n microstates\n };\n}\nfunction stopChildren(nextState, event, actorScope) {\n return resolveActionsAndContext(nextState, event, actorScope, Object.values(nextState.children).map(child => stopChild(child)), [], undefined);\n}\nfunction selectTransitions(event, nextState) {\n return nextState.machine.getTransitionData(nextState, event);\n}\nfunction selectEventlessTransitions(nextState, event) {\n const enabledTransitionSet = new Set();\n const atomicStates = nextState._nodes.filter(isAtomicStateNode);\n for (const stateNode of atomicStates) {\n loop: for (const s of [stateNode].concat(getProperAncestors(stateNode, undefined))) {\n if (!s.always) {\n continue;\n }\n for (const transition of s.always) {\n if (transition.guard === undefined || evaluateGuard(transition.guard, nextState.context, event, nextState)) {\n enabledTransitionSet.add(transition);\n break loop;\n }\n }\n }\n }\n return removeConflictingTransitions(Array.from(enabledTransitionSet), new Set(nextState._nodes), nextState.historyValue);\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 */\nfunction resolveStateValue(rootNode, stateValue) {\n const allStateNodes = getAllStateNodes(getStateNodes(rootNode, stateValue));\n return getStateValue(rootNode, [...allStateNodes]);\n}\n\nfunction isMachineSnapshot(value) {\n return !!value && typeof value === 'object' && 'machine' in value && 'value' in value;\n}\nconst machineSnapshotMatches = function matches(testValue) {\n return matchesState(testValue, this.value);\n};\nconst machineSnapshotHasTag = function hasTag(tag) {\n return this.tags.has(tag);\n};\nconst machineSnapshotCan = function can(event) {\n const transitionData = this.machine.getTransitionData(this, event);\n return !!transitionData?.length &&\n // Check that at least one transition is not forbidden\n transitionData.some(t => t.target !== undefined || t.actions.length);\n};\nconst machineSnapshotToJSON = function toJSON() {\n const {\n _nodes: nodes,\n tags,\n machine,\n getMeta,\n toJSON,\n can,\n hasTag,\n matches,\n ...jsonValues\n } = this;\n return {\n ...jsonValues,\n tags: Array.from(tags)\n };\n};\nconst machineSnapshotGetMeta = function getMeta() {\n return this._nodes.reduce((acc, stateNode) => {\n if (stateNode.meta !== undefined) {\n acc[stateNode.id] = stateNode.meta;\n }\n return acc;\n }, {});\n};\nfunction createMachineSnapshot(config, machine) {\n return {\n status: config.status,\n output: config.output,\n error: config.error,\n machine,\n context: config.context,\n _nodes: config._nodes,\n value: getStateValue(machine.root, config._nodes),\n tags: new Set(config._nodes.flatMap(sn => sn.tags)),\n children: config.children,\n historyValue: config.historyValue || {},\n matches: machineSnapshotMatches,\n hasTag: machineSnapshotHasTag,\n can: machineSnapshotCan,\n getMeta: machineSnapshotGetMeta,\n toJSON: machineSnapshotToJSON\n };\n}\nfunction cloneMachineSnapshot(snapshot, config = {}) {\n return createMachineSnapshot({\n ...snapshot,\n ...config\n }, snapshot.machine);\n}\nfunction getPersistedSnapshot(snapshot, options) {\n const {\n _nodes: nodes,\n tags,\n machine,\n children,\n context,\n can,\n hasTag,\n matches,\n getMeta,\n toJSON,\n ...jsonValues\n } = snapshot;\n const childrenJson = {};\n for (const id in children) {\n const child = children[id];\n childrenJson[id] = {\n snapshot: child.getPersistedSnapshot(options),\n src: child.src,\n systemId: child._systemId,\n syncSnapshot: child._syncSnapshot\n };\n }\n const persisted = {\n ...jsonValues,\n context: persistContext(context),\n children: childrenJson\n };\n return persisted;\n}\nfunction persistContext(contextPart) {\n let copy;\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) ? contextPart.slice() : {\n ...contextPart\n };\n copy[key] = {\n xstate$$type: $$ACTOR_TYPE,\n id: value.id\n };\n } else {\n const result = persistContext(value);\n if (result !== value) {\n copy ??= Array.isArray(contextPart) ? contextPart.slice() : {\n ...contextPart\n };\n copy[key] = result;\n }\n }\n }\n }\n return copy ?? contextPart;\n}\n\nfunction resolveRaise(_, snapshot, args, actionParams, {\n event: eventOrExpr,\n id,\n delay\n}, {\n internalQueue\n}) {\n const delaysMap = snapshot.machine.implementations.delays;\n if (typeof eventOrExpr === 'string') {\n throw new Error(\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n `Only event objects may be used with raise; use raise({ type: \"${eventOrExpr}\" }) instead`);\n }\n const resolvedEvent = typeof eventOrExpr === 'function' ? eventOrExpr(args, actionParams) : eventOrExpr;\n let resolvedDelay;\n if (typeof delay === 'string') {\n const configDelay = delaysMap && delaysMap[delay];\n resolvedDelay = typeof configDelay === 'function' ? configDelay(args, actionParams) : configDelay;\n } else {\n resolvedDelay = typeof delay === 'function' ? delay(args, actionParams) : delay;\n }\n if (typeof resolvedDelay !== 'number') {\n internalQueue.push(resolvedEvent);\n }\n return [snapshot, {\n event: resolvedEvent,\n id,\n delay: resolvedDelay\n }, undefined];\n}\nfunction executeRaise(actorScope, params) {\n const {\n event,\n delay,\n id\n } = params;\n if (typeof delay === 'number') {\n actorScope.defer(() => {\n const self = actorScope.self;\n actorScope.system.scheduler.schedule(self, self, event, delay, id);\n });\n return;\n }\n}\n/**\n * Raises an event. This places the event in the internal event queue, so that\n * the event is immediately consumed by the machine in the current step.\n *\n * @param eventType The event to raise.\n */\nfunction raise(eventOrExpr, options) {\n function raise(_args, _params) {\n }\n raise.type = 'xstate.raise';\n raise.event = eventOrExpr;\n raise.id = options?.id;\n raise.delay = options?.delay;\n raise.resolve = resolveRaise;\n raise.execute = executeRaise;\n return raise;\n}\n\nexport { $$ACTOR_TYPE as $, createActor as A, Actor as B, interpret as C, and as D, not as E, or as F, stateIn as G, isMachineSnapshot as H, getAllOwnEventDescriptors as I, matchesState as J, pathToStateValue as K, toObserver as L, cancel as M, NULL_EVENT as N, raise as O, spawnChild as P, stop as Q, stopChild as R, STATE_DELIMITER as S, ProcessingStatus as T, cloneMachineSnapshot as U, XSTATE_ERROR as V, createErrorActorEvent as W, XSTATE_STOP as X, toTransitionConfigArray as a, formatTransition as b, createInvokeId as c, formatInitialTransition as d, evaluateGuard as e, formatTransitions as f, getDelayedTransitions as g, getCandidates as h, getAllStateNodes as i, getStateNodes as j, createMachineSnapshot as k, isInFinalState as l, mapValues as m, macrostep as n, transitionNode as o, resolveActionsAndContext as p, createInitEvent as q, resolveStateValue as r, microstep as s, toArray as t, getInitialStateNodes as u, toStatePath as v, isStateId as w, getStateNodeByPath as x, getPersistedSnapshot as y, resolveReferencedActor as z };\n","import { X as XSTATE_STOP, A as createActor } from '../../dist/raise-c17ec2bc.esm.js';\nimport '../../dev/dist/xstate-dev.esm.js';\n\n/**\n * Represents an actor created by `fromTransition`.\n *\n * The type of `self` within the actor's logic.\n *\n * @example\n *\n * ```ts\n * import {\n * fromTransition,\n * createActor,\n * type AnyActorSystem\n * } from 'xstate';\n *\n * //* The actor's stored context.\n * type Context = {\n * // The current count.\n * count: number;\n * // The amount to increase `count` by.\n * step: number;\n * };\n * // The events the actor receives.\n * type Event = { type: 'increment' };\n * // The actor's input.\n * type Input = { step?: number };\n *\n * // Actor logic that increments `count` by `step` when it receives an event of\n * // type `increment`.\n * const logic = fromTransition<Context, Event, AnyActorSystem, Input>(\n * (state, event, actorScope) => {\n * actorScope.self;\n * // ^? TransitionActorRef<Context, Event>\n *\n * if (event.type === 'increment') {\n * return {\n * ...state,\n * count: state.count + state.step\n * };\n * }\n * return state;\n * },\n * ({ input, self }) => {\n * self;\n * // ^? TransitionActorRef<Context, Event>\n *\n * return {\n * count: 0,\n * step: input.step ?? 1\n * };\n * }\n * );\n *\n * const actor = createActor(logic, { input: { step: 10 } });\n * // ^? TransitionActorRef<Context, Event>\n * ```\n *\n * @see {@link fromTransition}\n */\n\n/**\n * Returns actor logic given a transition function and its initial state.\n *\n * A “transition function” is a function that takes the current `state` and\n * received `event` object as arguments, and returns the next state, similar to\n * a reducer.\n *\n * Actors created from transition logic (“transition actors”) can:\n *\n * - Receive events\n * - Emit snapshots of its state\n *\n * The transition function’s `state` is used as its transition actor’s\n * `context`.\n *\n * Note that the \"state\" for a transition function is provided by the initial\n * state argument, and is not the same as the State object of an actor or a\n * state within a machine configuration.\n *\n * @example\n *\n * ```ts\n * const transitionLogic = fromTransition(\n * (state, event) => {\n * if (event.type === 'increment') {\n * return {\n * ...state,\n * count: state.count + 1\n * };\n * }\n * return state;\n * },\n * { count: 0 }\n * );\n *\n * const transitionActor = createActor(transitionLogic);\n * transitionActor.subscribe((snapshot) => {\n * console.log(snapshot);\n * });\n * transitionActor.start();\n * // => {\n * // status: 'active',\n * // context: { count: 0 },\n * // ...\n * // }\n *\n * transitionActor.send({ type: 'increment' });\n * // => {\n * // status: 'active',\n * // context: { count: 1 },\n * // ...\n * // }\n * ```\n *\n * @param transition The transition function used to describe the transition\n * logic. It should return the next state given the current state and event.\n * It receives the following arguments:\n *\n * - `state` - the current state.\n * - `event` - the received event.\n * - `actorScope` - the actor scope object, with properties like `self` and\n * `system`.\n *\n * @param initialContext The initial state of the transition function, either an\n * object representing the state, or a function which returns a state object.\n * If a function, it will receive as its only argument an object with the\n * following properties:\n *\n * - `input` - the `input` provided to its parent transition actor.\n * - `self` - a reference to its parent transition actor.\n *\n * @returns Actor logic\n * @see {@link https://stately.ai/docs/input | Input docs} for more information about how input is passed\n */\nfunction fromTransition(transition, initialContext) {\n return {\n config: transition,\n transition: (snapshot, event, actorScope) => {\n return {\n ...snapshot,\n context: transition(snapshot.context, event, actorScope)\n };\n },\n getInitialSnapshot: (_, input) => {\n return {\n status: 'active',\n output: undefined,\n error: undefined,\n context: typeof initialContext === 'function' ? initialContext({\n input\n }) : initialContext\n };\n },\n getPersistedSnapshot: snapshot => snapshot,\n restoreSnapshot: snapshot => snapshot\n };\n}\n\nconst instanceStates = /* #__PURE__ */new WeakMap();\n\n/**\n * Represents an actor created by `fromCallback`.\n *\n * The type of `self` within the actor's logic.\n *\n * @example\n *\n * ```ts\n * import { fromCallback, createActor } from 'xstate';\n *\n * // The events the actor receives.\n * type Event = { type: 'someEvent' };\n * // The actor's input.\n * type Input = { name: string };\n *\n * // Actor logic that logs whenever it receives an event of type `someEvent`.\n * const logic = fromCallback<Event, Input>(({ self, input, receive }) => {\n * self;\n * // ^? CallbackActorRef<Event, Input>\n *\n * receive((event) => {\n * if (event.type === 'someEvent') {\n * console.log(`${input.name}: received \"someEvent\" event`);\n * // logs 'myActor: received \"someEvent\" event'\n * }\n * });\n * });\n *\n * const actor = createActor(logic, { input: { name: 'myActor' } });\n * // ^? CallbackActorRef<Event, Input>\n * ```\n *\n * @see {@link fromCallback}\n */\n\n/**\n * An actor logic creator which returns callback logic as defined by a callback\n * function.\n *\n * @remarks\n * Useful for subscription-based or other free-form logic that can send events\n * back to the parent actor.\n *\n * Actors created from callback logic (“callback actors”) can:\n *\n * - Receive events via the `receive` function\n * - Send events to the parent actor via the `sendBack` function\n *\n * Callback actors are a bit different from other actors in that they:\n *\n * - Do not work with `onDone`\n * - Do not produce a snapshot using `.getSnapshot()`\n * - Do not emit values when used with `.subscribe()`\n * - Can not be stopped with `.stop()`\n *\n * @example\n *\n * ```typescript\n * const callbackLogic = fromCallback(({ sendBack, receive }) => {\n * let lockStatus = 'unlocked';\n *\n * const handler = (event) => {\n * if (lockStatus === 'locked') {\n * return;\n * }\n * sendBack(event);\n * };\n *\n * receive((event) => {\n * if (event.type === 'lock') {\n * lockStatus = 'locked';\n * } else if (event.type === 'unlock') {\n * lockStatus = 'unlocked';\n * }\n * });\n *\n * document.body.addEventListener('click', handler);\n *\n * return () => {\n * document.body.removeEventListener('click', handler);\n * };\n * });\n * ```\n *\n * @param callback - The callback function used to describe the callback logic\n * The callback function is passed an object with the following properties:\n *\n * - `receive` - A function that can send events back to the parent actor; the\n * listener is then called whenever events are received by the callback\n * actor\n * - `sendBack` - A function that can send events back to the parent actor\n * - `input` - Data that was provided to the callback actor\n * - `self` - The parent actor of the callback actor\n * - `system` - The actor system to which the callback actor belongs The callback\n * function can (optionally) return a cleanup function, which is called\n * when the actor is stopped.\n *\n * @returns Callback logic\n * @see {@link CallbackLogicFunction} for more information about the callback function and its object argument\n * @see {@link https://stately.ai/docs/input | Input docs} for more information about how input is passed\n */\nfunction fromCallback(callback) {\n const logic = {\n config: callback,\n start: (state, actorScope) => {\n const {\n self,\n system,\n emit\n } = actorScope;\n const callbackState = {\n receivers: undefined,\n dispose: undefined\n };\n instanceStates.set(self, callbackState);\n callbackState.dispose = callback({\n input: state.input,\n system,\n self,\n sendBack: event => {\n if (self.getSnapshot().status === 'stopped') {\n return;\n }\n if (self._parent) {\n system._relay(self, self._parent, event);\n }\n },\n receive: listener => {\n callbackState.receivers ??= new Set();\n callbackState.receivers.add(listener);\n },\n emit\n });\n },\n transition: (state, event, actorScope) => {\n const callbackState = instanceStates.get(actorScope.self);\n if (event.type === XSTATE_STOP) {\n state = {\n ...state,\n status: 'stopped',\n error: undefined\n };\n callbackState.dispose?.();\n return state;\n }\n callbackState.receivers?.forEach(receiver => receiver(event));\n return state;\n },\n getInitialSnapshot: (_, input) => {\n return {\n status: 'active',\n output: undefined,\n error: undefined,\n input\n };\n },\n getPersistedSnapshot: snapshot => snapshot,\n restoreSnapshot: snapshot => snapshot\n };\n return logic;\n}\n\nconst XSTATE_OBSERVABLE_NEXT = 'xstate.observable.next';\nconst XSTATE_OBSERVABLE_ERROR = 'xstate.observable.error';\nconst XSTATE_OBSERVABLE_COMPLETE = 'xstate.observable.complete';\n\n/**\n * Represents an actor created by `fromObservable` or `fromEventObservable`.\n *\n * The type of `self` within the actor's logic.\n *\n * @example\n *\n * ```ts\n * import { fromObservable, createActor } from 'xstate';\n * import { interval } from 'rxjs';\n *\n * // The type of the value observed by the actor's logic.\n * type Context = number;\n * // The actor's input.\n * type Input = { period?: number };\n *\n * // Actor logic that observes a number incremented every `input.period`\n * // milliseconds (default: 1_000).\n * const logic = fromObservable<Context, Input>(({ input, self }) => {\n * self;\n * // ^? ObservableActorRef<Event, Input>\n *\n * return interval(input.period ?? 1_000);\n * });\n *\n * const actor = createActor(logic, { input: { period: 2_000 } });\n * // ^? ObservableActorRef<Event, Input>\n * ```\n *\n * @see {@link fromObservable}\n * @see {@link fromEventObservable}\n */\n\n/**\n * Observable actor logic is described by an observable stream of values. Actors\n * created from observable logic (“observable actors”) can:\n *\n * - Emit snapshots of the observable’s emitted value\n *\n * The observable’s emitted value is used as its observable actor’s `context`.\n *\n * Sending events to observable actors will have no effect.\n *\n * @example\n *\n * ```ts\n * import { fromObservable, createActor } from 'xstate';\n * import { interval } from 'rxjs';\n *\n * const logic = fromObservable((obj) => interval(1000));\n *\n * const actor = createActor(logic);\n *\n * actor.subscribe((snapshot) => {\n * console.log(snapshot.context);\n * });\n *\n * actor.start();\n * // At every second:\n * // Logs 0\n * // Logs 1\n * // Logs 2\n * // ...\n * ```\n *\n * @param observableCreator A function that creates an observable. It receives\n * one argument, an object with the following properties:\n *\n * - `input` - Data that was provided to the observable actor\n * - `self` - The parent actor\n * - `system` - The actor system to which the observable actor belongs\n *\n * It should return a {@link Subscribable}, which is compatible with an RxJS\n * Observable, although RxJS is not required to create them.\n * @see {@link https://rxjs.dev} for documentation on RxJS Observable and observable creators.\n * @see {@link Subscribable} interface in XState, which is based on and compatible with RxJS Observable.\n */\nfunction fromObservable(observableCreator) {\n // TODO: add event types\n const logic = {\n config: observableCreator,\n transition: (snapshot, event) => {\n if (snapshot.status !== 'active') {\n return snapshot;\n }\n switch (event.type) {\n case XSTATE_OBSERVABLE_NEXT:\n {\n const newSnapshot = {\n ...snapshot,\n context: event.data\n };\n return newSnapshot;\n }\n case XSTATE_OBSERVABLE_ERROR:\n return {\n ...snapshot,\n status: 'error',\n error: event.data,\n input: undefined,\n _subscription: undefined\n };\n case XSTATE_OBSERVABLE_COMPLETE:\n return {\n ...snapshot,\n status: 'done',\n input: undefined,\n _subscription: undefined\n };\n case XSTATE_STOP:\n snapshot._subscription.unsubscribe();\n return {\n ...snapshot,\n status: 'stopped',\n input: undefined,\n _subscription: undefined\n };\n default:\n return snapshot;\n }\n },\n getInitialSnapshot: (_, input) => {\n return {\n status: 'active',\n output: undefined,\n error: undefined,\n context: undefined,\n input,\n _subscription: undefined\n };\n },\n start: (state, {\n self,\n system,\n emit\n }) => {\n if (state.status === 'done') {\n // Do not restart a completed observable\n return;\n }\n state._subscription = observableCreator({\n input: state.input,\n system,\n self,\n emit\n }).subscribe({\n next: value => {\n system._relay(self, self, {\n type: XSTATE_OBSERVABLE_NEXT,\n data: value\n });\n },\n error: err => {\n system._relay(self, self, {\n type: XSTATE_OBSERVABLE_ERROR,\n data: err\n });\n },\n complete: () => {\n system._relay(self, self, {\n type: XSTATE_OBSERVABLE_COMPLETE\n });\n }\n });\n },\n getPersistedSnapshot: ({\n _subscription,\n ...state\n }) => state,\n restoreSnapshot: state => ({\n ...state,\n _subscription: undefined\n })\n };\n return logic;\n}\n\n/**\n * Creates event observable logic that listens to an observable that delivers\n * event objects.\n *\n * Event observable actor logic is described by an observable stream of\n * {@link https://stately.ai/docs/transitions#event-objects | event objects}.\n * Actors created from event observable logic (“event observable actors”) can:\n *\n * - Implicitly send events to its parent actor\n * - Emit snapshots of its emitted event objects\n *\n * Sending events to event observable actors will have no effect.\n *\n * @example\n *\n * ```ts\n * import {\n * fromEventObservable,\n * Subscribable,\n * EventObject,\n * createMachine,\n * createActor\n * } from 'xstate';\n * import { fromEvent } from 'rxjs';\n *\n * const mouseClickLogic = fromEventObservable(\n * () => fromEvent(document.body, 'click') as Subscribable<EventObject>\n * );\n *\n * const canvasMachine = createMachine({\n * invoke: {\n * // Will send mouse `click` events to the canvas actor\n * src: mouseClickLogic\n * }\n * });\n *\n * const canvasActor = createActor(canvasMachine);\n * canvasActor.start();\n * ```\n *\n * @param lazyObservable A function that creates an observable that delivers\n * event objects. It receives one argument, an object with the following\n * properties:\n *\n * - `input` - Data that was provided to the event observable actor\n * - `self` - The parent actor\n * - `system` - The actor system to which the event observable actor belongs.\n *\n * It should return a {@link Subscribable}, which is compatible with an RxJS\n * Observable, although RxJS is not required to create them.\n */\nfunction fromEventObservable(lazyObservable) {\n // TODO: event types\n const logic = {\n config: lazyObservable,\n transition: (state, event) => {\n if (state.status !== 'active') {\n return state;\n }\n switch (event.type) {\n case XSTATE_OBSERVABLE_ERROR:\n return {\n ...state,\n status: 'error',\n error: event.data,\n input: undefined,\n _subscription: undefined\n };\n case XSTATE_OBSERVABLE_COMPLETE:\n return {\n ...state,\n status: 'done',\n input: undefined,\n _subscription: undefined\n };\n case XSTATE_STOP:\n state._subscription.unsubscribe();\n return {\n ...state,\n status: 'stopped',\n input: undefined,\n _subscription: undefined\n };\n default:\n return state;\n }\n },\n getInitialSnapshot: (_, input) => {\n return {\n status: 'active',\n output: undefined,\n error: undefined,\n context: undefined,\n input,\n _subscription: undefined\n };\n },\n start: (state, {\n self,\n system,\n emit\n }) => {\n if (state.status === 'done') {\n // Do not restart a completed observable\n return;\n }\n state._subscription = lazyObservable({\n input: state.input,\n system,\n self,\n emit\n }).subscribe({\n next: value => {\n if (self._parent) {\n system._relay(self, self._parent, value);\n }\n },\n error: err => {\n system._relay(self, self, {\n type: XSTATE_OBSERVABLE_ERROR,\n data: err\n });\n },\n complete: () => {\n system._relay(self, self, {\n type: XSTATE_OBSERVABLE_COMPLETE\n });\n }\n });\n },\n getPersistedSnapshot: ({\n _subscription,\n ...snapshot\n }) => snapshot,\n restoreSnapshot: snapshot => ({\n ...snapshot,\n _subscription: undefined\n })\n };\n return logic;\n}\n\nconst XSTATE_PROMISE_RESOLVE = 'xstate.promise.resolve';\nconst XSTATE_PROMISE_REJECT = 'xstate.promise.reject';\n\n/**\n * Represents an actor created by `fromPromise`.\n *\n * The type of `self` within the actor's logic.\n *\n * @example\n *\n * ```ts\n * import { fromPromise, createActor } from 'xstate';\n *\n * // The actor's resolved output\n * type Output = string;\n * // The actor's input.\n * type Input = { message: string };\n *\n * // Actor logic that fetches the url of an image of a cat saying `input.message`.\n * const logic = fromPromise<Output, Input>(async ({ input, self }) => {\n * self;\n * // ^? PromiseActorRef<Output, Input>\n *\n * const data = await fetch(\n * `https://cataas.com/cat/says/${input.message}`\n * );\n * const url = await data.json();\n * return url;\n * });\n *\n * const actor = createActor(logic, { input: { message: 'hello world' } });\n * // ^? PromiseActorRef<Output, Input>\n * ```\n *\n * @see {@link fromPromise}\n */\n\nconst controllerMap = new WeakMap();\n\n/**\n * An actor logic creator which returns promise logic as defined by an async\n * process that resolves or rejects after some time.\n *\n * Actors created from promise actor logic (“promise actors”) can:\n *\n * - Emit the resolved value of the promise\n * - Output the resolved value of the promise\n *\n * Sending events to promise actors will have no effect.\n *\n * @example\n *\n * ```ts\n * const promiseLogic = fromPromise(async () => {\n * const result = await fetch('https://example.com/...').then((data) =>\n * data.json()\n * );\n *\n * return result;\n * });\n *\n * const promiseActor = createActor(promiseLogic);\n * promiseActor.subscribe((snapshot) => {\n * console.log(snapshot);\n * });\n * promiseActor.start();\n * // => {\n * // output: undefined,\n * // status: 'active'\n * // ...\n * // }\n *\n * // After promise resolves\n * // => {\n * // output: { ... },\n * // status: 'done',\n * // ...\n * // }\n * ```\n *\n * @param promiseCreator A function which returns a Promise, and accepts an\n * object with the following properties:\n *\n * - `input` - Data that was provided to the promise actor\n * - `self` - The parent actor of the promise actor\n * - `system` - The actor system to which the promise actor belongs\n *\n * @see {@link https://stately.ai/docs/input | Input docs} for more information about how input is passed\n */\nfunction fromPromise(promiseCreator) {\n const logic = {\n config: promiseCreator,\n transition: (state, event, scope) => {\n if (state.status !== 'active') {\n return state;\n }\n switch (event.type) {\n case XSTATE_PROMISE_RESOLVE:\n {\n const resolvedValue = event.data;\n return {\n ...state,\n status: 'done',\n output: resolvedValue,\n input: undefined\n };\n }\n case XSTATE_PROMISE_REJECT:\n return {\n ...state,\n status: 'error',\n error: event.data,\n input: undefined\n };\n case XSTATE_STOP:\n {\n controllerMap.get(scope.self)?.abort();\n return {\n ...state,\n status: 'stopped',\n input: undefined\n };\n }\n default:\n return state;\n }\n },\n start: (state, {\n self,\n system,\n emit\n }) => {\n // TODO: determine how to allow customizing this so that promises\n // can be restarted if necessary\n if (state.status !== 'active') {\n return;\n }\n const controller = new AbortController();\n controllerMap.set(self, controller);\n const resolvedPromise = Promise.resolve(promiseCreator({\n input: state.input,\n system,\n self,\n signal: controller.signal,\n emit\n }));\n resolvedPromise.then(response => {\n if (self.getSnapshot().status !== 'active') {\n return;\n }\n controllerMap.delete(self);\n system._relay(self, self, {\n type: XSTATE_PROMISE_RESOLVE,\n data: response\n });\n }, errorData => {\n if (self.getSnapshot().status !== 'active') {\n return;\n }\n controllerMap.delete(self);\n system._relay(self, self, {\n type: XSTATE_PROMISE_REJECT,\n data: errorData\n });\n });\n },\n getInitialSnapshot: (_, input) => {\n return {\n status: 'active',\n output: undefined,\n error: undefined,\n input\n };\n },\n getPersistedSnapshot: snapshot => snapshot,\n restoreSnapshot: snapshot => snapshot\n };\n return logic;\n}\n\nconst emptyLogic = fromTransition(_ => undefined, undefined);\nfunction createEmptyActor() {\n return createActor(emptyLogic);\n}\n\nexport { createEmptyActor, fromCallback, fromEventObservable, fromObservable, fromPromise, fromTransition };\n","import { T as ProcessingStatus, z as resolveReferencedActor, A as createActor, U as cloneMachineSnapshot, V as XSTATE_ERROR, W as createErrorActorEvent, e as evaluateGuard, M as cancel, O as raise, P as spawnChild, R as stopChild } from './raise-c17ec2bc.esm.js';\n\nfunction createSpawner(actorScope, {\n machine,\n context\n}, event, spawnedChildren) {\n const spawn = (src, options) => {\n if (typeof src === 'string') {\n const logic = resolveReferencedActor(machine, src);\n if (!logic) {\n throw new Error(`Actor logic '${src}' not implemented in machine '${machine.id}'`);\n }\n const actorRef = createActor(logic, {\n id: options?.id,\n parent: actorScope.self,\n syncSnapshot: options?.syncSnapshot,\n input: typeof options?.input === 'function' ? options.input({\n context,\n event,\n self: actorScope.self\n }) : options?.input,\n src,\n systemId: options?.systemId\n });\n spawnedChildren[actorRef.id] = actorRef;\n return actorRef;\n } else {\n const actorRef = createActor(src, {\n id: options?.id,\n parent: actorScope.self,\n syncSnapshot: options?.syncSnapshot,\n input: options?.input,\n src,\n systemId: options?.systemId\n });\n return actorRef;\n }\n };\n return (src, options) => {\n const actorRef = spawn(src, options); // TODO: fix types\n spawnedChildren[actorRef.id] = actorRef;\n actorScope.defer(() => {\n if (actorRef._processingStatus === ProcessingStatus.Stopped) {\n return;\n }\n actorRef.start();\n });\n return actorRef;\n };\n}\n\nfunction resolveAssign(actorScope, snapshot, actionArgs, actionParams, {\n assignment\n}) {\n if (!snapshot.context) {\n throw new Error('Cannot assign to undefined `context`. Ensure that `context` is defined in the machine config.');\n }\n const spawnedChildren = {};\n const assignArgs = {\n context: snapshot.context,\n event: actionArgs.event,\n spawn: createSpawner(actorScope, snapshot, actionArgs.event, spawnedChildren),\n self: actorScope.self,\n system: actorScope.system\n };\n let partialUpdate = {};\n if (typeof assignment === 'function') {\n partialUpdate = assignment(assignArgs, actionParams);\n } else {\n for (const key of Object.keys(assignment)) {\n const propAssignment = assignment[key];\n partialUpdate[key] = typeof propAssignment === 'function' ? propAssignment(assignArgs, actionParams) : propAssignment;\n }\n }\n const updatedContext = Object.assign({}, snapshot.context, partialUpdate);\n return [cloneMachineSnapshot(snapshot, {\n context: updatedContext,\n children: Object.keys(spawnedChildren).length ? {\n ...snapshot.children,\n ...spawnedChildren\n } : snapshot.children\n }), undefined, undefined];\n}\n/**\n * Updates the current context of the machine.\n *\n * @example\n *\n * ```ts\n * import { createMachine, assign } from 'xstate';\n *\n * const countMachine = createMachine({\n * context: {\n * count: 0,\n * message: ''\n * },\n * on: {\n * inc: {\n * actions: assign({\n * count: ({ context }) => context.count + 1\n * })\n * },\n * updateMessage: {\n * actions: assign(({ context, event }) => {\n * return {\n * message: event.message.trim()\n * };\n * })\n * }\n * }\n * });\n * ```\n *\n * @param assignment An object that represents the partial context to update, or\n * a function that returns an object that represents the partial context to\n * update.\n */\nfunction assign(assignment) {\n function assign(_args, _params) {\n }\n assign.type = 'xstate.assign';\n assign.assignment = assignment;\n assign.resolve = resolveAssign;\n return assign;\n}\n\nfunction resolveEmit(_, snapshot, args, actionParams, {\n event: eventOrExpr\n}) {\n const resolvedEvent = typeof eventOrExpr === 'function' ? eventOrExpr(args, actionParams) : eventOrExpr;\n return [snapshot, {\n event: resolvedEvent\n }, undefined];\n}\nfunction executeEmit(actorScope, {\n event\n}) {\n actorScope.defer(() => actorScope.emit(event));\n}\n/**\n * Emits an event to event handlers registered on the actor via `actor.on(event,\n * handler)`.\n *\n * @example\n *\n * ```ts\n * import { emit } from 'xstate';\n *\n * const machine = createMachine({\n * // ...\n * on: {\n * something: {\n * actions: emit({\n * type: 'emitted',\n * some: 'data'\n * })\n * }\n * }\n * // ...\n * });\n *\n * const actor = createActor(machine).start();\n *\n * actor.on('emitted', (event) => {\n * console.log(event);\n * });\n *\n * actor.send({ type: 'something' });\n * // logs:\n * // {\n * // type: 'emitted',\n * // some: 'data'\n * // }\n * ```\n */\nfunction emit(/** The event to emit, or an expression that returns an event to emit. */\neventOrExpr) {\n function emit(_args, _params) {\n }\n emit.type = 'xstate.emit';\n emit.event = eventOrExpr;\n emit.resolve = resolveEmit;\n emit.execute = executeEmit;\n return emit;\n}\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 */\n\n// https://github.com/microsoft/TypeScript/issues/23182#issuecomment-379091887\n\n// @TODO: Replace with native `NoInfer` when TS issue gets fixed:\n// https://github.com/microsoft/TypeScript/pull/57673\n\n/** @deprecated Use the built-in `NoInfer` type instead */\n\n/** The full definition of an event, with a string `type`. */\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 */\n\n/** @deprecated Use `AnyMachineSnapshot` instead */\n\n// TODO: possibly refactor this somehow, use even a simpler type, and maybe even make `machine.options` private or something\n/** @ignore */\n\nlet SpecialTargets = /*#__PURE__*/function (SpecialTargets) {\n SpecialTargets[\"Parent\"] = \"#_parent\";\n SpecialTargets[\"Internal\"] = \"#_internal\";\n return SpecialTargets;\n}({});\n\n/** @deprecated Use `AnyActor` instead. */\n\n// Based on RxJS types\n\n// TODO: in v6, this should only accept AnyActorLogic, like ActorRefFromLogic\n\n/** @deprecated Use `Actor<T>` instead. */\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 */\n\n/** @deprecated */\n\n// TODO: cover all that can be actually returned\n\nfunction resolveSendTo(actorScope, snapshot, args, actionParams, {\n to,\n event: eventOrExpr,\n id,\n delay\n}, extra) {\n const delaysMap = snapshot.machine.implementations.delays;\n if (typeof eventOrExpr === 'string') {\n throw new Error(\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n `Only event objects may be used with sendTo; use sendTo({ type: \"${eventOrExpr}\" }) instead`);\n }\n const resolvedEvent = typeof eventOrExpr === 'function' ? eventOrExpr(args, actionParams) : eventOrExpr;\n let resolvedDelay;\n if (typeof delay === 'string') {\n const configDelay = delaysMap && delaysMap[delay];\n resolvedDelay = typeof configDelay === 'function' ? configDelay(args, actionParams) : configDelay;\n } else {\n resolvedDelay = typeof delay === 'function' ? delay(args, actionParams) : delay;\n }\n const resolvedTarget = typeof to === 'function' ? to(args, actionParams) : to;\n let targetActorRef;\n if (typeof resolvedTarget === 'string') {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison\n if (resolvedTarget === SpecialTargets.Parent) {\n targetActorRef = actorScope.self._parent;\n }\n // eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison\n else if (resolvedTarget === SpecialTargets.Internal) {\n targetActorRef = actorScope.self;\n } else if (resolvedTarget.startsWith('#_')) {\n // SCXML compatibility: https://www.w3.org/TR/scxml/#SCXMLEventProcessor\n // #_invokeid. If the target is the special term '#_invokeid', where invokeid is the invokeid of an SCXML session that the sending session has created by <invoke>, the Processor must add the event to the external queue of that session.\n targetActorRef = snapshot.children[resolvedTarget.slice(2)];\n } else {\n targetActorRef = extra.deferredActorIds?.includes(resolvedTarget) ? resolvedTarget : snapshot.children[resolvedTarget];\n }\n if (!targetActorRef) {\n throw new Error(`Unable to send event to actor '${resolvedTarget}' from machine '${snapshot.machine.id}'.`);\n }\n } else {\n targetActorRef = resolvedTarget || actorScope.self;\n }\n return [snapshot, {\n to: targetActorRef,\n targetId: typeof resolvedTarget === 'string' ? resolvedTarget : undefined,\n event: resolvedEvent,\n id,\n delay: resolvedDelay\n }, undefined];\n}\nfunction retryResolveSendTo(_, snapshot, params) {\n if (typeof params.to === 'string') {\n params.to = snapshot.children[params.to];\n }\n}\nfunction executeSendTo(actorScope, params) {\n // this forms an outgoing events queue\n // thanks to that the recipient actors are able to read the *updated* snapshot value of the sender\n actorScope.defer(() => {\n const {\n to,\n event,\n delay,\n id\n } = params;\n if (typeof delay === 'number') {\n actorScope.system.scheduler.schedule(actorScope.self, to, event, delay, id);\n return;\n }\n actorScope.system._relay(actorScope.self,\n // at this point, in a deferred task, it should already be mutated by retryResolveSendTo\n // if it initially started as a string\n to, event.type === XSTATE_ERROR ? createErrorActorEvent(actorScope.self.id, event.data) : event);\n });\n}\n/**\n * Sends an event to an actor.\n *\n * @param actor The `ActorRef` to send the event to.\n * @param event The event to send, or an expression that evaluates to the event\n * to send\n * @param options Send action options\n *\n * - `id` - The unique send event identifier (used with `cancel()`).\n * - `delay` - The number of milliseconds to delay the sending of the event.\n */\nfunction sendTo(to, eventOrExpr, options) {\n function sendTo(_args, _params) {\n }\n sendTo.type = 'xstate.sendTo';\n sendTo.to = to;\n sendTo.event = eventOrExpr;\n sendTo.id = options?.id;\n sendTo.delay = options?.delay;\n sendTo.resolve = resolveSendTo;\n sendTo.retryResolve = retryResolveSendTo;\n sendTo.execute = executeSendTo;\n return sendTo;\n}\n\n/**\n * Sends an event to this machine's parent.\n *\n * @param event The event to send to the parent machine.\n * @param options Options to pass into the send event.\n */\nfunction sendParent(event, options) {\n return sendTo(SpecialTargets.Parent, event, options);\n}\n/**\n * Forwards (sends) an event to the `target` actor.\n *\n * @param target The target actor to forward the event to.\n * @param options Options to pass into the send action creator.\n */\nfunction forwardTo(target, options) {\n return sendTo(target, ({\n event\n }) => event, options);\n}\n\nfunction resolveEnqueueActions(actorScope, snapshot, args, actionParams, {\n collect\n}) {\n const actions = [];\n const enqueue = function enqueue(action) {\n actions.push(action);\n };\n enqueue.assign = (...args) => {\n actions.push(assign(...args));\n };\n enqueue.cancel = (...args) => {\n actions.push(cancel(...args));\n };\n enqueue.raise = (...args) => {\n // for some reason it fails to infer `TDelay` from `...args` here and picks its default (`never`)\n // then it fails to typecheck that because `...args` use `string` in place of `TDelay`\n actions.push(raise(...args));\n };\n enqueue.sendTo = (...args) => {\n // for some reason it fails to infer `TDelay` from `...args` here and picks its default (`never`)\n // then it fails to typecheck that because `...args` use `string` in place of `TDelay\n actions.push(sendTo(...args));\n };\n enqueue.sendParent = (...args) => {\n actions.push(sendParent(...args));\n };\n enqueue.spawnChild = (...args) => {\n actions.push(spawnChild(...args));\n };\n enqueue.stopChild = (...args) => {\n actions.push(stopChild(...args));\n };\n enqueue.emit = (...args) => {\n actions.push(emit(...args));\n };\n collect({\n context: args.context,\n event: args.event,\n enqueue,\n check: guard => evaluateGuard(guard, snapshot.context, args.event, snapshot),\n self: actorScope.self,\n system: actorScope.system\n }, actionParams);\n return [snapshot, undefined, actions];\n}\n/**\n * Creates an action object that will execute actions that are queued by the\n * `enqueue(action)` function.\n *\n * @example\n *\n * ```ts\n * import { createMachine, enqueueActions } from 'xstate';\n *\n * const machine = createMachine({\n * entry: enqueueActions(({ enqueue, check }) => {\n * enqueue.assign({ count: 0 });\n *\n * if (check('someGuard')) {\n * enqueue.assign({ count: 1 });\n * }\n *\n * enqueue('someAction');\n * })\n * });\n * ```\n */\nfunction enqueueActions(collect) {\n function enqueueActions(_args, _params) {\n }\n enqueueActions.type = 'xstate.enqueueActions';\n enqueueActions.collect = collect;\n enqueueActions.resolve = resolveEnqueueActions;\n return enqueueActions;\n}\n\nfunction resolveLog(_, snapshot, actionArgs, actionParams, {\n value,\n label\n}) {\n return [snapshot, {\n value: typeof value === 'function' ? value(actionArgs, actionParams) : value,\n label\n }, undefined];\n}\nfunction executeLog({\n logger\n}, {\n value,\n label\n}) {\n if (label) {\n logger(label, value);\n } else {\n logger(value);\n }\n}\n/**\n * @param expr The expression function to evaluate which will be logged. Takes\n * in 2 arguments:\n *\n * - `ctx` - the current state context\n * - `event` - the event that caused this action to be executed.\n *\n * @param label The label to give to the logged expression.\n */\nfunction log(value = ({\n context,\n event\n}) => ({\n context,\n event\n}), label) {\n function log(_args, _params) {\n }\n log.type = 'xstate.log';\n log.value = value;\n log.label = label;\n log.resolve = resolveLog;\n log.execute = executeLog;\n return log;\n}\n\nexport { SpecialTargets as S, assign as a, enqueueActions as b, sendTo as c, emit as e, forwardTo as f, log as l, sendParent as s };\n","export { createEmptyActor, fromCallback, fromEventObservable, fromObservable, fromPromise, fromTransition } from '../actors/dist/xstate-actors.esm.js';\nimport { t as toArray, S as STATE_DELIMITER, m as mapValues, f as formatTransitions, a as toTransitionConfigArray, b as formatTransition, N as NULL_EVENT, e as evaluateGuard, c as createInvokeId, g as getDelayedTransitions, d as formatInitialTransition, h as getCandidates, r as resolveStateValue, i as getAllStateNodes, j as getStateNodes, k as createMachineSnapshot, l as isInFinalState, n as macrostep, o as transitionNode, p as resolveActionsAndContext, q as createInitEvent, s as microstep, u as getInitialStateNodes, v as toStatePath, w as isStateId, x as getStateNodeByPath, y as getPersistedSnapshot, z as resolveReferencedActor, A as createActor, $ as $$ACTOR_TYPE } from './raise-c17ec2bc.esm.js';\nexport { B as Actor, I as __unsafe_getAllOwnEventDescriptors, D as and, M as cancel, A as createActor, j as getStateNodes, C as interpret, H as isMachineSnapshot, J as matchesState, E as not, F as or, K as pathToStateValue, O as raise, P as spawnChild, G as stateIn, Q as stop, R as stopChild, L as toObserver } from './raise-c17ec2bc.esm.js';\nimport { a as assign } from './log-3d9d72a9.esm.js';\nexport { S as SpecialTargets, a as assign, e as emit, b as enqueueActions, f as forwardTo, l as log, s as sendParent, c as sendTo } from './log-3d9d72a9.esm.js';\nimport '../dev/dist/xstate-dev.esm.js';\n\n/**\n * Asserts that the given event object is of the specified type or types. Throws\n * an error if the event object is not of the specified types.\n *\n * @example\n *\n * ```ts\n * // ...\n * entry: ({ event }) => {\n * assertEvent(event, 'doNothing');\n * // event is { type: 'doNothing' }\n * },\n * // ...\n * exit: ({ event }) => {\n * assertEvent(event, 'greet');\n * // event is { type: 'greet'; message: string }\n *\n * assertEvent(event, ['greet', 'notify']);\n * // event is { type: 'greet'; message: string }\n * // or { type: 'notify'; message: string; level: 'info' | 'error' }\n * },\n * ```\n */\nfunction assertEvent(event, type) {\n const types = toArray(type);\n if (!types.includes(event.type)) {\n const typesText = types.length === 1 ? `type \"${types[0]}\"` : `one of types \"${types.join('\", \"')}\"`;\n throw new Error(`Expected event ${JSON.stringify(event)} to have ${typesText}`);\n }\n}\n\nconst cache = new WeakMap();\nfunction memo(object, key, fn) {\n let memoizedData = cache.get(object);\n if (!memoizedData) {\n memoizedData = {\n [key]: fn()\n };\n cache.set(object, memoizedData);\n } else if (!(key in memoizedData)) {\n memoizedData[key] = fn();\n }\n return memoizedData[key];\n}\n\nconst EMPTY_OBJECT = {};\nconst toSerializableAction = action => {\n if (typeof action === 'string') {\n return {\n type: action\n };\n }\n if (typeof action === 'function') {\n if ('resolve' in action) {\n return {\n type: action.type\n };\n }\n return {\n type: action.name\n };\n }\n return action;\n};\nclass StateNode {\n constructor(/** The raw config used to create the machine. */\n config, options) {\n this.config = config;\n /**\n * The relative key of the state node, which represents its location in the\n * overall state value.\n */\n this.key = void 0;\n /** The unique ID of the state node. */\n this.id = void 0;\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 * - `'final'` - final state node\n */\n this.type = void 0;\n /** The string path from the root machine node to this node. */\n this.path = void 0;\n /** The child state nodes. */\n this.states = void 0;\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 this.history = void 0;\n /** The action(s) to be executed upon entering the state node. */\n this.entry = void 0;\n /** The action(s) to be executed upon exiting the state node. */\n this.exit = void 0;\n /** The parent state node. */\n this.parent = void 0;\n /** The root machine node. */\n this.machine = void 0;\n /**\n * The meta data associated with this state node, which will be returned in\n * State instances.\n */\n this.meta = void 0;\n /**\n * The output data sent with the \"xstate.done.state._id_\" event if this is a\n * final state node.\n */\n this.output = void 0;\n /**\n * The order this state node appears. Corresponds to the implicit document\n * order.\n */\n this.order = -1;\n this.description = void 0;\n this.tags = [];\n this.transitions = void 0;\n this.always = void 0;\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 this.id = this.config.id || [this.machine.id, ...this.path].join(STATE_DELIMITER);\n this.type = this.config.type || (this.config.states && Object.keys(this.config.states).length ? 'compound' : this.config.history ? 'history' : 'atomic');\n this.description = this.config.description;\n this.order = this.machine.idMap.size;\n this.machine.idMap.set(this.id, this);\n this.states = this.config.states ? mapValues(this.config.states, (stateConfig, key) => {\n const stateNode = new StateNode(stateConfig, {\n _parent: this,\n _key: key,\n _machine: this.machine\n });\n return stateNode;\n }) : EMPTY_OBJECT;\n if (this.type === 'compound' && !this.config.initial) {\n throw new Error(`No initial state specified for compound state node \"#${this.id}\". Try adding { initial: \"${Object.keys(this.states)[0]}\" } to the state config.`);\n }\n\n // History config\n this.history = this.config.history === true ? 'shallow' : this.config.history || false;\n this.entry = toArray(this.config.entry).slice();\n this.exit = toArray(this.config.exit).slice();\n this.meta = this.config.meta;\n this.output = this.type === 'final' || !this.parent ? this.config.output : undefined;\n this.tags = toArray(config.tags).slice();\n }\n\n /** @internal */\n _initialize() {\n this.transitions = formatTransitions(this);\n if (this.config.always) {\n this.always = toTransitionConfigArray(this.config.always).map(t => formatTransition(this, NULL_EVENT, t));\n }\n Object.keys(this.states).forEach(key => {\n this.states[key]._initialize();\n });\n }\n\n /** The well-structured state node definition. */\n get definition() {\n return {\n id: this.id,\n key: this.key,\n version: this.machine.version,\n type: this.type,\n initial: this.initial ? {\n target: this.initial.target,\n source: this,\n actions: this.initial.actions.map(toSerializableAction),\n eventType: null,\n reenter: false,\n toJSON: () => ({\n target: this.initial.target.map(t => `#${t.id}`),\n source: `#${this.id}`,\n actions: this.initial.actions.map(toSerializableAction),\n eventType: null\n })\n } : undefined,\n history: this.history,\n states: mapValues(this.states, state => {\n return state.definition;\n }),\n on: this.on,\n transitions: [...this.transitions.values()].flat().map(t => ({\n ...t,\n actions: t.actions.map(toSerializableAction)\n })),\n entry: this.entry.map(toSerializableAction),\n exit: this.exit.map(toSerializableAction),\n meta: this.meta,\n order: this.order || -1,\n output: this.output,\n invoke: this.invoke,\n description: this.description,\n tags: this.tags\n };\n }\n\n /** @internal */\n toJSON() {\n return this.definition;\n }\n\n /** The logic invoked as actors by this state node. */\n get invoke() {\n return memo(this, 'invoke', () => toArray(this.config.invoke).map((invokeConfig, i) => {\n const {\n src,\n systemId\n } = invokeConfig;\n const resolvedId = invokeConfig.id ?? createInvokeId(this.id, i);\n const sourceName = typeof src === 'string' ? src : `xstate.invoke.${createInvokeId(this.id, i)}`;\n return {\n ...invokeConfig,\n src: sourceName,\n id: resolvedId,\n systemId: systemId,\n toJSON() {\n const {\n onDone,\n onError,\n ...invokeDefValues\n } = invokeConfig;\n return {\n ...invokeDefValues,\n type: 'xstate.invoke',\n src: sourceName,\n id: resolvedId\n };\n }\n };\n }));\n }\n\n /** The mapping of events to transitions. */\n get on() {\n return memo(this, 'on', () => {\n const transitions = this.transitions;\n return [...transitions].flatMap(([descriptor, t]) => t.map(t => [descriptor, t])).reduce((map, [descriptor, transition]) => {\n map[descriptor] = map[descriptor] || [];\n map[descriptor].push(transition);\n return map;\n }, {});\n });\n }\n get after() {\n return memo(this, 'delayedTransitions', () => getDelayedTransitions(this));\n }\n get initial() {\n return memo(this, 'initial', () => formatInitialTransition(this, this.config.initial));\n }\n\n /** @internal */\n next(snapshot, event) {\n const eventType = event.type;\n const actions = [];\n let selectedTransition;\n const candidates = memo(this, `candidates-${eventType}`, () => getCandidates(this, eventType));\n for (const candidate of candidates) {\n const {\n guard\n } = candidate;\n const resolvedContext = snapshot.context;\n let guardPassed = false;\n try {\n guardPassed = !guard || evaluateGuard(guard, resolvedContext, event, snapshot);\n } catch (err) {\n const guardType = typeof guard === 'string' ? guard : typeof guard === 'object' ? guard.type : undefined;\n throw new Error(`Unable to evaluate guard ${guardType ? `'${guardType}' ` : ''}in transition for event '${eventType}' in state node '${this.id}':\\n${err.message}`);\n }\n if (guardPassed) {\n actions.push(...candidate.actions);\n selectedTransition = candidate;\n break;\n }\n }\n return selectedTransition ? [selectedTransition] : undefined;\n }\n\n /** All the event types accepted by this state node and its descendants. */\n get events() {\n return memo(this, 'events', () => {\n const {\n states\n } = this;\n const events = new Set(this.ownEvents);\n if (states) {\n for (const stateId of Object.keys(states)) {\n const state = states[stateId];\n if (state.states) {\n for (const event of state.events) {\n events.add(`${event}`);\n }\n }\n }\n }\n return Array.from(events);\n });\n }\n\n /**\n * All the events that have transitions directly from this state node.\n *\n * Excludes any inert events.\n */\n get ownEvents() {\n const events = new Set([...this.transitions.keys()].filter(descriptor => {\n return this.transitions.get(descriptor).some(transition => !(!transition.target && !transition.actions.length && !transition.reenter));\n }));\n return Array.from(events);\n }\n}\n\nconst STATE_IDENTIFIER = '#';\nclass StateMachine {\n constructor(/** The raw config used to create the machine. */\n config, implementations) {\n this.config = config;\n /** The machine's own version. */\n this.version = void 0;\n this.schemas = void 0;\n this.implementations = void 0;\n /** @internal */\n this.__xstatenode = true;\n /** @internal */\n this.idMap = new Map();\n this.root = void 0;\n this.id = void 0;\n this.states = void 0;\n this.events = void 0;\n this.id = config.id || '(machine)';\n this.implementations = {\n actors: implementations?.actors ?? {},\n actions: implementations?.actions ?? {},\n delays: implementations?.delays ?? {},\n guards: implementations?.guards ?? {}\n };\n this.version = this.config.version;\n this.schemas = this.config.schemas;\n this.transition = this.transition.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 this.root = new StateNode(config, {\n _key: this.id,\n _machine: this\n });\n this.root._initialize();\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 implementations and merges the\n * `context` (if provided).\n *\n * @param implementations Options (`actions`, `guards`, `actors`, `delays`,\n * `context`) to recursively merge with the existing options.\n * @returns A new `StateMachine` instance with the provided implementations.\n */\n provide(implementations) {\n const {\n actions,\n guards,\n actors,\n delays\n } = this.implementations;\n return new StateMachine(this.config, {\n actions: {\n ...actions,\n ...implementations.actions\n },\n guards: {\n ...guards,\n ...implementations.guards\n },\n actors: {\n ...actors,\n ...implementations.actors\n },\n delays: {\n ...delays,\n ...implementations.delays\n }\n });\n }\n resolveState(config) {\n const resolvedStateValue = resolveStateValue(this.root, config.value);\n const nodeSet = getAllStateNodes(getStateNodes(this.root, resolvedStateValue));\n return createMachineSnapshot({\n _nodes: [...nodeSet],\n context: config.context || {},\n children: {},\n status: isInFinalState(nodeSet, this.root) ? 'done' : config.status || 'active',\n output: config.output,\n error: config.error,\n historyValue: config.historyValue\n }, this);\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 transition(snapshot, event, actorScope) {\n return macrostep(snapshot, event, actorScope, []).snapshot;\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 microstep(snapshot, event, actorScope) {\n return macrostep(snapshot, event, actorScope, []).microstates;\n }\n getTransitionData(snapshot, event) {\n return transitionNode(this.root, snapshot.value, snapshot, event) || [];\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 getPreInitialState(actorScope, initEvent, internalQueue) {\n const {\n context\n } = this.config;\n const preInitial = createMachineSnapshot({\n context: typeof context !== 'function' && context ? context : {},\n _nodes: [this.root],\n children: {},\n status: 'active'\n }, this);\n if (typeof context === 'function') {\n const assignment = ({\n spawn,\n event,\n self\n }) => context({\n spawn,\n input: event.input,\n self\n });\n return resolveActionsAndContext(preInitial, initEvent, actorScope, [assign(assignment)], internalQueue, undefined);\n }\n return preInitial;\n }\n\n /**\n * Returns the initial `State` instance, with reference to `self` as an\n * `ActorRef`.\n */\n getInitialSnapshot(actorScope, input) {\n const initEvent = createInitEvent(input); // TODO: fix;\n const internalQueue = [];\n const preInitialState = this.getPreInitialState(actorScope, initEvent, internalQueue);\n const nextState = microstep([{\n target: [...getInitialStateNodes(this.root)],\n source: this.root,\n reenter: true,\n actions: [],\n eventType: null,\n toJSON: null // TODO: fix\n }], preInitialState, actorScope, initEvent, true, internalQueue);\n const {\n snapshot: macroState\n } = macrostep(nextState, initEvent, actorScope, internalQueue);\n return macroState;\n }\n start(snapshot) {\n Object.values(snapshot.children).forEach(child => {\n if (child.getSnapshot().status === 'active') {\n child.start();\n }\n });\n }\n getStateNodeById(stateId) {\n const fullPath = toStatePath(stateId);\n const relativePath = fullPath.slice(1);\n const resolvedStateId = isStateId(fullPath[0]) ? fullPath[0].slice(STATE_IDENTIFIER.length) : fullPath[0];\n const stateNode = this.idMap.get(resolvedStateId);\n if (!stateNode) {\n throw new Error(`Child state node '#${resolvedStateId}' does not exist on machine '${this.id}'`);\n }\n return getStateNodeByPath(stateNode, relativePath);\n }\n get definition() {\n return this.root.definition;\n }\n toJSON() {\n return this.definition;\n }\n getPersistedSnapshot(snapshot, options) {\n return getPersistedSnapshot(snapshot, options);\n }\n restoreSnapshot(snapshot, _actorScope) {\n const children = {};\n const snapshotChildren = snapshot.children;\n Object.keys(snapshotChildren).forEach(actorId => {\n const actorData = snapshotChildren[actorId];\n const childState = actorData.snapshot;\n const src = actorData.src;\n const logic = typeof src === 'string' ? resolveReferencedActor(this, src) : src;\n if (!logic) {\n return;\n }\n const actorRef = createActor(logic, {\n id: actorId,\n parent: _actorScope.self,\n syncSnapshot: actorData.syncSnapshot,\n snapshot: childState,\n src,\n systemId: actorData.systemId\n });\n children[actorId] = actorRef;\n });\n const restoredSnapshot = createMachineSnapshot({\n ...snapshot,\n children,\n _nodes: Array.from(getAllStateNodes(getStateNodes(this.root, snapshot.value)))\n }, this);\n const seen = new Set();\n function reviveContext(contextPart, children) {\n if (seen.has(contextPart)) {\n return;\n }\n seen.add(contextPart);\n for (const key in contextPart) {\n const value = contextPart[key];\n if (value && typeof value === 'object') {\n if ('xstate$$type' in value && value.xstate$$type === $$ACTOR_TYPE) {\n contextPart[key] = children[value.id];\n continue;\n }\n reviveContext(value, children);\n }\n }\n }\n reviveContext(restoredSnapshot.context, children);\n return restoredSnapshot;\n }\n}\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 implementations instead.\n */\nfunction createMachine(config, implementations) {\n return new StateMachine(config, implementations);\n}\n\n/** @internal */\nfunction createInertActorScope(actorLogic) {\n const self = createActor(actorLogic);\n const inertActorScope = {\n self,\n defer: () => {},\n id: '',\n logger: () => {},\n sessionId: '',\n stopChild: () => {},\n system: self.system,\n emit: () => {},\n actionExecutor: () => {}\n };\n return inertActorScope;\n}\n\n/** @deprecated Use `initialTransition(…)` instead. */\nfunction getInitialSnapshot(actorLogic, ...[input]) {\n const actorScope = createInertActorScope(actorLogic);\n return actorLogic.getInitialSnapshot(actorScope, input);\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 */\nfunction getNextSnapshot(actorLogic, snapshot, event) {\n const inertActorScope = createInertActorScope(actorLogic);\n inertActorScope.self._snapshot = snapshot;\n return actorLogic.transition(snapshot, event, inertActorScope);\n}\n\n// at the moment we allow extra actors - ones that are not specified by `children`\n// this could be reconsidered in the future\n\nfunction setup({\n schemas,\n actors,\n actions,\n guards,\n delays\n}) {\n return {\n createMachine: config => createMachine({\n ...config,\n schemas\n }, {\n actors,\n actions,\n guards,\n delays\n })\n };\n}\n\n// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging\n\n// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging\nclass SimulatedClock {\n constructor() {\n this.timeouts = new Map();\n this._now = 0;\n this._id = 0;\n this._flushing = false;\n this._flushingInvalidated = false;\n }\n now() {\n return this._now;\n }\n getId() {\n return this._id++;\n }\n setTimeout(fn, timeout) {\n this._flushingInvalidated = this._flushing;\n const id = this.getId();\n this.timeouts.set(id, {\n start: this.now(),\n timeout,\n fn\n });\n return id;\n }\n clearTimeout(id) {\n this._flushingInvalidated = this._flushing;\n this.timeouts.delete(id);\n }\n set(time) {\n if (this._now > time) {\n throw new Error('Unable to travel back in time');\n }\n this._now = time;\n this.flushTimeouts();\n }\n flushTimeouts() {\n if (this._flushing) {\n this._flushingInvalidated = true;\n return;\n }\n this._flushing = true;\n const sorted = [...this.timeouts].sort(([_idA, timeoutA], [_idB, timeoutB]) => {\n const endA = timeoutA.start + timeoutA.timeout;\n const endB = timeoutB.start + timeoutB.timeout;\n return endB > endA ? -1 : 1;\n });\n for (const [id, timeout] of sorted) {\n if (this._flushingInvalidated) {\n this._flushingInvalidated = false;\n this._flushing = false;\n this.flushTimeouts();\n return;\n }\n if (this.now() - timeout.start >= timeout.timeout) {\n this.timeouts.delete(id);\n timeout.fn.call(null);\n }\n }\n this._flushing = false;\n }\n increment(ms) {\n this._now += ms;\n this.flushTimeouts();\n }\n}\n\n/**\n * Returns a promise that resolves to the `output` of the actor when it is done.\n *\n * @example\n *\n * ```ts\n * const machine = createMachine({\n * // ...\n * output: {\n * count: 42\n * }\n * });\n *\n * const actor = createActor(machine);\n *\n * actor.start();\n *\n * const output = await toPromise(actor);\n *\n * console.log(output);\n * // logs { count: 42 }\n * ```\n */\nfunction toPromise(actor) {\n return new Promise((resolve, reject) => {\n actor.subscribe({\n complete: () => {\n resolve(actor.getSnapshot().output);\n },\n error: reject\n });\n });\n}\n\n/**\n * Given actor `logic`, a `snapshot`, and an `event`, returns a tuple of the\n * `nextSnapshot` and `actions` to execute.\n *\n * This is a pure function that does not execute `actions`.\n */\nfunction transition(logic, snapshot, event) {\n const executableActions = [];\n const actorScope = createInertActorScope(logic);\n actorScope.actionExecutor = action => {\n executableActions.push(action);\n };\n const nextSnapshot = logic.transition(snapshot, event, actorScope);\n return [nextSnapshot, executableActions];\n}\n\n/**\n * Given actor `logic` and optional `input`, returns a tuple of the\n * `nextSnapshot` and `actions` to execute from the initial transition (no\n * previous state).\n *\n * This is a pure function that does not execute `actions`.\n */\nfunction initialTransition(logic, ...[input]) {\n const executableActions = [];\n const actorScope = createInertActorScope(logic);\n actorScope.actionExecutor = action => {\n executableActions.push(action);\n };\n const nextSnapshot = logic.getInitialSnapshot(actorScope, input);\n return [nextSnapshot, executableActions];\n}\n\nconst defaultWaitForOptions = {\n timeout: Infinity // much more than 10 seconds\n};\n\n/**\n * Subscribes to an actor ref and waits for its emitted value to satisfy a\n * predicate, and then resolves with that value. Will throw if the desired state\n * is not reached after an optional timeout. (defaults to Infinity).\n *\n * @example\n *\n * ```js\n * const state = await waitFor(someService, (state) => {\n * return state.hasTag('loaded');\n * });\n *\n * state.hasTag('loaded'); // true\n * ```\n *\n * @param actorRef The actor ref to subscribe to\n * @param predicate Determines if a value matches the condition to wait for\n * @param options\n * @returns A promise that eventually resolves to the emitted value that matches\n * the condition\n */\nfunction waitFor(actorRef, predicate, options) {\n const resolvedOptions = {\n ...defaultWaitForOptions,\n ...options\n };\n return new Promise((res, rej) => {\n const {\n signal\n } = resolvedOptions;\n if (signal?.aborted) {\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n rej(signal.reason);\n return;\n }\n let done = false;\n const handle = resolvedOptions.timeout === Infinity ? undefined : setTimeout(() => {\n dispose();\n rej(new Error(`Timeout of ${resolvedOptions.timeout} ms exceeded`));\n }, resolvedOptions.timeout);\n const dispose = () => {\n clearTimeout(handle);\n done = true;\n sub?.unsubscribe();\n if (abortListener) {\n signal.removeEventListener('abort', abortListener);\n }\n };\n function checkEmitted(emitted) {\n if (predicate(emitted)) {\n dispose();\n res(emitted);\n }\n }\n\n /**\n * If the `signal` option is provided, this will be the listener for its\n * `abort` event\n */\n let abortListener;\n // eslint-disable-next-line prefer-const\n let sub; // avoid TDZ when disposing synchronously\n\n // See if the current snapshot already matches the predicate\n checkEmitted(actorRef.getSnapshot());\n if (done) {\n return;\n }\n\n // only define the `abortListener` if the `signal` option is provided\n if (signal) {\n abortListener = () => {\n dispose();\n // XState does not \"own\" the signal, so we should reject with its reason (if any)\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n rej(signal.reason);\n };\n signal.addEventListener('abort', abortListener);\n }\n sub = actorRef.subscribe({\n next: checkEmitted,\n error: err => {\n dispose();\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n rej(err);\n },\n complete: () => {\n dispose();\n rej(new Error(`Actor terminated without satisfying predicate`));\n }\n });\n if (done) {\n sub.unsubscribe();\n }\n });\n}\n\nexport { SimulatedClock, StateMachine, StateNode, assertEvent, createMachine, getInitialSnapshot, getNextSnapshot, initialTransition, setup, toPromise, transition, waitFor };\n","import { jsxs, jsx } from \"react/jsx-runtime\";\nimport { hues, white } from \"@sanity/color\";\nimport { forwardRef } from \"react\";\nconst GroqLogo = forwardRef(function(props, ref) {\n return /* @__PURE__ */ jsxs(\n \"svg\",\n {\n \"data-sanity-icon\": \"groq-logo\",\n height: \"1em\",\n viewBox: \"0 0 304 64\",\n fill: \"none\",\n xmlns: \"http://www.w3.org/2000/svg\",\n ...props,\n ref,\n children: [\n /* @__PURE__ */ jsx(\"path\", { d: \"M32 0L0 32H32V0Z\", fill: hues.magenta[400].hex }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M32 32H0L32 64V32Z\", fill: hues.green[300].hex }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M64 32H32V64L64 32Z\", fill: hues.purple[300].hex }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M112 0L80 32H112V0Z\", fill: hues.green[300].hex }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M112 0H80V32L112 0Z\", fill: hues.purple[300].hex }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M112 32H80L112 64V32Z\", fill: hues.yellow[200].hex }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M144 64L112 32V64H144Z\", fill: hues.blue[300].hex }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M80 32V64H112L80 32Z\", fill: hues.orange[400].hex }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M112 0V32H144L112 0Z\", fill: hues.magenta[400].hex }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M192 0L160 32H192V0Z\", fill: hues.yellow[200].hex }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M192 32H160L192 64V32Z\", fill: hues.orange[400].hex }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M224 32H192V64L224 32Z\", fill: hues.green[300].hex }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M192 0V32H224L192 0Z\", fill: hues.blue[300].hex }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M272 0L240 32H272V0Z\", fill: hues.purple[300].hex }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M304 32L272 64H304V32Z\", fill: hues.magenta[400].hex }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M272 32H240L272 64V32Z\", fill: hues.blue[300].hex }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M304 32H272V64L304 32Z\", fill: hues.yellow[200].hex }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M272 0V32H304L272 0Z\", fill: hues.green[300].hex })\n ]\n }\n );\n});\nGroqLogo.displayName = \"ForwardRef(GroqLogo)\";\nconst GroqMonogram = forwardRef(function(props, ref) {\n return /* @__PURE__ */ jsxs(\n \"svg\",\n {\n \"data-sanity-icon\": \"groq-monogram\",\n width: \"1em\",\n height: \"1em\",\n viewBox: \"0 0 128 128\",\n fill: \"none\",\n xmlns: \"http://www.w3.org/2000/svg\",\n ...props,\n ref,\n children: [\n /* @__PURE__ */ jsx(\"rect\", { width: \"128\", height: \"128\", rx: \"8\", fill: hues.green[950].hex }),\n /* @__PURE__ */ jsx(\"rect\", { y: \"32\", width: \"64\", height: \"64\", fill: hues.green[800].hex }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M64 32L32 64H64V32Z\", fill: hues.magenta[400].hex }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M64 64H32L64 96V64Z\", fill: hues.green[300].hex }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M96 64H64V96L96 64Z\", fill: hues.purple[300].hex })\n ]\n }\n );\n});\nGroqMonogram.displayName = \"ForwardRef(GroqMonogram)\";\nconst schemes = {\n light: [hues.red[200].hex, hues.red[300].hex, hues.red[500].hex],\n dark: [hues.gray[500].hex, hues.gray[300].hex, white.hex]\n}, SanityLogo = forwardRef(function(props, ref) {\n const { dark, ...svgProps } = props, scheme = schemes[dark ? \"dark\" : \"light\"];\n return /* @__PURE__ */ jsxs(\n \"svg\",\n {\n \"data-sanity-icon\": \"sanity-logo\",\n height: \"1em\",\n viewBox: \"0 0 352 100\",\n fill: \"none\",\n xmlns: \"http://www.w3.org/2000/svg\",\n ...svgProps,\n ref,\n children: [\n /* @__PURE__ */ jsx(\"path\", { d: \"M311.14 57.234V80.0016H298.499V57.234\", fill: scheme[1] }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M298.499 57.2341L319.889 20.0017H333.316L311.14 57.2341H298.499Z\", fill: scheme[2] }),\n /* @__PURE__ */ jsx(\n \"path\",\n {\n d: \"M298.499 57.2341L276.515 20.0017H290.345L305.239 45.5161L298.499 57.2341Z\",\n fill: scheme[1]\n }\n ),\n /* @__PURE__ */ jsx(\"path\", { d: \"M253.839 40.9625V80.0017H241.007V47.6275L253.839 40.9625Z\", fill: scheme[1] }),\n /* @__PURE__ */ jsx(\n \"path\",\n {\n d: \"M241.007 47.5944L273.538 30.9469L268.042 21.6519L241.007 34.8633V47.5944Z\",\n fill: scheme[0]\n }\n ),\n /* @__PURE__ */ jsx(\n \"path\",\n {\n d: \"M241.007 30.9469H221.404V20.0017H267.064L273.538 30.9469H253.839H241.007Z\",\n fill: scheme[2]\n }\n ),\n /* @__PURE__ */ jsx(\"path\", { d: \"M214.047 20.0017H201.311V80.0121H214.047V20.0017Z\", fill: scheme[2] }),\n /* @__PURE__ */ jsx(\"path\", { d: \"M149.39 37.8712V80.0017H137.153V20.0017L149.39 37.8712Z\", fill: scheme[1] }),\n /* @__PURE__ */ jsx(\n \"path\",\n {\n d: \"M151.282 20.0017L178.231 60.9939V80.0017L137.153 20.0017H151.282Z\",\n fill: scheme[2]\n }\n ),\n /* @__PURE__ */ jsx(\"path\", { d: \"M178.231 57.9129V20.0017H190.467V80.0017H178.231V57.9129Z\", fill: scheme[1] }),\n /* @__PURE__ */ jsx(\n \"path\",\n {\n d: \"M82.1168 80.9834L112.102 65.3053L108.405 55.7303L88.6644 64.9362L82.1168 80.9834Z\",\n fill: scheme[0]\n }\n ),\n /* @__PURE__ */ jsx(\n \"path\",\n {\n d: \"M100.657 35.5422L82.1167 80.9834L72.5807 72.7745L94.6719 20.0017L100.657 35.5422Z\",\n fill: scheme[1]\n }\n ),\n /* @__PURE__ */ jsx(\"path\", { d: \"M94.672 20.0017H107.312L130.69 80.0017H117.752L94.672 20.0017Z\", fill: scheme[2] }),\n /* @__PURE__ */ jsx(\n \"path\",\n {\n d: \"M25.1347 26.926C25.1347 35.2811 30.3864 40.2524 40.9004 42.8738L52.0417 45.4117C61.9923 47.6571 68.0519 53.2341 68.0519 62.3203C68.1293 66.2787 66.8194 70.1429 64.3417 73.2654C64.3417 64.2002 59.5684 59.302 48.0551 56.3568L37.1158 53.913C28.3559 51.9495 21.5946 47.3647 21.5946 37.4952C21.5485 33.6839 22.7939 29.9658 25.1347 26.926\",\n fill: scheme[2]\n }\n ),\n /* @__PURE__ */ jsx(\n \"path\",\n {\n d: \"M57.4954 60.0957C62.2475 63.0827 64.3311 67.2602 64.3311 73.255C60.3977 78.2054 53.4875 80.9834 45.3655 80.9834C31.6941 80.9834 22.1262 74.3725 20 62.8842H33.1292C34.8196 68.1584 39.2952 70.6022 45.2698 70.6022C52.5626 70.6022 57.4104 66.7798 57.506 60.0748\",\n fill: scheme[1]\n }\n ),\n /* @__PURE__ */ jsx(\n \"path\",\n {\n d: \"M31.9598 39.3124C29.7898 38.0455 28.0095 36.225 26.8079 34.0442C25.6062 31.8634 25.028 29.4036 25.1347 26.926C28.93 22.0174 35.5318 19.02 43.5794 19.02C57.506 19.02 65.5643 26.2472 67.5523 36.4195H54.9227C53.53 32.409 50.0431 29.2863 43.6858 29.2863C36.8926 29.2863 32.2575 33.1715 31.9917 39.3124\",\n fill: scheme[1]\n }\n )\n ]\n }\n );\n});\nSanityLogo.displayName = \"ForwardRef(SanityLogo)\";\nconst SANITY_MONOGRAM_COLOR = {\n bg1: hues.red[500].hex,\n bg2: hues.red[200].hex,\n fg: white.hex\n}, SanityMonogram = forwardRef(function(props, ref) {\n const { color = SANITY_MONOGRAM_COLOR, ...restProps } = props;\n return /* @__PURE__ */ jsxs(\n \"svg\",\n {\n \"data-sanity-icon\": \"sanity-monogram\",\n width: \"1em\",\n height: \"1em\",\n viewBox: \"0 0 128 128\",\n fill: \"none\",\n xmlns: \"http://www.w3.org/2000/svg\",\n ...restProps,\n ref,\n children: [\n /* @__PURE__ */ jsx(\"rect\", { width: \"128\", height: \"128\", rx: \"8\", fill: color.bg1 }),\n /* @__PURE__ */ jsx(\n \"path\",\n {\n d: \"M39.423 33.163C39.423 44.1615 46.3363 50.7056 60.1768 54.1564L74.843 57.4972C87.9418 60.453 95.9186 67.7945 95.9186 79.7554C96.0205 84.9662 94.2961 90.0531 91.0345 94.1635C91.0345 82.2301 84.751 75.7822 69.595 71.9052L55.1948 68.6882C43.6633 66.1035 34.7629 60.0681 34.7629 47.0761C34.7022 42.0589 36.3416 37.1644 39.423 33.163\",\n fill: color.fg\n }\n ),\n /* @__PURE__ */ jsx(\n \"path\",\n {\n d: \"M82.0221 76.827C88.2776 80.759 91.0206 86.2582 91.0206 94.1497C85.8426 100.666 76.7462 104.323 66.0545 104.323C48.0576 104.323 35.4626 95.6207 32.6637 80.4977H49.9468C52.172 87.4406 58.0636 90.6576 65.9285 90.6576C75.5287 90.6576 81.9102 85.6258 82.0361 76.7995\",\n fill: color.bg2\n }\n ),\n /* @__PURE__ */ jsx(\n \"path\",\n {\n d: \"M48.4075 49.4682C45.551 47.8004 43.2074 45.404 41.6256 42.5332C40.0437 39.6624 39.2826 36.4244 39.4231 33.1629C44.4191 26.7013 53.1096 22.7556 63.7034 22.7556C82.0362 22.7556 92.6439 32.2693 95.2609 45.66H78.6355C76.8022 40.3807 72.2121 36.27 63.8434 36.27C54.9009 36.27 48.7993 41.3843 48.4495 49.4682\",\n fill: color.bg2\n }\n )\n ]\n }\n );\n});\nSanityMonogram.displayName = \"ForwardRef(SanityMonogram)\";\nexport {\n GroqLogo,\n GroqMonogram,\n SanityLogo,\n SanityMonogram\n};\n//# sourceMappingURL=index.js.map\n"],"names":["isArray","argsOrArgArray","args","combineLatest","_i","resultSelector","popResultSelector","pipe","__spreadArray","__read","mapOneOrManyArgs","operate","source","subscriber","combineLatestInit","combineLatestWith","otherSources","e","t","r","a","n","s","o","c","i","u","l","l$1","_a","__publicField","__privateAdd","_e","_t","_r","_o","_s","_n","__privateSet","__privateGet","_b","h","d","p","f","b","m","w","y","define_process_env_default","F","O","j","v","x","E","k","q","A","S","M","_","P","I","T","C","stegaClean","result","ClientError","res","props","extractErrorProps","ServerError","body","stringifyBody","isMutationError","isActionError","allItems","items","item","itemsStr","httpErrorMessage","isPlainObject","obj","statusMessage","CorsOriginError","projectId2","url","origin","httpError","printWarnings","warn","msg","defineHttpRequest","envMiddleware2","getIt","retry","shouldRetry","jsonRequest","jsonResponse","progress","observable","Observable","err","attempt","options","isSafe","isQuery","isRetriableResponse","BASE_URL","generateHelpUrl","slug","VALID_ASSET_TYPES","VALID_INSERT_LOCATIONS","dataset","name","projectId","id","validateAssetType","type","validateObject","op","val","validateDocumentId","requireDocumentId","doc","validateInsert","at","selector","signature","valid","loc","hasDataset","config","requestTag","tag","once","fn","didCall","returnValue","createWarningPrinter","message","printCdnAndWithCredentialsWarning","printCdnWarning","printCdnPreviewDraftsWarning","printBrowserTokenWarning","printNoApiVersionSpecifiedWarning","defaultCdnHost","defaultConfig","LOCALHOSTS","isLocal","host","validateApiVersion","apiVersion","apiDate","validateApiPerspective","perspective","perspectiveValue","initConfig","prevConfig","specifiedConfig","newConfig","projectBased","helpUrl","isBrowser","isLocalhost","hostParts","protocol","cdnHost","getSelection","sel","selectionOpts","BasePatch","selection","operations","attrs","start","deleteCount","delAll","startIndex","delCount","delRange","rangeSelector","rev","merge","_ObservablePatch","client","_client","returnFirst","opts","ObservablePatch","_Patch","Patch","defaultMutateOptions","BaseTransaction","transactionId","documentId","mut","_Transaction","patchOrDocumentId","patchOps","isBuilder","patch","Transaction","_ObservableTransaction","ObservableTransaction","projectHeader","requestOptions","overrides","headers","token","withCredentials","timeout","encodeQueryString","query","params","searchParams","includeMutations","returnQuery","key","value","excludeFalsey","param","defValue","getMutationQuery","isResponse","event","getBody","indexBy","docs","attr","indexed","getQuerySizeLimit","_fetch","httpRequest","_stega","_params","stega","mapResponse","cache","next","reqOpts","$request","_dataRequest","from","stegaEncodeSourceMap","map","_getDocument","_getDataUrl","_requestObservable","filter","_getDocuments","ids","_createIfNotExists","_create","_createOrReplace","_delete","_mutate","mutations","muts","_action","actions","acts","skipCrossDatasetReferenceValidation","dryRun","endpoint","isMutation","isAction","strQuery","useGet","stringQuery","lastLiveEventId","cacheMode","uri","reqOptions","results","mutation","canUseCdn","useCdn","resultSourceMap","perspectiveOption","_getUrl","request","_withAbortSignal","_request","operation","path","catalog","baseUri","cdnUrl","signal","input","observer","abort","_createAbortError","subscription","isDomExceptionSupported","error","ObservableAssetsClient","_httpRequest","assetType","_upload","AssetsClient","observable2","lastValueFrom","meta","dataset2","assetEndpoint","optionsFromFile","label","title","description","creditLine","filename","file","defaults","defaults2","target","prop","pick","MAX_URL_LENGTH","possibleOptions","defaultOptions","_listen","requestTagPrefix","listenOpts","qs","listenFor","shouldEmitReconnect","esOptions","es","reconnectTimer","stopped","unsubscribed","open","onError","emitReconnect","unsubscribe","onChannelError","cooerceError","onMessage","evt","parseEvent$1","onDisconnect","getEventSource","EventSource2","evs","eventSource","reason","stop","data","extractErrorMessage","requiredApiVersion","LiveClient","includeDrafts","_tag","_apiVersion","parseEvent","EventSourceImplementation","ObservableDatasetsClient","_modify","DatasetsClient","method","ObservableProjectsClient","ProjectsClient","ObservableUsersClient","UsersClient","_ObservableSanityClient","_clientConfig","thisConfig","document","ObservableSanityClient","_SanityClient","SanityClient","defineCreateClientExports","ClassConstructor","defaultRequester","requester2","envMiddleware","exp","createClient","getGlobal","getDevTools","devToolsAdapter","service","devTools","Mailbox","_process","enqueued","consumed","STATE_DELIMITER","TARGETLESS_KEY","NULL_EVENT","STATE_IDENTIFIER","WILDCARD","XSTATE_INIT","XSTATE_ERROR","XSTATE_STOP","createAfterEvent","delayRef","createDoneStateEvent","output","createDoneActorEvent","invokeId","createErrorActorEvent","createInitEvent","reportUnhandledError","symbolObservable","matchesState","parentStateId","childStateId","parentStateValue","toStateValue","childStateValue","toStatePath","stateId","segment","stateValue","isMachineSnapshot","statePath","pathToStateValue","marker","previous","mapValues","collection","iteratee","collectionKeys","toArrayStrict","toArray","resolveOutput","mapper","context","self","isErrorActorEvent","toTransitionConfigArray","configLike","transitionLike","normalizeTarget","toObserver","nextHandler","errorHandler","completionHandler","isObserver","_c","createInvokeId","stateNodeId","index","resolveReferencedActor","machine","src","match","indexStr","nodeId","invokeConfig","createScheduledEventId","actorRef","idCounter","createSystem","rootActor","children","keyedActors","reverseKeyedActors","inspectionObservers","timerMap","clock","logger","scheduler","delay","scheduledEvent","scheduledEventId","system","sendInspectionEvent","resolvedInspectionEvent","sessionId","systemId","existing","observerOrFn","scheduledEvents","scheduledId","executingCustomAction","$$ACTOR_TYPE","ProcessingStatus","ms","Actor","logic","resolvedOptions","parent","syncSnapshot","inspect","child","emittedEvent","listeners","wildcardListener","allListeners","handler","action","exec","saveExecutingCustomAction","persistedState","snapshot","deferredFn","nextListenerOrObserver","errorListener","completeListener","wrappedHandler","initEvent","nextState","caughtError","reportError","err2","createActor","resolveCancel","actionArgs","actionParams","sendId","resolvedSendId","executeCancel","actorScope","cancel","_args","resolveSpawn","_actionParams","resolvedId","resolvedInput","cloneMachineSnapshot","executeSpawn","spawnChild","resolveStop","actorRefOrString","resolvedActorRef","executeStop","stopChild","evaluateGuard","guard","isInline","resolved","guardArgs","guardParams","isAtomicStateNode","stateNode","getChildren","sn","getProperAncestors","toStateNode","ancestors","getAllStateNodes","stateNodes","nodeSet","adjList","getAdjList","getInitialStateNodesWithTheirAncestors","initialStates","initialStateNode","getValueFromAdj","baseNode","childStateNodes","childStateNode","getStateValue","rootNode","isInFinalState","stateNodeSet","isStateId","str","getCandidates","receivedEventType","eventDescriptor","partialEventTokens","eventTokens","tokenIndex","partialEventToken","eventToken","getDelayedTransitions","afterConfig","mutateEntryExit","afterEvent","eventType","raise","configTransition","resolvedTransition","resolvedDelay","transition","delayedTransition","formatTransition","descriptor","transitionConfig","normalizedTarget","reenter","resolveTarget","formatTransitions","transitions","transitionsConfig","invokeDef","formatInitialTransition","_target","resolvedTarget","targets","isInternalTarget","getStateNodeByPath","resolveHistoryDefaultTransition","isHistoryNode","states","getInitialStateNodes","initialState","ancestor","set","iter","descStateNode","getStateNode","stateKey","arrayStatePath","currentStateNode","getStateNodes","childStateKeys","subStateKey","allSubStateNodes","subStateNode","subStateNodes","transitionAtomicNode","transitionCompoundNode","subStateKeys","transitionNode","transitionParallelNode","allInnerTransitions","subStateValue","innerTransitions","getHistoryNodes","isDescendant","parentStateNode","hasIntersection","s1","s2","set1","set2","removeConflictingTransitions","enabledTransitions","historyValue","filteredTransitions","t1","t1Preempted","transitionsToRemove","t2","computeExitSet","t3","findLeastCommonAncestor","head","tail","getEffectiveTargetStates","targetNode","node","getTransitionDomain","targetStates","lca","statesToExit","domain","areStateNodeCollectionsEqual","prevStateNodes","nextStateNodeSet","microstep","currentSnapshot","isInitial","internalQueue","mutStateNodeSet","exitStates","resolveActionsAndContext","enterStates","nextStateNodes","state","getMachineOutput","rootCompletionNode","doneStateEvent","nextSnapshot","statesToEnter","statesForDefaultEntry","computeEntrySet","completedNodes","stateNodeToEnter","initialActions","ancestorMarker","addDescendantStatesToEnter","addAncestorStatesToEnter","historyStateNodes","addProperAncestorStatesToEnter","historyDefaultTransition","reentrancyDomain","anc","_actionExecutor","changedHistory","exitStateNode","historyNode","predicate","def","getAction","actionType","resolveAndExecuteActionsWithContext","extra","retries","intermediateSnapshot","resolvedAction","builtinAction","deferredActorIds","macrostep","microstates","addMicrostate","microstate","stopChildren","nextEvent","currentEvent","isErr","selectTransitions","shouldSelectEventlessTransitions","selectEventlessTransitions","previousState","enabledTransitionSet","atomicStates","loop","resolveStateValue","allStateNodes","machineSnapshotMatches","testValue","machineSnapshotHasTag","machineSnapshotCan","transitionData","machineSnapshotToJSON","nodes","tags","getMeta","toJSON","can","hasTag","matches","jsonValues","machineSnapshotGetMeta","acc","createMachineSnapshot","getPersistedSnapshot","childrenJson","persistContext","contextPart","copy","resolveRaise","eventOrExpr","delaysMap","resolvedEvent","configDelay","executeRaise","instanceStates","fromCallback","callback","emit","callbackState","listener","receiver","XSTATE_OBSERVABLE_ERROR","XSTATE_OBSERVABLE_COMPLETE","fromEventObservable","lazyObservable","_subscription","createSpawner","spawnedChildren","spawn","resolveAssign","assignment","assignArgs","partialUpdate","propAssignment","updatedContext","assign","resolveEmit","executeEmit","SpecialTargets","resolveSendTo","to","targetActorRef","retryResolveSendTo","executeSendTo","sendTo","sendParent","resolveEnqueueActions","collect","enqueue","enqueueActions","assertEvent","types","typesText","memo","object","memoizedData","EMPTY_OBJECT","toSerializableAction","StateNode","stateConfig","sourceName","onDone","invokeDefValues","selectedTransition","candidates","candidate","resolvedContext","guardPassed","guardType","events","StateMachine","implementations","guards","actors","delays","resolvedStateValue","preInitial","preInitialState","macroState","fullPath","relativePath","resolvedStateId","_actorScope","snapshotChildren","actorId","actorData","childState","restoredSnapshot","seen","reviveContext","createMachine","setup","schemas","GroqLogo","forwardRef","ref","jsxs","jsx","hues","GroqMonogram","schemes","white","SanityLogo","dark","svgProps","scheme","SANITY_MONOGRAM_COLOR","SanityMonogram","color","restProps"],"mappings":";;;;;;;;;;;;AAAA,IAAIA,KAAU,MAAM;AACb,SAASC,GAAeC,GAAM;AACjC,SAAOA,EAA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